@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 199 lines 6.49 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 MAX_CONTEXT_LENGTH,
11 ensureProject,
12 locationParent,
13 normalizeLocation,
14 parseName,
15 replaceOnIdentity,
16 rfc1035,
17 sameJson,
18 sameText,
19 toPhysicalId,
20 userSynonyms,
21 waitUntilExists,
22 waitUntilGone,
23 ResourceNotResolved,
24 } from "./internal.ts";
25
26 export type Synonym = cw.GoogleCloudContentwarehouseV1SynonymSetSynonym;
27
28 export type SynonymSetProps = {
29 /**
30 * Context id (the `{context}` segment of
31 * `projects/{project}/locations/{location}/synonymSets/{context}`).
32 * If omitted, a unique RFC1035 context is generated. Immutable —
33 * changing it replaces the synonym set.
34 */
35 context?: string;
36 /**
37 * Multi-region location (`us` or `eu`). Immutable — changing it
38 * replaces the synonym set. `US` is accepted and normalized to `us`.
39 * @default "us"
40 */
41 location?: string;
42 /**
43 * Groups of synonymous words.
44 */
45 synonyms?: Synonym[];
46 };
47
48 export type SynonymSet = Resource<
49 "GCP.ContentWarehouse.SynonymSet",
50 SynonymSetProps,
51 {
52 /** Full resource name. */
53 name: string;
54 /** Context id (last path segment). */
55 context: string;
56 /** Project id. */
57 project: string;
58 /** Location id. */
59 location: string;
60 /** Synonym groups. */
61 synonyms: Synonym[] | undefined;
62 },
63 never,
64 Providers
65 >;
66
67 const DEFAULT_SYNONYMS: Synonym[] = [{ words: ["sale", "invoice", "bill"] }];
68
69 /**
70 * A Document AI Warehouse synonym set — custom search synonyms for a
71 * query context (`sales`, `engineering`, …).
72 *
73 * Synonym sets have no labels field; Alchemy identifies one by its
74 * context. Without state, a set found under an explicit `context` is
75 * reported as unowned. Context and location are immutable. Synonym groups update in place.
76 *
77 * ### Creating a Synonym Set
78 * **Example:** Sales synonyms
79 * ```typescript
80 * const synonyms = yield* GCP.ContentWarehouse.SynonymSet("Sales", {
81 * context: "sales",
82 * synonyms: [{ words: ["sale", "invoice", "bill"] }],
83 * });
84 * ```
85 *
86 * @resource
87 * @category ContentWarehouse
88 */
89 export const SynonymSet = Resource<SynonymSet>("GCP.ContentWarehouse.SynonymSet");
90
91 const resourceName = (project: string, location: string, context: string) =>
92 `${locationParent(project, location)}/synonymSets/${context}`;
93
94 const contextOf = (id: string, explicit: string | undefined, existing: string | undefined) =>
95 Effect.gen(function* () {
96 if (explicit !== undefined) {
97 return rfc1035(explicit, "sales").slice(0, MAX_CONTEXT_LENGTH);
98 }
99 if (existing !== undefined) return existing;
100 return yield* toPhysicalId(id, undefined, undefined, "syn");
101 });
102
103 const toAttrs = (item: cw.GoogleCloudContentwarehouseV1SynonymSet, project: string) => {
104 const name = item.name ?? "";
105 const parsed = parseName(name, "synonymSets");
106 return {
107 name,
108 context: item.context ?? parsed.id,
109 project: parsed.project || project,
110 location: parsed.location,
111 synonyms: userSynonyms(item.synonyms),
112 };
113 };
114
115 const getByName = (name: string) =>
116 name.length === 0
117 ? Effect.undefined
118 : cw
119 .getProjectsLocationsSynonymSets({ name })
120 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
121
122 export const SynonymSetProvider = () =>
123 Provider.succeed(SynonymSet, {
124 stables: ["name", "context", "project", "location"],
125
126 diff: Effect.fn(function* ({ news, olds, output }) {
127 if (!isResolved(news)) return undefined;
128 return replaceOnIdentity({
129 previousId: olds?.context ?? output?.context,
130 nextId: news.context,
131 previousLocation: olds?.location ?? output?.location,
132 nextLocation: news.location ?? olds?.location ?? output?.location,
133 });
134 }),
135
136 read: Effect.fn(function* ({ id, olds, output }) {
137 const env = yield* GcpEnvironment.current;
138 const location = normalizeLocation(olds?.location ?? output?.location);
139 const context = yield* contextOf(id, olds?.context, output?.context);
140 const existing = yield* getByName(
141 output?.name ?? resourceName(env.project, location, context),
142 );
143 if (existing === undefined) return undefined;
144 const attrs = toAttrs(existing, env.project);
145 // State or the generated context proves ownership.
146 return output !== undefined || olds?.context === undefined ? attrs : Unowned(attrs);
147 }),
148
149 reconcile: Effect.fn(function* ({ id, news, output }) {
150 const env = yield* GcpEnvironment.current;
151 const location = normalizeLocation(news.location ?? output?.location);
152 const parent = locationParent(env.project, location);
153 yield* ensureProject(parent);
154 const context = yield* contextOf(id, news.context, output?.context);
155 const name = resourceName(env.project, location, context);
156 const synonyms = news.synonyms ?? DEFAULT_SYNONYMS;
157
158 let current = yield* getByName(output?.name ?? name);
159
160 if (current === undefined) {
161 const created = yield* cw
162 .createProjectsLocationsSynonymSets({
163 parent,
164 body: { context, synonyms },
165 })
166 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
167 current = created ?? (yield* waitUntilExists(getByName(name), name));
168 }
169
170 if (current === undefined) {
171 return yield* new ResourceNotResolved({ resourceName: name });
172 }
173
174 const currentName = current.name ?? name;
175 const contextChanged = !sameText(current.context, context);
176 // `current.synonyms` may still hold an ownership group written by an
177 // earlier version; comparing raw groups removes it on the next patch.
178 const synonymsChanged = !sameJson(current.synonyms ?? [], synonyms);
179 if (contextChanged || synonymsChanged) {
180 current = yield* cw.patchProjectsLocationsSynonymSets({
181 name: currentName,
182 body: {
183 name: currentName,
184 context,
185 synonyms,
186 },
187 });
188 }
189
190 return toAttrs(current, env.project);
191 }),
192
193 delete: Effect.fn(function* ({ output }) {
194 yield* cw
195 .deleteProjectsLocationsSynonymSets({ name: output.name })
196 .pipe(Effect.catchTag("NotFound", () => Effect.void));
197 yield* waitUntilGone(getByName(output.name), output.name);
198 }),
199 });