The best way to control Claude Code, Codex and more from any computer or phone

main
ts 151 lines 5.38 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import * as Effect from "effect/Effect";
3 import {
4 alchemyLabelKeys,
5 createInternalLabels,
6 hasAlchemyLabels,
7 sanitizeLabelValue,
8 } from "../Labels.ts";
9
10 export const MAX_NAME_LENGTH = 64;
11
12 /** Locations swept by `list`: the stack region and the multi-regions (the API has no `locations/-` wildcard). */
13 export const listLocations = (region: string) => Array.from(new Set([region, "US", "EU"]));
14 const OWNER_PREFIX = "alch---";
15
16 export const lastSegment = (value: string) => {
17 const trimmed = value.replace(/\/+$/, "");
18 const parts = trimmed.split("/");
19 return parts[parts.length - 1] || trimmed;
20 };
21
22 export const normalizeLocation = (location: string) => {
23 const value = lastSegment(location);
24 const upper = value.toUpperCase();
25 if (upper === "US" || upper === "EU") return upper;
26 return value.toLowerCase();
27 };
28
29 export const parentOf = (project: string, location: string) =>
30 `projects/${project}/locations/${location}`;
31
32 export const parseResourceName = (
33 name: string,
34 collection: "capacityCommitments" | "reservationGroups",
35 ) => {
36 const parts = name.split("/").filter((part) => part.length > 0);
37 const collectionAt = parts.lastIndexOf(collection);
38 const locationsAt = parts.lastIndexOf("locations");
39 const projectsAt = parts.lastIndexOf("projects");
40 return {
41 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
42 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
43 resourceId:
44 collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
45 };
46 };
47
48 export const compact = <T extends Record<string, unknown>>(value: T): T =>
49 Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;
50
51 const sanitizeIdPart = (value: string) => {
52 const cleaned = sanitizeLabelValue(value)
53 .replace(/_/g, "-")
54 .replace(/-+/g, "-")
55 .replace(/^-|-$/g, "");
56 return cleaned.length > 0 ? cleaned : "x";
57 };
58
59 const ensureId = (value: string) => {
60 const cleaned = value
61 .toLowerCase()
62 .replace(/[^a-z0-9-]/g, "-")
63 .replace(/^-|-$/g, "")
64 .slice(0, MAX_NAME_LENGTH)
65 .replace(/-+$/g, "");
66 if (cleaned.length === 0) return "alchx";
67 return /^[a-z]/.test(cleaned) ? cleaned : `a${cleaned}`.slice(0, MAX_NAME_LENGTH);
68 };
69
70 export const encodeOwnershipId = (labels: Record<string, string>, extra?: string): string => {
71 let stack = sanitizeIdPart(labels[alchemyLabelKeys.stack] ?? "x");
72 let stage = sanitizeIdPart(labels[alchemyLabelKeys.stage] ?? "x");
73 let id = sanitizeIdPart(labels[alchemyLabelKeys.id] ?? "x");
74 let rest = extra ? sanitizeIdPart(extra) : "";
75 const build = () =>
76 rest.length > 0
77 ? `${OWNER_PREFIX}${stack}---${stage}---${id}---${rest}`
78 : `${OWNER_PREFIX}${stack}---${stage}---${id}`;
79 let name = build();
80 while (name.length > MAX_NAME_LENGTH) {
81 if (rest.length > 1) rest = rest.slice(0, -1);
82 else if (id.length > 1) id = id.slice(0, -1);
83 else if (stack.length > 1) stack = stack.slice(0, -1);
84 else if (stage.length > 1) stage = stage.slice(0, -1);
85 else break;
86 name = build();
87 }
88 return name.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
89 };
90
91 export const parseOwnershipId = (
92 resourceId: string | undefined,
93 ): { labels: Record<string, string> } => {
94 const value = resourceId ?? "";
95 if (!value.startsWith(OWNER_PREFIX)) return { labels: {} };
96 const parts = value.slice(OWNER_PREFIX.length).split("---");
97 if (parts.length < 3) return { labels: {} };
98 return {
99 labels: {
100 [alchemyLabelKeys.stack]: parts[0] ?? "",
101 [alchemyLabelKeys.stage]: parts[1] ?? "",
102 [alchemyLabelKeys.id]: parts[2] ?? "",
103 },
104 };
105 };
106
107 export const hasOwnershipMarker = (resourceId: string | undefined) =>
108 (resourceId ?? "").startsWith("alch-") &&
109 Object.keys(parseOwnershipId(resourceId).labels).some((key) => key.startsWith("alchemy-"));
110
111 const prefixMatch = (expected: string, observed: string) =>
112 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
113
114 export const ownedByAlchemy = (id: string, resourceId: string | undefined) =>
115 Effect.gen(function* () {
116 if (!hasOwnershipMarker(resourceId)) return false;
117 const expected = yield* createInternalLabels(id);
118 const { labels } = parseOwnershipId(resourceId);
119 const exact = yield* hasAlchemyLabels(id, labels);
120 if (exact) return true;
121 return (
122 prefixMatch(
123 sanitizeIdPart(expected[alchemyLabelKeys.stack] ?? ""),
124 labels[alchemyLabelKeys.stack] ?? "",
125 ) &&
126 prefixMatch(
127 sanitizeIdPart(expected[alchemyLabelKeys.stage] ?? ""),
128 labels[alchemyLabelKeys.stage] ?? "",
129 ) &&
130 prefixMatch(
131 sanitizeIdPart(expected[alchemyLabelKeys.id] ?? ""),
132 labels[alchemyLabelKeys.id] ?? "",
133 )
134 );
135 });
136
137 export const toResourceId = (id: string, requested: string | undefined, existing?: string) =>
138 Effect.gen(function* () {
139 const labels = yield* createInternalLabels(id);
140 if (requested !== undefined && requested.length > 0) {
141 if (requested.startsWith("alch-")) return ensureId(requested);
142 return encodeOwnershipId(labels, requested);
143 }
144 if (existing !== undefined && existing.length > 0) return existing;
145 const physical = yield* createPhysicalName({
146 id,
147 maxLength: 40,
148 lowercase: true,
149 });
150 return encodeOwnershipId(labels, physical);
151 });