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

main
ts 142 lines 4.8 KB
Raw
1 import * as firebase from "@distilled.cloud/gcp/firebase_v1beta1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Stream from "effect/Stream";
6 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
7 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
8
9 export const MAX_DISPLAY_NAME = 32;
10 export const MAX_PACKAGE_SUFFIX = 40;
11
12 export class ResourceNotResolved extends Data.TaggedError("GCP.Firebase.ResourceNotResolved")<{
13 resourceName: string;
14 }> {}
15
16 export const lastSegment = (value: string) => {
17 const trimmed = value.replace(/\/+$/, "");
18 const parts = trimmed.split("/");
19 return parts[parts.length - 1] || trimmed;
20 };
21
22 export const projectParent = (project: string) => `projects/${project}`;
23
24 export const encodeDisplayName = (
25 labels: Record<string, string>,
26 displayName: string | undefined,
27 ): string => {
28 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
29 const combined = displayName && displayName.length > 0 ? `${marker} ${displayName}` : marker;
30 return combined.slice(0, 1024);
31 };
32
33 export const parseDisplayName = (
34 displayName: string | undefined,
35 ): {
36 labels: Record<string, string>;
37 displayName: string | undefined;
38 } => {
39 if (!displayName?.startsWith("[alchemy ")) {
40 return { labels: {}, displayName };
41 }
42 const end = displayName.indexOf("]");
43 if (end < 0) return { labels: {}, displayName };
44 const labels: Record<string, string> = {};
45 for (const part of displayName.slice("[alchemy ".length, end).split(/\s+/)) {
46 const eq = part.indexOf("=");
47 if (eq > 0) {
48 labels[part.slice(0, eq)] = part.slice(eq + 1);
49 }
50 }
51 const rest = displayName.slice(end + 1).trim();
52 return { labels, displayName: rest.length > 0 ? rest : undefined };
53 };
54
55 export const hasOwnershipMarker = (displayName: string | undefined) =>
56 Object.keys(parseDisplayName(displayName).labels).some((key) => key.startsWith("alchemy-"));
57
58 export const ownedByAlchemy = (id: string, displayName: string | undefined) =>
59 Effect.gen(function* () {
60 const { labels } = parseDisplayName(displayName);
61 return yield* hasAlchemyLabels(id, labels);
62 });
63
64 export const toDisplayName = (id: string, explicit: string | undefined, existing?: string) =>
65 Effect.gen(function* () {
66 if (explicit !== undefined) return explicit;
67 if (existing !== undefined) return existing;
68 return yield* createPhysicalName({
69 id,
70 maxLength: MAX_DISPLAY_NAME,
71 lowercase: true,
72 });
73 });
74
75 export const ownedDisplayName = (
76 id: string,
77 requested: string | undefined,
78 existing: string | undefined,
79 ) =>
80 Effect.gen(function* () {
81 const labels = yield* createInternalLabels(id);
82 const user = yield* toDisplayName(id, requested, existing);
83 return encodeDisplayName(labels, user);
84 });
85
86 export const packageNameOf = (id: string, requested: string | undefined, existing?: string) =>
87 Effect.gen(function* () {
88 if (requested !== undefined) return requested;
89 if (existing !== undefined) return existing;
90 const suffix = yield* createPhysicalName({
91 id,
92 maxLength: MAX_PACKAGE_SUFFIX,
93 lowercase: true,
94 });
95 const cleaned = suffix.replace(/[^a-z0-9]/g, "");
96 return `com.alchemy.test.${cleaned || "app"}`;
97 });
98
99 /**
100 * Wait for a Firebase Management operation and return its final state
101 * (the created app name is in `response.name`). An operation that
102 * finished with `ALREADY_EXISTS` (6) is a lost create race. A freshly
103 * started operation can briefly read as NOT_FOUND; keep polling.
104 */
105 export const waitForOperation = (operation: firebase.Operation) => {
106 let latest = operation;
107 return waitForGcpOperation(
108 operation,
109 (name) =>
110 firebase.getOperations({ name }).pipe(
111 Effect.catchTag("NotFound", () =>
112 Effect.succeed<firebase.Operation>({ name, done: false }),
113 ),
114 Effect.tap((current) =>
115 Effect.sync(() => {
116 latest = current;
117 }),
118 ),
119 ),
120 { budget: "5 minutes" },
121 ).pipe(
122 Effect.map(() => latest),
123 Effect.catchIf(
124 (error) => error._tag === "GCP.OperationFailed" && error.code === 6,
125 () => Effect.succeed(latest),
126 ),
127 );
128 };
129
130 export const listAndroidApps = (project: string, showDeleted = false) =>
131 firebase.listProjectsAndroidApps
132 .pages({
133 parent: projectParent(project),
134 pageSize: 100,
135 showDeleted,
136 })
137 .pipe(
138 Stream.flatMap((page) => Stream.fromIterable(page.apps ?? [])),
139 Stream.runCollect,
140 Effect.map((chunk) => Array.from(chunk)),
141 Effect.catchTag("NotFound", () => Effect.succeed([] as firebase.AndroidApp[])),
142 );