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

main
ts 349 lines 12.2 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { orgIdOf, orgParent } from "./ownership.ts";
13
14 const MAX_TITLE_LENGTH = 255;
15
16 export type SitesApidocProps = {
17 /**
18 * Portal site id (the `{site}` segment of
19 * `organizations/{org}/sites/{site}`). Required. Immutable — changing
20 * it replaces the catalog item.
21 */
22 siteId: string;
23 /**
24 * Name of the backing API product. Required and immutable — a portal
25 * may have only one catalog item per API product. Changing it replaces
26 * the catalog item.
27 */
28 apiProductName: string;
29 /**
30 * Apigee organization id. Defaults to the stack GCP project. Immutable —
31 * changing it replaces the catalog item.
32 */
33 organization?: string;
34 /**
35 * Server-assigned catalog item id. Set when adopting an existing item.
36 * Immutable — changing it replaces the catalog item.
37 */
38 apiDocId?: string;
39 /**
40 * User-facing catalog title. Max 255 characters. If omitted, a unique
41 * title is generated from the stack, stage, and logical id.
42 */
43 title?: string;
44 /**
45 * Catalog item description shown on the portal (max 10,000
46 * characters).
47 */
48 description?: string;
49 /**
50 * When true, the catalog item is published to the portal.
51 * @default false
52 */
53 published?: boolean;
54 /**
55 * When true, anonymous users may view the catalog item.
56 * @default false
57 */
58 anonAllowed?: boolean;
59 /**
60 * When true, a callback URL is required when the API product is enabled
61 * in a developer app.
62 * @default false
63 */
64 requireCallbackUrl?: boolean;
65 /**
66 * Image URL or portal file path shown in the catalog.
67 */
68 imageUrl?: string;
69 /**
70 * IDs of API categories this catalog item belongs to.
71 */
72 categoryIds?: string[];
73 };
74
75 export type SitesApidoc = Resource<
76 "GCP.Apigee.SitesApidoc",
77 SitesApidocProps,
78 {
79 /** Full resource name `organizations/{org}/sites/{site}/apidocs/{id}`. */
80 name: string;
81 /** Server-assigned catalog item id. */
82 apiDocId: string;
83 /** Apigee organization id. */
84 organization: string;
85 /** Portal site id. */
86 siteId: string;
87 /** Backing API product name. */
88 apiProductName: string;
89 /** User-facing title. */
90 title: string;
91 /** Catalog item description. */
92 description: string | undefined;
93 /** Whether the catalog item is published. */
94 published: boolean;
95 /** Whether anonymous users may view the item. */
96 anonAllowed: boolean;
97 /** Whether a callback URL is required. */
98 requireCallbackUrl: boolean;
99 /** Catalog image URL, if set. */
100 imageUrl: string | undefined;
101 /** Category ids. */
102 categoryIds: string[];
103 /** Last-modified time in milliseconds since epoch. */
104 modified: string | undefined;
105 },
106 never,
107 Providers
108 >;
109
110 /**
111 * An Apigee integrated-portal catalog item (`apidoc`). Catalog items
112 * present API documentation and link a portal to a backing API product.
113 *
114 * API docs have no labels field and every text field is shown to portal
115 * users, so Alchemy finds its item by API product: `read` reports an item
116 * as owned only when it carries the generated title (an explicit `title`
117 * is reported as unowned — adopt it with `--adopt`), and nuke cannot
118 * discover items. `siteId`, `organization`, and
119 * `apiProductName` are identity — changing any of them replaces the item.
120 * Title, description, publish flags, image, and categories update in
121 * place.
122 *
123 * ### Creating a Catalog Item
124 * **Example:** Draft item for an API product
125 * ```typescript
126 * const doc = yield* GCP.Apigee.SitesApidoc("Checkout", {
127 * siteId: portal.siteId,
128 * apiProductName: product.name,
129 * title: "Checkout API",
130 * description: "place orders",
131 * });
132 * ```
133 *
134 * ### Updating a Catalog Item
135 * **Example:** Publish and recategorize
136 * ```typescript
137 * const doc = yield* GCP.Apigee.SitesApidoc("Checkout", {
138 * siteId: portal.siteId,
139 * apiProductName: product.name,
140 * title: "Checkout API",
141 * description: "place orders",
142 * published: true,
143 * categoryIds: [payments.categoryId],
144 * });
145 * ```
146 *
147 * @resource
148 * @category Apigee
149 */
150 export const SitesApidoc = Resource<SitesApidoc>("GCP.Apigee.SitesApidoc");
151
152 export class SitesApidocNotResolved extends Data.TaggedError("GCP.Apigee.SitesApidocNotResolved")<{
153 resourceName: string;
154 }> {}
155
156 const siteParent = (org: string, siteId: string) => `${orgParent(org)}/sites/${siteId}`;
157
158 const resourceName = (org: string, siteId: string, apiDocId: string) =>
159 `${siteParent(org, siteId)}/apidocs/${apiDocId}`;
160
161 const toTitle = (id: string, title: string | undefined, existing?: string) =>
162 Effect.gen(function* () {
163 if (title !== undefined) return title.slice(0, MAX_TITLE_LENGTH);
164 if (existing !== undefined) return existing.slice(0, MAX_TITLE_LENGTH);
165 return (yield* createPhysicalName({
166 id,
167 maxLength: MAX_TITLE_LENGTH,
168 lowercase: true,
169 })).slice(0, MAX_TITLE_LENGTH);
170 });
171
172 const unwrap = (
173 response: apigee.GoogleCloudApigeeV1ApiDocResponse | undefined,
174 ): apigee.GoogleCloudApigeeV1ApiDoc | undefined => response?.data;
175
176 const categoryIdsOf = (ids: ReadonlyArray<string> | undefined) =>
177 [...(ids ?? [])].filter((id) => id.length > 0).sort();
178
179 const sameIds = (
180 left: ReadonlyArray<string> | undefined,
181 right: ReadonlyArray<string> | undefined,
182 ) => JSON.stringify(categoryIdsOf(left)) === JSON.stringify(categoryIdsOf(right));
183
184 const toAttrs = (doc: apigee.GoogleCloudApigeeV1ApiDoc, org: string, siteId: string) => {
185 const apiDocId = doc.id ?? "";
186 return {
187 name: apiDocId ? resourceName(org, siteId, apiDocId) : "",
188 apiDocId,
189 organization: org,
190 siteId: doc.siteId ?? siteId,
191 apiProductName: doc.apiProductName ?? "",
192 title: doc.title ?? "",
193 description: doc.description,
194 published: doc.published === true,
195 anonAllowed: doc.anonAllowed === true,
196 requireCallbackUrl: doc.requireCallbackUrl === true,
197 imageUrl: doc.imageUrl,
198 categoryIds: categoryIdsOf(doc.categoryIds),
199 modified: doc.modified,
200 };
201 };
202
203 const getByName = (name: string) =>
204 apigee.getOrganizationsSitesApidocs({ name }).pipe(
205 Effect.map((response) => unwrap(response)),
206 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined),
207 );
208
209 const listBySite = (org: string, siteId: string) =>
210 apigee.listOrganizationsSitesApidocs
211 .pages({
212 parent: siteParent(org, siteId),
213 pageSize: 100,
214 })
215 .pipe(
216 Stream.flatMap((page) => Stream.fromIterable(page.data ?? [])),
217 Stream.runCollect,
218 Effect.map((chunk) => Array.from(chunk)),
219 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed([])),
220 );
221
222 const findByProduct = (org: string, siteId: string, apiProductName: string) =>
223 listBySite(org, siteId).pipe(
224 Effect.map((docs) => docs.find((doc) => doc.apiProductName === apiProductName)),
225 );
226
227 const toBody = (
228 news: SitesApidocProps,
229 title: string,
230 description: string | undefined,
231 ): apigee.GoogleCloudApigeeV1ApiDoc => ({
232 apiProductName: news.apiProductName,
233 title,
234 description,
235 published: news.published === true ? true : undefined,
236 anonAllowed: news.anonAllowed === true ? true : undefined,
237 requireCallbackUrl: news.requireCallbackUrl === true ? true : undefined,
238 imageUrl: news.imageUrl,
239 categoryIds: news.categoryIds,
240 });
241
242 export const SitesApidocProvider = () =>
243 Provider.succeed(SitesApidoc, {
244 stables: ["name", "apiDocId", "organization", "siteId", "apiProductName"],
245
246 diff: Effect.fn(function* ({ news, olds, output }) {
247 if (!isResolved(news)) return undefined;
248 const previousSite = olds?.siteId ?? output?.siteId;
249 const siteChanged = previousSite !== undefined && news.siteId !== previousSite;
250 const previousOrg = olds?.organization ?? output?.organization;
251 const orgChanged =
252 previousOrg !== undefined &&
253 news.organization !== undefined &&
254 orgIdOf(news.organization, previousOrg) !== previousOrg;
255 const previousProduct = olds?.apiProductName ?? output?.apiProductName;
256 const productChanged =
257 previousProduct !== undefined && news.apiProductName !== previousProduct;
258 const previousId = olds?.apiDocId ?? output?.apiDocId;
259 const idChanged =
260 previousId !== undefined && news.apiDocId !== undefined && news.apiDocId !== previousId;
261 if (siteChanged || orgChanged || productChanged || idChanged) {
262 return { action: "replace" as const, deleteFirst: false };
263 }
264 return undefined;
265 }),
266
267 read: Effect.fn(function* ({ id, olds, output }) {
268 const env = yield* GcpEnvironment.current;
269 const org = orgIdOf(olds?.organization ?? output?.organization, env.project);
270 const siteId = olds?.siteId ?? output?.siteId;
271 if (siteId === undefined) return undefined;
272 const apiDocId = olds?.apiDocId ?? output?.apiDocId;
273 const apiProductName = olds?.apiProductName ?? output?.apiProductName;
274 const name =
275 output?.name ?? (apiDocId !== undefined ? resourceName(org, siteId, apiDocId) : undefined);
276 const existing =
277 name !== undefined
278 ? yield* getByName(name)
279 : apiProductName !== undefined
280 ? yield* findByProduct(org, siteId, apiProductName)
281 : undefined;
282 if (existing === undefined) return undefined;
283 const attrs = toAttrs(existing, org, siteId);
284 const generated = yield* toTitle(id, undefined);
285 return attrs.title === generated ? attrs : Unowned(attrs);
286 }),
287
288 reconcile: Effect.fn(function* ({ id, news, output }) {
289 const env = yield* GcpEnvironment.current;
290 const org = orgIdOf(news.organization ?? output?.organization, env.project);
291 const siteId = news.siteId;
292 const title = yield* toTitle(id, news.title, output?.title);
293 const desiredDescription = news.description;
294
295 let current =
296 output?.name !== undefined
297 ? yield* getByName(output.name)
298 : news.apiDocId !== undefined
299 ? yield* getByName(resourceName(org, siteId, news.apiDocId))
300 : yield* findByProduct(org, siteId, news.apiProductName);
301
302 if (current === undefined) {
303 const created = yield* apigee
304 .createOrganizationsSitesApidocs({
305 parent: siteParent(org, siteId),
306 body: toBody(news, title, desiredDescription),
307 })
308 .pipe(
309 Effect.map((response) => unwrap(response)),
310 Effect.catchTag("Conflict", () => findByProduct(org, siteId, news.apiProductName)),
311 );
312 current = created ?? undefined;
313 }
314
315 if (current === undefined || !(current.id ?? "").length) {
316 return yield* new SitesApidocNotResolved({
317 resourceName: siteParent(org, siteId),
318 });
319 }
320
321 const desiredPublished = news.published === true;
322 const desiredAnon = news.anonAllowed === true;
323 const desiredCallback = news.requireCallbackUrl === true;
324 const changed =
325 (current.title ?? "") !== title ||
326 (current.description ?? "") !== (desiredDescription ?? "") ||
327 (current.published === true) !== desiredPublished ||
328 (current.anonAllowed === true) !== desiredAnon ||
329 (current.requireCallbackUrl === true) !== desiredCallback ||
330 (current.imageUrl ?? "") !== (news.imageUrl ?? "") ||
331 !sameIds(current.categoryIds, news.categoryIds);
332
333 if (changed) {
334 const updated = yield* apigee.updateOrganizationsSitesApidocs({
335 name: resourceName(org, siteId, current.id ?? ""),
336 body: toBody(news, title, desiredDescription),
337 });
338 current = unwrap(updated) ?? current;
339 }
340
341 return toAttrs(current, org, siteId);
342 }),
343
344 delete: Effect.fn(function* ({ output }) {
345 yield* apigee
346 .deleteOrganizationsSitesApidocs({ name: output.name })
347 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
348 }),
349 });