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

main
ts 69 lines 2.22 KB
Raw
1 import { listProjectBranches } from "@distilled.cloud/neon";
2 import type { Input } from "alchemy/Input";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5
6 /** Select an explicit branch or the project's current default branch, never both. */
7 export type BranchScope =
8 | {
9 /** Branch resource or explicit branch identity. */
10 branch: { projectId: string; branchId: string };
11 project?: never;
12 }
13 | {
14 /** Project whose default branch is selected at reconciliation time. */
15 project: { projectId: string };
16 branch?: never;
17 };
18
19 export interface ResolvedBranchScope {
20 /** Neon project ID. */
21 projectId: string;
22 /** Neon branch ID. */
23 branchId: string;
24 }
25
26 export class InvalidBranchScope extends Data.TaggedError("InvalidBranchScope")<{
27 message: string;
28 }> {}
29
30 /** Resolve lifecycle props after Alchemy has resolved resource references. */
31 export const resolveBranchScope = Effect.fn(function* (scope: Input.Resolve<BranchScope>) {
32 if ((scope.branch !== undefined) === (scope.project !== undefined)) {
33 return yield* new InvalidBranchScope({
34 message: "Specify exactly one of branch or project",
35 });
36 }
37 if (scope.branch !== undefined) {
38 const { projectId, branchId } = scope.branch;
39 if (!projectId || !branchId) {
40 return yield* new InvalidBranchScope({
41 message: "Branch requires projectId and branchId",
42 });
43 }
44 return { projectId, branchId };
45 }
46 const projectId = scope.project?.projectId;
47 if (!projectId) {
48 return yield* new InvalidBranchScope({
49 message: "Project requires projectId",
50 });
51 }
52 let cursor: string | undefined;
53 const seen = new Set<string>();
54 do {
55 const page = yield* listProjectBranches({ project_id: projectId, cursor });
56 const branch = page.branches.find((branch) => branch.default);
57 if (branch) return { projectId, branchId: branch.id };
58 cursor = page.pagination?.next;
59 if (cursor && seen.has(cursor)) {
60 return yield* new InvalidBranchScope({
61 message: "Branch pagination repeated a cursor",
62 });
63 }
64 if (cursor) seen.add(cursor);
65 } while (cursor);
66 return yield* new InvalidBranchScope({
67 message: `Project ${projectId} has no default branch`,
68 });
69 });