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

main
ts 326 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 AttributeValues,
12 type AttributeValuesMap,
13 type Documentation,
14 createOwnership,
15 encodeOwnership,
16 expandParent,
17 hasOwnershipMarker,
18 listApis,
19 listChildResources,
20 listVersions,
21 normalizeLocation,
22 ownedByAlchemy,
23 parseOwnership,
24 parseResourceName,
25 replaceOnIdentity,
26 sameJson,
27 sameStringList,
28 sameText,
29 toPhysicalId,
30 updateMaskOf,
31 } from "./internal.ts";
32
33 export type ApisVersionProps = {
34 /**
35 * Parent API. Full name
36 * `projects/{project}/locations/{location}/apis/{api}` or the API id
37 * (combined with `location`). Immutable — changing it replaces the
38 * version.
39 */
40 api: string;
41 /**
42 * Version id (the `{version}` segment of
43 * `.../apis/{api}/versions/{version}`). If omitted, a unique id is
44 * generated. Immutable — changing it replaces the version.
45 */
46 versionId?: string;
47 /**
48 * Location used when `api` is a bare id.
49 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
50 */
51 location?: string;
52 /**
53 * Display name. Defaults to the version id.
54 */
55 displayName?: string;
56 /**
57 * Human-readable description. Versions have no labels field, so Alchemy
58 * stamps ownership into a `[alchemy …]` prefix and strips it from
59 * attributes.
60 */
61 description?: string;
62 /**
63 * External documentation.
64 */
65 documentation?: Documentation;
66 /**
67 * Selected deployment resource name.
68 */
69 selectedDeployment?: string;
70 /**
71 * Deployment resource names linked to this version.
72 */
73 deployments?: string[];
74 /**
75 * User-defined attributes keyed by attribute resource name.
76 */
77 attributes?: AttributeValuesMap;
78 /** System attribute `system-lifecycle`. */
79 lifecycle?: AttributeValues;
80 /** System attribute `system-compliance`. */
81 compliance?: AttributeValues;
82 /** System attribute `system-accreditation`. */
83 accreditation?: AttributeValues;
84 };
85
86 export type ApisVersion = Resource<
87 "GCP.ApiHub.ApisVersion",
88 ApisVersionProps,
89 {
90 /** Full resource name. */
91 name: string;
92 /** Version id (last path segment). */
93 versionId: string;
94 /** Parent API resource name. */
95 api: string;
96 /** Project id. */
97 project: string;
98 /** Location id. */
99 location: string;
100 /** Display name. */
101 displayName: string | undefined;
102 /** User description with the Alchemy ownership prefix stripped. */
103 description: string | undefined;
104 /** Documentation. */
105 documentation: Documentation | undefined;
106 /** Selected deployment resource name. */
107 selectedDeployment: string | undefined;
108 /** Linked deployment resource names. */
109 deployments: string[];
110 /** Spec resource names. */
111 specs: string[];
112 /** Operation resource names. */
113 apiOperations: string[];
114 /** Definition resource names. */
115 definitions: string[];
116 /** User-defined attributes. */
117 attributes: AttributeValuesMap | undefined;
118 /** RFC3339 creation timestamp. */
119 createTime: string | undefined;
120 /** RFC3339 last-update timestamp. */
121 updateTime: string | undefined;
122 },
123 never,
124 Providers
125 >;
126
127 /**
128 * An API version in API Hub. Specs and operations hang off a version.
129 *
130 * Parent API, location, and id are immutable. Display name, description,
131 * documentation, deployments, and attributes update in place. Versions have
132 * no labels field — Alchemy stamps ownership into the description.
133 *
134 * ### Creating a Version
135 * **Example:** Version under an API
136 * ```typescript
137 * const api = yield* GCP.ApiHub.Api("Pets", { displayName: "pets" });
138 * const version = yield* GCP.ApiHub.ApisVersion("V1", {
139 * api: api.name,
140 * displayName: "v1",
141 * });
142 * ```
143 *
144 * @resource
145 * @category ApiHub
146 */
147 export const ApisVersion = Resource<ApisVersion>("GCP.ApiHub.ApisVersion");
148
149 const resourceName = (api: string, versionId: string) => `${api}/versions/${versionId}`;
150
151 const parentApi = (value: string, project: string, location: string) =>
152 expandParent(value, project, location, "apis");
153
154 const toAttrs = (
155 version: apihub.GoogleCloudApihubV1Version,
156 project: string,
157 region: string,
158 ): ApisVersion["Attributes"] => {
159 const name = version.name ?? "";
160 const parsed = parseResourceName(name, "versions", region);
161 const description = parseOwnership(version.description).text;
162 return {
163 name,
164 versionId: parsed.id,
165 api: parsed.parent,
166 project: parsed.project || project,
167 location: parsed.location,
168 displayName: version.displayName,
169 description,
170 documentation: version.documentation,
171 selectedDeployment: version.selectedDeployment,
172 deployments: [...(version.deployments ?? [])],
173 specs: [...(version.specs ?? [])],
174 apiOperations: [...(version.apiOperations ?? [])],
175 definitions: [...(version.definitions ?? [])],
176 attributes: version.attributes,
177 createTime: version.createTime,
178 updateTime: version.updateTime,
179 };
180 };
181
182 const getByName = (name: string) =>
183 name.length === 0
184 ? Effect.undefined
185 : apihub
186 .getProjectsLocationsApisVersions({ name })
187 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
188
189 const bodyOf = (
190 news: ApisVersionProps,
191 displayName: string,
192 description: string,
193 ): apihub.GoogleCloudApihubV1Version => ({
194 displayName,
195 description,
196 documentation: news.documentation,
197 selectedDeployment: news.selectedDeployment,
198 deployments: news.deployments,
199 attributes: news.attributes,
200 lifecycle: news.lifecycle,
201 compliance: news.compliance,
202 accreditation: news.accreditation,
203 });
204
205 export const ApisVersionProvider = () =>
206 Provider.succeed(ApisVersion, {
207 stables: ["name", "versionId", "api", "project", "location", "createTime"],
208
209 diff: Effect.fn(function* ({ news, olds, output }) {
210 if (!isResolved(news)) return undefined;
211 const env = yield* GcpEnvironment.current;
212 const location = normalizeLocation(
213 news.location ?? olds?.location ?? output?.location,
214 env.region,
215 );
216 return replaceOnIdentity({
217 previousId: olds?.versionId ?? output?.versionId,
218 nextId: news.versionId ?? olds?.versionId ?? output?.versionId,
219 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
220 nextLocation: location,
221 previousParent: olds?.api ?? output?.api,
222 nextParent: news.api ?? olds?.api ?? output?.api,
223 });
224 }),
225
226 read: Effect.fn(function* ({ id, olds, output }) {
227 const env = yield* GcpEnvironment.current;
228 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
229 const api = parentApi(olds?.api ?? output?.api ?? "", env.project, location);
230 const versionId = yield* toPhysicalId(id, olds?.versionId, output?.versionId);
231 const name = output?.name ?? resourceName(api, versionId);
232 const existing = yield* getByName(name);
233 if (existing === undefined) return undefined;
234 const attrs = toAttrs(existing, env.project, env.region);
235 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
236 }),
237
238 list: () =>
239 Effect.gen(function* () {
240 const env = yield* GcpEnvironment.current;
241 const apis = yield* listApis(`projects/${env.project}/locations/${env.region}`);
242 const versions = yield* listChildResources(apis, listVersions);
243 return versions
244 .filter((item) => hasOwnershipMarker(item.description))
245 .map((item) => toAttrs(item, env.project, env.region));
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, output }) {
249 const env = yield* GcpEnvironment.current;
250 const location = normalizeLocation(news.location ?? output?.location, env.region);
251 const api = parentApi(news.api, env.project, location);
252 const versionId = yield* toPhysicalId(id, news.versionId, output?.versionId);
253 const name = output?.name ?? resourceName(api, versionId);
254 const ownership = yield* createOwnership(id);
255 const description = encodeOwnership(ownership, news.description);
256 const displayName = news.displayName ?? versionId;
257 const desired = bodyOf(news, displayName, description);
258
259 let current = yield* getByName(name);
260
261 if (current === undefined) {
262 const created = yield* apihub
263 .createProjectsLocationsApisVersions({
264 parent: api,
265 versionId,
266 body: desired,
267 })
268 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
269 current = created ?? undefined;
270 }
271
272 if (current === undefined) {
273 return yield* new ApihubNotResolved({ resourceName: name });
274 }
275
276 const currentName = current.name ?? name;
277 const displayChanged = !sameText(current.displayName, displayName);
278 const descriptionChanged = !sameText(current.description, description);
279 const docsChanged = !sameJson(current.documentation, news.documentation);
280 const selectedChanged = !sameText(current.selectedDeployment, news.selectedDeployment);
281 const deploymentsChanged = !sameStringList(current.deployments, news.deployments);
282 const attributesChanged = !sameJson(current.attributes, news.attributes);
283 const lifecycleChanged = !sameJson(current.lifecycle, news.lifecycle);
284 const complianceChanged = !sameJson(current.compliance, news.compliance);
285 const accreditationChanged = !sameJson(current.accreditation, news.accreditation);
286
287 if (
288 displayChanged ||
289 descriptionChanged ||
290 docsChanged ||
291 selectedChanged ||
292 deploymentsChanged ||
293 attributesChanged ||
294 lifecycleChanged ||
295 complianceChanged ||
296 accreditationChanged
297 ) {
298 current = yield* apihub.patchProjectsLocationsApisVersions({
299 name: currentName,
300 updateMask: updateMaskOf(
301 displayChanged ? "display_name" : undefined,
302 descriptionChanged ? "description" : undefined,
303 docsChanged ? "documentation" : undefined,
304 selectedChanged ? "selected_deployment" : undefined,
305 deploymentsChanged ? "deployments" : undefined,
306 attributesChanged ? "attributes" : undefined,
307 lifecycleChanged ? "lifecycle" : undefined,
308 complianceChanged ? "compliance" : undefined,
309 accreditationChanged ? "accreditation" : undefined,
310 ),
311 body: { name: currentName, ...desired },
312 });
313 }
314
315 return toAttrs(current, env.project, env.region);
316 }),
317
318 delete: Effect.fn(function* ({ output }) {
319 yield* apihub
320 .deleteProjectsLocationsApisVersions({
321 name: output.name,
322 force: true,
323 })
324 .pipe(Effect.catchTag("NotFound", () => Effect.void));
325 }),
326 });