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

main
ts 434 lines 13.9 KB
Raw
1 import * as developerconnect from "@distilled.cloud/gcp/developerconnect_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 collectPages,
13 expandParent,
14 fingerprint,
15 listAtNested,
16 listLabeledPages,
17 normalizeLocation,
18 parseName,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 toPhysicalId,
22 userAnnotations,
23 userLabels,
24 waitForOperation,
25 waitUntilExists,
26 waitUntilGone,
27 listAtLocation,
28 } from "./internal.ts";
29
30 export type ConnectionsGitRepositoryLinkProps = {
31 /**
32 * Parent Developer Connect connection. Full name
33 * `projects/{project}/locations/{location}/connections/{connection}`
34 * or the connection id (combined with `location`). Immutable —
35 * changing it replaces the link.
36 */
37 connection: string;
38 /**
39 * Region used when `connection` is a bare id. Immutable — changing
40 * it replaces the link. `US-CENTRAL1` is accepted and normalized to
41 * `us-central1`.
42 * @default the stack's GCP region (`GCP.Region`, else the profile
43 * region, else `us-central1`)
44 */
45 location?: string;
46 /**
47 * Git repository link id (the `{gitRepositoryLink}` segment of
48 * `{connection}/gitRepositoryLinks/{gitRepositoryLink}`). If omitted,
49 * a unique RFC1035 name is generated. Unique within the connection.
50 * Immutable — changing it replaces the link.
51 */
52 gitRepositoryLinkId?: string;
53 /**
54 * Git clone HTTPS URI (e.g. `https://github.com/{owner}/{repo}.git`).
55 * Immutable — changing it replaces the link.
56 */
57 cloneUri: string;
58 /**
59 * User labels. Alchemy ownership labels are merged in automatically.
60 * The API has no patch method — changing labels replaces the link.
61 */
62 labels?: Record<string, string>;
63 /**
64 * User annotations (AIP-148). The API has no patch method — changing
65 * annotations replaces the link.
66 */
67 annotations?: Record<string, string>;
68 };
69
70 export type ConnectionsGitRepositoryLink = Resource<
71 "GCP.DeveloperConnect.ConnectionsGitRepositoryLink",
72 ConnectionsGitRepositoryLinkProps,
73 {
74 /** Full resource name. */
75 name: string;
76 /** Git repository link id (last path segment). */
77 gitRepositoryLinkId: string;
78 /** Parent connection resource name. */
79 connection: string;
80 /** Connection id (last path segment of the parent). */
81 connectionId: string;
82 /** Project id. */
83 project: string;
84 /** Location id. */
85 location: string;
86 /** Git clone HTTPS URI. */
87 cloneUri: string;
88 /** User labels (Alchemy ownership labels stripped). */
89 labels: Record<string, string>;
90 /** User annotations. */
91 annotations: Record<string, string>;
92 /** External id of the webhook created for the repository. */
93 webhookId: string | undefined;
94 /** Git proxy URI when the parent connection has git proxy enabled. */
95 gitProxyUri: string | undefined;
96 /** True while Developer Connect is applying the link. */
97 reconciling: boolean;
98 /** Server checksum of the resource. */
99 etag: string | undefined;
100 /** Server-generated resource uid. */
101 uid: string | undefined;
102 /** RFC3339 creation timestamp. */
103 createTime: string | undefined;
104 /** RFC3339 last-update timestamp. */
105 updateTime: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * A Developer Connect git repository link — associates a remote Git
113 * repository with a {@link Connection} so webhooks and clone tokens
114 * can be issued.
115 *
116 * Changing `gitRepositoryLinkId`, `connection`, `location`, `cloneUri`,
117 * labels, or annotations replaces the link. There is no update API;
118 * every user-facing field is immutable.
119 *
120 * ### Creating a Git Repository Link
121 * **Example:** Generated name
122 * ```typescript
123 * const github = yield* GCP.DeveloperConnect.Connection("Github", {
124 * githubConfig: { githubApp: "DEVELOPER_CONNECT" },
125 * });
126 * const source = yield* GCP.DeveloperConnect.ConnectionsGitRepositoryLink(
127 * "Source",
128 * {
129 * connection: github.name,
130 * cloneUri: "https://github.com/{owner}/{repo}.git",
131 * },
132 * );
133 * ```
134 *
135 * **Example:** Named link with labels
136 * ```typescript
137 * const source = yield* GCP.DeveloperConnect.ConnectionsGitRepositoryLink(
138 * "Source",
139 * {
140 * connection: github.name,
141 * gitRepositoryLinkId: "app-source",
142 * cloneUri: "https://github.com/{owner}/{repo}.git",
143 * labels: { env: "prod" },
144 * },
145 * );
146 * ```
147 *
148 * ### Fetching Git Refs
149 * **Example:** List branches
150 * ```typescript
151 * const fetchGitRefs = yield* GCP.DeveloperConnect.FetchGitRefs(source);
152 * const { refNames } = yield* fetchGitRefs({ refType: "BRANCH" });
153 * ```
154 *
155 * ### Cloning with a Token
156 * **Example:** Fetch a read token
157 * ```typescript
158 * const fetchReadToken = yield* GCP.DeveloperConnect.FetchReadToken(source);
159 * const { token } = yield* fetchReadToken();
160 * ```
161 *
162 * @resource
163 * @category DeveloperConnect
164 */
165 export const ConnectionsGitRepositoryLink = Resource<ConnectionsGitRepositoryLink>(
166 "GCP.DeveloperConnect.ConnectionsGitRepositoryLink",
167 );
168
169 const parseLinkName = (name: string, region: string) => {
170 const parsed = parseName(name, "gitRepositoryLinks", region);
171 const connectionParsed = parseName(parsed.parent, "connections", region);
172 return {
173 project: parsed.project,
174 location: parsed.location,
175 gitRepositoryLinkId: parsed.id,
176 connection: parsed.parent,
177 connectionId: connectionParsed.id,
178 };
179 };
180
181 const resolveParent = (
182 project: string,
183 connection: string,
184 location: string | undefined,
185 region: string,
186 ) => {
187 if (connection.includes("/")) {
188 const parsed = parseLinkName(
189 connection.includes("/gitRepositoryLinks/")
190 ? connection
191 : `${connection.replace(/\/+$/, "")}/gitRepositoryLinks/_`,
192 region,
193 );
194 return {
195 parent: parsed.connection,
196 location: parsed.location,
197 project: parsed.project || project,
198 connectionId: parsed.connectionId,
199 };
200 }
201 const loc = normalizeLocation(location, region);
202 return {
203 parent: expandParent(connection, project, loc, "connections"),
204 location: loc,
205 project,
206 connectionId: connection,
207 };
208 };
209
210 const parentKey = (
211 connection: string | undefined,
212 location: string | undefined,
213 region: string,
214 ) => {
215 if (connection === undefined || connection === "") return undefined;
216 const parsed = resolveParent("", connection, location, region);
217 return `${parsed.location}/${parsed.connectionId}`;
218 };
219
220 const resourceName = (parent: string, gitRepositoryLinkId: string) =>
221 `${parent}/gitRepositoryLinks/${gitRepositoryLinkId}`;
222
223 const toAttrs = (item: developerconnect.GitRepositoryLink, project: string, region: string) => {
224 const name = item.name ?? "";
225 const parsed = parseLinkName(name, region);
226 return {
227 name,
228 gitRepositoryLinkId: parsed.gitRepositoryLinkId,
229 connection: parsed.connection,
230 connectionId: parsed.connectionId,
231 project: parsed.project || project,
232 location: parsed.location,
233 cloneUri: item.cloneUri ?? "",
234 labels: userLabels(item.labels),
235 annotations: userAnnotations(item.annotations),
236 webhookId: item.webhookId,
237 gitProxyUri: item.gitProxyUri,
238 reconciling: item.reconciling === true,
239 etag: item.etag,
240 uid: item.uid,
241 createTime: item.createTime,
242 updateTime: item.updateTime,
243 };
244 };
245
246 const getByName = (name: string) =>
247 developerconnect
248 .getProjectsLocationsConnectionsGitRepositoryLinks({ name })
249 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
250
251 const listLinksAt = (parent: string) =>
252 listLabeledPages(
253 developerconnect.listProjectsLocationsConnectionsGitRepositoryLinks.pages({
254 parent,
255 pageSize: 1000,
256 }),
257 (page) => page.gitRepositoryLinks,
258 (item) => item.labels,
259 );
260
261 const listOwned = (project: string, region: string) =>
262 Effect.gen(function* () {
263 const wildcard = yield* listAtNested(project, "connections/-", region, (parent) =>
264 listLinksAt(parent),
265 );
266 if (wildcard.length > 0) return wildcard;
267 const connections = yield* listAtLocation(project, region, (parent) =>
268 collectPages(
269 developerconnect.listProjectsLocationsConnections.pages({
270 parent,
271 pageSize: 1000,
272 }),
273 (page) => page.connections,
274 ),
275 );
276 const pages = yield* Effect.forEach(
277 connections,
278 (connection) =>
279 connection.name
280 ? listLinksAt(connection.name)
281 : Effect.succeed([] as developerconnect.GitRepositoryLink[]),
282 { concurrency: 4 },
283 );
284 return pages.flat();
285 });
286
287 export const ConnectionsGitRepositoryLinkProvider = () =>
288 Provider.succeed(ConnectionsGitRepositoryLink, {
289 stables: [
290 "name",
291 "gitRepositoryLinkId",
292 "connection",
293 "connectionId",
294 "project",
295 "location",
296 "cloneUri",
297 "uid",
298 "createTime",
299 ],
300
301 diff: Effect.fn(function* ({ news, olds, output }) {
302 if (!isResolved(news)) return undefined;
303 const env = yield* GcpEnvironment.current;
304 if (output === undefined && olds === undefined) return undefined;
305 const previousUri = olds?.cloneUri ?? output?.cloneUri ?? "";
306 const nextUri = news.cloneUri ?? previousUri;
307 return replaceOnIdentity({
308 previousId: olds?.gitRepositoryLinkId ?? output?.gitRepositoryLinkId,
309 nextId:
310 news.gitRepositoryLinkId ?? olds?.gitRepositoryLinkId ?? output?.gitRepositoryLinkId,
311 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
312 nextLocation: normalizeLocation(
313 news.location ?? olds?.location ?? output?.location,
314 env.region,
315 ),
316 previousParent: parentKey(
317 olds?.connection ?? output?.connection,
318 olds?.location ?? output?.location,
319 env.region,
320 ),
321 nextParent:
322 news.connection !== undefined
323 ? parentKey(
324 news.connection,
325 news.location ?? olds?.location ?? output?.location,
326 env.region,
327 )
328 : parentKey(
329 olds?.connection ?? output?.connection,
330 news.location ?? olds?.location ?? output?.location,
331 env.region,
332 ),
333 extra:
334 (previousUri !== "" && nextUri !== previousUri) ||
335 fingerprint(toLabels(olds?.labels ?? output?.labels)) !==
336 fingerprint(toLabels(news.labels)) ||
337 fingerprint(olds?.annotations ?? output?.annotations) !== fingerprint(news.annotations),
338 });
339 }),
340
341 read: Effect.fn(function* ({ id, olds, output }) {
342 const env = yield* GcpEnvironment.current;
343 let name = output?.name;
344 if (name === undefined || name.length === 0) {
345 const connectionRef = olds?.connection ?? output?.connection;
346 if (typeof connectionRef !== "string" || connectionRef.length === 0) {
347 return undefined;
348 }
349 const gitRepositoryLinkId = yield* toPhysicalId(
350 id,
351 olds?.gitRepositoryLinkId,
352 output?.gitRepositoryLinkId,
353 "gitrepositorylink",
354 );
355 const parent = resolveParent(
356 env.project,
357 connectionRef,
358 olds?.location ?? output?.location,
359 env.region,
360 );
361 name = resourceName(parent.parent, gitRepositoryLinkId);
362 }
363 const existing = yield* getByName(name);
364 if (existing === undefined) return undefined;
365 const attrs = toAttrs(existing, env.project, env.region);
366 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
367 }),
368
369 list: () =>
370 Effect.gen(function* () {
371 const env = yield* GcpEnvironment.current;
372 const items = yield* listOwned(env.project, env.region);
373 return items.map((item) => toAttrs(item, env.project, env.region));
374 }),
375
376 reconcile: Effect.fn(function* ({ id, news, output }) {
377 const env = yield* GcpEnvironment.current;
378 const gitRepositoryLinkId = yield* toPhysicalId(
379 id,
380 news.gitRepositoryLinkId,
381 output?.gitRepositoryLinkId,
382 "gitrepositorylink",
383 );
384 const parent = resolveParent(
385 env.project,
386 news.connection ?? output?.connection ?? "",
387 news.location ?? output?.location,
388 env.region,
389 );
390 const name = resourceName(parent.parent, gitRepositoryLinkId);
391 const desiredLabels = {
392 ...toLabels(news.labels),
393 ...(yield* createInternalLabels(id)),
394 };
395
396 let current = yield* getByName(output?.name ?? name);
397
398 if (current === undefined) {
399 const created = yield* developerconnect
400 .createProjectsLocationsConnectionsGitRepositoryLinks({
401 parent: parent.parent,
402 gitRepositoryLinkId,
403 body: {
404 cloneUri: news.cloneUri,
405 labels: desiredLabels,
406 annotations: news.annotations,
407 },
408 })
409 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
410 if (created !== undefined) {
411 yield* waitForOperation(created);
412 }
413 current = yield* waitUntilExists(getByName(name), name);
414 }
415
416 if (current === undefined) {
417 return yield* new ResourceNotResolved({ resourceName: name });
418 }
419
420 return toAttrs(current, env.project, env.region);
421 }),
422
423 delete: Effect.fn(function* ({ output }) {
424 const name = output.name;
425 if (name === undefined || name.length === 0) return;
426 const operation = yield* developerconnect
427 .deleteProjectsLocationsConnectionsGitRepositoryLinks({ name })
428 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
429 if (operation !== undefined) {
430 yield* waitForOperation(operation, { notFoundOk: true });
431 }
432 yield* waitUntilGone(getByName(name), name);
433 }),
434 });