@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 281 lines 9.5 KB
Raw
1 import * as apihub from "@distilled.cloud/gcp/apihub_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 ApihubNotResolved,
11 createOwnership,
12 encodeOwnership,
13 hasOwnershipMarker,
14 listCurations,
15 locationParent,
16 normalizeLocation,
17 ownedByAlchemy,
18 parseOwnership,
19 parseResourceName,
20 replaceOnIdentity,
21 sameJson,
22 sameText,
23 toPhysicalId,
24 updateMaskOf,
25 } from "./internal.ts";
26
27 export type ApplicationIntegrationEndpoint = {
28 /**
29 * REST URI that triggers an Application Integration workflow.
30 * Format:
31 * `https://integrations.googleapis.com/v1/projects/{project}/locations/{location}/integrations/{integration}:execute`
32 */
33 uri: string;
34 /** API trigger id of the Application Integration workflow. */
35 triggerId: string;
36 };
37
38 export type CurationEndpoint = {
39 /** Application Integration endpoint invoked for curation. */
40 applicationIntegrationEndpointDetails: ApplicationIntegrationEndpoint;
41 };
42
43 export type CurationProps = {
44 /**
45 * Curation id (the `{curation}` segment of
46 * `projects/{project}/locations/{location}/curations/{curation}`). If
47 * omitted, a unique id is generated. Immutable — changing it replaces
48 * the curation.
49 */
50 curationId?: string;
51 /**
52 * Location (`us-central1`, …). Immutable — changing it replaces the
53 * curation.
54 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
55 */
56 location?: string;
57 /**
58 * Display name. Defaults to the curation id.
59 */
60 displayName?: string;
61 /**
62 * Human-readable description. Curations have no labels field, so Alchemy
63 * stamps ownership into a `[alchemy …]` prefix and strips it from
64 * attributes.
65 */
66 description?: string;
67 /**
68 * Endpoint invoked with API metadata. Immutable — changing it replaces
69 * the curation.
70 */
71 endpoint: CurationEndpoint;
72 };
73
74 export type Curation = Resource<
75 "GCP.ApiHub.Curation",
76 CurationProps,
77 {
78 /** Full resource name. */
79 name: string;
80 /** Curation id (last path segment). */
81 curationId: string;
82 /** Project id. */
83 project: string;
84 /** Location id. */
85 location: string;
86 /** Display name. */
87 displayName: string | undefined;
88 /** User description with the Alchemy ownership prefix stripped. */
89 description: string | undefined;
90 /** Endpoint. */
91 endpoint: CurationEndpoint | undefined;
92 /** Plugin instances using this curation. */
93 pluginInstanceActions: apihub.GoogleCloudApihubV1PluginInstanceActionID[];
94 /** Last execution state. */
95 lastExecutionState: string | undefined;
96 /** Last execution error code. */
97 lastExecutionErrorCode: string | undefined;
98 /** Last execution error message. */
99 lastExecutionErrorMessage: string | undefined;
100 /** RFC3339 creation timestamp. */
101 createTime: string | undefined;
102 /** RFC3339 last-update timestamp. */
103 updateTime: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A curation resource in API Hub. Plugin instances invoke the endpoint
111 * with API metadata and receive curated metadata back.
112 *
113 * Location, id, and endpoint are immutable. Display name and description
114 * update in place. Curations have no labels field — Alchemy stamps
115 * ownership into the description.
116 *
117 * ### Creating a Curation
118 * **Example:** Application Integration endpoint
119 * ```typescript
120 * const curation = yield* GCP.ApiHub.Curation("Curate", {
121 * displayName: "curate-apis",
122 * endpoint: {
123 * applicationIntegrationEndpointDetails: {
124 * uri: "https://integrations.googleapis.com/v1/projects/my-project/locations/us-central1/integrations/curate:execute",
125 * triggerId: "api_trigger/curate",
126 * },
127 * },
128 * });
129 * ```
130 *
131 * @resource
132 * @category ApiHub
133 */
134 export const Curation = Resource<Curation>("GCP.ApiHub.Curation");
135
136 const resourceName = (project: string, location: string, curationId: string) =>
137 `${locationParent(project, location)}/curations/${curationId}`;
138
139 const toEndpoint = (
140 endpoint: apihub.GoogleCloudApihubV1Endpoint | undefined,
141 ): CurationEndpoint | undefined => {
142 const details = endpoint?.applicationIntegrationEndpointDetails;
143 if (details?.uri === undefined || details.triggerId === undefined) {
144 return undefined;
145 }
146 return {
147 applicationIntegrationEndpointDetails: {
148 uri: details.uri,
149 triggerId: details.triggerId,
150 },
151 };
152 };
153
154 const toAttrs = (curation: apihub.GoogleCloudApihubV1Curation, project: string, region: string) => {
155 const name = curation.name ?? "";
156 const parsed = parseResourceName(name, "curations", region);
157 return {
158 name,
159 curationId: parsed.id,
160 project: parsed.project || project,
161 location: parsed.location,
162 displayName: curation.displayName,
163 description: parseOwnership(curation.description).text,
164 endpoint: toEndpoint(curation.endpoint),
165 pluginInstanceActions: curation.pluginInstanceActions ?? [],
166 lastExecutionState: curation.lastExecutionState,
167 lastExecutionErrorCode: curation.lastExecutionErrorCode,
168 lastExecutionErrorMessage: curation.lastExecutionErrorMessage,
169 createTime: curation.createTime,
170 updateTime: curation.updateTime,
171 };
172 };
173
174 const getByName = (name: string) =>
175 name.length === 0
176 ? Effect.undefined
177 : apihub
178 .getProjectsLocationsCurations({ name })
179 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
180
181 export const CurationProvider = () =>
182 Provider.succeed(Curation, {
183 stables: ["name", "curationId", "project", "location", "createTime"],
184
185 diff: Effect.fn(function* ({ news, olds, output }) {
186 if (!isResolved(news)) return undefined;
187 const env = yield* GcpEnvironment.current;
188 return replaceOnIdentity({
189 previousId: olds?.curationId ?? output?.curationId,
190 nextId: news.curationId ?? olds?.curationId ?? output?.curationId,
191 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
192 nextLocation: normalizeLocation(
193 news.location ?? olds?.location ?? output?.location,
194 env.region,
195 ),
196 extra: !sameJson(news.endpoint ?? olds?.endpoint, olds?.endpoint ?? output?.endpoint),
197 });
198 }),
199
200 read: Effect.fn(function* ({ id, olds, output }) {
201 const env = yield* GcpEnvironment.current;
202 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
203 const curationId = yield* toPhysicalId(id, olds?.curationId, output?.curationId);
204 const name = output?.name ?? resourceName(env.project, location, curationId);
205 const existing = yield* getByName(name);
206 if (existing === undefined) return undefined;
207 const attrs = toAttrs(existing, env.project, env.region);
208 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
209 }),
210
211 list: () =>
212 Effect.gen(function* () {
213 const env = yield* GcpEnvironment.current;
214 const items = yield* listCurations(locationParent(env.project, env.region));
215 return items
216 .filter((item) => hasOwnershipMarker(item.description))
217 .map((item) => toAttrs(item, env.project, env.region));
218 }),
219
220 reconcile: Effect.fn(function* ({ id, news, output }) {
221 const env = yield* GcpEnvironment.current;
222 const location = normalizeLocation(news.location ?? output?.location, env.region);
223 const parent = locationParent(env.project, location);
224 const curationId = yield* toPhysicalId(id, news.curationId, output?.curationId);
225 const name = output?.name ?? resourceName(env.project, location, curationId);
226 const ownership = yield* createOwnership(id);
227 const description = encodeOwnership(ownership, news.description);
228 const displayName = news.displayName ?? curationId;
229 const endpoint: apihub.GoogleCloudApihubV1Endpoint = {
230 applicationIntegrationEndpointDetails: news.endpoint.applicationIntegrationEndpointDetails,
231 };
232
233 let current = yield* getByName(name);
234
235 if (current === undefined) {
236 const created = yield* apihub
237 .createProjectsLocationsCurations({
238 parent,
239 curationId,
240 body: {
241 displayName,
242 description,
243 endpoint,
244 },
245 })
246 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
247 current = created ?? undefined;
248 }
249
250 if (current === undefined) {
251 return yield* new ApihubNotResolved({ resourceName: name });
252 }
253
254 const currentName = current.name ?? name;
255 const displayChanged = !sameText(current.displayName, displayName);
256 const descriptionChanged = !sameText(current.description, description);
257
258 if (displayChanged || descriptionChanged) {
259 current = yield* apihub.patchProjectsLocationsCurations({
260 name: currentName,
261 updateMask: updateMaskOf(
262 displayChanged ? "display_name" : undefined,
263 descriptionChanged ? "description" : undefined,
264 ),
265 body: {
266 name: currentName,
267 displayName,
268 description,
269 },
270 });
271 }
272
273 return toAttrs(current, env.project, env.region);
274 }),
275
276 delete: Effect.fn(function* ({ output }) {
277 yield* apihub
278 .deleteProjectsLocationsCurations({ name: output.name })
279 .pipe(Effect.catchTag("NotFound", () => Effect.void));
280 }),
281 });