The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import * as cloudasset from "@distilled.cloud/gcp/cloudasset_v1"; |
| 2 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 3 | import * as pubsub from "@distilled.cloud/gcp/pubsub_v1"; |
| 4 | import * as serviceusage from "@distilled.cloud/gcp/unstable/serviceusage_v1beta1"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { alchemyLabelKeys, hasAlchemyLabels } from "../Labels.ts"; |
| 10 | import { waitForOperation } from "../Operation.ts"; |
| 11 | |
| 12 | export const MAX_ID_LENGTH = 63; |
| 13 | export const MAX_SAVED_QUERY_DESCRIPTION = 255; |
| 14 | export const NO_OP_EXPRESSION = "true"; |
| 15 | export const PUBLISHER_ROLE = "roles/pubsub.publisher"; |
| 16 | |
| 17 | export const lastSegment = (value: string) => { |
| 18 | const trimmed = value.replace(/\/+$/, ""); |
| 19 | const parts = trimmed.split("/"); |
| 20 | return parts[parts.length - 1] || trimmed; |
| 21 | }; |
| 22 | |
| 23 | export const parentOf = (name: string, collection: string) => { |
| 24 | const parts = name.split("/").filter((part) => part.length > 0); |
| 25 | const at = parts.lastIndexOf(collection); |
| 26 | return at > 0 ? parts.slice(0, at).join("/") : parts.slice(0, -1).join("/"); |
| 27 | }; |
| 28 | |
| 29 | export const projectParent = (project: string) => `projects/${project}`; |
| 30 | |
| 31 | /** Cloud Asset get/delete names require a numeric project, folder, or org. */ |
| 32 | export const scopeParent = (project: string, explicit?: string) => |
| 33 | Effect.gen(function* () { |
| 34 | if (explicit !== undefined && explicit.length > 0) { |
| 35 | if (!explicit.startsWith("projects/")) return explicit.replace(/\/+$/, ""); |
| 36 | const id = lastSegment(explicit); |
| 37 | if (/^\d+$/.test(id)) return `projects/${id}`; |
| 38 | const number = yield* projectNumberOf(id); |
| 39 | return `projects/${number}`; |
| 40 | } |
| 41 | const number = yield* projectNumberOf(project); |
| 42 | return `projects/${number}`; |
| 43 | }); |
| 44 | |
| 45 | export const rfc1035 = (name: string, maxLength = MAX_ID_LENGTH): string => { |
| 46 | let next = name |
| 47 | .toLowerCase() |
| 48 | .replace(/[^a-z0-9-]/g, "-") |
| 49 | .replace(/-+/g, "-") |
| 50 | .replace(/^-+|-+$/g, ""); |
| 51 | if (!/^[a-z]/.test(next)) next = `a${next}`; |
| 52 | next = next.slice(0, maxLength).replace(/-+$/g, ""); |
| 53 | if (next.length < 4) next = `${next}feed`.slice(0, maxLength); |
| 54 | if (next.length === 0) return "feed"; |
| 55 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, maxLength - 1)}0`; |
| 56 | return next.slice(0, maxLength); |
| 57 | }; |
| 58 | |
| 59 | export const toPhysicalId = ( |
| 60 | id: string, |
| 61 | explicit: string | undefined, |
| 62 | existing: string | undefined, |
| 63 | maxLength = MAX_ID_LENGTH, |
| 64 | ) => |
| 65 | Effect.gen(function* () { |
| 66 | if (explicit !== undefined) return rfc1035(explicit, maxLength); |
| 67 | if (existing !== undefined) return existing; |
| 68 | return rfc1035(yield* createPhysicalName({ id, maxLength, lowercase: true }), maxLength); |
| 69 | }); |
| 70 | |
| 71 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 72 | (left ?? "") === (right ?? ""); |
| 73 | |
| 74 | export const sortedStrings = (values: readonly string[] | undefined) => |
| 75 | [...(values ?? [])].slice().sort(); |
| 76 | |
| 77 | export const sameStringList = ( |
| 78 | left: readonly string[] | undefined, |
| 79 | right: readonly string[] | undefined, |
| 80 | ) => JSON.stringify(sortedStrings(left)) === JSON.stringify(sortedStrings(right)); |
| 81 | |
| 82 | const canonical = (value: unknown): unknown => { |
| 83 | if (value === undefined || value === null) return undefined; |
| 84 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 85 | if (typeof value === "string") return value.length === 0 ? undefined : value; |
| 86 | if (Array.isArray(value)) { |
| 87 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 88 | return items.length === 0 ? undefined : items; |
| 89 | } |
| 90 | if (typeof value === "object") { |
| 91 | const entries = Object.entries(value as Record<string, unknown>) |
| 92 | .map(([key, item]) => [key, canonical(item)] as const) |
| 93 | .filter(([, item]) => item !== undefined) |
| 94 | .sort(([left], [right]) => left.localeCompare(right)); |
| 95 | if (entries.length === 0) return undefined; |
| 96 | return Object.fromEntries(entries); |
| 97 | } |
| 98 | return undefined; |
| 99 | }; |
| 100 | |
| 101 | export const sameJson = (left: unknown, right: unknown) => |
| 102 | JSON.stringify(canonical(left) ?? null) === JSON.stringify(canonical(right) ?? null); |
| 103 | |
| 104 | export const updateMaskOf = (...fields: Array<string | undefined>) => |
| 105 | fields.filter((field): field is string => field !== undefined).join(","); |
| 106 | |
| 107 | export const encodeDescription = ( |
| 108 | labels: Record<string, string>, |
| 109 | description: string | undefined, |
| 110 | maxLength?: number, |
| 111 | ): string => { |
| 112 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 113 | const combined = description && description.length > 0 ? `${marker}\n${description}` : marker; |
| 114 | return maxLength !== undefined ? combined.slice(0, maxLength) : combined; |
| 115 | }; |
| 116 | |
| 117 | export const parseDescription = ( |
| 118 | description: string | undefined, |
| 119 | ): { |
| 120 | labels: Record<string, string>; |
| 121 | description: string | undefined; |
| 122 | } => { |
| 123 | if (!description?.startsWith("[alchemy ")) { |
| 124 | return { labels: {}, description }; |
| 125 | } |
| 126 | const end = description.indexOf("]"); |
| 127 | if (end < 0) return { labels: {}, description }; |
| 128 | const labels: Record<string, string> = {}; |
| 129 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 130 | const eq = part.indexOf("="); |
| 131 | if (eq > 0) { |
| 132 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 133 | } |
| 134 | } |
| 135 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 136 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 137 | }; |
| 138 | |
| 139 | export const hasOwnershipMarker = (description: string | undefined) => |
| 140 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 141 | |
| 142 | export const ownedByAlchemy = (id: string, description: string | undefined) => |
| 143 | Effect.gen(function* () { |
| 144 | const { labels } = parseDescription(description); |
| 145 | return yield* hasAlchemyLabels(id, labels); |
| 146 | }); |
| 147 | |
| 148 | export const replaceOn = (previous: string | undefined, next: string | undefined) => |
| 149 | previous !== undefined && next !== undefined && previous !== next |
| 150 | ? ({ action: "replace" as const, deleteFirst: false } as const) |
| 151 | : undefined; |
| 152 | |
| 153 | export const collectPages = <Page, A, E, R>( |
| 154 | pages: Stream.Stream<Page, E, R>, |
| 155 | items: (page: Page) => readonly A[] | undefined, |
| 156 | ) => |
| 157 | pages.pipe( |
| 158 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 159 | Stream.runCollect, |
| 160 | Effect.map((chunk) => Array.from(chunk)), |
| 161 | ); |
| 162 | |
| 163 | export const topicResource = (topic: string, project: string) => |
| 164 | topic.includes("/") ? topic : `projects/${project}/topics/${topic}`; |
| 165 | |
| 166 | export const projectNumberOf = (project: string) => |
| 167 | resourcemanager.getProjects({ name: `projects/${project}` }).pipe( |
| 168 | Effect.map((resource) => { |
| 169 | const number = lastSegment(resource.name ?? ""); |
| 170 | return /^\d+$/.test(number) ? number : project; |
| 171 | }), |
| 172 | ); |
| 173 | |
| 174 | /** |
| 175 | * The Cloud Asset service agent (`service-{number}@gcp-sa-cloudasset…`) is |
| 176 | * created lazily by Google — on a fresh project it does not exist until |
| 177 | * something asks for it, and granting it a role fails with |
| 178 | * `IamMemberNotFound`. Generating the identity is idempotent. |
| 179 | */ |
| 180 | const ensureCloudAssetServiceIdentity = (projectNumber: string) => |
| 181 | Effect.gen(function* () { |
| 182 | const operation = yield* serviceusage |
| 183 | .generateServiceIdentityServices({ |
| 184 | parent: `projects/${projectNumber}/services/cloudasset.googleapis.com`, |
| 185 | }) |
| 186 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 187 | if (operation === undefined) return; |
| 188 | yield* waitForOperation(operation, (name) => serviceusage.getOperations({ name }), { |
| 189 | budget: "2 minutes", |
| 190 | interval: "2 seconds", |
| 191 | }); |
| 192 | }); |
| 193 | |
| 194 | export const grantCloudAssetPublisher = (project: string, topic: string) => |
| 195 | Effect.gen(function* () { |
| 196 | const resource = topicResource(topic, project); |
| 197 | const projectNumber = yield* projectNumberOf(project); |
| 198 | yield* ensureCloudAssetServiceIdentity(projectNumber); |
| 199 | const member = `serviceAccount:service-${projectNumber}@gcp-sa-cloudasset.iam.gserviceaccount.com`; |
| 200 | yield* grantTopicPublisher(resource, member); |
| 201 | }); |
| 202 | |
| 203 | const grantTopicPublisher = (resource: string, member: string) => |
| 204 | Effect.gen(function* () { |
| 205 | const policy = yield* pubsub.getIamPolicyProjectsTopics({ resource }); |
| 206 | const bindings = (policy.bindings ?? []).map((binding) => ({ |
| 207 | ...binding, |
| 208 | members: [...(binding.members ?? [])], |
| 209 | })); |
| 210 | const publisher = bindings.find((binding) => binding.role === PUBLISHER_ROLE); |
| 211 | if (publisher?.members?.includes(member)) return; |
| 212 | if (publisher) { |
| 213 | publisher.members = [...(publisher.members ?? []), member]; |
| 214 | } else { |
| 215 | bindings.push({ role: PUBLISHER_ROLE, members: [member] }); |
| 216 | } |
| 217 | yield* pubsub.setIamPolicyProjectsTopics({ |
| 218 | resource, |
| 219 | body: { policy: { ...policy, bindings } }, |
| 220 | }); |
| 221 | }).pipe( |
| 222 | Effect.retry({ |
| 223 | // IamMemberNotFound: a just-generated service agent takes a few |
| 224 | // seconds to become visible to IAM. |
| 225 | while: (error) => error._tag === "Conflict" || error._tag === "IamMemberNotFound", |
| 226 | times: 8, |
| 227 | schedule: Schedule.spaced("2 seconds"), |
| 228 | }), |
| 229 | ); |
| 230 | |
| 231 | /** `feeds.list` is unpaginated: it returns every feed under the parent. */ |
| 232 | export const listFeeds = (parent: string) => |
| 233 | cloudasset.listFeeds({ parent }).pipe(Effect.map((page) => page.feeds ?? [])); |
| 234 | |
| 235 | export const listSavedQueries = (parent: string) => |
| 236 | collectPages( |
| 237 | cloudasset.listSavedQueries.pages({ parent, pageSize: 100 }), |
| 238 | (page) => page.savedQueries, |
| 239 | ); |