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

main
ts 297 lines 10.1 KB
Raw
1 import * as cw from "@distilled.cloud/gcp/contentwarehouse_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import { createInternalLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 LIST_LOCATIONS,
12 appendProperties,
13 collectPages,
14 defaultTextProperty,
15 encodeOwnership,
16 ensureProject,
17 hasOwnershipMarker,
18 ignoreList,
19 lastSegment,
20 locationParent,
21 normalizeLocation,
22 ownedByAlchemy,
23 parseName,
24 parseOwnership,
25 replaceOnIdentity,
26 sameText,
27 toPhysicalId,
28 waitUntilExists,
29 waitUntilGone,
30 ResourceNotResolved,
31 } from "./internal.ts";
32
33 export type PropertyDefinition = cw.GoogleCloudContentwarehouseV1PropertyDefinition;
34
35 export type DocumentSchemaProps = {
36 /**
37 * Document schema id (the `{documentSchema}` segment of
38 * `projects/{project}/locations/{location}/documentSchemas/{documentSchema}`).
39 * Assigned by the API on create. Immutable — changing it replaces the
40 * schema. Supply it to adopt an existing schema.
41 */
42 documentSchemaId?: string;
43 /**
44 * Multi-region location (`us` or `eu`). Immutable — changing it
45 * replaces the schema. `US` is accepted and normalized to `us`.
46 * @default "us"
47 */
48 location?: string;
49 /**
50 * Unique display name within the project. Defaults to a generated id.
51 */
52 displayName?: string;
53 /**
54 * Schema description. Document schemas have no labels field, so Alchemy
55 * stamps ownership into a `[alchemy …]` prefix and strips it from
56 * attributes.
57 */
58 description?: string;
59 /**
60 * When true the schema describes a folder rather than a document.
61 * @default false
62 */
63 documentIsFolder?: boolean;
64 /**
65 * Property definitions. Updates may only append new properties — existing
66 * definitions cannot be mutated in place.
67 */
68 propertyDefinitions?: PropertyDefinition[];
69 };
70
71 export type DocumentSchema = Resource<
72 "GCP.ContentWarehouse.DocumentSchema",
73 DocumentSchemaProps,
74 {
75 /** Full resource name. */
76 name: string;
77 /** Document schema id (last path segment). */
78 documentSchemaId: string;
79 /** Project id. */
80 project: string;
81 /** Location id. */
82 location: string;
83 /** Display name. */
84 displayName: string | undefined;
85 /** User description with the Alchemy ownership prefix stripped. */
86 description: string | undefined;
87 /** Whether this schema describes a folder. */
88 documentIsFolder: boolean;
89 /** Property definitions. */
90 propertyDefinitions: PropertyDefinition[] | undefined;
91 /** RFC3339 creation timestamp. */
92 createTime: string | undefined;
93 /** RFC3339 last-update timestamp. */
94 updateTime: string | undefined;
95 },
96 never,
97 Providers
98 >;
99
100 /**
101 * A Document AI Warehouse document schema describing document structure.
102 *
103 * Schemas have no labels field — Alchemy stamps ownership into the
104 * description so `list` / nuke can find them. Location is immutable.
105 * Description and newly appended properties update in place; existing
106 * property definitions cannot be rewritten.
107 *
108 * The project must be initialized for Document AI Warehouse in `us` or
109 * `eu` before schemas can be created.
110 *
111 * ### Creating a Document Schema
112 * **Example:** Text document schema
113 * ```typescript
114 * const schema = yield* GCP.ContentWarehouse.DocumentSchema("Invoice", {
115 * displayName: "invoice",
116 * propertyDefinitions: [
117 * { name: "title", isSearchable: true, textTypeOptions: {} },
118 * ],
119 * });
120 * ```
121 *
122 * @resource
123 * @category ContentWarehouse
124 */
125 export const DocumentSchema = Resource<DocumentSchema>("GCP.ContentWarehouse.DocumentSchema");
126
127 const resourceName = (project: string, location: string, documentSchemaId: string) =>
128 `${locationParent(project, location)}/documentSchemas/${documentSchemaId}`;
129
130 const toAttrs = (item: cw.GoogleCloudContentwarehouseV1DocumentSchema, project: string) => {
131 const name = item.name ?? "";
132 const parsed = parseName(name, "documentSchemas");
133 return {
134 name,
135 documentSchemaId: parsed.id,
136 project: parsed.project || project,
137 location: parsed.location,
138 displayName: item.displayName,
139 description: parseOwnership(item.description).text,
140 documentIsFolder: item.documentIsFolder === true,
141 propertyDefinitions: item.propertyDefinitions,
142 createTime: item.createTime,
143 updateTime: item.updateTime,
144 };
145 };
146
147 const getByName = (name: string) =>
148 name.length === 0
149 ? Effect.undefined
150 : cw
151 .getProjectsLocationsDocumentSchemas({ name })
152 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
153
154 const listAt = (parent: string) =>
155 collectPages(
156 cw.listProjectsLocationsDocumentSchemas.pages({
157 parent,
158 pageSize: 1000,
159 }),
160 (page) => page.documentSchemas,
161 ).pipe(ignoreList([] as cw.GoogleCloudContentwarehouseV1DocumentSchema[]));
162
163 const findOwned = (id: string, items: readonly cw.GoogleCloudContentwarehouseV1DocumentSchema[]) =>
164 Effect.gen(function* () {
165 for (const item of items) {
166 if (yield* ownedByAlchemy(id, item.description)) return item;
167 }
168 return undefined as cw.GoogleCloudContentwarehouseV1DocumentSchema | undefined;
169 });
170
171 const listOwned = (project: string) =>
172 Effect.forEach(LIST_LOCATIONS, (location) => listAt(locationParent(project, location)), {
173 concurrency: 2,
174 }).pipe(
175 Effect.map((groups) => groups.flat().filter((item) => hasOwnershipMarker(item.description))),
176 );
177
178 export const DocumentSchemaProvider = () =>
179 Provider.succeed(DocumentSchema, {
180 stables: ["name", "documentSchemaId", "project", "location", "createTime"],
181
182 diff: Effect.fn(function* ({ news, olds, output }) {
183 if (!isResolved(news)) return undefined;
184 const folderChanged =
185 (olds?.documentIsFolder ?? output?.documentIsFolder ?? false) !==
186 (news.documentIsFolder ?? false);
187 return replaceOnIdentity({
188 previousId: olds?.documentSchemaId ?? output?.documentSchemaId,
189 nextId: news.documentSchemaId,
190 previousLocation: olds?.location ?? output?.location,
191 nextLocation: news.location ?? olds?.location ?? output?.location,
192 extra: folderChanged,
193 });
194 }),
195
196 read: Effect.fn(function* ({ id, olds, output }) {
197 const env = yield* GcpEnvironment.current;
198 const location = normalizeLocation(olds?.location ?? output?.location);
199 const documentSchemaId = olds?.documentSchemaId ?? output?.documentSchemaId;
200 const name =
201 output?.name ??
202 (documentSchemaId ? resourceName(env.project, location, documentSchemaId) : "");
203 let existing = yield* getByName(name);
204 if (existing === undefined) {
205 const listed = yield* listAt(locationParent(env.project, location));
206 existing = yield* findOwned(id, listed);
207 }
208 if (existing === undefined) return undefined;
209 const attrs = toAttrs(existing, env.project);
210 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
211 }),
212
213 list: () =>
214 Effect.gen(function* () {
215 const env = yield* GcpEnvironment.current;
216 const items = yield* listOwned(env.project);
217 return items.map((item) => toAttrs(item, env.project));
218 }),
219
220 reconcile: Effect.fn(function* ({ id, news, output }) {
221 const env = yield* GcpEnvironment.current;
222 const location = normalizeLocation(news.location ?? output?.location);
223 const parent = locationParent(env.project, location);
224 yield* ensureProject(parent);
225 const documentSchemaId = yield* toPhysicalId(
226 id,
227 news.documentSchemaId,
228 output?.documentSchemaId,
229 "schema",
230 );
231 const ownership = yield* createInternalLabels(id);
232 const description = encodeOwnership(ownership, news.description);
233 const displayName = news.displayName ?? documentSchemaId;
234 const propertyDefinitions = news.propertyDefinitions ?? [defaultTextProperty()];
235 const documentIsFolder = news.documentIsFolder === true;
236
237 const findInParent = listAt(parent).pipe(Effect.flatMap((items) => findOwned(id, items)));
238 let current = (yield* getByName(output?.name ?? "")) ?? (yield* findInParent);
239
240 if (current === undefined) {
241 const created = yield* cw
242 .createProjectsLocationsDocumentSchemas({
243 parent,
244 body: {
245 displayName,
246 description,
247 documentIsFolder,
248 propertyDefinitions,
249 },
250 })
251 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
252 current = created ?? (yield* findInParent);
253 if (current === undefined) {
254 current = yield* waitUntilExists(
255 Effect.flatMap(listAt(parent), (items) => findOwned(id, items)),
256 `${parent}/documentSchemas/${documentSchemaId}`,
257 );
258 }
259 }
260
261 if (current === undefined) {
262 return yield* new ResourceNotResolved({
263 resourceName: output?.name ?? resourceName(env.project, location, documentSchemaId),
264 });
265 }
266
267 const currentName = current.name ?? "";
268 const appended = appendProperties(current.propertyDefinitions, propertyDefinitions);
269 const descriptionChanged = !sameText(current.description, description);
270 const displayChanged = !sameText(current.displayName, displayName);
271 if (descriptionChanged || displayChanged || appended.appended) {
272 current = yield* cw.patchProjectsLocationsDocumentSchemas({
273 name: currentName,
274 body: {
275 documentSchema: {
276 name: currentName,
277 displayName,
278 description,
279 documentIsFolder,
280 propertyDefinitions: appended.properties,
281 },
282 },
283 });
284 }
285
286 return toAttrs(current, env.project);
287 }),
288
289 delete: Effect.fn(function* ({ output }) {
290 yield* cw
291 .deleteProjectsLocationsDocumentSchemas({ name: output.name })
292 .pipe(Effect.catchTag("NotFound", () => Effect.void));
293 yield* waitUntilGone(getByName(output.name), output.name);
294 }),
295 });
296
297 export const documentSchemaIdOf = lastSegment;