@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 339 lines 11.5 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 type { Providers } from "../Providers.ts";
9 import {
10 ensureProject,
11 lastSegment,
12 locationParent,
13 normalizeLocation,
14 parseName,
15 replaceOnIdentity,
16 sameJson,
17 sameText,
18 toPhysicalId,
19 waitUntilExists,
20 waitUntilGone,
21 ResourceNotResolved,
22 } from "./internal.ts";
23
24 export type DocumentProperty = cw.GoogleCloudContentwarehouseV1Property;
25
26 export type DocumentProps = {
27 /**
28 * Document id (the `{document}` segment of
29 * `projects/{project}/locations/{location}/documents/{document}`).
30 * Assigned by the API on create. Immutable — changing it replaces the
31 * document. Supply it to adopt an existing document.
32 */
33 documentId?: string;
34 /**
35 * Customer-assigned reference id, unique per project and location.
36 * If omitted, a unique id is generated and used for lookup.
37 * Immutable — changing it replaces the document.
38 */
39 referenceId?: string;
40 /**
41 * Multi-region location (`us` or `eu`). Immutable — changing it
42 * replaces the document. `US` is accepted and normalized to `us`.
43 * @default "us"
44 */
45 location?: string;
46 /**
47 * Parent document schema resource name
48 * `projects/{project}/locations/{location}/documentSchemas/{schema}`.
49 * Immutable — changing it replaces the document.
50 */
51 documentSchemaName: string;
52 /**
53 * Display name shown in the UI.
54 * @default the document's `referenceId`
55 */
56 displayName?: string;
57 /**
58 * Title describing the document.
59 */
60 title?: string;
61 /**
62 * Inline plain-text content.
63 */
64 plainText?: string;
65 /**
66 * Cloud Storage path of the raw document (`gs://bucket/object`).
67 */
68 rawDocumentPath?: string;
69 /**
70 * URI used to display the document.
71 */
72 displayUri?: string;
73 /**
74 * Category of the original content (`CONTENT_CATEGORY_IMAGE`, …).
75 */
76 contentCategory?: string;
77 /**
78 * When true, skip text extraction on create.
79 * @default true
80 */
81 textExtractionDisabled?: boolean;
82 /**
83 * User-supplied metadata properties matching the schema.
84 */
85 properties?: DocumentProperty[];
86 };
87
88 export type Document = Resource<
89 "GCP.ContentWarehouse.Document",
90 DocumentProps,
91 {
92 /** Full resource name. */
93 name: string;
94 /** Document id (last path segment). */
95 documentId: string;
96 /** Customer-assigned reference id. */
97 referenceId: string | undefined;
98 /** Project id. */
99 project: string;
100 /** Location id. */
101 location: string;
102 /** Parent document schema resource name. */
103 documentSchemaName: string | undefined;
104 /** Display name. */
105 displayName: string | undefined;
106 /** Title. */
107 title: string | undefined;
108 /** Inline plain-text content. */
109 plainText: string | undefined;
110 /** Cloud Storage path of the raw document. */
111 rawDocumentPath: string | undefined;
112 /** Display URI. */
113 displayUri: string | undefined;
114 /** Content category. */
115 contentCategory: string | undefined;
116 /** User-supplied metadata properties. */
117 properties: DocumentProperty[] | undefined;
118 /** Creator. */
119 creator: string | undefined;
120 /** RFC3339 creation timestamp. */
121 createTime: string | undefined;
122 /** RFC3339 last-update timestamp. */
123 updateTime: string | undefined;
124 },
125 never,
126 Providers
127 >;
128
129 /**
130 * A Document AI Warehouse document — structured content plus metadata
131 * that conforms to a {@link DocumentSchema}.
132 *
133 * Documents have no labels field, so Alchemy identifies a document by its
134 * `referenceId`: one found under the generated id is adopted, one found
135 * under an explicit `referenceId` without state is reported as unowned.
136 * Location, schema, and
137 * reference id are immutable. Display name, title, and plain text update
138 * in place.
139 *
140 * ### Creating a Document
141 * **Example:** Plain-text document
142 * ```typescript
143 * const schema = yield* GCP.ContentWarehouse.DocumentSchema("Note", {});
144 * const document = yield* GCP.ContentWarehouse.Document("Welcome", {
145 * documentSchemaName: schema.name,
146 * displayName: "welcome",
147 * plainText: "hello warehouse",
148 * });
149 * ```
150 *
151 * @resource
152 * @category ContentWarehouse
153 */
154 export const Document = Resource<Document>("GCP.ContentWarehouse.Document");
155
156 const resourceName = (project: string, location: string, documentId: string) =>
157 `${locationParent(project, location)}/documents/${documentId}`;
158
159 const referenceName = (project: string, location: string, referenceId: string) =>
160 `${locationParent(project, location)}/documents/referenceId/${referenceId}`;
161
162 const toAttrs = (item: cw.GoogleCloudContentwarehouseV1Document, project: string) => {
163 const name = item.name ?? "";
164 const parsed = parseName(name, "documents");
165 const id = parsed.id === "referenceId" ? lastSegment(name) : parsed.id;
166 return {
167 name,
168 documentId: id,
169 referenceId: item.referenceId,
170 project: parsed.project || project,
171 location: parsed.location,
172 documentSchemaName: item.documentSchemaName,
173 displayName: item.displayName,
174 title: item.title,
175 plainText: item.plainText,
176 rawDocumentPath: item.rawDocumentPath,
177 displayUri: item.displayUri,
178 contentCategory: item.contentCategory,
179 properties: item.properties,
180 creator: item.creator,
181 createTime: item.createTime,
182 updateTime: item.updateTime,
183 };
184 };
185
186 const getByName = (name: string) =>
187 name.length === 0
188 ? Effect.undefined
189 : cw
190 .getProjectsLocationsDocuments({ name })
191 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
192
193 export const DocumentProvider = () =>
194 Provider.succeed(Document, {
195 stables: ["name", "documentId", "referenceId", "project", "location", "createTime"],
196
197 diff: Effect.fn(function* ({ news, olds, output }) {
198 if (!isResolved(news)) return undefined;
199 const schemaChanged =
200 (olds?.documentSchemaName ?? output?.documentSchemaName) !== undefined &&
201 news.documentSchemaName !== (olds?.documentSchemaName ?? output?.documentSchemaName);
202 return replaceOnIdentity({
203 previousId: olds?.referenceId ?? output?.referenceId,
204 nextId: news.referenceId,
205 previousLocation: olds?.location ?? output?.location,
206 nextLocation: news.location ?? olds?.location ?? output?.location,
207 extra: schemaChanged,
208 });
209 }),
210
211 read: Effect.fn(function* ({ id, olds, output }) {
212 const env = yield* GcpEnvironment.current;
213 const location = normalizeLocation(olds?.location ?? output?.location);
214 const documentId = olds?.documentId ?? output?.documentId;
215 const referenceId = olds?.referenceId ?? output?.referenceId;
216 const name =
217 output?.name ??
218 (documentId
219 ? resourceName(env.project, location, documentId)
220 : referenceId
221 ? referenceName(env.project, location, referenceId)
222 : "");
223 let existing = yield* getByName(name);
224 if (existing === undefined && referenceId) {
225 existing = yield* getByName(referenceName(env.project, location, referenceId));
226 }
227 if (existing === undefined && output === undefined) {
228 // No labels: a document is identified by its reference id.
229 const generated = yield* toPhysicalId(id, undefined, undefined, "doc");
230 existing = yield* getByName(referenceName(env.project, location, referenceId ?? generated));
231 if (existing === undefined) return undefined;
232 const attrs = toAttrs(existing, env.project);
233 return referenceId === undefined ? attrs : Unowned(attrs);
234 }
235 if (existing === undefined) return undefined;
236 return toAttrs(existing, env.project);
237 }),
238
239 reconcile: Effect.fn(function* ({ id, news, output }) {
240 const env = yield* GcpEnvironment.current;
241 const location = normalizeLocation(news.location ?? output?.location);
242 const parent = locationParent(env.project, location);
243 yield* ensureProject(parent);
244 const referenceId = yield* toPhysicalId(id, news.referenceId, output?.referenceId, "doc");
245 const displayName = news.displayName ?? referenceId;
246 const title = news.title ?? news.displayName ?? referenceId;
247 const textExtractionDisabled = news.textExtractionDisabled ?? true;
248 const lookup = output?.name ?? referenceName(env.project, location, referenceId);
249
250 let current = yield* getByName(lookup);
251 if (current === undefined) {
252 current = yield* getByName(referenceName(env.project, location, referenceId));
253 }
254
255 if (current === undefined) {
256 const created = yield* cw
257 .createProjectsLocationsDocuments({
258 parent,
259 body: {
260 document: {
261 displayName,
262 title,
263 plainText: news.plainText ?? title,
264 documentSchemaName: news.documentSchemaName,
265 referenceId,
266 rawDocumentPath: news.rawDocumentPath,
267 displayUri: news.displayUri,
268 contentCategory: news.contentCategory,
269 textExtractionDisabled,
270 properties: news.properties,
271 },
272 },
273 })
274 .pipe(
275 Effect.map((response) => response.document),
276 Effect.catchTag("Conflict", () =>
277 getByName(referenceName(env.project, location, referenceId)),
278 ),
279 );
280 current =
281 created ??
282 (yield* waitUntilExists(
283 getByName(referenceName(env.project, location, referenceId)),
284 referenceName(env.project, location, referenceId),
285 ));
286 }
287
288 if (current === undefined) {
289 return yield* new ResourceNotResolved({ resourceName: lookup });
290 }
291
292 const currentName = current.name ?? lookup;
293 const displayChanged = !sameText(current.displayName, displayName);
294 const titleChanged = !sameText(current.title, title);
295 const textChanged = !sameText(current.plainText, news.plainText ?? title);
296 const uriChanged = !sameText(current.displayUri, news.displayUri);
297 const pathChanged = !sameText(current.rawDocumentPath, news.rawDocumentPath);
298 const propertiesChanged = !sameJson(current.properties, news.properties);
299 if (
300 displayChanged ||
301 titleChanged ||
302 textChanged ||
303 uriChanged ||
304 pathChanged ||
305 propertiesChanged
306 ) {
307 const updated = yield* cw.patchProjectsLocationsDocuments({
308 name: currentName,
309 body: {
310 document: {
311 name: currentName,
312 displayName,
313 title,
314 plainText: news.plainText ?? title,
315 documentSchemaName: news.documentSchemaName,
316 referenceId,
317 rawDocumentPath: news.rawDocumentPath,
318 displayUri: news.displayUri,
319 contentCategory: news.contentCategory,
320 properties: news.properties,
321 },
322 updateOptions: {
323 updateType: "UPDATE_TYPE_REPLACE",
324 },
325 },
326 });
327 current = updated.document ?? current;
328 }
329
330 return toAttrs(current, env.project);
331 }),
332
333 delete: Effect.fn(function* ({ output }) {
334 yield* cw
335 .deleteProjectsLocationsDocuments({ name: output.name })
336 .pipe(Effect.catchTag("NotFound", () => Effect.void));
337 yield* waitUntilGone(getByName(output.name), output.name);
338 }),
339 });