The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { PrismaApiError } from "@alchemy.run/prisma/Client"; |
| 2 | import { Credentials, fromApiToken } from "@distilled.cloud/prisma"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as HttpBody from "effect/http/HttpBody"; |
| 5 | import * as HttpClient from "effect/http/HttpClient"; |
| 6 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Redacted from "effect/Redacted"; |
| 9 | import * as Result from "effect/Result"; |
| 10 | |
| 11 | /** |
| 12 | * An in-memory Prisma Management API served over a fake `HttpClient`. |
| 13 | * |
| 14 | * This is `test/Prisma/Client.test.ts`'s harness (its `Captured` log, |
| 15 | * `HttpClient.make` stub, `HttpBody` decoding, and `json`/`data`/`page` |
| 16 | * helpers) lifted into a fixture so provider suites can share it. The only |
| 17 | * change is that the `fixtureResponse` if-chain is supplied by the caller |
| 18 | * instead of being hard-coded, which lets each suite declare exactly the |
| 19 | * routes the resources under test call — resource files migrate to distilled |
| 20 | * ops one dispatch at a time, so route coverage grows with them. |
| 21 | * |
| 22 | * The provider tests used to inject a fake `PrismaManagementClient`. Resource |
| 23 | * files calling generated distilled operations bypass that seam, so the fake |
| 24 | * moves one layer down and speaks the wire instead. Tests therefore exercise |
| 25 | * distilled's schema decoding and its status-to-tag matching, which the |
| 26 | * client-level fake never touched. |
| 27 | */ |
| 28 | |
| 29 | export const FAKE_API_BASE_URL = "https://api.prisma.test"; |
| 30 | |
| 31 | /** Shape of a captured request, as in `Client.test.ts`. */ |
| 32 | export interface Captured { |
| 33 | readonly url: string; |
| 34 | readonly method: string; |
| 35 | readonly pathname: string; |
| 36 | readonly search: string; |
| 37 | readonly authorization: string | undefined; |
| 38 | readonly bodyJson: unknown; |
| 39 | } |
| 40 | |
| 41 | export const json = (value: unknown, init?: ResponseInit) => |
| 42 | new Response(JSON.stringify(value), { |
| 43 | status: 200, |
| 44 | headers: { "content-type": "application/json" }, |
| 45 | ...init, |
| 46 | }); |
| 47 | |
| 48 | /** `{ data }` — the Management API's single-resource envelope. */ |
| 49 | export const data = <T>(value: T, init?: ResponseInit) => json({ data: value }, init); |
| 50 | |
| 51 | /** `{ data, pagination }` — the Management API's list envelope. */ |
| 52 | export const page = <T>( |
| 53 | items: ReadonlyArray<T>, |
| 54 | hasMore = false, |
| 55 | nextCursor: string | null = null, |
| 56 | ) => json({ data: items, pagination: { hasMore, nextCursor } }); |
| 57 | |
| 58 | /** `204 No Content` — the Management API's delete responses. */ |
| 59 | export const noContent = () => new Response(null, { status: 204 }); |
| 60 | |
| 61 | /** `{ error: { code, message } }` with a real status code. */ |
| 62 | export const failure = (status: number, code: string, message: string, hint?: string) => |
| 63 | json({ error: hint === undefined ? { code, message } : { code, message, hint } }, { status }); |
| 64 | |
| 65 | export const notFound = (message = "Not found") => failure(404, "not_found", message); |
| 66 | |
| 67 | export const conflict = (message = "Already exists") => failure(409, "already_exists", message); |
| 68 | |
| 69 | export const badRequest = (message = "Invalid request") => failure(400, "bad_request", message); |
| 70 | |
| 71 | export interface FakeManagementApi { |
| 72 | /** Fake transport plus the credentials the generated operations resolve. */ |
| 73 | readonly layer: Layer.Layer<HttpClient.HttpClient | Credentials>; |
| 74 | /** Every request the fake served, in order. */ |
| 75 | readonly captured: Captured[]; |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * Build the fake from a `fixtureResponse`-style function: match on |
| 80 | * `request.method` / `request.pathname` and return a `Response`, exactly as |
| 81 | * `Client.test.ts` does. An unmatched request should return a failing status |
| 82 | * so the test fails loudly rather than proceeding on something plausible. |
| 83 | */ |
| 84 | export const makeFakeManagementApi = ( |
| 85 | fixtureResponse: (request: Captured) => Response, |
| 86 | ): FakeManagementApi => { |
| 87 | const captured: Captured[] = []; |
| 88 | |
| 89 | const client = HttpClient.make((request) => |
| 90 | Effect.sync(() => { |
| 91 | const url = new URL(request.url); |
| 92 | const body = request.body as HttpBody.HttpBody; |
| 93 | const bodyText = body._tag === "Uint8Array" ? new TextDecoder().decode(body.body) : ""; |
| 94 | const entry: Captured = { |
| 95 | url: request.url, |
| 96 | method: request.method, |
| 97 | pathname: url.pathname, |
| 98 | search: url.search, |
| 99 | authorization: request.headers.authorization, |
| 100 | bodyJson: bodyText ? JSON.parse(bodyText) : undefined, |
| 101 | }; |
| 102 | captured.push(entry); |
| 103 | return HttpClientResponse.fromWeb(request, fixtureResponse(entry)); |
| 104 | }), |
| 105 | ); |
| 106 | |
| 107 | return { |
| 108 | layer: Layer.mergeAll( |
| 109 | Layer.succeed(HttpClient.HttpClient, client), |
| 110 | fromApiToken({ |
| 111 | apiToken: Redacted.make("fake-service-token"), |
| 112 | apiBaseUrl: FAKE_API_BASE_URL, |
| 113 | }), |
| 114 | ), |
| 115 | captured, |
| 116 | }; |
| 117 | }; |
| 118 | |
| 119 | /** |
| 120 | * The catch-all arm of a suite's `fixtureResponse`, as in `Client.test.ts`. |
| 121 | * |
| 122 | * Deliberately a 400: an unregistered route is a harness bug and must fail |
| 123 | * the test immediately. A 5xx would be a transient category, so the retry |
| 124 | * policy would replay it eight times before surfacing anything. |
| 125 | */ |
| 126 | export const unhandled = (request: Captured) => |
| 127 | json( |
| 128 | { |
| 129 | error: { |
| 130 | code: "unhandled", |
| 131 | message: `Unhandled fixture request ${request.method} ${request.pathname}${request.search}`, |
| 132 | }, |
| 133 | }, |
| 134 | { status: 400 }, |
| 135 | ); |
| 136 | |
| 137 | /** `METHOD /path` for every request served, for call-order assertions. */ |
| 138 | export const routesOf = (captured: ReadonlyArray<Captured>) => |
| 139 | captured.map((request) => `${request.method} ${request.pathname}`); |
| 140 | |
| 141 | /** |
| 142 | * Adapter plumbing for suites whose route table is still expressed as |
| 143 | * client-shaped handlers. |
| 144 | * |
| 145 | * Those suites declare a plain object of synchronous `Effect` handlers and |
| 146 | * map them onto the wire. Every suite used to carry its own copy of this |
| 147 | * dispatch code, which drifted; it lives here instead, so all of them agree |
| 148 | * on how a handler's result becomes a response and on what a missing handler |
| 149 | * does. |
| 150 | */ |
| 151 | |
| 152 | /** Run a synchronous fixture handler and capture its success or failure. */ |
| 153 | export const runHandler = (effect: Effect.Effect<any, any>) => |
| 154 | Effect.runSync(Effect.result(effect)); |
| 155 | |
| 156 | /** |
| 157 | * Injected `PrismaApiError`s keep their real status; anything else becomes a |
| 158 | * 400 — never a 5xx, whose transient category the retry policy would replay. |
| 159 | */ |
| 160 | const errorResponse = (error: unknown): Response => |
| 161 | error instanceof PrismaApiError |
| 162 | ? failure(error.status, "error", error.message) |
| 163 | : failure(400, "error", String(error)); |
| 164 | |
| 165 | /** A handler's result on the wire; `undefined` reads as a 404. */ |
| 166 | export const asResponse = ( |
| 167 | outcome: ReturnType<typeof runHandler>, |
| 168 | wrap: (value: unknown) => Response, |
| 169 | ): Response => |
| 170 | Result.isFailure(outcome) |
| 171 | ? errorResponse(outcome.failure) |
| 172 | : outcome.success === undefined |
| 173 | ? notFound("not found") |
| 174 | : wrap(outcome.success); |
| 175 | |
| 176 | /** A delete handler's result on the wire: `204`, or the injected failure. */ |
| 177 | export const voidResponse = (outcome: ReturnType<typeof runHandler>): Response => |
| 178 | Result.isFailure(outcome) ? errorResponse(outcome.failure) : noContent(); |
| 179 | |
| 180 | export interface HandlerDispatch { |
| 181 | /** Call a handler and envelope its value; a missing handler is `unhandled`. */ |
| 182 | readonly call: ( |
| 183 | handler: unknown, |
| 184 | args: ReadonlyArray<unknown>, |
| 185 | wrap?: (value: unknown) => Response, |
| 186 | ) => Response; |
| 187 | /** Same, for the delete routes that answer `204`. */ |
| 188 | readonly callVoid: (handler: unknown, args: ReadonlyArray<unknown>) => Response; |
| 189 | /** The `{ data, pagination }` wrap for list routes. */ |
| 190 | readonly list: (value: unknown) => Response; |
| 191 | } |
| 192 | |
| 193 | /** |
| 194 | * Bind the dispatch helpers to one captured request. Every verb — DELETE |
| 195 | * included — routes through here, so a route whose handler the suite never |
| 196 | * stubbed returns the diagnosable `unhandled` 400 instead of throwing. |
| 197 | */ |
| 198 | export const dispatchTo = (request: Captured): HandlerDispatch => ({ |
| 199 | call: (handler, args, wrap = (value) => data(value)) => |
| 200 | typeof handler === "function" |
| 201 | ? asResponse(runHandler((handler as any)(...args)), wrap) |
| 202 | : unhandled(request), |
| 203 | callVoid: (handler, args) => |
| 204 | typeof handler === "function" |
| 205 | ? voidResponse(runHandler((handler as any)(...args))) |
| 206 | : unhandled(request), |
| 207 | list: (value) => page(value as unknown[]), |
| 208 | }); |
| 209 | |
| 210 | /** |
| 211 | * Wire-shaped payload builders. |
| 212 | * |
| 213 | * Distilled decodes every response against the generated schema, so a fake |
| 214 | * payload has to carry the fields the API really returns — including the |
| 215 | * deprecated ones the create routes still send (`apiKeys`, |
| 216 | * `connectionString`, `directConnection`). These builders supply that |
| 217 | * skeleton so suites only state what the assertion cares about. |
| 218 | */ |
| 219 | |
| 220 | const REF_BASE = `${FAKE_API_BASE_URL}/v1`; |
| 221 | |
| 222 | const ref = (collection: string, id: string, name: string) => ({ |
| 223 | id, |
| 224 | url: `${REF_BASE}/${collection}/${id}`, |
| 225 | name, |
| 226 | }); |
| 227 | |
| 228 | export const WIRE_CREATED_AT = "2024-01-01T00:00:00.000Z"; |
| 229 | |
| 230 | export interface WireProjectOptions { |
| 231 | readonly id?: string; |
| 232 | readonly name?: string; |
| 233 | readonly logicalId?: string | null; |
| 234 | readonly defaultRegion?: string | null; |
| 235 | readonly workspaceId?: string; |
| 236 | readonly createdAt?: string; |
| 237 | } |
| 238 | |
| 239 | export const wireProject = (options: WireProjectOptions = {}) => { |
| 240 | const id = options.id ?? "project-1"; |
| 241 | return { |
| 242 | id, |
| 243 | type: "project", |
| 244 | url: `${REF_BASE}/projects/${id}`, |
| 245 | name: options.name ?? "app", |
| 246 | logicalId: options.logicalId ?? null, |
| 247 | createdAt: options.createdAt ?? WIRE_CREATED_AT, |
| 248 | defaultRegion: options.defaultRegion === undefined ? "us-east-1" : options.defaultRegion, |
| 249 | workspace: ref("workspaces", options.workspaceId ?? "workspace-1", "team"), |
| 250 | }; |
| 251 | }; |
| 252 | |
| 253 | export interface WireConnectionOptions { |
| 254 | readonly id?: string; |
| 255 | readonly name?: string; |
| 256 | readonly databaseId?: string; |
| 257 | readonly databaseName?: string; |
| 258 | readonly directConnectionString?: string; |
| 259 | readonly pooledConnectionString?: string; |
| 260 | } |
| 261 | |
| 262 | export const wireConnection = (options: WireConnectionOptions = {}) => { |
| 263 | const id = options.id ?? "connection-1"; |
| 264 | return { |
| 265 | id, |
| 266 | type: "connection", |
| 267 | url: `${REF_BASE}/connections/${id}`, |
| 268 | name: options.name ?? "default", |
| 269 | createdAt: WIRE_CREATED_AT, |
| 270 | kind: "postgres", |
| 271 | endpoints: { |
| 272 | direct: { |
| 273 | host: "db.prisma.test", |
| 274 | port: 5432, |
| 275 | ...(options.directConnectionString === undefined |
| 276 | ? {} |
| 277 | : { connectionString: options.directConnectionString }), |
| 278 | }, |
| 279 | ...(options.pooledConnectionString === undefined |
| 280 | ? {} |
| 281 | : { |
| 282 | pooled: { |
| 283 | host: "pool.prisma.test", |
| 284 | port: 5432, |
| 285 | connectionString: options.pooledConnectionString, |
| 286 | }, |
| 287 | }), |
| 288 | }, |
| 289 | database: ref("databases", options.databaseId ?? "database-1", options.databaseName ?? "main"), |
| 290 | }; |
| 291 | }; |
| 292 | |
| 293 | export interface WireDatabaseOptions { |
| 294 | readonly id?: string; |
| 295 | readonly name?: string; |
| 296 | readonly status?: "failure" | "provisioning" | "ready" | "recovering"; |
| 297 | readonly isDefault?: boolean; |
| 298 | readonly defaultConnectionId?: string | null; |
| 299 | readonly connections?: ReadonlyArray<ReturnType<typeof wireConnection>>; |
| 300 | readonly projectId?: string; |
| 301 | readonly projectName?: string; |
| 302 | readonly regionId?: string | null; |
| 303 | readonly branchId?: string | null; |
| 304 | } |
| 305 | |
| 306 | export const wireDatabase = (options: WireDatabaseOptions = {}) => { |
| 307 | const id = options.id ?? "database-1"; |
| 308 | const regionId = options.regionId === undefined ? "us-east-1" : options.regionId; |
| 309 | return { |
| 310 | id, |
| 311 | type: "database", |
| 312 | url: `${REF_BASE}/databases/${id}`, |
| 313 | name: options.name ?? "main", |
| 314 | status: options.status ?? "ready", |
| 315 | createdAt: WIRE_CREATED_AT, |
| 316 | isDefault: options.isDefault ?? false, |
| 317 | defaultConnectionId: options.defaultConnectionId ?? null, |
| 318 | connections: options.connections ?? [], |
| 319 | project: ref("projects", options.projectId ?? "project-1", options.projectName ?? "app"), |
| 320 | region: regionId === null ? null : { id: regionId, name: regionId }, |
| 321 | source: { type: "empty" }, |
| 322 | branchId: options.branchId ?? null, |
| 323 | }; |
| 324 | }; |
| 325 | |
| 326 | /** |
| 327 | * The create/restore routes additionally return the deprecated top-level |
| 328 | * credential fields; distilled's schema requires them. |
| 329 | */ |
| 330 | export const wireCreatedDatabase = (options: WireDatabaseOptions = {}) => ({ |
| 331 | ...wireDatabase(options), |
| 332 | apiKeys: [], |
| 333 | connectionString: "postgres://direct", |
| 334 | directConnection: { |
| 335 | host: "db.prisma.test", |
| 336 | user: "prisma", |
| 337 | pass: "secret", |
| 338 | }, |
| 339 | }); |