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

main
ts 609 lines 19.4 KB
Raw
1 import * as Repos from "@distilled.cloud/github/repos";
2 import * as Users from "@distilled.cloud/github/users";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { withBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts";
10 import type * as GitHub from "./Providers.ts";
11
12 export class RepositoryOperationFailed extends Data.TaggedError("RepositoryOperationFailed")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface RepositoryProps {
18 /**
19 * Repository owner — a user or organization login.
20 *
21 * Changing the owner replaces the repository: a NEW, EMPTY repository is
22 * created under the new owner — history, issues, and pull requests are
23 * not carried over. The old repository is retained on GitHub under the
24 * default `retain` removal policy; it is only deleted when the resource
25 * opted into deletion via `destroy()`. To actually move a repository
26 * between owners with its history, transfer it in the GitHub UI/API
27 * first, then update `owner` here and deploy with `--adopt`.
28 */
29 owner: string;
30
31 /**
32 * Repository name. Renaming (deploying with the same logical ID and a
33 * different `name`) renames the existing repository in place rather than
34 * replacing it.
35 */
36 name: string;
37
38 /**
39 * Short description shown on the repository page.
40 */
41 description?: string;
42
43 /**
44 * Homepage URL shown on the repository page.
45 */
46 homepage?: string;
47
48 /**
49 * Repository visibility. `internal` is only valid for repositories owned by
50 * an organization on GitHub Enterprise. When omitted, GitHub's default
51 * applies (`public`).
52 * @default "public"
53 */
54 visibility?: "public" | "private" | "internal";
55
56 /**
57 * Whether the Issues tab is enabled.
58 * @default true
59 */
60 hasIssues?: boolean;
61
62 /**
63 * Whether the Projects tab is enabled.
64 * @default true
65 */
66 hasProjects?: boolean;
67
68 /**
69 * Whether the Wiki tab is enabled.
70 * @default true
71 */
72 hasWiki?: boolean;
73
74 /**
75 * Whether GitHub Discussions are enabled.
76 * @default false
77 */
78 hasDiscussions?: boolean;
79
80 /**
81 * Whether the repository is a template repository.
82 * @default false
83 */
84 isTemplate?: boolean;
85
86 /**
87 * Whether the repository is archived (read-only).
88 * @default false
89 */
90 archived?: boolean;
91
92 /**
93 * The default branch name. Only applied to repositories that already have
94 * at least one branch — setting it on an empty repository has no effect.
95 */
96 defaultBranch?: string;
97
98 /**
99 * Whether squash merges are allowed.
100 * @default true
101 */
102 allowSquashMerge?: boolean;
103
104 /**
105 * Whether merge commits are allowed.
106 * @default true
107 */
108 allowMergeCommit?: boolean;
109
110 /**
111 * Whether rebase merges are allowed.
112 * @default true
113 */
114 allowRebaseMerge?: boolean;
115
116 /**
117 * Whether auto-merge is enabled for pull requests.
118 * @default false
119 */
120 allowAutoMerge?: boolean;
121
122 /**
123 * Whether head branches are automatically deleted after a pull request is
124 * merged.
125 * @default false
126 */
127 deleteBranchOnMerge?: boolean;
128
129 /**
130 * Repository topics. The provided list fully replaces the existing topics.
131 */
132 topics?: string[];
133
134 /**
135 * Initialize the repository with an empty README on creation. Only used at
136 * create time — ignored on subsequent updates.
137 * @default false
138 */
139 autoInit?: boolean;
140
141 /**
142 * Name of the `.gitignore` template to apply on creation (e.g. `"Node"`).
143 * Only used at create time.
144 */
145 gitignoreTemplate?: string;
146
147 /**
148 * Keyword of the license template to apply on creation (e.g. `"mit"`).
149 * Only used at create time.
150 */
151 licenseTemplate?: string;
152
153 /**
154 * Override the GitHub host or API base URL for this resource only (e.g.
155 * `github.example.com` for GitHub Enterprise). Falls back to
156 * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth
157 * provider. Changing it replaces the resource — the same name on a
158 * different GitHub instance is a different physical resource.
159 */
160 baseUrl?: string;
161 }
162
163 export interface Repository extends Resource<
164 "GitHub.Repository",
165 RepositoryProps,
166 {
167 /**
168 * Numeric GitHub repository ID.
169 */
170 repoId: number;
171
172 /**
173 * GraphQL node ID of the repository.
174 */
175 nodeId: string;
176
177 /**
178 * Full name in `owner/name` form.
179 */
180 fullName: string;
181
182 /**
183 * URL to view the repository in a browser.
184 */
185 htmlUrl: string;
186
187 /**
188 * Git protocol clone URL (`git://`).
189 */
190 gitUrl: string;
191
192 /**
193 * SSH clone URL (`git@github.com:owner/name.git`).
194 */
195 sshUrl: string;
196
197 /**
198 * HTTPS clone URL.
199 */
200 cloneUrl: string;
201
202 /**
203 * The resolved default branch name.
204 */
205 defaultBranch: string;
206
207 /**
208 * ISO-8601 timestamp of when the repository was created.
209 */
210 createdAt: string;
211
212 /**
213 * ISO-8601 timestamp of the last update.
214 */
215 updatedAt: string;
216 },
217 never,
218 GitHub.Providers
219 > {}
220
221 /**
222 * A GitHub repository.
223 *
224 * `Repository` manages the lifecycle of a repository owned by a user or
225 * organization. The repository is created on first deploy and its settings are
226 * converged on every subsequent deploy.
227 *
228 * Repositories default to **retain** on removal — destroying the stack does
229 * NOT delete the repository on GitHub, protecting its irreplaceable history
230 * (issues, pull requests, commits). Opt in to actual deletion by wrapping the
231 * resource (or the whole stack) in {@link destroy}() from
232 * `alchemy/RemovalPolicy`.
233 *
234 * Authentication is resolved via the GitHub `Credentials` service supplied by
235 * `GitHub.providers()` (env, stored PAT, `gh` CLI, or OAuth). The token needs
236 * `repo` scope (and `delete_repo` when deletion is opted in via `destroy()`).
237 * ### Creating a Repository
238 * **Example:** Basic Repository
239 * ```typescript
240 * const repo = yield* GitHub.Repository("api", {
241 * owner: "my-org",
242 * name: "api",
243 * description: "API service",
244 * autoInit: true,
245 * });
246 * ```
247 *
248 * **Example:** Private Repository with Settings
249 * ```typescript
250 * const repo = yield* GitHub.Repository("internal-tools", {
251 * owner: "my-org",
252 * name: "internal-tools",
253 * visibility: "private",
254 * hasWiki: false,
255 * hasProjects: false,
256 * deleteBranchOnMerge: true,
257 * });
258 * ```
259 *
260 * **Example:** Initialize from Templates
261 * The `autoInit`, `gitignoreTemplate`, and `licenseTemplate` props seed the
262 * first commit. They are only honored at create time — changing them on a
263 * later deploy has no effect on an existing repository.
264 * ```typescript
265 * const repo = yield* GitHub.Repository("service", {
266 * owner: "my-org",
267 * name: "service",
268 * autoInit: true,
269 * gitignoreTemplate: "Node",
270 * licenseTemplate: "mit",
271 * });
272 * ```
273 *
274 * ### Topics and Merge Configuration
275 * **Example:** Repository with Topics and Merge Policy
276 * ```typescript
277 * const repo = yield* GitHub.Repository("sdk", {
278 * owner: "my-org",
279 * name: "sdk",
280 * topics: ["typescript", "effect", "sdk"],
281 * allowMergeCommit: false,
282 * allowRebaseMerge: false,
283 * allowSquashMerge: true,
284 * allowAutoMerge: true,
285 * });
286 * ```
287 *
288 * ### Renaming a Repository
289 * **Example:** Rename in Place
290 * Keep the same logical ID and change `name` to rename the live repository
291 * instead of replacing it — the repository's history, issues, and pull
292 * requests are preserved. Only changing `owner` triggers a replacement.
293 * ```typescript
294 * // First deploy creates "api".
295 * const repo = yield* GitHub.Repository("api", {
296 * owner: "my-org",
297 * name: "api",
298 * });
299 *
300 * // A later deploy with the SAME logical ID ("api") renames it to "gateway".
301 * const repo = yield* GitHub.Repository("api", {
302 * owner: "my-org",
303 * name: "gateway",
304 * });
305 * ```
306 *
307 * ### Archiving a Repository
308 * **Example:** Make a Repository Read-Only
309 * Archiving sets the repository to read-only. Set `archived` back to `false`
310 * on a later deploy to un-archive it.
311 * ```typescript
312 * yield* GitHub.Repository("legacy", {
313 * owner: "my-org",
314 * name: "legacy-service",
315 * archived: true,
316 * });
317 * ```
318 *
319 * ### Wiring with Other Resources
320 * The repository's outputs can drive other GitHub resources so the whole
321 * repository configuration lives in one program.
322 *
323 * **Example:** Seed a Variable into the Repository
324 * ```typescript
325 * const repo = yield* GitHub.Repository("api", {
326 * owner: "my-org",
327 * name: "api",
328 * autoInit: true,
329 * });
330 *
331 * yield* GitHub.Variable("region", {
332 * owner: "my-org",
333 * repository: repo.name!,
334 * name: "AWS_REGION",
335 * value: "us-east-1",
336 * });
337 * ```
338 *
339 * **Example:** Store a Secret in the Repository
340 * ```typescript
341 * import * as Redacted from "effect/Redacted";
342 *
343 * const repo = yield* GitHub.Repository("api", {
344 * owner: "my-org",
345 * name: "api",
346 * autoInit: true,
347 * });
348 *
349 * yield* GitHub.Secret("deploy-token", {
350 * owner: "my-org",
351 * repository: repo.name!,
352 * name: "DEPLOY_TOKEN",
353 * value: Redacted.make("my-secret-value"),
354 * });
355 * ```
356 *
357 * ### Deleting a Repository
358 * **Example:** Allow Repository Deletion
359 * ```typescript
360 * import { destroy } from "alchemy/RemovalPolicy";
361 *
362 * yield* GitHub.Repository("ephemeral", {
363 * owner: "my-org",
364 * name: "ephemeral-preview",
365 * }).pipe(destroy());
366 * ```
367 *
368 * @resource
369 * @product Repository
370 */
371 export const Repository = Resource<Repository>("GitHub.Repository", {
372 defaultRemovalPolicy: "retain",
373 });
374
375 export const RepositoryProvider = () =>
376 Provider.succeed(Repository, {
377 stables: ["repoId", "nodeId"],
378
379 // Structural changes are the owner (we deliberately do NOT call GitHub's
380 // transfer API — user-to-user transfers require out-of-band acceptance
381 // and cannot converge deterministically) and the host (the same repo
382 // name on a different GitHub instance is a different repository). A
383 // `name` change is a rename, handled in `reconcile`, not a replacement.
384 //
385 // Replacement is guarded by the resource's default `retain` removal
386 // policy: the engine creates the new repository and RETAINS the old one
387 // on GitHub (Apply honors `retain` for the replaced old generation), so
388 // history is never destroyed unless the user opted into `destroy()`.
389 diff: Effect.fn(function* ({ news, olds }) {
390 if (!isResolved(news)) return;
391 if (olds === undefined) return;
392 if (news.owner !== olds.owner || (yield* gitHubBaseUrlChanged(olds, news))) {
393 return { action: "replace" };
394 }
395 }),
396
397 reconcile: Effect.fn(
398 function* ({ news, olds }) {
399 const getRepo = (repo: string) =>
400 Repos.get({ owner: news.owner, repo }).pipe(
401 Effect.catchTag("NotFound", () => Effect.undefined),
402 );
403
404 // Observe — probe for the live repository under the desired name. On a
405 // rename (name changed since last deploy) the desired name 404s, so fall
406 // back to the prior name so we converge by renaming rather than creating
407 // a duplicate.
408 let observed = yield* getRepo(news.name);
409 if (observed === undefined && olds?.name !== undefined && olds.name !== news.name) {
410 observed = yield* getRepo(olds.name);
411 }
412
413 // Ensure — create the repository when it does not exist. The owner may be
414 // a user or an organization; pick the matching create endpoint.
415 if (observed === undefined) {
416 const owner = yield* Users.getByUsername({ username: news.owner });
417
418 const createInput = {
419 name: news.name,
420 description: news.description,
421 homepage: news.homepage,
422 has_issues: news.hasIssues,
423 has_projects: news.hasProjects,
424 has_wiki: news.hasWiki,
425 is_template: news.isTemplate,
426 auto_init: news.autoInit,
427 gitignore_template: news.gitignoreTemplate,
428 license_template: news.licenseTemplate,
429 allow_squash_merge: news.allowSquashMerge,
430 allow_merge_commit: news.allowMergeCommit,
431 allow_rebase_merge: news.allowRebaseMerge,
432 allow_auto_merge: news.allowAutoMerge,
433 delete_branch_on_merge: news.deleteBranchOnMerge,
434 };
435
436 observed = yield* (
437 owner.type === "Organization"
438 ? // The org endpoint accepts `visibility` directly, which is the
439 // sole authority over public/private/internal. `internal` is
440 // only valid here.
441 Repos.createInOrg({ org: news.owner, ...createInput, visibility: news.visibility })
442 : // A personal account is either a `User` or a `Bot`; both create
443 // through the authenticated-user endpoint, which only
444 // understands the boolean `private` flag.
445 Repos.createForAuthenticatedUser({
446 ...createInput,
447 private: news.visibility ? news.visibility !== "public" : undefined,
448 })
449 ).pipe(
450 // A 422 means the name already exists — treat as a create race
451 // and re-observe so the sync step converges its settings.
452 Effect.catchTag("UnprocessableEntity", () => Effect.undefined),
453 );
454
455 if (observed === undefined) {
456 observed = yield* getRepo(news.name);
457 }
458 if (observed === undefined) {
459 return yield* new RepositoryOperationFailed({
460 message: `Failed to create or locate GitHub repository ${news.owner}/${news.name}`,
461 });
462 }
463 }
464
465 // Sync — converge settings (and the name on a rename) against the live
466 // repository. GitHub's update is an idempotent PATCH, so we always issue
467 // it with the desired settings. `archived` is applied in a separate,
468 // later PATCH because an archived repository rejects any other settings
469 // change in the same call.
470 const repoName = observed.name;
471 const updateInput = {
472 owner: news.owner,
473 repo: repoName,
474 name: news.name,
475 description: news.description,
476 homepage: news.homepage,
477 private: news.visibility ? news.visibility !== "public" : undefined,
478 visibility: news.visibility,
479 has_issues: news.hasIssues,
480 has_projects: news.hasProjects,
481 has_wiki: news.hasWiki,
482 has_discussions: news.hasDiscussions,
483 is_template: news.isTemplate,
484 allow_squash_merge: news.allowSquashMerge,
485 allow_merge_commit: news.allowMergeCommit,
486 allow_rebase_merge: news.allowRebaseMerge,
487 allow_auto_merge: news.allowAutoMerge,
488 delete_branch_on_merge: news.deleteBranchOnMerge,
489 // Only set the default branch when it actually differs from the
490 // observed branch. GitHub returns 422 if the branch does not yet
491 // exist (e.g. an empty repo), so the 422 handler below strips it and
492 // retries rather than hard-failing — the branch may be created right
493 // after this deploy.
494 default_branch:
495 news.defaultBranch !== undefined && observed.default_branch !== news.defaultBranch
496 ? news.defaultBranch
497 : undefined,
498 };
499
500 const updated = yield* Repos.update(updateInput).pipe(
501 // A 422 on a default-branch update usually means the branch does not
502 // exist yet. Drop it and retry so the rest of the settings still
503 // converge.
504 Effect.catchTag("UnprocessableEntity", (error) => {
505 if (!updateInput.default_branch) return Effect.fail(error);
506 const { default_branch: _default_branch, ...withoutBranch } = updateInput;
507 return Repos.update(withoutBranch);
508 }),
509 );
510
511 // Sync — apply `archived` in its own PATCH. Use the confirmed
512 // post-rename name from the first update so the call targets the right
513 // repo. Archiving is one-directional in this PATCH: only send it when
514 // explicitly provided.
515 if (news.archived !== undefined) {
516 yield* Repos.update({ owner: news.owner, repo: updated.name, archived: news.archived });
517 }
518
519 // Sync — topics are managed via a dedicated endpoint. The provided list
520 // fully replaces existing topics, so removing the field (defined -> undefined)
521 // must clear them. Use the confirmed post-rename name from the first PATCH.
522 if (news.topics !== undefined || olds?.topics !== undefined) {
523 yield* Repos.replaceAllTopics({
524 owner: news.owner,
525 repo: updated.name,
526 names: news.topics ?? [],
527 });
528 }
529
530 return attrsOf(updated);
531 },
532 (effect, { news }) => effect.pipe(withBaseUrl(news.baseUrl)),
533 ),
534
535 // Enumerate every repository the authenticated token can see. GitHub has no
536 // account/region scope resolved from env services — the ambient scope is the
537 // token itself, so we list the authenticated user's repositories (across all
538 // owners/orgs the token is a member of), every page. Each list item is a
539 // full repository object, so it hydrates directly into the same
540 // `Attributes` shape `read` returns.
541 list: Effect.fn(function* () {
542 const repos = yield* Stream.runCollect(
543 Repos.listForAuthenticatedUser.items({ per_page: 100 }),
544 );
545 return repos.map(attrsOf);
546 }),
547
548 // Read by the numeric repository ID, which is stable across renames. This
549 // refreshes the output attributes (including the current name) so that a
550 // subsequent delete targets the live repository even when a prior rename's
551 // state persistence failed.
552 read: Effect.fn(
553 function* ({ output }) {
554 if (output === undefined) {
555 return undefined;
556 }
557 return yield* Repos.getById({ id: output.repoId }).pipe(
558 Effect.map(attrsOf),
559 Effect.catchTag("NotFound", () => Effect.undefined),
560 );
561 },
562 (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)),
563 ),
564
565 delete: Effect.fn(
566 function* ({ olds, output }) {
567 // Resolve the current repository name via the stable numeric ID. A rename
568 // whose state persistence failed leaves `olds.name` stale; deleting by
569 // the stale name 404s and silently leaves the repo behind. Looking it up
570 // by `repoId` gives us the live name.
571 const current =
572 output?.repoId !== undefined
573 ? yield* Repos.getById({ id: output.repoId }).pipe(
574 Effect.catchTag("NotFound", () => Effect.undefined),
575 )
576 : undefined;
577
578 yield* Repos.Delete({
579 owner: current?.owner.login ?? olds.owner,
580 repo: current?.name ?? olds.name,
581 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
582 },
583 (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)),
584 ),
585 });
586
587 const attrsOf = (data: {
588 id: number;
589 node_id: string;
590 full_name: string;
591 html_url: string;
592 git_url: string;
593 ssh_url: string;
594 clone_url: string;
595 default_branch: string;
596 created_at: string | null;
597 updated_at: string | null;
598 }) => ({
599 repoId: data.id,
600 nodeId: data.node_id,
601 fullName: data.full_name,
602 htmlUrl: data.html_url,
603 gitUrl: data.git_url,
604 sshUrl: data.ssh_url,
605 cloneUrl: data.clone_url,
606 defaultBranch: data.default_branch,
607 createdAt: data.created_at ?? new Date().toISOString(),
608 updatedAt: data.updated_at ?? new Date().toISOString(),
609 });