The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as apigee from "@distilled.cloud/gcp/apigee_v1"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import { GcpEnvironment } from "../Environment.ts"; |
| 5 | import { alchemyLabelKeys, hasAlchemyLabels } from "../Labels.ts"; |
| 6 | |
| 7 | export const lastSegment = (value: string) => { |
| 8 | const trimmed = value.replace(/\/+$/, ""); |
| 9 | const parts = trimmed.split("/"); |
| 10 | return parts[parts.length - 1] || trimmed; |
| 11 | }; |
| 12 | |
| 13 | export const segmentAfter = (value: string, key: string) => { |
| 14 | const parts = value.split("/").filter((part) => part.length > 0); |
| 15 | const index = parts.lastIndexOf(key); |
| 16 | return index >= 0 && parts[index + 1] ? parts[index + 1]! : undefined; |
| 17 | }; |
| 18 | |
| 19 | export const stripRevision = (name: string) => { |
| 20 | const parts = name.split("/").filter((part) => part.length > 0); |
| 21 | const index = parts.lastIndexOf("revisions"); |
| 22 | return index >= 0 ? parts.slice(0, index).join("/") : name; |
| 23 | }; |
| 24 | |
| 25 | export const organizationIdOf = (value: string | undefined, project: string) => { |
| 26 | if (value === undefined || value.length === 0) return project; |
| 27 | return segmentAfter(value, "organizations") ?? lastSegment(value); |
| 28 | }; |
| 29 | |
| 30 | export const environmentIdOf = (value: string) => |
| 31 | segmentAfter(value, "environments") ?? lastSegment(value); |
| 32 | |
| 33 | export const organizationNameOf = (organizationId: string) => `organizations/${organizationId}`; |
| 34 | |
| 35 | export const environmentNameOf = (organizationId: string, environmentId: string) => |
| 36 | `organizations/${organizationId}/environments/${environmentId}`; |
| 37 | |
| 38 | export const parseOrgEnv = (name: string) => ({ |
| 39 | organizationId: segmentAfter(name, "organizations") ?? "", |
| 40 | environmentId: segmentAfter(name, "environments") ?? "", |
| 41 | }); |
| 42 | |
| 43 | export const missingToUndefined = <A, E extends { readonly _tag: string }, R>( |
| 44 | effect: Effect.Effect<A, E, R>, |
| 45 | ) => |
| 46 | effect.pipe( |
| 47 | Effect.catchIf( |
| 48 | ( |
| 49 | error, |
| 50 | ): error is E & { |
| 51 | readonly _tag: "NotFound" | "ApigeeResourceNotFound"; |
| 52 | } => error._tag === "NotFound" || error._tag === "ApigeeResourceNotFound", |
| 53 | () => Effect.succeed(undefined as A | undefined), |
| 54 | ), |
| 55 | ); |
| 56 | |
| 57 | export const emptyOnMissing = <A, E extends { readonly _tag: string }, R>( |
| 58 | effect: Effect.Effect<A, E, R>, |
| 59 | empty: A, |
| 60 | ) => |
| 61 | effect.pipe( |
| 62 | Effect.catchIf( |
| 63 | ( |
| 64 | error, |
| 65 | ): error is E & { |
| 66 | readonly _tag: "NotFound" | "ApigeeResourceNotFound"; |
| 67 | } => error._tag === "NotFound" || error._tag === "ApigeeResourceNotFound", |
| 68 | () => Effect.succeed(empty), |
| 69 | ), |
| 70 | ); |
| 71 | |
| 72 | export const deployedConfig = (parent: string) => |
| 73 | missingToUndefined( |
| 74 | apigee.getDeployedConfigOrganizationsEnvironments({ |
| 75 | name: `${parent}/deployedConfig`, |
| 76 | }), |
| 77 | ); |
| 78 | |
| 79 | export const namesFromConfig = (items: readonly { name?: string }[] | undefined): string[] => |
| 80 | (items ?? []) |
| 81 | .map((item) => item.name) |
| 82 | .filter((name): name is string => typeof name === "string" && name.length > 0) |
| 83 | .map((name) => lastSegment(stripRevision(name))); |
| 84 | |
| 85 | export const toResourceId = ( |
| 86 | id: string, |
| 87 | explicit: string | undefined, |
| 88 | existing: string | undefined, |
| 89 | options?: { maxLength?: number; rfc1035?: boolean }, |
| 90 | ) => |
| 91 | Effect.gen(function* () { |
| 92 | if (explicit !== undefined) return explicit; |
| 93 | if (existing !== undefined) return existing; |
| 94 | const maxLength = options?.maxLength ?? 63; |
| 95 | const generated = yield* createPhysicalName({ |
| 96 | id, |
| 97 | maxLength, |
| 98 | lowercase: true, |
| 99 | }); |
| 100 | if (options?.rfc1035 !== true) return generated; |
| 101 | let next = generated |
| 102 | .toLowerCase() |
| 103 | .replace(/[^a-z0-9-]/g, "-") |
| 104 | .replace(/-+/g, "-") |
| 105 | .replace(/^-+/, "") |
| 106 | .replace(/-+$/, ""); |
| 107 | if (!/^[a-z]/.test(next)) next = `a${next}`; |
| 108 | next = next.slice(0, maxLength).replace(/-+$/, ""); |
| 109 | return next.length > 0 ? next : "resource"; |
| 110 | }); |
| 111 | |
| 112 | export const encodeDescription = ( |
| 113 | labels: Record<string, string>, |
| 114 | description: string | undefined, |
| 115 | ): string => { |
| 116 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 117 | return description ? `${marker}\n${description}` : marker; |
| 118 | }; |
| 119 | |
| 120 | export const parseDescription = ( |
| 121 | description: string | undefined, |
| 122 | ): { |
| 123 | labels: Record<string, string>; |
| 124 | description: string | undefined; |
| 125 | } => { |
| 126 | if (!description?.startsWith("[alchemy ")) { |
| 127 | return { labels: {}, description }; |
| 128 | } |
| 129 | const end = description.indexOf("]"); |
| 130 | if (end < 0) return { labels: {}, description }; |
| 131 | const labels: Record<string, string> = {}; |
| 132 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 133 | const eq = part.indexOf("="); |
| 134 | if (eq > 0) { |
| 135 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 136 | } |
| 137 | } |
| 138 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 139 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 140 | }; |
| 141 | |
| 142 | export const hasOwnershipMarker = (description: string | undefined) => |
| 143 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 144 | |
| 145 | export const ownedById = (id: string, labels: Record<string, string>) => |
| 146 | hasAlchemyLabels(id, labels); |
| 147 | |
| 148 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 149 | (left ?? "") === (right ?? ""); |
| 150 | |
| 151 | export const sameList = ( |
| 152 | left: readonly string[] | undefined, |
| 153 | right: readonly string[] | undefined, |
| 154 | ) => [...(left ?? [])].sort().join("\0") === [...(right ?? [])].sort().join("\0"); |
| 155 | |
| 156 | export type ProjectEnvironment = { |
| 157 | organizationId: string; |
| 158 | environmentId: string; |
| 159 | parent: string; |
| 160 | }; |
| 161 | |
| 162 | export const listProjectEnvironments = Effect.fn(function* () { |
| 163 | const env = yield* GcpEnvironment.current; |
| 164 | const page = yield* emptyOnMissing(apigee.listOrganizations({ parent: "organizations" }), { |
| 165 | organizations: [] as apigee.GoogleCloudApigeeV1OrganizationProjectMappingList, |
| 166 | }); |
| 167 | const mappings = (page.organizations ?? []).filter( |
| 168 | (mapping) => |
| 169 | mapping.projectId === env.project || (mapping.projectIds ?? []).includes(env.project), |
| 170 | ); |
| 171 | const orgs = |
| 172 | mappings.length > 0 ? mappings : [{ organization: env.project, projectId: env.project }]; |
| 173 | const found: ProjectEnvironment[] = []; |
| 174 | for (const mapping of orgs) { |
| 175 | const organizationId = mapping.organization ?? env.project; |
| 176 | const organization = yield* missingToUndefined( |
| 177 | apigee.getOrganizations({ |
| 178 | name: organizationNameOf(organizationId), |
| 179 | }), |
| 180 | ); |
| 181 | const environments = organization?.environments ?? []; |
| 182 | for (const environmentId of environments) { |
| 183 | if (!environmentId) continue; |
| 184 | found.push({ |
| 185 | organizationId, |
| 186 | environmentId, |
| 187 | parent: environmentNameOf(organizationId, environmentId), |
| 188 | }); |
| 189 | } |
| 190 | } |
| 191 | return found; |
| 192 | }); |
| 193 | |
| 194 | export const listNameArray = (values: readonly string[] | undefined): string[] => |
| 195 | (values ?? []).filter((value) => typeof value === "string" && value.length > 0); |
| 196 | |
| 197 | export const namesFromListPayload = (payload: unknown): string[] => { |
| 198 | if (Array.isArray(payload)) { |
| 199 | return payload.flatMap((item) => |
| 200 | typeof item === "string" |
| 201 | ? [item] |
| 202 | : item && typeof item === "object" && "name" in item |
| 203 | ? typeof (item as { name?: unknown }).name === "string" |
| 204 | ? [(item as { name: string }).name] |
| 205 | : [] |
| 206 | : [], |
| 207 | ); |
| 208 | } |
| 209 | if (payload && typeof payload === "object") { |
| 210 | for (const key of [ |
| 211 | "keystores", |
| 212 | "aliases", |
| 213 | "keyvaluemaps", |
| 214 | "references", |
| 215 | "targetServers", |
| 216 | "targetservers", |
| 217 | "values", |
| 218 | ] as const) { |
| 219 | const value = (payload as Record<string, unknown>)[key]; |
| 220 | if (Array.isArray(value)) return namesFromListPayload(value); |
| 221 | } |
| 222 | } |
| 223 | return []; |
| 224 | }; |