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

main
ts 270 lines 9.68 KB
Raw
1 import * as retail from "@distilled.cloud/gcp/retail_v2";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Stream from "effect/Stream";
6
7 export const DEFAULT_LOCATION = "global";
8 export const DEFAULT_CATALOG = "default_catalog";
9 export const DEFAULT_BRANCH = "default_branch";
10 export const MAX_ID_LENGTH = 63;
11 export const MAX_MODEL_ID_LENGTH = 40;
12 export const MAX_PRODUCT_ID_LENGTH = 128;
13 export const MAX_DISPLAY_NAME_LENGTH = 128;
14 export const MAX_MODEL_DISPLAY_NAME_LENGTH = 1024;
15
16 export class RetailNotResolved extends Data.TaggedError("GCP.Retail.ResourceNotResolved")<{
17 resourceName: string;
18 }> {}
19
20 export const lastSegment = (value: string) => {
21 const trimmed = value.replace(/\/+$/, "");
22 const parts = trimmed.split("/");
23 return parts[parts.length - 1] || trimmed;
24 };
25
26 export const parentOf = (name: string, collection?: string) => {
27 if (collection !== undefined) {
28 const marker = `/${collection}/`;
29 const index = name.lastIndexOf(marker);
30 return index >= 0 ? name.slice(0, index) : name;
31 }
32 const parts = name.split("/").filter((part) => part.length > 0);
33 return parts.slice(0, -2).join("/");
34 };
35
36 export const normalizeLocation = (location: string | undefined) =>
37 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
38
39 export const normalizeCatalog = (catalog: string | undefined) =>
40 lastSegment(catalog ?? DEFAULT_CATALOG);
41
42 export const normalizeBranch = (branch: string | undefined) =>
43 lastSegment(branch ?? DEFAULT_BRANCH);
44
45 export const locationParent = (project: string, location: string) =>
46 `projects/${project}/locations/${location}`;
47
48 export const catalogName = (project: string, location: string, catalogId: string) =>
49 `${locationParent(project, location)}/catalogs/${catalogId}`;
50
51 export const expandCatalog = (value: string | undefined, project: string, location: string) => {
52 const raw = (value ?? DEFAULT_CATALOG).replace(/\/+$/, "");
53 if (raw.includes("/")) return raw;
54 return catalogName(project, location, raw);
55 };
56
57 export const branchName = (catalog: string, branchId: string) => `${catalog}/branches/${branchId}`;
58
59 export const parseResourceName = (name: string, collection: string) => {
60 const parts = name.split("/").filter((part) => part.length > 0);
61 const collectionAt = parts.lastIndexOf(collection);
62 const locationsAt = parts.lastIndexOf("locations");
63 const projectsAt = parts.lastIndexOf("projects");
64 const catalogsAt = parts.lastIndexOf("catalogs");
65 const branchesAt = parts.lastIndexOf("branches");
66 return {
67 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
68 location:
69 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
70 catalogId: catalogsAt >= 0 && parts[catalogsAt + 1] ? parts[catalogsAt + 1]! : DEFAULT_CATALOG,
71 catalog: catalogsAt >= 0 ? parts.slice(0, catalogsAt + 2).join("/") : parentOf(name),
72 branchId: branchesAt >= 0 && parts[branchesAt + 1] ? parts[branchesAt + 1]! : DEFAULT_BRANCH,
73 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
74 parent:
75 collectionAt > 0
76 ? parts.slice(0, collectionAt).join("/")
77 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
78 };
79 };
80
81 export const slugNoDigits = (name: string, maxLength: number, minLength = 4): string => {
82 let next = name
83 .toLowerCase()
84 .replace(/[0-9]/g, (digit) => "abcdefghij"[Number(digit)]!)
85 .replace(/[^a-z_-]/g, "-")
86 .replace(/-+/g, "-")
87 .replace(/^-+|-+$/g, "");
88 if (!/^[a-z]/.test(next)) next = `r${next}`;
89 next = next.slice(0, maxLength).replace(/[-_]+$/g, "");
90 if (next.length < minLength) next = `${next}xxxx`.slice(0, minLength);
91 return next.length > 0 ? next : "resource";
92 };
93
94 export const productIdOf = (name: string, maxLength = MAX_PRODUCT_ID_LENGTH) => {
95 let next = name
96 .toLowerCase()
97 .replace(/[^a-z0-9_-]/g, "-")
98 .replace(/-+/g, "-")
99 .replace(/^-+|-+$/g, "");
100 if (!/^[a-z]/.test(next)) next = `p${next}`;
101 next = next.slice(0, maxLength).replace(/[-_]+$/g, "");
102 return next.length > 0 ? next : "product";
103 };
104
105 export const toPhysical = (
106 id: string,
107 explicit: string | undefined,
108 existing: string | undefined,
109 format: (name: string) => string,
110 maxLength: number,
111 ) =>
112 Effect.gen(function* () {
113 if (explicit !== undefined) return explicit;
114 if (existing !== undefined) return existing;
115 return format(
116 yield* createPhysicalName({
117 id,
118 maxLength,
119 lowercase: true,
120 }),
121 );
122 });
123
124 export const canonical = (value: unknown): unknown => {
125 if (value === undefined || value === null) return undefined;
126 if (typeof value === "boolean" || typeof value === "number") return value;
127 if (typeof value === "string") {
128 return value.length === 0 ? undefined : value;
129 }
130 if (Array.isArray(value)) {
131 const items = value.map(canonical).filter((item) => item !== undefined);
132 return items.length === 0 ? undefined : items;
133 }
134 if (typeof value === "object") {
135 const entries = Object.entries(value as Record<string, unknown>)
136 .map(([key, item]) => [key, canonical(item)] as const)
137 .filter(([, item]) => item !== undefined)
138 .sort(([left], [right]) => left.localeCompare(right));
139 if (entries.length === 0) return undefined;
140 return Object.fromEntries(entries);
141 }
142 return undefined;
143 };
144
145 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
146
147 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
148
149 export const sameStringList = (
150 left: readonly string[] | undefined,
151 right: readonly string[] | undefined,
152 ) => fingerprint([...(left ?? [])].sort()) === fingerprint([...(right ?? [])].sort());
153
154 export const sameText = (left: string | undefined, right: string | undefined) =>
155 (left ?? "") === (right ?? "");
156
157 export const updateMaskOf = (...fields: Array<string | undefined>) =>
158 fields.filter((field): field is string => field !== undefined).join(",");
159
160 export const replaceOnIdentity = (input: {
161 previousId?: string;
162 nextId?: string;
163 previousParent?: string;
164 nextParent?: string;
165 }) => {
166 const idChanged =
167 input.previousId !== undefined &&
168 input.nextId !== undefined &&
169 input.previousId !== input.nextId;
170 const parentChanged =
171 (input.previousParent ?? "") !== "" &&
172 (input.nextParent ?? "") !== "" &&
173 (input.previousParent ?? "") !== (input.nextParent ?? "");
174 if (!idChanged && !parentChanged) return undefined;
175 return {
176 action: "replace" as const,
177 deleteFirst:
178 !parentChanged && input.previousId !== undefined && input.nextId === input.previousId,
179 };
180 };
181
182 const emptyList = <A>() => Effect.succeed<A[]>([]);
183
184 export const collectPages = <Page, Item, E, R>(
185 pages: Stream.Stream<Page, E, R>,
186 items: (page: Page) => readonly Item[] | null | undefined,
187 ) =>
188 pages.pipe(
189 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
190 Stream.runCollect,
191 Effect.map((chunk) => Array.from(chunk) as Item[]),
192 );
193
194 /** Locations `list` scans: `global`, the pre-`GCP.Region` default, and the stack region. */
195 export const listLocations = (region: string): string[] => [
196 ...new Set(["global", "us-central1", region]),
197 ];
198
199 export const listCatalogs = (project: string, location: string) =>
200 collectPages(
201 retail.listProjectsLocationsCatalogs.pages({
202 parent: locationParent(project, location),
203 pageSize: 100,
204 }),
205 (page) => page.catalogs,
206 ).pipe(Effect.catchTag("NotFound", () => emptyList<retail.GoogleCloudRetailV2Catalog>()));
207
208 export const listProjectCatalogs = (project: string, region: string) =>
209 Effect.forEach(listLocations(region), (location) => listCatalogs(project, location), {
210 concurrency: 2,
211 }).pipe(
212 Effect.map((groups) => {
213 const seen = new Set<string>();
214 const catalogs: retail.GoogleCloudRetailV2Catalog[] = [];
215 for (const catalog of groups.flat()) {
216 const name = catalog.name ?? "";
217 if (name.length === 0 || seen.has(name)) continue;
218 seen.add(name);
219 catalogs.push(catalog);
220 }
221 return catalogs;
222 }),
223 );
224
225 export const listControls = (parent: string) =>
226 parent.length === 0
227 ? emptyList<retail.GoogleCloudRetailV2Control>()
228 : collectPages(
229 retail.listProjectsLocationsCatalogsControls.pages({
230 parent,
231 pageSize: 100,
232 }),
233 (page) => page.controls,
234 ).pipe(Effect.catchTag("NotFound", () => emptyList<retail.GoogleCloudRetailV2Control>()));
235
236 export const listServingConfigs = (parent: string) =>
237 parent.length === 0
238 ? emptyList<retail.GoogleCloudRetailV2ServingConfig>()
239 : collectPages(
240 retail.listProjectsLocationsCatalogsServingConfigs.pages({
241 parent,
242 pageSize: 100,
243 }),
244 (page) => page.servingConfigs,
245 ).pipe(
246 Effect.catchTag("NotFound", () => emptyList<retail.GoogleCloudRetailV2ServingConfig>()),
247 );
248
249 export const listModels = (parent: string) =>
250 parent.length === 0
251 ? emptyList<retail.GoogleCloudRetailV2Model>()
252 : collectPages(
253 retail.listProjectsLocationsCatalogsModels.pages({
254 parent,
255 pageSize: 100,
256 }),
257 (page) => page.models,
258 ).pipe(Effect.catchTag("NotFound", () => emptyList<retail.GoogleCloudRetailV2Model>()));
259
260 export const listProducts = (parent: string) =>
261 parent.length === 0
262 ? emptyList<retail.GoogleCloudRetailV2Product>()
263 : collectPages(
264 retail.listProjectsLocationsCatalogsBranchesProducts.pages({
265 parent,
266 pageSize: 100,
267 readMask: "*",
268 }),
269 (page) => page.products,
270 ).pipe(Effect.catchTag("NotFound", () => emptyList<retail.GoogleCloudRetailV2Product>()));