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

main
ts 192 lines 6.42 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import { tagRecord } from "alchemy/Tags";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import * as Stream from "effect/Stream";
7 import { stripInternalLabels } from "../Labels.ts";
8
9 export const MAX_NAME_LENGTH = 63;
10
11 export class ResourceNotResolved extends Data.TaggedError("GCP.SaasServiceManagement.NotResolved")<{
12 resourceName: string;
13 }> {}
14
15 export class ResourceStillExists extends Data.TaggedError("GCP.SaasServiceManagement.StillExists")<{
16 resourceName: string;
17 }> {}
18
19 export const lastSegment = (value: string) => {
20 const trimmed = value.replace(/\/+$/, "");
21 const parts = trimmed.split("/");
22 return parts[parts.length - 1] || trimmed;
23 };
24
25 export const rfc1035 = (name: string, fallback = "saas", maxLength = MAX_NAME_LENGTH): string => {
26 let next = name
27 .toLowerCase()
28 .replace(/[^a-z0-9-]/g, "-")
29 .replace(/-+/g, "-")
30 .replace(/^-+/, "")
31 .replace(/-+$/, "");
32 if (!/^[a-z]/.test(next)) {
33 next = `${fallback[0] ?? "s"}${next}`;
34 }
35 next = next.slice(0, maxLength).replace(/-+$/, "");
36 if (next.length === 0) return fallback;
37 if (!/[a-z0-9]$/.test(next)) {
38 next = `${next.slice(0, maxLength - 1)}0`;
39 }
40 return next.slice(0, maxLength);
41 };
42
43 export const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
44
45 export const parentOf = (project: string, location: string) =>
46 `projects/${project}/locations/${location}`;
47
48 export const resourceName = (project: string, location: string, collection: string, id: string) =>
49 `${parentOf(project, location)}/${collection}/${id}`;
50
51 export const parseName = (name: string, collection: string) => {
52 const parts = name.split("/").filter((part) => part.length > 0);
53 const collectionAt = parts.lastIndexOf(collection);
54 const locationsAt = parts.lastIndexOf("locations");
55 const projectsAt = parts.lastIndexOf("projects");
56 return {
57 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
58 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
59 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
60 };
61 };
62
63 export const toPhysicalId = (
64 id: string,
65 explicit: string | undefined,
66 existing: string | undefined,
67 fallback = "saas",
68 ) =>
69 Effect.gen(function* () {
70 if (explicit !== undefined) return rfc1035(explicit, fallback);
71 if (existing !== undefined) return existing;
72 return rfc1035(
73 yield* createPhysicalName({
74 id,
75 maxLength: MAX_NAME_LENGTH,
76 lowercase: true,
77 }),
78 fallback,
79 );
80 });
81
82 export const expandName = (
83 value: string,
84 project: string,
85 location: string,
86 collection: string,
87 ) => {
88 const trimmed = value.replace(/\/+$/, "");
89 if (trimmed.includes("/")) return trimmed;
90 return resourceName(project, location, collection, trimmed);
91 };
92
93 export const userLabels = (
94 labels: Record<string, string | undefined> | null | undefined,
95 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
96
97 export const userAnnotations = (
98 annotations: Record<string, string | undefined> | null | undefined,
99 ): Record<string, string> =>
100 Object.fromEntries(
101 Object.entries(annotations ?? {}).filter(
102 (entry): entry is [string, string] => entry[1] !== undefined && entry[1].length > 0,
103 ),
104 );
105
106 export const hasAlchemyLabelKeys = (
107 labels: Record<string, string | undefined> | null | undefined,
108 ) => Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
109
110 export const canonical = (value: unknown): unknown => {
111 if (value === undefined || value === null) return undefined;
112 if (typeof value === "boolean" || typeof value === "number") return value;
113 if (typeof value === "string") {
114 return value.length === 0 ? undefined : value;
115 }
116 if (Array.isArray(value)) {
117 const items = value.map(canonical).filter((item) => item !== undefined);
118 return items.length === 0 ? undefined : items;
119 }
120 if (typeof value === "object") {
121 const entries = Object.entries(value as Record<string, unknown>)
122 .map(([key, item]) => [key, canonical(item)] as const)
123 .filter(([, item]) => item !== undefined)
124 .sort(([left], [right]) => left.localeCompare(right));
125 if (entries.length === 0) return undefined;
126 return Object.fromEntries(entries);
127 }
128 return undefined;
129 };
130
131 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
132
133 export const fieldMask = (fields: Array<string | false | undefined>) =>
134 fields.filter((field): field is string => typeof field === "string").join(",");
135
136 export const sameRef = (left: string | undefined, right: string | undefined) =>
137 lastSegment(left ?? "") === lastSegment(right ?? "");
138
139 export const replaceOnIdentity = (input: {
140 previousId: string | undefined;
141 nextId: string | undefined;
142 previousLocation: string;
143 nextLocation: string;
144 extra?: boolean;
145 }) => {
146 const replace =
147 (input.extra ?? false) ||
148 (input.previousId !== undefined &&
149 input.nextId !== undefined &&
150 input.nextId !== input.previousId) ||
151 input.previousLocation !== input.nextLocation;
152 if (!replace) return undefined;
153 const samePhysical =
154 input.previousLocation === input.nextLocation &&
155 input.previousId !== undefined &&
156 input.nextId === input.previousId;
157 return {
158 action: "replace" as const,
159 deleteFirst: samePhysical,
160 };
161 };
162
163 export const waitUntilGone = <A, E extends { readonly _tag: string }, R>(
164 get: Effect.Effect<A | undefined, E, R>,
165 name: string,
166 ): Effect.Effect<void, E | ResourceStillExists, R> =>
167 get.pipe(
168 Effect.filterOrFail(
169 (value) => value === undefined,
170 () => new ResourceStillExists({ resourceName: name }),
171 ),
172 Effect.retry({
173 while: (error) => error._tag === "GCP.SaasServiceManagement.StillExists",
174 times: 10,
175 schedule: Schedule.spaced("2 seconds"),
176 }),
177 Effect.asVoid,
178 );
179
180 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
181 stream: Stream.Stream<Page, E, R>,
182 pick: (page: Page) => readonly Item[] | undefined,
183 ) =>
184 stream.pipe(
185 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
186 Stream.runCollect,
187 Effect.map((chunk) => Array.from(chunk)),
188 Effect.catchIf(
189 (error): error is Extract<E, { readonly _tag: "NotFound" }> => error._tag === "NotFound",
190 () => Effect.succeed([] as Item[]),
191 ),
192 );