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

main
ts 331 lines 10.9 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 type AttributeValuesMap,
12 type Documentation,
13 createOwnership,
14 encodeOwnership,
15 hasOwnershipMarker,
16 listApis,
17 listChildResources,
18 listOperations,
19 listVersions,
20 normalizeLocation,
21 ownedByAlchemy,
22 parseOwnership,
23 parseResourceName,
24 replaceOnIdentity,
25 sameJson,
26 sameText,
27 toPhysicalId,
28 updateMaskOf,
29 } from "./internal.ts";
30
31 export type HttpOperation = {
32 /** HTTP method. Required on create. */
33 method?:
34 | "METHOD_UNSPECIFIED"
35 | "GET"
36 | "PUT"
37 | "POST"
38 | "DELETE"
39 | "OPTIONS"
40 | "HEAD"
41 | "PATCH"
42 | "TRACE"
43 | (string & {});
44 /** Path relative to the server endpoint. Required on create. */
45 path?: {
46 path?: string;
47 description?: string;
48 };
49 };
50
51 export type OperationDetails = {
52 /** HTTP operation. Required on create when not using MCP. */
53 httpOperation?: HttpOperation;
54 /** Description of the operation. Alchemy stamps ownership here. */
55 description?: string;
56 /** When true, the operation is deprecated. */
57 deprecated?: boolean;
58 /** External documentation. */
59 documentation?: Documentation;
60 /** MCP tool details. */
61 mcpTool?: apihub.GoogleCloudApihubV1McpTool;
62 };
63
64 export type ApisVersionsOperationProps = {
65 /**
66 * Parent version. Full name
67 * `projects/{project}/locations/{location}/apis/{api}/versions/{version}`.
68 * Immutable — changing it replaces the operation.
69 */
70 version: string;
71 /**
72 * Operation id (the `{operation}` segment of
73 * `.../versions/{version}/operations/{operation}`). If omitted, a unique
74 * id is generated. Immutable — changing it replaces the operation.
75 */
76 apiOperationId?: string;
77 /**
78 * Location used when parsing parent names.
79 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
80 */
81 location?: string;
82 /**
83 * Operation details. `httpOperation.method` and `httpOperation.path.path`
84 * are required on create. Description is stamped with `[alchemy …]`
85 * because operations have no labels field.
86 */
87 details: OperationDetails;
88 /**
89 * User-defined attributes keyed by attribute resource name.
90 */
91 attributes?: AttributeValuesMap;
92 };
93
94 export type ApisVersionsOperation = Resource<
95 "GCP.ApiHub.ApisVersionsOperation",
96 ApisVersionsOperationProps,
97 {
98 /** Full resource name. */
99 name: string;
100 /** Operation id (last path segment). */
101 apiOperationId: string;
102 /** Parent version resource name. */
103 version: string;
104 /** Project id. */
105 project: string;
106 /** Location id. */
107 location: string;
108 /** Spec that produced this operation, if parsed from a spec. */
109 spec: string | undefined;
110 /** Operation details with the Alchemy ownership prefix stripped. */
111 details: OperationDetails | undefined;
112 /** User-defined attributes. */
113 attributes: AttributeValuesMap | undefined;
114 /** RFC3339 creation timestamp. */
115 createTime: string | undefined;
116 /** RFC3339 last-update timestamp. */
117 updateTime: string | undefined;
118 },
119 never,
120 Providers
121 >;
122
123 /**
124 * An API operation in an API Hub version. Operations can be created only
125 * when the version has no spec-parsed operations.
126 *
127 * Parent version and id are immutable. Description, documentation, HTTP
128 * path/method, deprecation, and attributes update in place. Operations
129 * have no labels field — Alchemy stamps ownership into
130 * `details.description`.
131 *
132 * ### Creating an Operation
133 * **Example:** GET /pets
134 * ```typescript
135 * const version = yield* GCP.ApiHub.ApisVersion("V1", { api: api.name });
136 * const operation = yield* GCP.ApiHub.ApisVersionsOperation("ListPets", {
137 * version: version.name,
138 * details: {
139 * httpOperation: { method: "GET", path: { path: "/pets" } },
140 * description: "list pets",
141 * },
142 * });
143 * ```
144 *
145 * @resource
146 * @category ApiHub
147 */
148 export const ApisVersionsOperation = Resource<ApisVersionsOperation>(
149 "GCP.ApiHub.ApisVersionsOperation",
150 );
151
152 const resourceName = (version: string, apiOperationId: string) =>
153 `${version}/operations/${apiOperationId}`;
154
155 const toDetails = (
156 details: apihub.GoogleCloudApihubV1OperationDetails | undefined,
157 ): OperationDetails | undefined => {
158 if (details === undefined) return undefined;
159 const parsed = parseOwnership(details.description);
160 return {
161 httpOperation: details.httpOperation,
162 description: parsed.text,
163 deprecated: details.deprecated,
164 documentation: details.documentation,
165 mcpTool: details.mcpTool,
166 };
167 };
168
169 const toAttrs = (
170 operation: apihub.GoogleCloudApihubV1ApiOperation,
171 project: string,
172 region: string,
173 ): ApisVersionsOperation["Attributes"] => {
174 const name = operation.name ?? "";
175 const parsed = parseResourceName(name, "operations", region);
176 return {
177 name,
178 apiOperationId: parsed.id,
179 version: parsed.parent,
180 project: parsed.project || project,
181 location: parsed.location,
182 spec: operation.spec,
183 details: toDetails(operation.details),
184 attributes: operation.attributes,
185 createTime: operation.createTime,
186 updateTime: operation.updateTime,
187 };
188 };
189
190 const getByName = (name: string) =>
191 name.length === 0
192 ? Effect.undefined
193 : apihub
194 .getProjectsLocationsApisVersionsOperations({ name })
195 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
196
197 const detailsOf = (
198 news: ApisVersionsOperationProps,
199 description: string,
200 ): apihub.GoogleCloudApihubV1OperationDetails => ({
201 httpOperation: news.details.httpOperation,
202 description,
203 deprecated: news.details.deprecated,
204 documentation: news.details.documentation,
205 mcpTool: news.details.mcpTool,
206 });
207
208 export const ApisVersionsOperationProvider = () =>
209 Provider.succeed(ApisVersionsOperation, {
210 stables: ["name", "apiOperationId", "version", "project", "location", "createTime"],
211
212 diff: Effect.fn(function* ({ news, olds, output }) {
213 if (!isResolved(news)) return undefined;
214 const env = yield* GcpEnvironment.current;
215 return replaceOnIdentity({
216 previousId: olds?.apiOperationId ?? output?.apiOperationId,
217 nextId: news.apiOperationId ?? olds?.apiOperationId ?? output?.apiOperationId,
218 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
219 nextLocation: normalizeLocation(
220 news.location ?? olds?.location ?? output?.location,
221 env.region,
222 ),
223 previousParent: olds?.version ?? output?.version,
224 nextParent: news.version ?? olds?.version ?? output?.version,
225 });
226 }),
227
228 read: Effect.fn(function* ({ id, olds, output }) {
229 const env = yield* GcpEnvironment.current;
230 const version = olds?.version ?? output?.version ?? "";
231 const apiOperationId = yield* toPhysicalId(id, olds?.apiOperationId, output?.apiOperationId);
232 const name = output?.name ?? resourceName(version, apiOperationId);
233 const existing = yield* getByName(name);
234 if (existing === undefined) return undefined;
235 const attrs = toAttrs(existing, env.project, env.region);
236 return (yield* ownedByAlchemy(id, existing.details?.description)) ? attrs : Unowned(attrs);
237 }),
238
239 list: () =>
240 Effect.gen(function* () {
241 const env = yield* GcpEnvironment.current;
242 const apis = yield* listApis(`projects/${env.project}/locations/${env.region}`);
243 const versions = yield* listChildResources(apis, listVersions);
244 const operations = yield* listChildResources(versions, listOperations);
245 return operations
246 .filter((item) => hasOwnershipMarker(item.details?.description))
247 .map((item) => toAttrs(item, env.project, env.region));
248 }),
249
250 reconcile: Effect.fn(function* ({ id, news, output }) {
251 const env = yield* GcpEnvironment.current;
252 const version = news.version.replace(/\/+$/, "");
253 const apiOperationId = yield* toPhysicalId(id, news.apiOperationId, output?.apiOperationId);
254 const name = output?.name ?? resourceName(version, apiOperationId);
255 const ownership = yield* createOwnership(id);
256 const description = encodeOwnership(ownership, news.details.description);
257 const details = detailsOf(news, description);
258
259 let current = yield* getByName(name);
260
261 if (current === undefined) {
262 const created = yield* apihub
263 .createProjectsLocationsApisVersionsOperations({
264 parent: version,
265 apiOperationId,
266 body: {
267 details,
268 attributes: news.attributes,
269 },
270 })
271 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
272 current = created ?? undefined;
273 }
274
275 if (current === undefined) {
276 return yield* new ApihubNotResolved({ resourceName: name });
277 }
278
279 const currentName = current.name ?? name;
280 const descriptionChanged = !sameText(current.details?.description, description);
281 const docsChanged = !sameJson(current.details?.documentation, news.details.documentation);
282 const pathChanged = !sameJson(
283 current.details?.httpOperation?.path,
284 news.details.httpOperation?.path,
285 );
286 const methodChanged = !sameText(
287 current.details?.httpOperation?.method,
288 news.details.httpOperation?.method,
289 );
290 const deprecatedChanged =
291 (current.details?.deprecated === true) !== (news.details.deprecated === true);
292 const mcpChanged = !sameJson(current.details?.mcpTool, news.details.mcpTool);
293 const attributesChanged = !sameJson(current.attributes, news.attributes);
294
295 if (
296 descriptionChanged ||
297 docsChanged ||
298 pathChanged ||
299 methodChanged ||
300 deprecatedChanged ||
301 mcpChanged ||
302 attributesChanged
303 ) {
304 current = yield* apihub.patchProjectsLocationsApisVersionsOperations({
305 name: currentName,
306 updateMask: updateMaskOf(
307 descriptionChanged ? "details.description" : undefined,
308 docsChanged ? "details.documentation" : undefined,
309 pathChanged ? "details.http_operation.path" : undefined,
310 methodChanged ? "details.http_operation.method" : undefined,
311 deprecatedChanged ? "details.deprecated" : undefined,
312 mcpChanged ? "details.mcp_tool" : undefined,
313 attributesChanged ? "attributes" : undefined,
314 ),
315 body: {
316 name: currentName,
317 details,
318 attributes: news.attributes,
319 },
320 });
321 }
322
323 return toAttrs(current, env.project, env.region);
324 }),
325
326 delete: Effect.fn(function* ({ output }) {
327 yield* apihub
328 .deleteProjectsLocationsApisVersionsOperations({ name: output.name })
329 .pipe(Effect.catchTag("NotFound", () => Effect.void));
330 }),
331 });