@executor-js/emulate 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +333 -3
- package/dist/api.js +125 -13
- package/dist/api.js.map +1 -1
- package/dist/{dist-YPRJYQHW.js → dist-FE2JWST3.js} +846 -234
- package/dist/dist-FE2JWST3.js.map +1 -0
- package/dist/{dist-K4CVTD6K.js → dist-KBZ6SM7D.js} +357 -12
- package/dist/dist-KBZ6SM7D.js.map +1 -0
- package/dist/{dist-RMPDKZUA.js → dist-OT6R2YO2.js} +440 -81
- package/dist/dist-OT6R2YO2.js.map +1 -0
- package/dist/{dist-WBKONLOE.js → dist-OVTPVMMW.js} +636 -165
- package/dist/dist-OVTPVMMW.js.map +1 -0
- package/dist/{dist-BTEY33DJ.js → dist-QXFWC3LV.js} +567 -75
- package/dist/dist-QXFWC3LV.js.map +1 -0
- package/dist/{dist-IYZPDKJW.js → dist-S47YJ552.js} +543 -43
- package/dist/dist-S47YJ552.js.map +1 -0
- package/dist/{dist-XM5HSBDC.js → dist-TWJXVA7X.js} +268 -30
- package/dist/dist-TWJXVA7X.js.map +1 -0
- package/dist/{dist-JJ2ZRCAX.js → dist-YXHZTLFR.js} +138 -7
- package/dist/dist-YXHZTLFR.js.map +1 -0
- package/dist/index.js +10 -10
- package/dist/index.js.map +1 -1
- package/package.json +4 -7
- package/dist/dist-BTEY33DJ.js.map +0 -1
- package/dist/dist-IYZPDKJW.js.map +0 -1
- package/dist/dist-JJ2ZRCAX.js.map +0 -1
- package/dist/dist-K4CVTD6K.js.map +0 -1
- package/dist/dist-RMPDKZUA.js.map +0 -1
- package/dist/dist-WBKONLOE.js.map +0 -1
- package/dist/dist-XM5HSBDC.js.map +0 -1
- package/dist/dist-YPRJYQHW.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../@emulators/core/src/store.ts","../../@emulators/core/src/http.ts","../../@emulators/core/src/webhooks.ts","../../@emulators/core/src/middleware/error-handler.ts","../../@emulators/core/src/middleware/auth.ts","../../@emulators/core/src/debug.ts","../../@emulators/core/src/fonts.ts","../../@emulators/core/src/ledger.ts","../../@emulators/core/src/manifest.ts","../../@emulators/core/src/ui.ts","../../@emulators/core/src/control-plane.ts","../../@emulators/core/src/server.ts","../../@emulators/core/src/service-host.ts","../../@emulators/core/src/middleware/pagination.ts","../../@emulators/core/src/oauth-helpers.ts","../../@emulators/core/src/persistence.ts","../src/registry.ts","../src/commands/start.ts","../src/portless.ts","../src/base-url.ts","../src/commands/init.ts","../src/commands/list.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { startCommand } from \"./commands/start.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { listCommand } from \"./commands/list.js\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nconst defaultPort = process.env.EMULATE_PORT ?? process.env.PORT ?? \"4000\";\n\nconst program = new Command();\n\nprogram\n .name(\"emulate\")\n .description(\"Local drop-in replacement services for CI and no-network sandboxes\")\n .version(pkg.version);\n\nprogram\n .command(\"start\", { isDefault: true })\n .description(\"Start the emulator server\")\n .option(\"-p, --port <port>\", \"Base port\", defaultPort)\n .option(\"-s, --service <services>\", \"Comma-separated services to enable\")\n .option(\"--seed <file>\", \"Path to seed config file\")\n .option(\"--base-url <url>\", \"Override advertised base URL (supports {service} template)\")\n .option(\"--portless\", \"Serve over HTTPS via portless (auto-registers aliases)\")\n .addHelpText(\n \"after\",\n `\n\nControl plane (under /_emulate on each service):\n GET /_emulate HTML landing page\n GET /_emulate/manifest machine-readable service manifest\n GET /_emulate/quickstart copy/paste getting-started snippet\n GET /_emulate/specs spec sources and coverage status\n GET /_emulate/coverage per-operation coverage and summary\n GET /_emulate/connections copyable SDK, CLI, env, and curl snippets\n GET /_emulate/openapi OpenAPI document (when supported)\n GET /_emulate/graphql GraphQL surface (when supported)\n GET /_emulate/mcp MCP surface (when supported)\n GET /_emulate/state current emulator state\n GET /_emulate/ledger request ledger (DELETE to clear)\n GET /_emulate/logs webhook deliveries and recent requests\n POST /_emulate/instances create an instance\n POST /_emulate/seed seed state\n POST /_emulate/reset reset state\n POST /_emulate/credentials mint a credential (bearer token, API key, or\n OAuth client, depending on the service's auth)\n\nGlobal catalog:\n GET /_emulate/services machine-readable catalog of every hosted service\n\n Use /_emulate/manifest and /_emulate/coverage to discover supported surfaces\n and honest coverage, /_emulate/credentials to create credentials,\n /_emulate/seed to load fixtures, and /_emulate/ledger to validate API calls.\n\nHosted services:\n All 13 services are available on emulators.dev: github, vercel, google, okta,\n microsoft, spotify, slack, apple, aws, resend, stripe, mongoatlas, clerk,\n x, workos, autumn.\n Service host: <service>.emulators.dev (useful without an instance; serves\n a service-level /_emulate control plane)\n Instance host: <service>.<instance>.emulators.dev\n Local/path form: <origin>/<service>/<instance>\n\n The apex emulators.dev is the catalog landing page that lists every emulator\n and links to its host. Per-service docs live at https://docs.emulators.dev/\n <service>.\n`,\n )\n .action(async (opts) => {\n const port = parseInt(opts.port, 10);\n if (Number.isNaN(port) || port < 1 || port > 65535) {\n console.error(`Invalid port: ${opts.port}`);\n process.exit(1);\n }\n await startCommand({\n port,\n service: opts.service,\n seed: opts.seed,\n baseUrl: opts.baseUrl,\n portless: opts.portless,\n });\n });\n\nprogram\n .command(\"init\")\n .description(\"Generate a starter config file\")\n .option(\"-s, --service <service>\", \"Service to generate config for\", \"all\")\n .action((opts) => {\n initCommand({ service: opts.service });\n });\n\nprogram\n .command(\"list\")\n .alias(\"list-services\")\n .description(\"List available services\")\n .action(() => {\n listCommand();\n });\n\nprogram.parse();\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport interface CollectionSnapshot<T extends Entity = Entity> {\n items: T[];\n autoId: number;\n indexFields: string[];\n}\n\nexport interface StoreSnapshot {\n collections: Record<string, CollectionSnapshot>;\n data: Record<string, unknown>;\n}\n\nexport function serializeValue(value: unknown): unknown {\n if (value instanceof Map) {\n return { __type: \"Map\" as const, entries: [...value.entries()].map(([k, v]) => [k, serializeValue(v)]) };\n }\n if (value instanceof Set) {\n return { __type: \"Set\" as const, values: [...value.values()] };\n }\n return value;\n}\n\nexport function deserializeValue(value: unknown): unknown {\n if (value !== null && typeof value === \"object\" && \"__type\" in value) {\n const tagged = value as Record<string, unknown>;\n if (tagged.__type === \"Map\") {\n const entries = tagged.entries as [unknown, unknown][];\n return new Map(entries.map(([k, v]) => [k, deserializeValue(v)]));\n }\n if (tagged.__type === \"Set\") {\n return new Set(tagged.values as unknown[]);\n }\n }\n return value;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids)\n .map((id) => this.items.get(id)!)\n .filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n\n snapshot(): CollectionSnapshot<T> {\n return {\n items: this.all(),\n autoId: this.autoId,\n indexFields: this.fieldNames,\n };\n }\n\n restore(snap: CollectionSnapshot<T>): void {\n this.clear();\n this.autoId = snap.autoId;\n for (const item of snap.items) {\n this.items.set(item.id, item);\n this.addToIndex(item);\n }\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`,\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n\n snapshot(): StoreSnapshot {\n const collections: Record<string, CollectionSnapshot> = {};\n for (const [name, col] of this.collections) {\n collections[name] = col.snapshot();\n }\n const data: Record<string, unknown> = {};\n for (const [key, value] of this._data) {\n data[key] = serializeValue(value);\n }\n return { collections, data };\n }\n\n restore(snap: StoreSnapshot): void {\n const snapshotNames = new Set(Object.keys(snap.collections));\n for (const name of this.collections.keys()) {\n if (!snapshotNames.has(name)) {\n this.collections.delete(name);\n }\n }\n for (const [name, colSnap] of Object.entries(snap.collections)) {\n const indexFields = colSnap.indexFields as (keyof Entity)[];\n const col = this.collection(name, indexFields);\n col.restore(colSnap as CollectionSnapshot<any>);\n }\n this._data.clear();\n for (const [key, value] of Object.entries(snap.data)) {\n this._data.set(key, deserializeValue(value));\n }\n }\n}\n","import { createServer as createNodeServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\n\ntype BodyInit = ConstructorParameters<typeof Response>[0];\ntype HeadersInit = ConstructorParameters<typeof Headers>[0];\ntype FormDataEntryValue = string | File;\n\nexport type ContentfulStatusCode = number;\nexport type Next = () => Promise<Response | void>;\n\ntype VariablesOf<E> = unknown extends E\n ? Record<string, any>\n : E extends { Variables: infer V }\n ? V\n : Record<string, any>;\ntype HandlerResult = Response | void | Promise<Response | void>;\n\nexport type Handler<E = unknown, P extends string = string> = (c: Context<E, P>, next: Next) => HandlerResult;\nexport type MiddlewareHandler<E = unknown> = Handler<E>;\nexport type ErrorHandler<E = unknown> = (err: unknown, c: Context<E>) => Response | Promise<Response>;\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\ninterface CompiledPath {\n pattern: string;\n regex: RegExp;\n paramNames: string[];\n}\n\ninterface Route<E> {\n method: string;\n compiled: CompiledPath;\n handlers: Handler<E>[];\n}\n\ninterface MatchedHandler<E> {\n handler: Handler<E>;\n params: Record<string, string>;\n}\n\nexport interface ServeOptions {\n fetch: FetchHandler;\n port?: number;\n hostname?: string;\n}\n\nexport interface CorsOptions {\n origin?: string;\n allowMethods?: string[];\n allowHeaders?: string[];\n credentials?: boolean;\n maxAge?: number;\n}\n\nexport class HonoRequest {\n readonly raw: Request;\n readonly url: string;\n readonly method: string;\n readonly path: string;\n /** The matched route pattern (e.g. /repos/:owner/:repo), when a route matched. */\n readonly routePath?: string;\n\n constructor(\n request: Request,\n private readonly params: Record<string, string>,\n routePath?: string,\n ) {\n this.raw = request;\n this.url = request.url;\n this.method = request.method;\n this.path = new URL(request.url).pathname;\n this.routePath = routePath;\n }\n\n header(): Record<string, string>;\n header(name: string): string | undefined;\n header(name?: string): Record<string, string> | string | undefined {\n if (name) return this.raw.headers.get(name) ?? undefined;\n const headers: Record<string, string> = {};\n this.raw.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return headers;\n }\n\n query(name: string): string | undefined {\n return new URL(this.url).searchParams.get(name) ?? undefined;\n }\n\n queries(name: string): string[] | undefined {\n const values = new URL(this.url).searchParams.getAll(name);\n return values.length > 0 ? values : undefined;\n }\n\n param(): Record<string, string>;\n param(name: string): string;\n param(name?: string): Record<string, string> | string {\n if (!name) return { ...this.params };\n return this.params[name] ?? \"\";\n }\n\n json<T = any>(): Promise<T> {\n return this.raw.json() as Promise<T>;\n }\n\n text(): Promise<string> {\n return this.raw.text();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.raw.arrayBuffer();\n }\n\n async parseBody(): Promise<Record<string, FormDataEntryValue | FormDataEntryValue[]>> {\n const contentType = this.header(\"Content-Type\") ?? \"\";\n if (contentType.includes(\"multipart/form-data\")) {\n return formDataToObject(await this.raw.formData());\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params = new URLSearchParams(await this.raw.text());\n const out: Record<string, string | string[]> = {};\n for (const [key, value] of params) {\n appendBodyValue(out, key, value);\n }\n return out;\n }\n if (contentType.includes(\"application/json\")) {\n const body = await this.raw.json().catch(() => ({}));\n return body && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, FormDataEntryValue | FormDataEntryValue[]>)\n : {};\n }\n return {};\n }\n}\n\nexport class Context<E = unknown, _P extends string = string> {\n readonly req: HonoRequest;\n private readonly vars = new Map<string, unknown>();\n private readonly responseHeaders = new Headers();\n private responseStatus = 200;\n\n constructor(\n request: Request,\n params: Record<string, string>,\n private readonly notFoundHandler: (c: Context<E>) => Response | Promise<Response>,\n routePath?: string,\n ) {\n this.req = new HonoRequest(request, params, routePath);\n }\n\n get<K extends keyof VariablesOf<E> & string>(key: K): VariablesOf<E>[K] | undefined {\n return this.vars.get(key) as VariablesOf<E>[K] | undefined;\n }\n\n set<K extends keyof VariablesOf<E> & string>(key: K, value: VariablesOf<E>[K]): void {\n this.vars.set(key, value);\n }\n\n header(name: string, value: string): void {\n this.responseHeaders.set(name, value);\n }\n\n status(status: number): void {\n this.responseStatus = status;\n }\n\n json(data: unknown, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(JSON.stringify(data), status, defaultContentType(headers, \"application/json; charset=UTF-8\"));\n }\n\n text(text: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(text, status, defaultContentType(headers, \"text/plain; charset=UTF-8\"));\n }\n\n html(html: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(html, status, defaultContentType(headers, \"text/html; charset=UTF-8\"));\n }\n\n body(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(body, status, headers);\n }\n\n redirect(location: string, status: ContentfulStatusCode = 302): Response {\n return this.response(null, status, { Location: location });\n }\n\n notFound(): Response | Promise<Response> {\n return this.notFoundHandler(this);\n }\n\n finalize(response: Response): Response {\n if (!hasHeaders(this.responseHeaders)) return response;\n const headers = new Headers(response.headers);\n this.responseHeaders.forEach((value, key) => {\n headers.set(key, value);\n });\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n private response(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n const merged = new Headers(headers);\n this.responseHeaders.forEach((value, key) => {\n merged.set(key, value);\n });\n return new Response(body, {\n status: status ?? this.responseStatus,\n headers: merged,\n });\n }\n}\n\nexport class Hono<E = unknown> {\n private readonly middleware: Route<E>[] = [];\n private readonly routes: Route<E>[] = [];\n private errorHandler: ErrorHandler<E> = (err) => {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return new Response(message, { status: 500 });\n };\n private notFoundHandler: (c: Context<E>) => Response | Promise<Response> = () =>\n new Response(\"404 Not Found\", { status: 404 });\n\n use<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;\n use(...handlers: Handler<E>[]): this;\n use<P extends string = string>(pathOrHandler: string | Handler<E>, ...handlers: Handler<E, P>[]): this {\n if (typeof pathOrHandler === \"string\") {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(pathOrHandler), handlers: handlers as Handler<E>[] });\n } else {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(\"*\"), handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n on<P extends string = string>(method: string, path: string, ...handlers: Handler<E, P>[]): this {\n this.routes.push({ method: method.toUpperCase(), compiled: compilePath(path), handlers: handlers as Handler<E>[] });\n return this;\n }\n\n get<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"GET\", path, ...handlers);\n }\n\n post<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"POST\", path, ...handlers);\n }\n\n put<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PUT\", path, ...handlers);\n }\n\n patch<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PATCH\", path, ...handlers);\n }\n\n delete<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"DELETE\", path, ...handlers);\n }\n\n onError(handler: ErrorHandler<E>): this {\n this.errorHandler = handler;\n return this;\n }\n\n notFound(handler: (c: Context<E>) => Response | Promise<Response>): this {\n this.notFoundHandler = handler;\n return this;\n }\n\n async request(input: string | Request, init?: RequestInit): Promise<Response> {\n if (input instanceof Request) return this.fetch(input);\n const url = input.startsWith(\"/\") ? `http://localhost${input}` : input;\n return this.fetch(new Request(url, init));\n }\n\n fetch = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const path = url.pathname;\n const method = request.method.toUpperCase();\n const matched = this.match(method, path);\n const context = new Context<E>(request, matched.params, this.notFoundHandler, matched.routePattern);\n\n try {\n const response = await this.dispatch(context, matched.handlers);\n return context.finalize(response ?? (await this.notFoundHandler(context)));\n } catch (err) {\n return context.finalize(await this.errorHandler(err, context));\n }\n };\n\n private match(\n method: string,\n path: string,\n ): { handlers: MatchedHandler<E>[]; params: Record<string, string>; routePattern?: string } {\n const handlers: MatchedHandler<E>[] = [];\n const params: Record<string, string> = {};\n\n for (const route of this.middleware) {\n const match = matchPath(route.compiled, path);\n if (!match) continue;\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n const route =\n this.routes.find((candidate) => candidate.method === method && matchPath(candidate.compiled, path) != null) ??\n (method === \"HEAD\"\n ? this.routes.find((candidate) => candidate.method === \"GET\" && matchPath(candidate.compiled, path) != null)\n : undefined);\n\n if (route) {\n const match = matchPath(route.compiled, path) ?? {};\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n return { handlers, params, routePattern: route?.compiled.pattern };\n }\n\n private async dispatch(context: Context<E>, handlers: MatchedHandler<E>[]): Promise<Response | void> {\n let index = -1;\n const run = async (nextIndex: number): Promise<Response | void> => {\n if (nextIndex <= index) throw new Error(\"next() called multiple times\");\n index = nextIndex;\n const matched = handlers[nextIndex];\n if (!matched) return undefined;\n\n const originalParams = context.req.param();\n Object.assign(originalParams, matched.params);\n\n let nextResponse: Response | void = undefined;\n let nextCalled = false;\n const next: Next = async () => {\n nextCalled = true;\n nextResponse = await run(nextIndex + 1);\n return nextResponse;\n };\n\n const response = await matched.handler(context, next);\n if (response instanceof Response) return response;\n if (nextCalled) return nextResponse;\n return response;\n };\n\n return run(0);\n }\n}\n\nexport function cors(options: CorsOptions = {}): MiddlewareHandler {\n const origin = options.origin ?? \"*\";\n const allowMethods = options.allowMethods ?? [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"];\n\n return async (c, next) => {\n c.header(\"Access-Control-Allow-Origin\", origin);\n if (options.credentials) c.header(\"Access-Control-Allow-Credentials\", \"true\");\n\n if (c.req.method.toUpperCase() === \"OPTIONS\") {\n c.header(\"Access-Control-Allow-Methods\", allowMethods.join(\",\"));\n const allowHeaders = options.allowHeaders?.join(\",\") ?? c.req.header(\"Access-Control-Request-Headers\");\n if (allowHeaders) c.header(\"Access-Control-Allow-Headers\", allowHeaders);\n if (options.maxAge != null) c.header(\"Access-Control-Max-Age\", String(options.maxAge));\n return c.body(null, 204);\n }\n\n await next();\n };\n}\n\nexport function serve(options: ServeOptions): Server {\n const port = options.port ?? 3000;\n const server = createNodeServer(async (req, res) => {\n try {\n const request = nodeRequestToFetchRequest(req);\n const response = await options.fetch(request);\n await writeFetchResponse(res, response, req.method?.toUpperCase() === \"HEAD\");\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=UTF-8\");\n res.end(message);\n }\n });\n server.listen(port, options.hostname);\n return server;\n}\n\nfunction compilePath(pattern: string): CompiledPath {\n if (pattern === \"*\" || pattern === \"/*\") {\n return { pattern, regex: /^.*$/, paramNames: [] };\n }\n\n const paramNames: string[] = [];\n let source = \"^\";\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n if (char !== \":\") {\n source += escapeRegex(char);\n continue;\n }\n\n let name = \"\";\n i++;\n while (i < pattern.length && /[A-Za-z0-9_]/.test(pattern[i])) {\n name += pattern[i];\n i++;\n }\n i--;\n paramNames.push(name);\n\n if (pattern[i + 1] === \"{\") {\n const close = pattern.indexOf(\"}\", i + 2);\n if (close < 0) throw new Error(`Invalid route pattern: ${pattern}`);\n const expr = pattern.slice(i + 2, close);\n source += `(${expr})`;\n i = close;\n } else {\n source += \"([^/]+)\";\n }\n }\n source += \"$\";\n return { pattern, regex: new RegExp(source), paramNames };\n}\n\nfunction matchPath(compiled: CompiledPath, path: string): Record<string, string> | null {\n const match = compiled.regex.exec(path);\n if (!match) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < compiled.paramNames.length; i++) {\n params[compiled.paramNames[i]] = decodePathParam(match[i + 1] ?? \"\");\n }\n return params;\n}\n\nfunction decodePathParam(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\nfunction hasHeaders(headers: Headers): boolean {\n for (const _ of headers) return true;\n return false;\n}\n\nfunction defaultContentType(headers: HeadersInit | undefined, contentType: string): Headers {\n const out = new Headers(headers);\n if (!out.has(\"Content-Type\")) {\n out.set(\"Content-Type\", contentType);\n }\n return out;\n}\n\nfunction formDataToObject(formData: FormData): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n const out: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n for (const [key, value] of formData) {\n appendBodyValue(out, key, value);\n }\n return out;\n}\n\nfunction appendBodyValue<T>(target: Record<string, T | T[]>, key: string, value: T): void {\n const existing = target[key];\n if (existing === undefined) {\n target[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n target[key] = [existing, value];\n }\n}\n\nfunction nodeRequestToFetchRequest(req: IncomingMessage): Request {\n const host = req.headers.host ?? \"localhost\";\n const url = new URL(req.url ?? \"/\", `http://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else {\n headers.set(key, value);\n }\n }\n\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n return new Request(url.toString(), {\n method,\n headers,\n body: hasBody ? (req as unknown as BodyInit) : undefined,\n duplex: \"half\",\n } as RequestInit & { duplex: string });\n}\n\nasync function writeFetchResponse(res: ServerResponse, response: Response, headOnly: boolean): Promise<void> {\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n\n const headersWithCookies = response.headers as Headers & { getSetCookie?: () => string[] };\n const cookies = headersWithCookies.getSetCookie?.();\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\" && cookies && cookies.length > 0) return;\n res.setHeader(key, value);\n });\n if (cookies && cookies.length > 0) {\n res.setHeader(\"Set-Cookie\", cookies);\n }\n\n if (headOnly || !response.body) {\n res.end();\n return;\n }\n\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!res.write(value)) {\n await new Promise<void>((resolve) => res.once(\"drain\", resolve));\n }\n }\n res.end();\n } catch (err) {\n res.destroy(err instanceof Error ? err : undefined);\n }\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>,\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(\n event: string,\n action: string | undefined,\n payload: unknown,\n owner: string,\n repo?: string,\n ): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return event === \"ping\" || s.events.includes(\"*\") || s.events.includes(event);\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ContentfulStatusCode, ErrorHandler, MiddlewareHandler } from \"../http.js\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Route handlers throw to the app error handler.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode,\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"../http.js\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport interface TokenEntry {\n token: string;\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function serializeTokenMap(tokenMap: TokenMap): TokenEntry[] {\n return [...tokenMap.entries()].map(([token, user]) => ({\n token,\n login: user.login,\n id: user.id,\n scopes: user.scopes,\n }));\n}\n\nexport function restoreTokenMap(tokenMap: TokenMap, tokens: TokenEntry[]): void {\n tokenMap.clear();\n for (const t of tokens) {\n tokenMap.set(t.token, { login: t.login, id: t.id, scopes: t.scopes });\n }\n}\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n /** Correlation id for the active request, set by the ledger middleware. */\n correlationId?: string;\n /** Provider operation id a handler can advertise for the ledger. */\n operationId?: string;\n /** Side effects a handler records onto the active request's ledger entry. */\n ledgerEffects?: import(\"../ledger.js\").LedgerSideEffect[];\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(Buffer.from(payloadB64, \"base64url\").toString());\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n","const isDebug =\n typeof process !== \"undefined\" &&\n (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\n// Read the cosmetic font/favicon assets lazily and defensively: on a real\n// filesystem (Node/Bun hosts) this serves them; on filesystem-less runtimes\n// (e.g. Cloudflare Workers) the read fails and the route 404s, but — crucially —\n// importing this module touches neither fs NOR import.meta.url at load time\n// (workerd leaves import.meta.url undefined, which would crash `fileURLToPath`),\n// so `createServer` boots everywhere. API emulation never needs these assets.\nconst assetCache = new Map<string, Buffer | null>();\nfunction loadAsset(name: string): Buffer | null {\n if (assetCache.has(name)) return assetCache.get(name)!;\n let buf: Buffer | null = null;\n try {\n const dir = dirname(fileURLToPath(import.meta.url));\n buf = readFileSync(join(dir, \"fonts\", name));\n } catch {\n buf = null;\n }\n assetCache.set(name, buf);\n return buf;\n}\n\nconst FONT_NAMES = new Set([\"geist-sans.woff2\", \"GeistPixel-Square.woff2\"]);\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n if (!FONT_NAMES.has(name)) return c.notFound();\n const buf = loadAsset(name);\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n\n app.get(\"/_emulate/favicon.ico\", (c) => {\n const buf = loadAsset(\"favicon.ico\");\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"image/x-icon\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n },\n });\n });\n}\n","import type { MiddlewareHandler } from \"./http.js\";\nimport type { AppEnv, AuthUser, AuthApp } from \"./middleware/auth.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\n\nexport interface LedgerIdentity {\n user?: Pick<AuthUser, \"login\" | \"id\" | \"scopes\">;\n app?: Pick<AuthApp, \"appId\" | \"slug\" | \"name\">;\n}\n\nexport interface LedgerSideEffect {\n type: \"create\" | \"update\" | \"delete\" | \"custom\";\n collection?: string;\n id?: string | number;\n summary?: string;\n}\n\nexport interface LedgerWebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n status_code: number | null;\n success: boolean;\n}\n\nexport interface LedgerEntry {\n id: string;\n /** Correlation id: honored from X-Correlation-Id / X-Request-Id or generated. */\n correlationId: string;\n timestamp: string;\n method: string;\n host: string;\n path: string;\n query: string;\n /** Matched route pattern, e.g. /repos/:owner/:repo/issues. */\n route?: string;\n /** Provider operation id, when the handler advertises one. */\n operationId?: string;\n request: {\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n identity: LedgerIdentity;\n response: {\n status: number;\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n /** Human/agent-readable one-liner, e.g. \"POST /repos/:owner/:repo -> 201\". */\n summary: string;\n sideEffects: LedgerSideEffect[];\n webhookDeliveries: LedgerWebhookDelivery[];\n durationMs: number;\n}\n\nexport interface LedgerOptions {\n maxEntries?: number;\n maxBodyChars?: number;\n /** When provided, webhook deliveries fired during a request are correlated onto its entry. */\n webhooks?: WebhookDispatcher;\n}\n\nexport interface LedgerSnapshot {\n entries: LedgerEntry[];\n counter: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 1000;\nconst DEFAULT_MAX_BODY_CHARS = 20000;\nconst REDACTED = \"[redacted]\";\nconst SENSITIVE_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"x-github-token\",\n \"stripe-signature\",\n]);\nconst SENSITIVE_KEYS = /token|secret|password|authorization|api[_-]?key|client[_-]?secret|private[_-]?key/i;\n\nexport class RequestLedger {\n private entries: LedgerEntry[] = [];\n private counter = 1;\n\n constructor(private readonly options: LedgerOptions = {}) {}\n\n add(entry: Omit<LedgerEntry, \"id\">): LedgerEntry {\n const saved = { ...entry, id: `req_${this.counter++}` };\n this.entries.push(saved);\n const max = this.options.maxEntries ?? DEFAULT_MAX_ENTRIES;\n if (this.entries.length > max) {\n this.entries.splice(0, this.entries.length - max);\n }\n return saved;\n }\n\n list(limit?: number): LedgerEntry[] {\n const all = [...this.entries].reverse();\n return limit != null ? all.slice(0, limit) : all;\n }\n\n clear(): void {\n this.entries.length = 0;\n this.counter = 1;\n }\n\n /** Serialize for durable persistence (e.g. a Cloudflare Durable Object). */\n serialize(): LedgerSnapshot {\n return { entries: [...this.entries], counter: this.counter };\n }\n\n restore(snapshot: LedgerSnapshot | undefined): void {\n if (!snapshot) return;\n this.entries = Array.isArray(snapshot.entries) ? [...snapshot.entries] : [];\n this.counter = typeof snapshot.counter === \"number\" ? snapshot.counter : this.entries.length + 1;\n }\n}\n\nfunction correlationIdFor(headers: Record<string, string>): string {\n const provided = headers[\"x-correlation-id\"] ?? headers[\"x-request-id\"];\n if (provided && provided.length <= 200) return provided;\n return `cor_${crypto.randomUUID().replace(/-/g, \"\")}`;\n}\n\nexport function createLedgerMiddleware(ledger: RequestLedger, options: LedgerOptions = {}): MiddlewareHandler<AppEnv> {\n const maxBodyChars = options.maxBodyChars ?? DEFAULT_MAX_BODY_CHARS;\n const webhooks = options.webhooks;\n\n return async (c, next) => {\n if (c.req.path.startsWith(\"/_emulate\")) {\n await next();\n return;\n }\n\n const started = Date.now();\n const url = new URL(c.req.url);\n const rawHeaders = c.req.header();\n const correlationId = correlationIdFor(rawHeaders);\n c.set(\"correlationId\", correlationId);\n c.set(\"ledgerEffects\", []);\n c.header(\"X-Correlation-Id\", correlationId);\n\n const requestBody = await readBody(c.req.raw.clone(), maxBodyChars);\n const requestHeaders = redactHeaders(rawHeaders);\n\n // Snapshot existing webhook delivery ids so we can correlate the ones this\n // request fires. Exact under the serialized execution of a Durable Object;\n // best-effort on the concurrent local dev server.\n const beforeDeliveryIds = webhooks ? new Set(webhooks.getDeliveries().map((d) => d.id)) : undefined;\n\n const response = await next();\n if (!response) return;\n\n const responseBody = await readBody(response.clone(), maxBodyChars);\n const route = c.req.routePath;\n const operationId = c.get(\"operationId\");\n const sideEffects = (c.get(\"ledgerEffects\") as LedgerSideEffect[] | undefined) ?? [];\n const webhookDeliveries: LedgerWebhookDelivery[] =\n webhooks && beforeDeliveryIds\n ? webhooks\n .getDeliveries()\n .filter((d) => !beforeDeliveryIds.has(d.id))\n .map((d) => ({\n id: d.id,\n hook_id: d.hook_id,\n event: d.event,\n action: d.action,\n status_code: d.status_code,\n success: d.success,\n }))\n : [];\n\n ledger.add({\n correlationId,\n timestamp: new Date().toISOString(),\n method: c.req.method.toUpperCase(),\n host: url.host,\n path: url.pathname,\n query: url.search,\n route,\n operationId,\n request: {\n headers: requestHeaders,\n ...requestBody,\n },\n identity: {\n user: c.get(\"authUser\"),\n app: c.get(\"authApp\"),\n },\n response: {\n status: response.status,\n headers: redactHeaders(headersToRecord(response.headers)),\n ...responseBody,\n },\n summary: `${c.req.method.toUpperCase()} ${route ?? url.pathname} -> ${response.status}`,\n sideEffects,\n webhookDeliveries,\n durationMs: Date.now() - started,\n });\n\n return response;\n };\n}\n\n/** Record a side effect onto the active request's ledger entry. */\nexport function recordSideEffect(\n c: { get: (key: \"ledgerEffects\") => LedgerSideEffect[] | undefined },\n effect: LedgerSideEffect,\n): void {\n const effects = c.get(\"ledgerEffects\");\n if (effects) effects.push(effect);\n}\n\nasync function readBody(\n responseOrRequest: Request | Response,\n maxChars: number,\n): Promise<{ body?: unknown; bodyTruncated?: boolean }> {\n const method = responseOrRequest instanceof Request ? responseOrRequest.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") return {};\n\n const contentType = responseOrRequest.headers.get(\"content-type\") ?? \"\";\n if (responseOrRequest instanceof Response && responseOrRequest.status === 204) return {};\n\n let text: string;\n try {\n text = await responseOrRequest.text();\n } catch {\n return {};\n }\n if (!text) return {};\n\n const truncated = text.length > maxChars;\n const clipped = truncated ? text.slice(0, maxChars) : text;\n if (contentType.includes(\"application/json\")) {\n try {\n return { body: redactValue(JSON.parse(clipped)), bodyTruncated: truncated || undefined };\n } catch {\n return { body: clipped, bodyTruncated: truncated || undefined };\n }\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params: Record<string, string> = {};\n for (const [key, value] of new URLSearchParams(clipped)) {\n params[key] = SENSITIVE_KEYS.test(key) ? REDACTED : value;\n }\n return { body: params, bodyTruncated: truncated || undefined };\n }\n return { body: clipped, bodyTruncated: truncated || undefined };\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nfunction redactHeaders(headers: Record<string, string>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n out[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? REDACTED : value;\n }\n return out;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactValue);\n if (!value || typeof value !== \"object\") return value;\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n out[key] = SENSITIVE_KEYS.test(key) ? REDACTED : redactValue(child);\n }\n return out;\n}\n","export type SpecKind = \"openapi\" | \"graphql\" | \"mcp\" | \"google-discovery\" | \"oauth-metadata\" | \"manual\";\nexport type SpecCoverage = \"generated\" | \"hand-authored\" | \"partial\" | \"unsupported\";\n\n/**\n * Per-operation coverage. The vision asks for honest, operation-level coverage\n * boundaries (generated / hand-authored / partial / unsupported) instead of a\n * single label stamped across an entire spec. A plugin declares the operations\n * it actually implements; `GET /_emulate/coverage` reports them with a summary.\n */\nexport interface OperationCoverage {\n operationId: string;\n method?: string;\n path?: string;\n status: SpecCoverage;\n summary?: string;\n}\n\nexport interface SpecManifest {\n kind: SpecKind;\n title: string;\n url?: string;\n coverage: SpecCoverage;\n operations?: OperationCoverage[];\n notes?: string;\n}\n\nexport interface SurfaceManifest {\n id: string;\n kind: \"rest\" | \"oauth\" | \"oidc\" | \"graphql\" | \"mcp\" | \"webhooks\" | \"ui\" | \"provider-specific\";\n title: string;\n basePath?: string;\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface AuthCapabilityManifest {\n id: string;\n title: string;\n type:\n | \"api-key\"\n | \"bearer-token\"\n | \"oauth-client-credentials\"\n | \"oauth-authorization-code\"\n | \"oidc\"\n | \"jwt-app\"\n | \"dynamic-client-registration\"\n | \"webhook-secret\"\n | \"provider-specific\";\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface ScenarioManifest {\n id: string;\n title: string;\n description?: string;\n}\n\n/** A seedable area of the instance, surfaced so agents can discover the seed shape. */\nexport interface SeedFieldManifest {\n key: string;\n title: string;\n description?: string;\n example?: unknown;\n}\n\nexport interface SeedSchemaManifest {\n description?: string;\n fields: SeedFieldManifest[];\n /** A full example seed body that can be POSTed to /_emulate/seed. */\n example?: unknown;\n}\n\nexport interface StateCollectionManifest {\n name: string;\n title?: string;\n description?: string;\n}\n\nexport interface StateModelManifest {\n description?: string;\n collections: StateCollectionManifest[];\n}\n\nexport interface ResetBehaviorManifest {\n description: string;\n reseeds: boolean;\n clearsLedger: boolean;\n clearsWebhooks: boolean;\n}\n\nexport type InspectorTabKind = \"landing\" | \"ledger\" | \"state\" | \"logs\" | \"credentials\" | \"seed\" | \"spec\" | \"custom\";\n\nexport interface InspectorTabManifest {\n id: string;\n title: string;\n kind: InspectorTabKind;\n description?: string;\n}\n\n/** Describes what the request ledger records and how durable it is. */\nexport interface LedgerCapabilitiesManifest {\n description?: string;\n recordsFields: string[];\n redactsSensitive: boolean;\n correlationId: boolean;\n webhookDeliveries: boolean;\n sideEffects: boolean;\n persistent: boolean;\n maxEntries?: number;\n}\n\nexport type ConnectionKind = \"sdk\" | \"cli\" | \"env\" | \"curl\" | \"config\" | \"mcp\";\n\n/**\n * A copyable connection snippet. The `template` uses {{placeholders}} that the\n * control plane resolves against the live instance ({{baseUrl}}, {{controlBaseUrl}},\n * {{service}}, {{instance}}, {{token}}, {{clientId}}, {{clientSecret}}). This is\n * how a human or agent copies ready-to-run SDK / CLI / app config without repo\n * context.\n */\nexport interface ConnectionSnippet {\n id: string;\n title: string;\n kind: ConnectionKind;\n language?: string;\n description?: string;\n template: string;\n}\n\nexport interface ServiceManifest {\n id: string;\n name: string;\n description: string;\n surfaces: SurfaceManifest[];\n auth: AuthCapabilityManifest[];\n specs: SpecManifest[];\n scenarios?: ScenarioManifest[];\n seedSchema?: SeedSchemaManifest;\n stateModel?: StateModelManifest;\n resetBehavior?: ResetBehaviorManifest;\n inspectorTabs?: InspectorTabManifest[];\n ledger?: LedgerCapabilitiesManifest;\n connections?: ConnectionSnippet[];\n docsUrl?: string;\n}\n\nexport interface EmulatorInstanceInfo {\n service: string;\n instance?: string;\n baseUrl: string;\n controlBaseUrl: string;\n providerBaseUrl: string;\n}\n\n/**\n * Reset, ledger capabilities, inspector tabs and base connection snippets are the\n * same for every emulator because they all run on the shared core control plane.\n * Defining them once here keeps per-plugin manifests focused on service-specific\n * surface, auth, seed, and SDK details, and guarantees the control plane never\n * lies about a capability it actually provides.\n */\nexport const CORE_RESET_BEHAVIOR: ResetBehaviorManifest = {\n description: \"Resets the instance to its seeded baseline.\",\n reseeds: true,\n clearsLedger: true,\n clearsWebhooks: true,\n};\n\nexport function coreLedgerCapabilities(persistent: boolean): LedgerCapabilitiesManifest {\n return {\n description: \"Recent provider requests with sensitive headers and fields redacted.\",\n recordsFields: [\n \"timestamp\",\n \"method\",\n \"host\",\n \"path\",\n \"route\",\n \"operationId\",\n \"correlationId\",\n \"identity\",\n \"request\",\n \"response\",\n \"summary\",\n \"sideEffects\",\n \"webhookDeliveries\",\n \"durationMs\",\n ],\n redactsSensitive: true,\n correlationId: true,\n webhookDeliveries: true,\n sideEffects: true,\n persistent,\n maxEntries: 1000,\n };\n}\n\nexport function coreInspectorTabs(manifest: ServiceManifest): InspectorTabManifest[] {\n const tabs: InspectorTabManifest[] = [\n {\n id: \"overview\",\n title: \"Overview\",\n kind: \"landing\",\n description: \"Service surfaces, base URLs, and connection snippets.\",\n },\n {\n id: \"ledger\",\n title: \"Ledger\",\n kind: \"ledger\",\n description: \"Recent provider requests recorded by the emulator.\",\n },\n { id: \"state\", title: \"State\", kind: \"state\", description: \"Current seeded and mutated instance state.\" },\n {\n id: \"credentials\",\n title: \"Credentials\",\n kind: \"credentials\",\n description: \"Mint tokens, API keys, or OAuth clients.\",\n },\n ];\n if (manifest.seedSchema || (manifest.scenarios && manifest.scenarios.length > 0)) {\n tabs.push({ id: \"seed\", title: \"Seed\", kind: \"seed\", description: \"Seed state or load a scenario.\" });\n }\n if (manifest.specs.some((s) => s.kind === \"openapi\" || s.kind === \"graphql\")) {\n tabs.push({ id: \"spec\", title: \"Spec\", kind: \"spec\", description: \"OpenAPI / GraphQL spec sources and coverage.\" });\n }\n if (manifest.surfaces.some((s) => s.kind === \"webhooks\")) {\n tabs.push({\n id: \"logs\",\n title: \"Webhooks\",\n kind: \"logs\",\n description: \"Webhook deliveries dispatched by the emulator.\",\n });\n }\n return tabs;\n}\n\n/** Connection snippets every emulator can offer (env + curl against the control plane). */\nexport function coreConnections(): ConnectionSnippet[] {\n return [\n {\n id: \"base-url\",\n title: \"Base URL (env)\",\n kind: \"env\",\n language: \"bash\",\n description: \"Point your SDK or app at the emulator instead of the real provider.\",\n template: \"{{SERVICE_UPPER}}_BASE_URL={{baseUrl}}\",\n },\n {\n id: \"create-credential\",\n title: \"Create a credential\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Mint a working credential for this instance.\",\n template:\n 'curl -s -X POST {{controlBaseUrl}}/credentials \\\\\\n -H \"content-type: application/json\" \\\\\\n -d \\'{\"type\":\"{{defaultAuthType}}\"}\\'',\n },\n {\n id: \"inspect-ledger\",\n title: \"Inspect requests\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Read the request ledger to validate how your app called the service.\",\n template: \"curl -s {{controlBaseUrl}}/ledger\",\n },\n ];\n}\n\n/**\n * Merge the shared core capabilities into a plugin manifest so every served\n * manifest fully describes reset behavior, ledger capabilities, inspector tabs,\n * and at least the base connection snippets, without each plugin repeating them.\n */\nexport function enrichManifest(manifest: ServiceManifest, opts: { ledgerPersistent?: boolean } = {}): ServiceManifest {\n return {\n ...manifest,\n resetBehavior: manifest.resetBehavior ?? CORE_RESET_BEHAVIOR,\n ledger: manifest.ledger ?? coreLedgerCapabilities(opts.ledgerPersistent ?? false),\n inspectorTabs: manifest.inspectorTabs ?? coreInspectorTabs(manifest),\n connections: [...(manifest.connections ?? []), ...coreConnections()],\n };\n}\n\nexport interface ConnectionVars {\n baseUrl: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n service: string;\n instance?: string;\n token?: string;\n clientId?: string;\n clientSecret?: string;\n defaultAuthType?: string;\n}\n\nexport interface ResolvedConnection extends ConnectionSnippet {\n body: string;\n}\n\n/** Interpolate a connection snippet template against live instance values. */\nexport function resolveConnections(connections: ConnectionSnippet[], vars: ConnectionVars): ResolvedConnection[] {\n const map: Record<string, string> = {\n baseUrl: vars.baseUrl,\n providerBaseUrl: vars.providerBaseUrl,\n controlBaseUrl: vars.controlBaseUrl,\n service: vars.service,\n SERVICE_UPPER: vars.service.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\"),\n instance: vars.instance ?? \"default\",\n token: vars.token ?? \"<token>\",\n clientId: vars.clientId ?? \"<client_id>\",\n clientSecret: vars.clientSecret ?? \"<client_secret>\",\n defaultAuthType: vars.defaultAuthType ?? \"bearer-token\",\n };\n return connections.map((snippet) => ({\n ...snippet,\n body: snippet.template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => map[key] ?? `{{${key}}}`),\n }));\n}\n\n/** A summary of declared per-operation coverage across a manifest's specs. */\nexport function coverageReport(manifest: ServiceManifest): {\n operations: OperationCoverage[];\n summary: Record<SpecCoverage, number>;\n specs: Array<{ kind: SpecKind; title: string; coverage: SpecCoverage; operationCount: number }>;\n} {\n const operations: OperationCoverage[] = [];\n const summary: Record<SpecCoverage, number> = {\n generated: 0,\n \"hand-authored\": 0,\n partial: 0,\n unsupported: 0,\n };\n const specs = manifest.specs.map((spec) => {\n const ops = spec.operations ?? [];\n for (const op of ops) {\n operations.push(op);\n summary[op.status] += 1;\n }\n return { kind: spec.kind, title: spec.title, coverage: spec.coverage, operationCount: ops.length };\n });\n return { operations, summary, specs };\n}\n\nexport function createDefaultManifest(service: string): ServiceManifest {\n return {\n id: service,\n name: service,\n description: `Stateful ${service} API emulator.`,\n surfaces: [{ id: \"rest\", kind: \"rest\", title: \"REST API\", status: \"partial\" }],\n auth: [{ id: \"bearer\", title: \"Bearer token\", type: \"bearer-token\", status: \"partial\" }],\n specs: [{ kind: \"manual\", title: \"Hand-authored emulator behavior\", coverage: \"partial\" }],\n };\n}\n","export function escapeHtml(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"'\");\n}\n\nconst CSS = `\n@font-face{\n font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;\n src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');\n}\n@font-face{\n font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;\n src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');\n}\n*{box-sizing:border-box;margin:0;padding:0}\nbody{\n font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;\n background:#000;color:#33ff00;min-height:100vh;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n}\n.emu-bar{\n border-bottom:1px solid #0a3300;padding:10px 20px;\n display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;\n}\n.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}\n.emu-bar-links{margin-left:auto;display:flex;gap:16px;}\n.emu-bar-links a{\n color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;\n}\n.emu-bar-links a:hover{color:#33ff00;}\n.emu-bar-links a .full{display:inline;}\n.emu-bar-links a .short{display:none;}\n@media(max-width:600px){\n .emu-bar-links a .full{display:none;}\n .emu-bar-links a .short{display:inline;}\n}\n\n.content{\n display:flex;align-items:center;justify-content:center;\n min-height:calc(100vh - 42px);padding:24px 16px;\n}\n.content-inner{width:100%;max-width:420px;}\n.card-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;\n}\n.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}\n.powered-by{\n position:fixed;bottom:0;left:0;right:0;\n text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;\n font-family:'Geist Pixel',monospace;\n}\n.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.powered-by a:hover{color:#33ff00;}\n\n.error-title{\n font-family:'Geist Pixel',monospace;\n color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;\n}\n.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}\n.error-card{text-align:center;}\n\n.user-form{margin-bottom:8px;}\n.user-form:last-of-type{margin-bottom:0;}\n.user-btn{\n width:100%;display:flex;align-items:center;gap:12px;\n padding:10px 12px;border:1px solid #0a3300;border-radius:8px;\n background:#000;color:inherit;cursor:pointer;text-align:left;\n font:inherit;transition:border-color .15s;\n}\n.user-btn:hover{border-color:#33ff00;}\n.avatar{\n width:36px;height:36px;border-radius:50%;\n background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.user-text{min-width:0;}\n.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}\n.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}\n.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}\n\n.settings-layout{\n max-width:920px;margin:0 auto;padding:28px 20px;\n display:flex;gap:28px;\n}\n.settings-sidebar{width:200px;flex-shrink:0;}\n.settings-sidebar a{\n display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;\n text-decoration:none;font-size:.8125rem;transition:color .15s;\n}\n.settings-sidebar a:hover{color:#33ff00;}\n.settings-sidebar a.active{color:#33ff00;font-weight:600;}\n.settings-main{flex:1;min-width:0;}\n\n.s-card{\n padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;\n}\n.s-card:last-child{border-bottom:none;}\n.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}\n.s-icon{\n width:42px;height:42px;border-radius:8px;\n background:#0a3300;display:flex;align-items:center;justify-content:center;\n font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.s-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.25rem;font-weight:600;color:#33ff00;\n}\n.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.section-heading{\n font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;\n display:flex;align-items:center;justify-content:space-between;\n}\n.perm-list{list-style:none;}\n.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}\n.check{color:#33ff00;}\n.org-row{\n display:flex;align-items:center;gap:8px;padding:7px 0;\n border-bottom:1px solid #0a3300;font-size:.8125rem;\n}\n.org-row:last-child{border-bottom:none;}\n.org-icon{\n width:22px;height:22px;border-radius:4px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;\n font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.org-name{font-weight:600;color:#33ff00;}\n.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}\n.badge-granted{background:#0a3300;color:#33ff00;}\n.badge-denied{background:#1a0a0a;color:#ff4444;}\n.badge-requested{background:#0a3300;color:#1a8c00;}\n.btn-revoke{\n display:inline-block;padding:5px 14px;border-radius:6px;\n border:1px solid #0a3300;background:transparent;color:#ff4444;\n font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;\n}\n.btn-revoke:hover{border-color:#ff4444;}\n.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}\n.info-text a,.section-heading a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.info-text a:hover,.section-heading a:hover{color:#33ff00;}\ncode{font-family:'Geist Mono','SF Mono',ui-monospace,monospace;font-size:.8125rem;color:#33ff00;word-break:break-all;}\n.code-block{\n background:#020;border:1px solid #0a3300;border-radius:6px;padding:10px 12px;\n margin:8px 0 12px;overflow-x:auto;\n}\n.code-block code{white-space:pre;word-break:normal;display:block;line-height:1.5;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n\n.inspector-layout{max-width:960px;margin:0 auto;padding:28px 20px;}\n.inspector-tabs{display:flex;gap:4px;margin-bottom:20px;}\n.inspector-tabs a{\n padding:7px 16px;border-radius:6px;text-decoration:none;\n font-size:.8125rem;color:#1a8c00;border:1px solid transparent;\n transition:color .15s,border-color .15s;\n}\n.inspector-tabs a:hover{color:#33ff00;}\n.inspector-tabs a.active{color:#33ff00;font-weight:600;border-color:#0a3300;background:#0a3300;}\n.inspector-section{margin-bottom:24px;}\n.inspector-section h2{\n font-family:'Geist Pixel',monospace;\n font-size:1rem;font-weight:600;color:#33ff00;margin-bottom:10px;\n}\n.inspector-section h3{\n font-family:'Geist Pixel',monospace;\n font-size:.875rem;font-weight:600;color:#1a8c00;margin:16px 0 8px;\n}\n.inspector-table{width:100%;border-collapse:collapse;margin-bottom:12px;}\n.inspector-table th,.inspector-table td{\n text-align:left;padding:8px 12px;border-bottom:1px solid #0a3300;\n font-size:.8125rem;\n}\n.inspector-table th{color:#1a8c00;font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;}\n.inspector-table td{color:#33ff00;}\n.inspector-table tbody tr{transition:background .1s;}\n.inspector-table tbody tr:hover{background:#0a3300;}\n.inspector-empty{color:#1a8c00;text-align:center;padding:20px 0;font-size:.8125rem;}\n\n.checkout-layout{\n display:flex;min-height:calc(100vh - 42px);\n}\n.checkout-summary{\n flex:1;background:#020;padding:48px 40px 48px 10%;\n display:flex;flex-direction:column;justify-content:center;\n border-right:1px solid #0a3300;\n}\n.checkout-form-side{\n flex:1;background:#000;padding:48px 10% 48px 40px;\n display:flex;flex-direction:column;justify-content:center;\n}\n.checkout-merchant{\n display:flex;align-items:center;gap:10px;margin-bottom:6px;\n}\n.checkout-merchant-name{\n font-family:'Geist Pixel',monospace;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-test-badge{\n font-size:.625rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n background:#0a3300;color:#1a8c00;padding:2px 8px;border-radius:4px;\n}\n.checkout-total{\n font-family:'Geist Pixel',monospace;\n font-size:2rem;font-weight:700;color:#33ff00;margin:8px 0 28px;\n}\n.checkout-line-item{\n display:flex;align-items:center;gap:14px;padding:14px 0;\n border-bottom:1px solid #0a3300;\n}\n.checkout-line-item:first-child{border-top:1px solid #0a3300;}\n.checkout-item-icon{\n width:42px;height:42px;border-radius:6px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;font-size:.875rem;font-weight:700;color:#116600;\n}\n.checkout-item-details{flex:1;min-width:0;}\n.checkout-item-name{font-size:.875rem;font-weight:600;color:#33ff00;}\n.checkout-item-qty{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.checkout-item-price{\n font-size:.875rem;font-weight:600;color:#33ff00;text-align:right;white-space:nowrap;\n}\n.checkout-item-unit{font-size:.6875rem;color:#1a8c00;text-align:right;margin-top:2px;}\n.checkout-totals{margin-top:20px;}\n.checkout-totals-row{\n display:flex;justify-content:space-between;padding:6px 0;\n font-size:.8125rem;color:#1a8c00;\n}\n.checkout-totals-row.total{\n border-top:1px solid #0a3300;margin-top:8px;padding-top:14px;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-form-section{margin-bottom:24px;}\n.checkout-form-label{\n font-size:.8125rem;font-weight:600;color:#33ff00;margin-bottom:8px;display:block;\n}\n.checkout-input{\n width:100%;padding:10px 12px;border:1px solid #0a3300;border-radius:6px;\n background:#020;color:#33ff00;font:inherit;font-size:.875rem;\n transition:border-color .15s;outline:none;\n}\n.checkout-input:focus{border-color:#33ff00;}\n.checkout-input::placeholder{color:#116600;}\n.checkout-card-box{\n border:1px solid #0a3300;border-radius:6px;padding:14px;\n background:#020;\n}\n.checkout-card-row{\n display:flex;gap:12px;margin-top:10px;\n}\n.checkout-card-row .checkout-input{flex:1;}\n.checkout-sim-note{\n font-size:.6875rem;color:#1a8c00;margin-top:10px;text-align:center;\n font-style:italic;\n}\n.checkout-pay-btn{\n width:100%;padding:14px;border:none;border-radius:8px;\n background:#33ff00;color:#000;font:inherit;font-size:.9375rem;font-weight:700;\n cursor:pointer;transition:background .15s;\n font-family:'Geist Pixel',monospace;\n}\n.checkout-pay-btn:hover{background:#44ff22;}\n.checkout-cancel{\n text-align:center;margin-top:14px;\n}\n.checkout-cancel a{\n color:#1a8c00;text-decoration:none;font-size:.8125rem;\n transition:color .15s;\n}\n.checkout-cancel a:hover{color:#33ff00;}\n@media(max-width:768px){\n .checkout-layout{flex-direction:column;}\n .checkout-summary{padding:32px 20px;border-right:none;border-bottom:1px solid #0a3300;}\n .checkout-form-side{padding:32px 20px;}\n}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <a href=\"https://github.com/vercel-labs/emulate/issues\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Report Issue</span><span class=\"short\">Report</span></a>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<link rel=\"icon\" href=\"/_emulate/favicon.ico\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(title: string, subtitle: string, body: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(title: string, sidebarHtml: string, bodyHtml: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface InspectorTab {\n id: string;\n label: string;\n href: string;\n}\n\nexport function renderInspectorPage(\n title: string,\n tabs: InspectorTab[],\n activeTab: string,\n body: string,\n service?: string,\n): string {\n const tabLinks = tabs\n .map(\n (t) => `<a href=\"${escapeAttr(t.href)}\" class=\"${t.id === activeTab ? \"active\" : \"\"}\">${escapeHtml(t.label)}</a>`,\n )\n .join(\"\");\n\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"inspector-layout\">\n <nav class=\"inspector-tabs\">${tabLinks}</nav>\n ${body}\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderFormPostPage(action: string, fields: Record<string, string>, service?: string): string {\n const hiddens = Object.entries(fields)\n .filter(([, v]) => v != null)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\\n\");\n\n return `${head(\"Redirecting\")}\n<body onload=\"document.forms[0].submit()\">\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\" style=\"text-align:center\">\n <div class=\"card-subtitle\">Redirecting…</div>\n <form method=\"POST\" action=\"${escapeAttr(action)}\">\n${hiddens}\n <noscript><button type=\"submit\" class=\"user-btn\" style=\"margin-top:12px;justify-content:center\">\n <span class=\"user-login\">Continue</span>\n </button></noscript>\n </form>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface CheckoutLineItem {\n name: string;\n quantity: number;\n unitPrice: number;\n totalPrice: number;\n currency: string;\n}\n\nexport interface CheckoutPageOptions {\n merchantName?: string;\n lineItems: CheckoutLineItem[];\n subtotal: number;\n total: number;\n currency: string;\n sessionId: string;\n cancelUrl?: string | null;\n}\n\nexport function renderCheckoutPage(opts: CheckoutPageOptions, service?: string): string {\n const fmt = (cents: number, cur: string) => `$${(cents / 100).toFixed(2)} ${cur.toUpperCase()}`;\n const fmtShort = (cents: number) => `$${(cents / 100).toFixed(2)}`;\n\n const itemsHtml =\n opts.lineItems.length > 0\n ? opts.lineItems\n .map((li) => {\n const initial = li.name.charAt(0).toUpperCase();\n const unitNote =\n li.quantity > 1 ? `<div class=\"checkout-item-unit\">${fmtShort(li.unitPrice)} each</div>` : \"\";\n return `<div class=\"checkout-line-item\">\n <div class=\"checkout-item-icon\">${escapeHtml(initial)}</div>\n <div class=\"checkout-item-details\">\n <div class=\"checkout-item-name\">${escapeHtml(li.name)}</div>\n <div class=\"checkout-item-qty\">Qty ${li.quantity}</div>\n </div>\n <div>\n <div class=\"checkout-item-price\">${fmtShort(li.totalPrice)}</div>\n ${unitNote}\n </div>\n</div>`;\n })\n .join(\"\")\n : '<p class=\"empty\">No line items</p>';\n\n const totalsHtml = `<div class=\"checkout-totals\">\n <div class=\"checkout-totals-row\">\n <span>Subtotal</span><span>${fmtShort(opts.subtotal)}</span>\n </div>\n <div class=\"checkout-totals-row total\">\n <span>Total due</span><span>${fmt(opts.total, opts.currency)}</span>\n </div>\n</div>`;\n\n const cancelHtml = opts.cancelUrl\n ? `<div class=\"checkout-cancel\"><a href=\"${escapeAttr(opts.cancelUrl)}\">Cancel</a></div>`\n : \"\";\n\n const merchant = opts.merchantName ? escapeHtml(opts.merchantName) : \"Checkout\";\n\n return `${head(\"Checkout\")}\n<body>\n${emuBar(service)}\n<div class=\"checkout-layout\">\n <div class=\"checkout-summary\">\n <div class=\"checkout-merchant\">\n <span class=\"checkout-merchant-name\">${merchant}</span>\n <span class=\"checkout-test-badge\">Test Mode</span>\n </div>\n <div class=\"checkout-total\">${fmtShort(opts.total)}</div>\n ${itemsHtml}\n ${totalsHtml}\n </div>\n <div class=\"checkout-form-side\">\n <form method=\"post\" action=\"/checkout/${escapeAttr(opts.sessionId)}/complete\">\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Email</label>\n <input type=\"email\" name=\"email\" class=\"checkout-input\" placeholder=\"you@example.com\"/>\n </div>\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Card information</label>\n <div class=\"checkout-card-box\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"1234 1234 1234 1234\" disabled/>\n <div class=\"checkout-card-row\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"MM / YY\" disabled/>\n <input type=\"text\" class=\"checkout-input\" placeholder=\"CVC\" disabled/>\n </div>\n </div>\n <div class=\"checkout-sim-note\">Card fields are simulated. Payment will be auto-approved.</div>\n </div>\n <button type=\"submit\" class=\"checkout-pay-btn\">Pay ${fmtShort(opts.total)}</button>\n </form>\n ${cancelHtml}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>` : \"\";\n const emailLine = opts.email ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>` : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import type { Context, Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\nimport type { Store } from \"./store.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\nimport type { RequestLedger } from \"./ledger.js\";\nimport type { ConnectionVars, EmulatorInstanceInfo, ResolvedConnection, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport type { TokenMap } from \"./middleware/auth.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\n\nexport interface CredentialRequest {\n type?: string;\n login?: string;\n name?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n [key: string]: unknown;\n}\n\nexport interface IssuedCredential {\n type: string;\n token?: string;\n login?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n token_url?: string;\n authorization_url?: string;\n notes?: string;\n [key: string]: unknown;\n}\n\nexport interface ControlPlaneOptions {\n manifest: ServiceManifest;\n instance: EmulatorInstanceInfo;\n store: Store;\n webhooks: WebhookDispatcher;\n ledger: RequestLedger;\n tokenMap?: TokenMap;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport const INSTANCE_NOTES = \"Hosted deployments create instances lazily when the returned URL is first used.\";\n\nexport interface InstanceCreation {\n service: string;\n instance: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n pathUrl: string;\n hostHint: string;\n notes: string;\n}\n\n/** The single, canonical shape for POST /_emulate/instances, shared by every host. */\nexport function buildInstanceCreation(args: {\n service: string;\n instance: string;\n providerBaseUrl: string;\n pathOrigin: string;\n hostSuffix: string;\n}): InstanceCreation {\n return {\n service: args.service,\n instance: args.instance,\n providerBaseUrl: args.providerBaseUrl,\n controlBaseUrl: `${args.providerBaseUrl}/_emulate`,\n pathUrl: `${args.pathOrigin}/${args.service}/${args.instance}`,\n hostHint: `${args.service}.${args.instance}.${args.hostSuffix}`,\n notes: INSTANCE_NOTES,\n };\n}\n\nfunction connectionVars(\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n overrides?: Partial<ConnectionVars>,\n): ConnectionVars {\n return {\n baseUrl: instance.providerBaseUrl,\n providerBaseUrl: instance.providerBaseUrl,\n controlBaseUrl: instance.controlBaseUrl,\n service: manifest.id,\n instance: instance.instance,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n ...overrides,\n };\n}\n\nexport function registerControlPlane(app: Hono<AppEnv>, options: ControlPlaneOptions): void {\n const { instance, store, webhooks, ledger } = options;\n const manifest = enrichManifest(options.manifest, { ledgerPersistent: options.ledgerPersistent });\n const hostSuffix = options.hostSuffix ?? \"emulators.dev\";\n\n app.get(\"/_emulate\", (c) => c.html(renderLandingPage(manifest, instance)));\n app.get(\"/_emulate/manifest\", (c) =>\n c.json({\n manifest,\n instance,\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance)),\n }),\n );\n app.get(\"/_emulate/quickstart\", (c) => c.text(renderQuickstart(manifest, instance)));\n app.get(\"/_emulate/specs\", (c) => c.json({ specs: manifest.specs, surfaces: manifest.surfaces }));\n app.get(\"/_emulate/coverage\", (c) => c.json(coverageReport(manifest)));\n app.get(\"/_emulate/connections\", (c) => {\n const overrides: Partial<ConnectionVars> = {};\n const token = c.req.query(\"token\");\n const clientId = c.req.query(\"client_id\");\n const clientSecret = c.req.query(\"client_secret\");\n if (token) overrides.token = token;\n if (clientId) overrides.clientId = clientId;\n if (clientSecret) overrides.clientSecret = clientSecret;\n return c.json({\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance, overrides)),\n });\n });\n app.get(\"/_emulate/openapi\", (c) => redirectToSpec(c, manifest, instance, \"openapi\"));\n app.get(\"/_emulate/graphql\", (c) => endpointForSurface(c, manifest, instance, \"graphql\"));\n app.get(\"/_emulate/mcp\", (c) => endpointForSurface(c, manifest, instance, \"mcp\"));\n app.get(\"/_emulate/state\", (c) => c.json(store.snapshot()));\n app.get(\"/_emulate/ledger\", (c) => {\n const limitParam = c.req.query(\"limit\");\n const limit = limitParam ? Number.parseInt(limitParam, 10) : undefined;\n return c.json({ entries: ledger.list(Number.isFinite(limit) ? limit : undefined) });\n });\n app.delete(\"/_emulate/ledger\", (c) => {\n ledger.clear();\n return c.json({ ok: true });\n });\n app.get(\"/_emulate/logs\", (c) => c.json({ webhooks: webhooks.getDeliveries(), requests: ledger.list(100) }));\n app.post(\"/_emulate/reset\", async (c) => {\n if (options.reset) {\n await options.reset();\n } else {\n store.reset();\n webhooks.clear();\n ledger.clear();\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/seed\", async (c) => {\n if (!options.seed) {\n return c.json({ error: \"unsupported\", message: \"This emulator does not support runtime seeding.\" }, 501);\n }\n const body = await c.req.json().catch(() => undefined);\n try {\n await options.seed(body);\n } catch (err) {\n return c.json({ error: \"invalid_seed\", message: err instanceof Error ? err.message : \"Seed failed.\" }, 400);\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/credentials\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as CredentialRequest;\n try {\n if (options.issueCredential) {\n const credential = await options.issueCredential(body);\n return c.json({ credential });\n }\n const credential = issueDefaultCredential(body, manifest, options.tokenMap);\n if (!credential) {\n return c.json({ error: \"unsupported\", message: \"This emulator cannot create that credential type.\" }, 501);\n }\n return c.json({ credential });\n } catch (err) {\n return c.json(\n { error: \"unsupported\", message: err instanceof Error ? err.message : \"Credential creation failed.\" },\n 400,\n );\n }\n });\n app.post(\"/_emulate/instances\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as { instance?: string; service?: string };\n const nextInstance = slug(body.instance ?? `${manifest.id}-${randomId().slice(0, 8)}`);\n const service = slug(body.service ?? manifest.id);\n const origin = new URL(instance.providerBaseUrl).origin;\n return c.json(\n buildInstanceCreation({\n service,\n instance: nextInstance,\n providerBaseUrl: `${origin}/${service}/${nextInstance}`,\n pathOrigin: origin,\n hostSuffix,\n }),\n );\n });\n}\n\nexport function renderLandingPage(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const surfaces = manifest.surfaces\n .map(\n (surface) =>\n `<tr><td>${escapeHtml(surface.title)}</td><td><span class=\"badge\">${escapeHtml(surface.status)}</span></td><td><code>${escapeHtml(surface.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const auth = manifest.auth\n .map((cap) => `<li><span class=\"badge\">${escapeHtml(cap.status)}</span> ${escapeHtml(cap.title)}</li>`)\n .join(\"\");\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const instanceLabel = instance.instance ? ` · instance <code>${escapeHtml(instance.instance)}</code>` : \"\";\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Base URLs${instanceLabel}</div>\n <p class=\"info-text\">Provider: <code>${escapeHtml(instance.providerBaseUrl)}</code></p>\n <p class=\"info-text\">Control: <code>${escapeHtml(instance.controlBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Credentials</div>\n <ul class=\"perm-list\">${auth}</ul>\n </div>\n ${renderConnectionsHtml(connections)}\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">${controlLinks()}</p>\n </div>\n `,\n manifest.id,\n );\n}\n\nfunction renderConnectionsHtml(connections: ResolvedConnection[]): string {\n if (connections.length === 0) return \"\";\n const blocks = connections\n .map(\n (c) =>\n `<div class=\"section-heading\">${escapeHtml(c.title)}</div><pre class=\"code-block\"><code>${escapeHtml(c.body)}</code></pre>`,\n )\n .join(\"\");\n return `<div class=\"s-card\"><div class=\"section-heading\">Connect</div>${blocks}</div>`;\n}\n\nfunction controlLinks(): string {\n const routes = [\"manifest\", \"quickstart\", \"specs\", \"coverage\", \"connections\", \"state\", \"ledger\", \"logs\"];\n return routes.map((r) => `<a href=\"/_emulate/${r}\">${r}</a>`).join(\" | \");\n}\n\nexport function renderQuickstart(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const lines = [\n `# ${manifest.name} Emulator`,\n \"\",\n manifest.description,\n \"\",\n `Provider base URL: ${instance.providerBaseUrl}`,\n `Control base URL: ${instance.controlBaseUrl}`,\n \"\",\n \"Supported surfaces:\",\n ...manifest.surfaces.map((s) => `- ${s.title}: ${s.status}${s.basePath ? ` at ${s.basePath}` : \"\"}`),\n \"\",\n \"Control endpoints:\",\n `- ${instance.controlBaseUrl}/manifest`,\n `- ${instance.controlBaseUrl}/coverage`,\n `- ${instance.controlBaseUrl}/connections`,\n `- ${instance.controlBaseUrl}/state`,\n `- ${instance.controlBaseUrl}/ledger`,\n `- POST ${instance.controlBaseUrl}/credentials`,\n `- POST ${instance.controlBaseUrl}/seed`,\n `- POST ${instance.controlBaseUrl}/reset`,\n \"\",\n \"Connect:\",\n ...connections.flatMap((c) => [\"\", `## ${c.title}`, c.body]),\n ];\n return lines.join(\"\\n\");\n}\n\nfunction issueDefaultCredential(\n request: CredentialRequest,\n manifest: ServiceManifest,\n tokenMap: TokenMap | undefined,\n): IssuedCredential | null {\n const type = request.type ?? manifest.auth[0]?.type ?? \"bearer-token\";\n if (type !== \"bearer-token\" && type !== \"api-key\") return null;\n if (!tokenMap) return null;\n const token = typeof request.token === \"string\" && request.token ? request.token : `emu_${manifest.id}_${randomId()}`;\n const login = request.login ?? \"admin\";\n const scopes = Array.isArray(request.scopes) ? request.scopes.filter((s): s is string => typeof s === \"string\") : [];\n tokenMap.set(token, { login, id: Date.now(), scopes });\n return { type, token, login, scopes };\n}\n\nfunction redirectToSpec(c: Context<AppEnv>, manifest: ServiceManifest, instance: EmulatorInstanceInfo, kind: string) {\n const spec = manifest.specs.find((s) => s.kind === kind && s.url);\n if (spec?.url) return c.redirect(resolveUrl(instance.providerBaseUrl, spec.url));\n const advertised = manifest.specs.some((s) => s.kind === kind);\n if (kind === \"openapi\" && advertised) return c.redirect(`${instance.providerBaseUrl}/openapi.json`);\n return c.json({ error: \"not_found\", message: `No ${kind} spec is advertised for this emulator.` }, 404);\n}\n\nfunction endpointForSurface(\n c: Context<AppEnv>,\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n kind: \"graphql\" | \"mcp\",\n) {\n const surface = manifest.surfaces.find((s) => s.kind === kind && s.basePath);\n if (!surface?.basePath) {\n return c.json({ error: \"not_found\", message: `No ${kind} surface is advertised for this emulator.` }, 404);\n }\n return c.json({ endpoint: resolveUrl(instance.providerBaseUrl, surface.basePath), surface });\n}\n\nfunction resolveUrl(baseUrl: string, pathOrUrl: string): string {\n if (/^https?:\\/\\//i.test(pathOrUrl)) return pathOrUrl;\n return `${baseUrl}${pathOrUrl.startsWith(\"/\") ? \"\" : \"/\"}${pathOrUrl}`;\n}\n\nfunction randomId(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction slug(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n","import { Hono, cors } from \"./http.js\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport {\n authMiddleware,\n type AuthFallback,\n type TokenMap,\n type AppKeyResolver,\n type AppEnv,\n} from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\nimport { RequestLedger, createLedgerMiddleware } from \"./ledger.js\";\nimport { registerControlPlane, type CredentialRequest, type IssuedCredential } from \"./control-plane.js\";\nimport { createDefaultManifest, type ServiceManifest } from \"./manifest.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n manifest?: ServiceManifest;\n instance?: string;\n enableControlPlane?: boolean;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form surfaced in control-plane responses. */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n const ledger = new RequestLedger();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://docs.emulators.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n if (options.enableControlPlane !== false) {\n const manifest = options.manifest ?? createDefaultManifest(plugin.name);\n registerControlPlane(app, {\n manifest,\n instance: {\n service: manifest.id,\n instance: options.instance,\n baseUrl,\n providerBaseUrl: baseUrl,\n controlBaseUrl: `${baseUrl}/_emulate`,\n },\n store,\n webhooks,\n ledger,\n tokenMap,\n ledgerPersistent: options.ledgerPersistent,\n hostSuffix: options.hostSuffix,\n reset: options.reset,\n seed: options.seed,\n issueCredential: options.issueCredential,\n });\n }\n\n app.use(\"*\", createLedgerMiddleware(ledger, { webhooks }));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403,\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404,\n ),\n );\n\n return { app, store, webhooks, ledger, port, baseUrl, tokenMap };\n}\n","import type { EmulatorInstanceInfo, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\nimport { renderQuickstart, INSTANCE_NOTES } from \"./control-plane.js\";\n\nexport interface ServiceHostContext {\n manifest: ServiceManifest;\n service: string;\n /** Apex origin for the path form, e.g. https://emulators.dev. */\n origin: string;\n /** Request protocol including the colon, e.g. \"https:\". */\n protocol: string;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix: string;\n /** Whether the deployed host persists the ledger across eviction. */\n ledgerPersistent?: boolean;\n}\n\nconst SAMPLE_INSTANCE = \"your-instance\";\n\nfunction sampleInstanceInfo(ctx: ServiceHostContext): EmulatorInstanceInfo {\n const providerBaseUrl = `${ctx.protocol}//${ctx.service}.${SAMPLE_INSTANCE}.${ctx.hostSuffix}`;\n return {\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n baseUrl: providerBaseUrl,\n providerBaseUrl,\n controlBaseUrl: `${providerBaseUrl}/_emulate`,\n };\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n\n/**\n * Serve the service-level control plane on a bare service host (e.g.\n * github.emulators.dev) so a human or agent can read the manifest, quickstart,\n * specs, coverage, and connection snippets WITHOUT first creating an instance.\n * Returns null for paths this should not handle (so the caller can fall through\n * to the interactive console SPA).\n */\nexport function serviceHostControlPlane(path: string, method: string, ctx: ServiceHostContext): Response | null {\n if (!path.startsWith(\"/_emulate\")) return null;\n if (method !== \"GET\" && method !== \"HEAD\") return null;\n\n const manifest = enrichManifest(ctx.manifest, { ledgerPersistent: ctx.ledgerPersistent });\n const sample = sampleInstanceInfo(ctx);\n const connections = resolveConnections(manifest.connections ?? [], {\n baseUrl: sample.providerBaseUrl,\n providerBaseUrl: sample.providerBaseUrl,\n controlBaseUrl: sample.controlBaseUrl,\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n });\n\n switch (path) {\n case \"/_emulate\":\n return new Response(renderServiceLanding(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n case \"/_emulate/manifest\":\n return json({ manifest, instance: null, sampleInstance: sample, connections });\n case \"/_emulate/quickstart\":\n return new Response(renderServiceQuickstart(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n });\n case \"/_emulate/specs\":\n return json({ specs: manifest.specs, surfaces: manifest.surfaces });\n case \"/_emulate/coverage\":\n return json(coverageReport(manifest));\n case \"/_emulate/connections\":\n return json({ connections });\n case \"/_emulate/openapi\": {\n const spec = manifest.specs.find((s) => s.kind === \"openapi\");\n if (!spec) return json({ error: \"not_found\", message: \"No OpenAPI spec is advertised for this emulator.\" }, 404);\n return json({\n openapi: `${sample.providerBaseUrl}${spec.url ?? \"/openapi.json\"}`,\n note: \"Create an instance, then fetch this URL for the live spec.\",\n });\n }\n default:\n return null;\n }\n}\n\nfunction renderServiceQuickstart(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const base = renderQuickstart(manifest, sample);\n const header = [\n `# ${manifest.name} Emulator (service host)`,\n \"\",\n \"Create an instance:\",\n `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances -H 'content-type: application/json' -d '{\"instance\":\"my-run\"}'`,\n `# ${INSTANCE_NOTES}`,\n \"\",\n \"Then use the returned providerBaseUrl / controlBaseUrl. Example below uses a sample instance.\",\n \"\",\n ];\n return header.join(\"\\n\") + base;\n}\n\nfunction renderServiceLanding(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const surfaces = manifest.surfaces\n .map(\n (s) =>\n `<tr><td>${escapeHtml(s.title)}</td><td><span class=\"badge\">${escapeHtml(s.status)}</span></td><td><code>${escapeHtml(s.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const createCurl = `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances \\\\\n -H \"content-type: application/json\" \\\\\n -d '{\"instance\":\"my-run\"}'`;\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Create an instance</div>\n <p class=\"info-text\">Each instance is isolated, stateful, and addressable at its own host.</p>\n <pre class=\"code-block\"><code>${escapeHtml(createCurl)}</code></pre>\n <p class=\"info-text\">${escapeHtml(INSTANCE_NOTES)}</p>\n <p class=\"info-text\">Sample instance host: <code>${escapeHtml(sample.providerBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">\n <a href=\"/_emulate/manifest\">manifest</a> | <a href=\"/_emulate/quickstart\">quickstart</a> |\n <a href=\"/_emulate/specs\">specs</a> | <a href=\"/_emulate/coverage\">coverage</a> |\n <a href=\"/_emulate/connections\">connections</a>\n </p>\n </div>\n `,\n manifest.id,\n );\n}\n\nexport interface ServiceCatalogEntry {\n id: string;\n name: string;\n description: string;\n}\n\n/**\n * Server-rendered catalog landing for the apex host. Readable by an agent over a\n * raw fetch (no JS): it lists every emulator with its host and manifest URL. The\n * interactive console SPA is served instead only for browser navigations.\n */\nexport function renderCatalogPage(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): string {\n const rows = entries\n .map((e) => {\n const host = `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`;\n return `<a class=\"app-link\" href=\"${escapeHtml(host)}\">\n <img src=\"/_emulate/icons/${escapeHtml(e.id)}\" alt=\"\" width=\"24\" height=\"24\" style=\"object-fit:contain\" />\n <span><span class=\"app-link-name\">${escapeHtml(e.name)}</span><span class=\"app-link-scopes\">${escapeHtml(host)}</span></span>\n </a>`;\n })\n .join(\"\");\n return renderCardPage(\n \"Emulate\",\n \"Stateful integration emulators for real developer APIs. Each emulator has its own host; open one or fetch its manifest.\",\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Emulators</div>\n ${rows}\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">For agents</div>\n <p class=\"info-text\">Machine-readable catalog: <a href=\"/_emulate/services\">/_emulate/services</a></p>\n <p class=\"info-text\">Each service host serves <code>/_emulate/manifest</code>, <code>/_emulate/quickstart</code>, and <code>/_emulate/connections</code>, and the provider API directly against a default instance.</p>\n </div>\n `,\n );\n}\n\n/** A machine-readable index of the services a host serves, with both URL forms. */\nexport function servicesCatalog(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): Response {\n const services = entries.map((e) => ({\n id: e.id,\n name: e.name,\n description: e.description,\n icon: `${ctx.origin}/_emulate/icons/${e.id}`,\n serviceHost: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`,\n instanceHostPattern: `${ctx.protocol}//${e.id}.<instance>.${ctx.hostSuffix}`,\n pathForm: `${ctx.origin}/${e.id}/<instance>`,\n manifest: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}/_emulate/manifest`,\n }));\n return new Response(JSON.stringify({ services }), {\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n","import type { Context } from \"../http.js\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(c: Context, totalCount: number, page: number, perPage: number): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nexport interface PersistenceAdapter {\n load(): Promise<string | null>;\n save(data: string): Promise<void>;\n}\n\nexport function filePersistence(path: string): PersistenceAdapter {\n return {\n async load() {\n try {\n return await readFile(path, \"utf-8\");\n } catch {\n return null;\n }\n },\n async save(data: string) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, data, \"utf-8\");\n },\n };\n}\n","import type {\n ServicePlugin,\n Store,\n AppKeyResolver,\n AuthFallback,\n WebhookDispatcher,\n ServiceManifest,\n CredentialRequest,\n IssuedCredential,\n TokenMap,\n} from \"@emulators/core\";\n\nexport interface LoadedService {\n plugin: ServicePlugin;\n // Each plugin owns its manifest (the single source of truth). load() resolves\n // it lazily alongside the plugin so the CLI never eager-loads every service.\n manifest: ServiceManifest;\n seedFromConfig?(store: Store, baseUrl: string, config: unknown, webhooks?: WebhookDispatcher): void;\n createAppKeyResolver?(store: Store): AppKeyResolver;\n ensureUser?(store: Store, baseUrl: string, login: string): number;\n issueCredential?(\n store: Store,\n baseUrl: string,\n tokenMap: TokenMap,\n request: CredentialRequest,\n webhooks?: WebhookDispatcher,\n ): IssuedCredential;\n}\n\nexport interface ServiceEntry {\n label: string;\n endpoints: string;\n load(): Promise<LoadedService>;\n defaultFallback(svcSeedConfig?: Record<string, unknown>): AuthFallback;\n initConfig: Record<string, unknown>;\n}\n\nconst SERVICE_NAME_LIST = [\n \"vercel\",\n \"github\",\n \"google\",\n \"slack\",\n \"apple\",\n \"microsoft\",\n \"okta\",\n \"aws\",\n \"resend\",\n \"stripe\",\n \"mongoatlas\",\n \"clerk\",\n \"spotify\",\n \"x\",\n \"workos\",\n \"autumn\",\n] as const;\nexport type ServiceName = (typeof SERVICE_NAME_LIST)[number];\nexport const SERVICE_NAMES: readonly ServiceName[] = SERVICE_NAME_LIST;\n\nexport function issueServiceCredential(\n service: ServiceName,\n loaded: LoadedService,\n store: Store,\n baseUrl: string,\n tokenMap: TokenMap,\n request: CredentialRequest,\n webhooks?: WebhookDispatcher,\n): IssuedCredential {\n if (loaded.issueCredential) {\n return loaded.issueCredential(store, baseUrl, tokenMap, request, webhooks);\n }\n const type = request.type ?? loaded.manifest.auth[0]?.type ?? \"bearer-token\";\n if (type === \"bearer-token\" || type === \"api-key\") {\n const login = request.login ?? \"admin\";\n const scopes = Array.isArray(request.scopes)\n ? request.scopes.filter((s): s is string => typeof s === \"string\")\n : [];\n const id = loaded.ensureUser?.(store, baseUrl, login) ?? Date.now();\n const token =\n typeof request.token === \"string\" && request.token.length > 0 ? request.token : defaultToken(service, type);\n tokenMap.set(token, { login, id, scopes });\n return { type, token, login, scopes };\n }\n\n if (\n type === \"oauth-authorization-code\" ||\n type === \"oauth-client-credentials\" ||\n type === \"dynamic-client-registration\"\n ) {\n if (!loaded.seedFromConfig) throw new Error(`Credential type ${type} is not supported by ${service}`);\n const clientId = request.client_id ?? defaultClientId(service);\n const clientSecret = request.client_secret ?? defaultClientSecret(service);\n const redirectUris = normalizeRedirectUris(request.redirect_uris);\n const name = request.name ?? `${SERVICE_REGISTRY[service].label.replace(/ emulator$/i, \"\")} Client`;\n const seed = credentialSeed(service, { clientId, clientSecret, redirectUris, name, request });\n if (!seed) throw new Error(`Credential type ${type} is not supported by ${service}`);\n loaded.seedFromConfig(store, baseUrl, seed, webhooks);\n return {\n type,\n client_id: clientId,\n client_secret: clientSecret,\n redirect_uris: redirectUris,\n authorization_url: authorizationUrlFor(service, baseUrl),\n token_url: tokenUrlFor(service, baseUrl),\n };\n }\n\n throw new Error(`Credential type ${type} is not supported by ${service}`);\n}\n\nfunction defaultToken(service: ServiceName, type: string): string {\n const prefix = type === \"api-key\" ? apiKeyPrefix(service) : `emu_${service}`;\n return `${prefix}_${randomId()}`;\n}\n\nfunction apiKeyPrefix(service: ServiceName): string {\n if (service === \"stripe\") return \"sk_test\";\n if (service === \"resend\") return \"re\";\n if (service === \"clerk\") return \"sk_test\";\n return `emu_${service}`;\n}\n\nfunction defaultClientId(service: ServiceName): string {\n if (service === \"spotify\") return `app_${randomId().slice(0, 18)}`;\n if (service === \"github\") return `Iv1.${randomId().slice(0, 16)}`;\n if (service === \"google\") return `${randomId().slice(0, 24)}.apps.googleusercontent.com`;\n return `${service}_${randomId().slice(0, 18)}`;\n}\n\nfunction defaultClientSecret(service: ServiceName): string {\n if (service === \"google\") return `GOCSPX-${randomId().slice(0, 24)}`;\n return `secret_${randomId()}`;\n}\n\nfunction normalizeRedirectUris(value: unknown): string[] {\n if (Array.isArray(value)) {\n const uris = value.filter((uri): uri is string => typeof uri === \"string\" && uri.length > 0);\n if (uris.length > 0) return uris;\n }\n return [\"http://localhost:3000/callback\"];\n}\n\nfunction credentialSeed(\n service: ServiceName,\n args: {\n clientId: string;\n clientSecret: string;\n redirectUris: string[];\n name: string;\n request: CredentialRequest;\n },\n): unknown | null {\n const { clientId, clientSecret, redirectUris, name, request } = args;\n if (service === \"github\") {\n return { oauth_apps: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }] };\n }\n if (service === \"google\" || service === \"apple\" || service === \"microsoft\") {\n return { oauth_clients: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }] };\n }\n if (service === \"okta\") {\n return {\n oauth_clients: [\n {\n client_id: clientId,\n client_secret: clientSecret,\n name,\n redirect_uris: redirectUris,\n auth_server_id: typeof request.auth_server_id === \"string\" ? request.auth_server_id : \"default\",\n },\n ],\n };\n }\n if (service === \"slack\") {\n return {\n oauth_apps: [\n {\n client_id: clientId,\n client_secret: clientSecret,\n name,\n redirect_uris: redirectUris,\n scopes: Array.isArray(request.scopes) ? request.scopes : [\"chat:write\", \"channels:read\", \"users:read\"],\n user_scopes: Array.isArray(request.user_scopes) ? request.user_scopes : [],\n },\n ],\n };\n }\n if (service === \"vercel\") {\n return { integrations: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }] };\n }\n if (service === \"spotify\") {\n return { clients: [{ client_id: clientId, client_secret: clientSecret, name }] };\n }\n if (service === \"clerk\") {\n return {\n oauth_applications: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }],\n };\n }\n if (service === \"x\") {\n return {\n oauth_clients: [\n {\n client_id: clientId,\n client_secret: clientSecret,\n client_type: \"confidential\",\n name,\n redirect_uris: redirectUris,\n },\n ],\n };\n }\n return null;\n}\n\nfunction tokenUrlFor(service: ServiceName, baseUrl: string): string | undefined {\n const paths: Partial<Record<ServiceName, string>> = {\n github: \"/login/oauth/access_token\",\n google: \"/token\",\n apple: \"/auth/token\",\n microsoft: \"/oauth2/v2.0/token\",\n okta: \"/oauth2/default/v1/token\",\n slack: \"/api/oauth.v2.access\",\n vercel: \"/v2/oauth/access_token\",\n spotify: \"/api/token\",\n clerk: \"/oauth/token\",\n x: \"/2/oauth2/token\",\n };\n const path = paths[service];\n return path ? `${baseUrl}${path}` : undefined;\n}\n\nfunction authorizationUrlFor(service: ServiceName, baseUrl: string): string | undefined {\n const paths: Partial<Record<ServiceName, string>> = {\n github: \"/login/oauth/authorize\",\n google: \"/o/oauth2/v2/auth\",\n apple: \"/auth/authorize\",\n microsoft: \"/oauth2/v2.0/authorize\",\n okta: \"/oauth2/default/v1/authorize\",\n slack: \"/oauth/v2/authorize\",\n vercel: \"/integrations/oauth/authorize\",\n clerk: \"/oauth/authorize\",\n x: \"/2/oauth2/authorize\",\n };\n const path = paths[service];\n return path ? `${baseUrl}${path}` : undefined;\n}\n\nfunction randomId(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nexport const SERVICE_REGISTRY: Record<ServiceName, ServiceEntry> = {\n vercel: {\n label: \"Vercel REST API emulator\",\n endpoints: \"projects, deployments, domains, env vars, users, teams, file uploads, protection bypass\",\n async load() {\n const mod = await import(\"@emulators/vercel\");\n return {\n plugin: mod.vercelPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ username: login }] });\n return mod.getVercelStore(store).users.findOneBy(\"username\", login)?.id ?? 1;\n },\n };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ username?: string }> | undefined)?.[0]?.username ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [] };\n },\n initConfig: {\n vercel: {\n users: [{ username: \"developer\", name: \"Developer\", email: \"dev@example.com\" }],\n teams: [{ slug: \"my-team\", name: \"My Team\" }],\n projects: [{ name: \"my-app\", team: \"my-team\", framework: \"nextjs\" }],\n integrations: [\n {\n client_id: \"oac_example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My Vercel App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/vercel\"],\n },\n ],\n },\n },\n },\n\n github: {\n label: \"GitHub REST API emulator\",\n endpoints:\n \"users, repos, issues, PRs, comments, reviews, labels, milestones, branches, git data, orgs, teams, releases, webhooks, search, actions, checks, rate limit\",\n async load() {\n const mod = await import(\"@emulators/github\");\n return {\n plugin: mod.githubPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n createAppKeyResolver(store: Store): AppKeyResolver {\n return (appId: number) => {\n try {\n const gh = mod.getGitHubStore(store);\n const ghApp = gh.apps.all().find((a) => a.app_id === appId);\n if (!ghApp) return null;\n return { privateKey: ghApp.private_key, slug: ghApp.slug, name: ghApp.name };\n } catch {\n return null;\n }\n };\n },\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ login }] });\n return mod.getGitHubStore(store).users.findOneBy(\"login\", login)?.id ?? 1;\n },\n };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ login?: string }> | undefined)?.[0]?.login ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n },\n initConfig: {\n github: {\n users: [\n {\n login: \"octocat\",\n name: \"The Octocat\",\n email: \"octocat@github.com\",\n bio: \"I am the Octocat\",\n company: \"GitHub\",\n location: \"San Francisco\",\n },\n ],\n orgs: [{ login: \"my-org\", name: \"My Organization\", description: \"A test organization\" }],\n repos: [\n {\n owner: \"octocat\",\n name: \"hello-world\",\n description: \"My first repository\",\n language: \"JavaScript\",\n topics: [\"hello\", \"world\"],\n auto_init: true,\n },\n {\n owner: \"my-org\",\n name: \"org-repo\",\n description: \"An organization repository\",\n language: \"TypeScript\",\n auto_init: true,\n },\n ],\n oauth_apps: [\n {\n client_id: \"Iv1.example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/github\"],\n },\n ],\n },\n },\n },\n\n google: {\n label: \"Google OAuth 2.0 / OpenID Connect + Gmail, Calendar, and Drive emulator\",\n endpoints:\n \"OAuth authorize, token exchange, userinfo, OIDC discovery, token revocation, Gmail messages/drafts/threads/labels/history/settings, Calendar lists/events/freebusy, Drive files/uploads\",\n async load() {\n const mod = await import(\"@emulators/google\");\n return { plugin: mod.googlePlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@gmail.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\"] };\n },\n initConfig: {\n google: {\n users: [\n {\n email: \"testuser@example.com\",\n name: \"Test User\",\n picture: \"https://lh3.googleusercontent.com/a/default-user\",\n email_verified: true,\n },\n ],\n oauth_clients: [\n {\n client_id: \"example-client-id.apps.googleusercontent.com\",\n client_secret: \"GOCSPX-example_secret\",\n name: \"Code App (Google)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/google\"],\n },\n ],\n labels: [\n {\n id: \"Label_ops\",\n user_email: \"testuser@example.com\",\n name: \"Ops/Review\",\n color_background: \"#DDEEFF\",\n color_text: \"#111111\",\n },\n ],\n messages: [\n {\n id: \"msg_welcome\",\n user_email: \"testuser@example.com\",\n from: \"welcome@example.com\",\n to: \"testuser@example.com\",\n subject: \"Welcome to the Gmail emulator\",\n body_text: \"You can now test Gmail, Calendar, and Drive flows locally.\",\n label_ids: [\"INBOX\", \"UNREAD\", \"CATEGORY_UPDATES\"],\n date: \"2025-01-04T10:00:00.000Z\",\n },\n ],\n calendars: [\n {\n id: \"primary\",\n user_email: \"testuser@example.com\",\n summary: \"testuser@example.com\",\n primary: true,\n selected: true,\n time_zone: \"UTC\",\n },\n ],\n calendar_events: [\n {\n id: \"evt_kickoff\",\n user_email: \"testuser@example.com\",\n calendar_id: \"primary\",\n summary: \"Project Kickoff\",\n start_date_time: \"2025-01-10T09:00:00.000Z\",\n end_date_time: \"2025-01-10T09:30:00.000Z\",\n },\n ],\n drive_items: [\n {\n id: \"drv_docs\",\n user_email: \"testuser@example.com\",\n name: \"Docs\",\n mime_type: \"application/vnd.google-apps.folder\",\n parent_ids: [\"root\"],\n },\n ],\n },\n },\n },\n\n slack: {\n label: \"Slack API emulator\",\n endpoints:\n \"auth, chat, conversations, users, profiles, presence, files, pins, bookmarks, views, reactions, team, OAuth, incoming webhooks, inspector\",\n async load() {\n const mod = await import(\"@emulators/slack\");\n return { plugin: mod.slackPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return {\n login: \"U000000001\",\n id: 1,\n scopes: [],\n };\n },\n initConfig: {\n slack: {\n team: { name: \"My Workspace\", domain: \"my-workspace\" },\n users: [\n {\n name: \"developer\",\n real_name: \"Developer\",\n email: \"dev@example.com\",\n profile: {\n title: \"Local Developer\",\n status_text: \"Testing locally\",\n status_emoji: \":computer:\",\n },\n presence: \"active\",\n },\n ],\n channels: [\n { name: \"general\", topic: \"General discussion\" },\n { name: \"random\", topic: \"Random stuff\" },\n ],\n bots: [{ name: \"my-bot\" }],\n oauth_apps: [\n {\n client_id: \"12345.67890\",\n client_secret: \"example_client_secret\",\n app_id: \"A000000001\",\n name: \"My Slack App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/slack\"],\n scopes: [\n \"chat:write\",\n \"channels:read\",\n \"channels:history\",\n \"channels:join\",\n \"channels:manage\",\n \"channels:write\",\n \"groups:read\",\n \"groups:history\",\n \"groups:write\",\n \"im:read\",\n \"im:history\",\n \"im:write\",\n \"mpim:read\",\n \"mpim:history\",\n \"mpim:write\",\n \"users:read\",\n \"users:read.email\",\n \"users.profile:read\",\n \"users.profile:write\",\n \"users:write\",\n \"files:read\",\n \"files:write\",\n \"pins:read\",\n \"pins:write\",\n \"bookmarks:read\",\n \"bookmarks:write\",\n \"reactions:read\",\n \"reactions:write\",\n \"team:read\",\n ],\n user_scopes: [\"users:read\", \"users.profile:read\"],\n bot_name: \"my-bot\",\n },\n ],\n strict_scopes: false,\n },\n },\n },\n\n apple: {\n label: \"Apple Sign In / OAuth emulator\",\n endpoints: \"OAuth authorize, token exchange, JWKS\",\n async load() {\n const mod = await import(\"@emulators/apple\");\n return { plugin: mod.applePlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@icloud.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"name\"] };\n },\n initConfig: {\n apple: {\n users: [{ email: \"testuser@icloud.com\", name: \"Test User\" }],\n oauth_clients: [\n {\n client_id: \"com.example.app\",\n team_id: \"TEAM001\",\n name: \"My Apple App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/apple\"],\n },\n ],\n },\n },\n },\n\n microsoft: {\n label: \"Microsoft Entra ID OAuth 2.0 / OpenID Connect emulator\",\n endpoints: \"OAuth authorize, token exchange, userinfo, OIDC discovery, Graph /me, logout, token revocation\",\n async load() {\n const mod = await import(\"@emulators/microsoft\");\n return { plugin: mod.microsoftPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@outlook.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\", \"User.Read\"] };\n },\n initConfig: {\n microsoft: {\n users: [{ email: \"testuser@outlook.com\", name: \"Test User\" }],\n oauth_clients: [\n {\n client_id: \"example-client-id\",\n client_secret: \"example-client-secret\",\n name: \"My Microsoft App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/microsoft-entra-id\"],\n },\n ],\n },\n },\n },\n\n okta: {\n label: \"Okta OAuth 2.0 / OpenID Connect + management API emulator\",\n endpoints:\n \"OIDC discovery, JWKS, OAuth authorize/token/userinfo/introspect/revoke/logout, users, groups, apps, authorization servers\",\n async load() {\n const mod = await import(\"@emulators/okta\");\n return { plugin: mod.oktaPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstLogin =\n (cfg?.users as Array<{ login?: string; email?: string }> | undefined)?.[0]?.login ??\n (cfg?.users as Array<{ login?: string; email?: string }> | undefined)?.[0]?.email ??\n \"testuser@okta.local\";\n return { login: firstLogin, id: 1, scopes: [\"openid\", \"profile\", \"email\", \"groups\"] };\n },\n initConfig: {\n okta: {\n users: [{ login: \"testuser@okta.local\", email: \"testuser@okta.local\", first_name: \"Test\", last_name: \"User\" }],\n groups: [{ name: \"Everyone\", description: \"All users\", type: \"BUILT_IN\", okta_id: \"00g_everyone\" }],\n authorization_servers: [{ id: \"default\", name: \"default\", audiences: [\"api://default\"] }],\n oauth_clients: [\n {\n client_id: \"okta-test-client\",\n client_secret: \"okta-test-secret\",\n name: \"Sample OIDC Client\",\n redirect_uris: [\"http://localhost:3000/callback\"],\n auth_server_id: \"default\",\n },\n ],\n },\n },\n },\n\n aws: {\n label: \"AWS cloud service emulator\",\n endpoints:\n \"S3 (buckets, objects), SQS (queues, messages), IAM (users, roles, access keys), STS (assume role, caller identity)\",\n async load() {\n const mod = await import(\"@emulators/aws\");\n return {\n plugin: mod.awsPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n issueCredential(\n store: Store,\n baseUrl: string,\n _tokenMap: TokenMap,\n request: CredentialRequest,\n ): IssuedCredential {\n const userName = request.login ?? \"developer\";\n mod.seedFromConfig(store, baseUrl, { iam: { users: [{ user_name: userName, create_access_key: true }] } });\n const user = mod.getAwsStore(store).iamUsers.findOneBy(\"user_name\", userName);\n const key = user?.access_keys.find((candidate) => candidate.status === \"Active\");\n if (!user || !key) throw new Error(\"Failed to create AWS access key\");\n return {\n type: \"provider-specific\",\n provider: \"aws\",\n user_name: user.user_name,\n access_key_id: key.access_key_id,\n secret_access_key: key.secret_access_key,\n region: \"us-east-1\",\n };\n },\n };\n },\n defaultFallback() {\n return { login: \"admin\", id: 1, scopes: [\"s3:*\", \"sqs:*\", \"iam:*\", \"sts:*\"] };\n },\n initConfig: {\n aws: {\n region: \"us-east-1\",\n s3: { buckets: [{ name: \"my-app-bucket\" }, { name: \"my-app-uploads\" }] },\n sqs: { queues: [{ name: \"my-app-events\" }, { name: \"my-app-dlq\" }] },\n iam: {\n users: [{ user_name: \"developer\", create_access_key: true }],\n roles: [{ role_name: \"lambda-execution-role\", description: \"Role for Lambda function execution\" }],\n },\n },\n },\n },\n resend: {\n label: \"Resend email API emulator\",\n endpoints: \"emails, domains, contacts, API keys, inbox UI\",\n async load() {\n const mod = await import(\"@emulators/resend\");\n return { plugin: mod.resendPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"re_test_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n resend: {\n domains: [{ name: \"example.com\", region: \"us-east-1\" }],\n contacts: [{ email: \"test@example.com\", first_name: \"Test\", last_name: \"User\" }],\n },\n },\n },\n stripe: {\n label: \"Stripe payments emulator\",\n endpoints:\n \"customers, payment methods, customer sessions, payment intents, charges, products, prices, checkout sessions, webhooks\",\n async load() {\n const mod = await import(\"@emulators/stripe\");\n return { plugin: mod.stripePlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"sk_test_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n stripe: {\n customers: [{ email: \"test@example.com\", name: \"Test Customer\" }],\n products: [{ name: \"Pro Plan\", description: \"Monthly pro subscription\" }],\n prices: [{ product_name: \"Pro Plan\", currency: \"usd\", unit_amount: 2000 }],\n },\n },\n },\n mongoatlas: {\n label: \"MongoDB Atlas service emulator\",\n endpoints:\n \"Atlas Admin API v2 (projects, clusters, database users, databases, collections), Atlas Data API v1 (findOne, find, insertOne, insertMany, updateOne, updateMany, deleteOne, deleteMany, aggregate)\",\n async load() {\n const mod = await import(\"@emulators/mongoatlas\");\n return { plugin: mod.mongoatlasPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"admin\", id: 1, scopes: [] };\n },\n initConfig: {\n mongoatlas: {\n projects: [{ name: \"Project0\" }],\n clusters: [{ name: \"Cluster0\", project: \"Project0\" }],\n database_users: [{ username: \"admin\", project: \"Project0\" }],\n databases: [{ cluster: \"Cluster0\", name: \"test\", collections: [\"items\"] }],\n },\n },\n },\n clerk: {\n label: \"Clerk authentication and user management emulator\",\n endpoints:\n \"OIDC discovery, JWKS, OAuth authorize/token/userinfo, users, email addresses, organizations, memberships, invitations, sessions\",\n async load() {\n const mod = await import(\"@emulators/clerk\");\n return { plugin: mod.clerkPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail =\n (cfg?.users as Array<{ email_addresses?: string[] }> | undefined)?.[0]?.email_addresses?.[0] ??\n \"test@example.com\";\n return { login: firstEmail, id: 1, scopes: [] };\n },\n initConfig: {\n clerk: {\n users: [\n {\n first_name: \"Test\",\n last_name: \"User\",\n email_addresses: [\"test@example.com\"],\n password: \"clerk_test_password\",\n },\n ],\n organizations: [\n {\n name: \"My Company\",\n slug: \"my-company\",\n members: [{ email: \"test@example.com\", role: \"admin\" }],\n },\n ],\n oauth_applications: [\n {\n client_id: \"clerk_emulate_client\",\n client_secret: \"clerk_emulate_secret\",\n name: \"Emulate App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/clerk\"],\n },\n ],\n },\n },\n },\n spotify: {\n label: \"Spotify Web API emulator\",\n endpoints: \"client credentials token endpoint, catalog search, artists, albums, and tracks\",\n async load() {\n const mod = await import(\"@emulators/spotify\");\n return { plugin: mod.spotifyPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"spotify-app\", id: 1, scopes: [] };\n },\n initConfig: {\n spotify: {\n clients: [{ client_id: \"demo-client-id\", client_secret: \"demo-client-secret\", name: \"Demo App\" }],\n },\n },\n },\n x: {\n label: \"X (Twitter) API v2 emulator\",\n endpoints:\n \"OAuth 2.0 authorize/token/revoke (Authorization Code with PKCE + app-only client credentials), users, tweets\",\n async load() {\n const mod = await import(\"@emulators/x\");\n return {\n plugin: mod.xPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ username: login }] });\n return mod.getXStore(store).users.findOneBy(\"username\", login.toLowerCase().replace(/^@/, \"\"))?.id ?? 1;\n },\n };\n },\n defaultFallback(cfg) {\n const firstUsername = (cfg?.users as Array<{ username?: string }> | undefined)?.[0]?.username ?? \"developer\";\n return { login: firstUsername, id: 1, scopes: [\"tweet.read\", \"users.read\"] };\n },\n initConfig: {\n x: {\n users: [\n {\n username: \"developer\",\n name: \"Developer\",\n description: \"Building with the X API v2 emulator.\",\n verified: true,\n followers_count: 1200,\n following_count: 320,\n },\n ],\n oauth_clients: [\n {\n client_id: \"x-confidential-client\",\n client_secret: \"x-confidential-secret\",\n client_type: \"confidential\",\n name: \"My X App (confidential)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n {\n client_id: \"x-public-client\",\n client_type: \"public\",\n name: \"My X App (public)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n ],\n tweets: [{ text: \"Hello from the X API v2 emulator.\", author: \"developer\", like_count: 42, retweet_count: 7 }],\n },\n },\n },\n workos: {\n label: \"WorkOS emulator\",\n endpoints:\n \"AuthKit user management (hosted login, code/refresh grants, sealed-session JWKS), organizations, memberships, invitations, API keys, Vault KV, OAuth authorization server\",\n async load() {\n const mod = await import(\"@emulators/workos\");\n return {\n plugin: mod.workosPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ email: login }] });\n return mod.getWorkosStore(store).users.findOneBy(\"email\", login)?.id ?? 1;\n },\n };\n },\n defaultFallback() {\n return { login: \"sk_emulate_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n workos: {\n users: [{ email: \"admin@example.com\", first_name: \"Admin\", last_name: \"User\" }],\n organizations: [{ name: \"Acme\", members: [\"admin@example.com\"] }],\n },\n },\n },\n autumn: {\n label: \"Autumn billing emulator\",\n endpoints: \"customers (get_or_create with seedable subscriptions), usage tracking, plans/features/events lists\",\n async load() {\n const mod = await import(\"@emulators/autumn\");\n return {\n plugin: mod.autumnPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n };\n },\n defaultFallback() {\n return { login: \"am_emulate_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n autumn: {\n customers: [{ id: \"org_paid_example\", subscriptions: [{ plan_id: \"pro\", status: \"active\" }] }],\n },\n },\n },\n};\n\nexport const DEFAULT_TOKENS = {\n tokens: {\n test_token_admin: {\n login: \"admin\",\n scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n },\n test_token_user1: {\n login: \"octocat\",\n scopes: [\"repo\", \"user\"],\n },\n },\n};\n","import { createServer, serve, type AppKeyResolver, type Store } from \"@emulators/core\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES, issueServiceCredential, type ServiceName } from \"../registry.js\";\nimport { readFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { parse as parseYaml } from \"yaml\";\nimport pc from \"picocolors\";\nimport { ensurePortless, registerAliases, removeAliases, portlessBaseUrl, type PortlessAlias } from \"../portless.js\";\nimport { resolveBaseUrl } from \"../base-url.js\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nexport interface StartOptions {\n port: number;\n service?: string;\n seed?: string;\n baseUrl?: string;\n portless?: boolean;\n}\n\ninterface SeedConfig {\n tokens?: Record<string, { login: string; scopes?: string[] }>;\n [service: string]: unknown;\n}\n\ninterface LoadResult {\n config: SeedConfig;\n source: string;\n}\n\nfunction loadSeedConfig(seedPath?: string): LoadResult | null {\n if (seedPath) {\n const fullPath = resolve(seedPath);\n if (!existsSync(fullPath)) {\n console.error(`Seed file not found: ${fullPath}`);\n process.exit(1);\n }\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: seedPath };\n } catch (err) {\n console.error(`Failed to parse ${seedPath}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n\n const autoFiles = [\n \"emulate.config.yaml\",\n \"emulate.config.yml\",\n \"emulate.config.json\",\n \"service-emulator.config.yaml\",\n \"service-emulator.config.yml\",\n \"service-emulator.config.json\",\n ];\n\n for (const file of autoFiles) {\n const fullPath = resolve(file);\n if (existsSync(fullPath)) {\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: file };\n } catch (err) {\n console.error(`Failed to parse ${file}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n }\n\n return null;\n}\n\nfunction inferServicesFromConfig(config: SeedConfig): ServiceName[] | null {\n const found = SERVICE_NAMES.filter((k) => k in config);\n return found.length > 0 ? [...found] : null;\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const { port: basePort } = options;\n\n if (options.portless && options.baseUrl) {\n console.error(\"--portless and --base-url are mutually exclusive.\");\n process.exit(1);\n }\n\n const loaded = loadSeedConfig(options.seed);\n const seedConfig = loaded?.config ?? null;\n const configSource = loaded?.source ?? null;\n\n let services: ServiceName[];\n if (options.service) {\n services = options.service.split(\",\").map((s) => s.trim()) as ServiceName[];\n } else if (seedConfig) {\n services = inferServicesFromConfig(seedConfig) ?? [...SERVICE_NAMES];\n } else {\n services = [...SERVICE_NAMES];\n }\n\n for (const svc of services) {\n if (!SERVICE_REGISTRY[svc]) {\n console.error(`Unknown service: ${svc}`);\n process.exit(1);\n }\n }\n\n const tokens: Record<string, { login: string; id: number; scopes?: string[] }> = {};\n if (seedConfig?.tokens) {\n let tokenId = 100;\n for (const [token, user] of Object.entries(seedConfig.tokens)) {\n tokens[token] = { login: user.login, id: tokenId++, scopes: user.scopes };\n }\n } else {\n tokens[\"test_token_admin\"] = { login: \"admin\", id: 2, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n }\n\n if (options.portless) {\n await ensurePortless();\n }\n\n interface PreparedService {\n svc: ServiceName;\n entry: (typeof SERVICE_REGISTRY)[ServiceName];\n loadedSvc: Awaited<ReturnType<(typeof SERVICE_REGISTRY)[ServiceName][\"load\"]>>;\n svcSeedConfig: Record<string, unknown> | undefined;\n port: number;\n baseUrl: string;\n }\n\n const portlessAliases: PortlessAlias[] = [];\n const prepared: PreparedService[] = [];\n\n for (let i = 0; i < services.length; i++) {\n const svc = services[i];\n const entry = SERVICE_REGISTRY[svc];\n const loadedSvc = await entry.load();\n\n const svcSeedConfig = seedConfig?.[svc] as Record<string, unknown> | undefined;\n const port = (svcSeedConfig?.port as number | undefined) ?? basePort + i;\n\n if (options.portless) {\n portlessAliases.push({ name: `${svc}.emulate`, port });\n }\n\n const seedBaseUrl =\n typeof svcSeedConfig?.baseUrl === \"string\" && svcSeedConfig.baseUrl.length > 0\n ? svcSeedConfig.baseUrl\n : undefined;\n const effectiveBaseUrl = options.portless ? portlessBaseUrl(svc) : options.baseUrl;\n const baseUrl = resolveBaseUrl({ service: svc, port, baseUrl: effectiveBaseUrl, seedBaseUrl });\n\n prepared.push({ svc, entry, loadedSvc, svcSeedConfig, port, baseUrl });\n }\n\n if (portlessAliases.length > 0) {\n registerAliases(portlessAliases);\n }\n\n const serviceUrls: Array<{ name: string; url: string }> = [];\n const stores: Store[] = [];\n const httpServers: ReturnType<typeof serve>[] = [];\n\n for (const { svc, entry, loadedSvc, svcSeedConfig, port, baseUrl } of prepared) {\n serviceUrls.push({ name: svc, url: baseUrl });\n\n // eslint-disable-next-line prefer-const -- reassigned after closure captures it\n let cachedResolver: AppKeyResolver | undefined;\n const appKeyResolver: AppKeyResolver | undefined = loadedSvc.createAppKeyResolver\n ? (appId) => cachedResolver!(appId)\n : undefined;\n\n const fallbackUser = entry.defaultFallback(svcSeedConfig);\n\n let resetService = () => {};\n let applyRuntimeSeed = (_seed: unknown) => {};\n const { app, store, webhooks, ledger, tokenMap } = createServer(loadedSvc.plugin, {\n port,\n baseUrl,\n tokens,\n appKeyResolver,\n fallbackUser,\n manifest: loadedSvc.manifest,\n instance: svc,\n reset: () => resetService(),\n seed: (seed) => applyRuntimeSeed(seed),\n issueCredential: (request) => issueServiceCredential(svc, loadedSvc, store, baseUrl, tokenMap, request, webhooks),\n });\n cachedResolver = loadedSvc.createAppKeyResolver?.(store);\n stores.push(store);\n\n resetService = () => {\n store.reset();\n webhooks.clear();\n ledger.clear();\n loadedSvc.plugin.seed?.(store, baseUrl);\n if (svcSeedConfig && loadedSvc.seedFromConfig) {\n loadedSvc.seedFromConfig(store, baseUrl, svcSeedConfig, webhooks);\n }\n };\n applyRuntimeSeed = (seed) => {\n if (seed && loadedSvc.seedFromConfig) {\n loadedSvc.seedFromConfig(store, baseUrl, seed, webhooks);\n }\n };\n resetService();\n\n const httpServer = serve({ fetch: app.fetch, port });\n httpServers.push(httpServer);\n }\n\n printBanner(serviceUrls, tokens, configSource);\n\n const shutdown = () => {\n console.log(`\\n${pc.dim(\"Shutting down...\")}`);\n if (portlessAliases.length > 0) {\n removeAliases(portlessAliases);\n }\n for (const store of stores) {\n store.reset();\n }\n for (const srv of httpServers) {\n srv.close();\n }\n process.exit(0);\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n}\n\nfunction printBanner(\n services: Array<{ name: string; url: string }>,\n tokens: Record<string, { login: string; id: number; scopes?: string[] }>,\n configSource: string | null,\n): void {\n const lines: string[] = [];\n lines.push(\"\");\n lines.push(` ${pc.bold(\"emulate\")} ${pc.dim(`v${pkg.version}`)}`);\n lines.push(\"\");\n\n const maxNameLen = Math.max(...services.map((s) => s.name.length));\n for (const { name, url } of services) {\n lines.push(` ${pc.cyan(name.padEnd(maxNameLen + 2))}${pc.bold(url)}`);\n }\n lines.push(\"\");\n\n const tokenEntries = Object.entries(tokens);\n if (tokenEntries.length > 0) {\n lines.push(` ${pc.dim(\"Tokens\")}`);\n for (const [token, user] of tokenEntries) {\n lines.push(` ${pc.dim(token)} ${pc.dim(\"->\")} ${user.login}`);\n }\n lines.push(\"\");\n }\n\n if (configSource) {\n lines.push(` ${pc.dim(\"Config:\")} ${configSource}`);\n } else {\n lines.push(` ${pc.dim(\"Config:\")} defaults ${pc.dim(\"(run\")} npx emulate init ${pc.dim(\"to customize)\")}`);\n }\n lines.push(\"\");\n\n console.log(lines.join(\"\\n\"));\n}\n","import { execSync, spawnSync } from \"child_process\";\nimport { createInterface } from \"readline\";\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nfunction hasPortless(): boolean {\n const result = spawnSync(\"portless\", [\"--version\"], { stdio: \"ignore\" });\n return result.status === 0;\n}\n\nfunction promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer) => {\n rl.close();\n const normalized = answer.trim().toLowerCase();\n resolve(normalized === \"\" || normalized === \"y\" || normalized === \"yes\");\n });\n });\n}\n\nfunction isProxyRunning(): boolean {\n const result = spawnSync(\"portless\", [\"list\"], { stdio: \"ignore\" });\n return result.status === 0;\n}\n\nexport async function ensurePortless(): Promise<void> {\n if (!hasPortless()) {\n if (!isInteractive()) {\n console.error(\"portless is required but not installed. Run: npm i -g portless\");\n process.exit(1);\n }\n\n const yes = await promptYesNo(\"portless is not installed. Install it now? (npm i -g portless) [Y/n] \");\n if (!yes) {\n console.error(\"Cannot continue without portless.\");\n process.exit(1);\n }\n\n try {\n execSync(\"npm i -g portless\", { stdio: \"inherit\" });\n } catch {\n console.error(\"Failed to install portless.\");\n process.exit(1);\n }\n\n if (!hasPortless()) {\n console.error(\"portless was installed but could not be found on PATH.\");\n process.exit(1);\n }\n }\n\n if (!isProxyRunning()) {\n console.error(\"portless proxy is not running. Start it with: portless proxy start\");\n process.exit(1);\n }\n}\n\nexport interface PortlessAlias {\n name: string;\n port: number;\n}\n\nexport function registerAliases(aliases: PortlessAlias[]): void {\n const registered: PortlessAlias[] = [];\n for (const { name, port } of aliases) {\n const result = spawnSync(\"portless\", [\"alias\", name, String(port), \"--force\"], {\n stdio: \"inherit\",\n });\n if (result.status !== 0) {\n if (registered.length > 0) {\n removeAliases(registered);\n }\n throw new Error(`Failed to register portless alias: ${name} -> ${port}`);\n }\n registered.push({ name, port });\n }\n}\n\nexport function removeAliases(aliases: PortlessAlias[]): void {\n for (const { name } of aliases) {\n const result = spawnSync(\"portless\", [\"alias\", \"--remove\", name], { stdio: \"ignore\" });\n if (result.status !== 0) {\n console.error(`Warning: failed to remove portless alias: ${name}`);\n }\n }\n}\n\nexport function portlessBaseUrl(serviceName: string): string {\n return `https://${serviceName}.emulate.localhost`;\n}\n","export interface ResolveBaseUrlOptions {\n service: string;\n port: number;\n baseUrl?: string;\n seedBaseUrl?: string;\n}\n\n/**\n * Fallback chain:\n * 1. Per-service baseUrl from seed config\n * 2. Explicit baseUrl (CLI flag or programmatic option)\n * 3. EMULATE_BASE_URL env var (with {service} interpolation)\n * 4. PORTLESS_URL env var (with {service} interpolation)\n * 5. http://localhost:<port>\n */\nexport function resolveBaseUrl(opts: ResolveBaseUrlOptions): string {\n if (opts.seedBaseUrl) {\n return opts.seedBaseUrl.replace(/\\{service\\}/g, opts.service);\n }\n if (opts.baseUrl) {\n return opts.baseUrl.replace(/\\{service\\}/g, opts.service);\n }\n const envBaseUrl = process.env.EMULATE_BASE_URL;\n if (envBaseUrl) {\n return envBaseUrl.replace(/\\{service\\}/g, opts.service);\n }\n const portlessUrl = process.env.PORTLESS_URL;\n if (portlessUrl) {\n return portlessUrl.replace(/\\{service\\}/g, opts.service);\n }\n return `http://localhost:${opts.port}`;\n}\n","import { writeFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { stringify as yamlStringify } from \"yaml\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES, DEFAULT_TOKENS, type ServiceName } from \"../registry.js\";\n\ninterface InitOptions {\n service: string;\n}\n\nexport function initCommand(options: InitOptions): void {\n const filename = \"emulate.config.yaml\";\n const fullPath = resolve(filename);\n\n if (existsSync(fullPath)) {\n console.error(`Config file already exists: ${filename}`);\n process.exit(1);\n }\n\n let config: Record<string, unknown>;\n if (options.service === \"all\") {\n config = { ...DEFAULT_TOKENS };\n for (const name of SERVICE_NAMES) {\n Object.assign(config, SERVICE_REGISTRY[name].initConfig);\n }\n } else {\n const entry = SERVICE_REGISTRY[options.service as ServiceName];\n if (!entry) {\n console.error(`Unknown service: ${options.service}. Available: ${SERVICE_NAMES.join(\", \")}, all`);\n process.exit(1);\n }\n config = { ...DEFAULT_TOKENS, ...entry.initConfig };\n }\n\n const content = yamlStringify(config);\n writeFileSync(fullPath, content, \"utf-8\");\n\n console.log(`Created ${filename}`);\n console.log(`\\nRun 'npx emulate' to start the emulator.`);\n}\n","import { SERVICE_REGISTRY } from \"../registry.js\";\n\nexport function listCommand(): void {\n console.log(\"\\nAvailable services:\\n\");\n for (const [name, entry] of Object.entries(SERVICE_REGISTRY)) {\n console.log(` ${name.padEnd(10)}${entry.label}`);\n console.log(` Endpoints: ${entry.endpoints}`);\n console.log();\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,eAAe;;;AEAxB,SAAS,gBAAgB,wBAAgF;ACAzG,SAAS,kBAAkB;AIA3B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;ANoCvB,SAAS,eAAe,OAAyB;AACtD,MAAI,iBAAiB,KAAK;AACxB,WAAO,EAAE,QAAQ,OAAgB,SAAS,CAAC,GAAG,MAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,EAAE;EACzG;AACA,MAAI,iBAAiB,KAAK;AACxB,WAAO,EAAE,QAAQ,OAAgB,QAAQ,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE;EAC/D;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,OAAyB;AACxD,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,YAAY,OAAO;AACpE,UAAM,SAAS;AACf,QAAI,OAAO,WAAW,OAAO;AAC3B,YAAM,UAAU,OAAO;AACvB,aAAO,IAAI,IAAI,QAAQ,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;IAClE;AACA,QAAI,OAAO,WAAW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omId","readFileSync","resolve","readFileSync","existsSync","resolve","resolve","existsSync","pkg"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../@emulators/core/src/store.ts","../../@emulators/core/src/http.ts","../../@emulators/core/src/webhooks.ts","../../@emulators/core/src/middleware/error-handler.ts","../../@emulators/core/src/middleware/auth.ts","../../@emulators/core/src/debug.ts","../../@emulators/core/src/fonts.ts","../../@emulators/core/src/ledger.ts","../../@emulators/core/src/manifest.ts","../../@emulators/core/src/ui.ts","../../@emulators/core/src/control-plane.ts","../../@emulators/core/src/server.ts","../../@emulators/core/src/service-host.ts","../../@emulators/core/src/middleware/pagination.ts","../../@emulators/core/src/oauth-helpers.ts","../../@emulators/core/src/persistence.ts","../../@emulators/core/src/client.ts","../src/registry.ts","../src/commands/start.ts","../src/portless.ts","../src/base-url.ts","../src/commands/init.ts","../src/commands/list.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { startCommand } from \"./commands/start.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { listCommand } from \"./commands/list.js\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nconst defaultPort = process.env.EMULATE_PORT ?? process.env.PORT ?? \"4000\";\n\nconst program = new Command();\n\nprogram\n .name(\"emulate\")\n .description(\"Local drop-in replacement services for CI and no-network sandboxes\")\n .version(pkg.version);\n\nprogram\n .command(\"start\", { isDefault: true })\n .description(\"Start the emulator server\")\n .option(\"-p, --port <port>\", \"Base port\", defaultPort)\n .option(\"-s, --service <services>\", \"Comma-separated services to enable\")\n .option(\"--seed <file>\", \"Path to seed config file\")\n .option(\"--base-url <url>\", \"Override advertised base URL (supports {service} template)\")\n .option(\"--portless\", \"Serve over HTTPS via portless (auto-registers aliases)\")\n .addHelpText(\n \"after\",\n `\n\nControl plane (under /_emulate on each service):\n GET /_emulate HTML landing page\n GET /_emulate/manifest machine-readable service manifest\n GET /_emulate/quickstart copy/paste getting-started snippet\n GET /_emulate/specs spec sources and coverage status\n GET /_emulate/coverage per-operation coverage and summary\n GET /_emulate/connections copyable SDK, CLI, env, and curl snippets\n GET /_emulate/openapi OpenAPI document (when supported)\n GET /_emulate/graphql GraphQL surface (when supported)\n GET /_emulate/mcp MCP surface (when supported)\n GET /_emulate/state current emulator state\n GET /_emulate/ledger request ledger (DELETE to clear)\n GET /_emulate/logs webhook deliveries and recent requests\n POST /_emulate/instances create an instance\n POST /_emulate/seed seed state\n POST /_emulate/reset reset state\n POST /_emulate/credentials mint a credential (bearer token, API key, or\n OAuth client, depending on the service's auth)\n\nGlobal catalog:\n GET /_emulate/services machine-readable catalog of every hosted service\n\n Use /_emulate/manifest and /_emulate/coverage to discover supported surfaces\n and honest coverage, /_emulate/credentials to create credentials,\n /_emulate/seed to load fixtures, and /_emulate/ledger to validate API calls.\n\nHosted services:\n All 13 services are available on emulators.dev: github, vercel, google, okta,\n microsoft, spotify, slack, apple, aws, resend, stripe, mongoatlas, clerk,\n x, workos, autumn.\n Service host: <service>.emulators.dev (useful without an instance; serves\n a service-level /_emulate control plane)\n Instance host: <service>.<instance>.emulators.dev\n Local/path form: <origin>/<service>/<instance>\n\n The apex emulators.dev is the catalog landing page that lists every emulator\n and links to its host. Per-service docs live at https://docs.emulators.dev/\n <service>.\n`,\n )\n .action(async (opts) => {\n const port = parseInt(opts.port, 10);\n if (Number.isNaN(port) || port < 1 || port > 65535) {\n console.error(`Invalid port: ${opts.port}`);\n process.exit(1);\n }\n await startCommand({\n port,\n service: opts.service,\n seed: opts.seed,\n baseUrl: opts.baseUrl,\n portless: opts.portless,\n });\n });\n\nprogram\n .command(\"init\")\n .description(\"Generate a starter config file\")\n .option(\"-s, --service <service>\", \"Service to generate config for\", \"all\")\n .action((opts) => {\n initCommand({ service: opts.service });\n });\n\nprogram\n .command(\"list\")\n .alias(\"list-services\")\n .description(\"List available services\")\n .action(() => {\n listCommand();\n });\n\nprogram.parse();\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport interface CollectionSnapshot<T extends Entity = Entity> {\n items: T[];\n autoId: number;\n indexFields: string[];\n}\n\nexport interface StoreSnapshot {\n collections: Record<string, CollectionSnapshot>;\n data: Record<string, unknown>;\n}\n\nexport function serializeValue(value: unknown): unknown {\n if (value instanceof Map) {\n return { __type: \"Map\" as const, entries: [...value.entries()].map(([k, v]) => [k, serializeValue(v)]) };\n }\n if (value instanceof Set) {\n return { __type: \"Set\" as const, values: [...value.values()] };\n }\n return value;\n}\n\nexport function deserializeValue(value: unknown): unknown {\n if (value !== null && typeof value === \"object\" && \"__type\" in value) {\n const tagged = value as Record<string, unknown>;\n if (tagged.__type === \"Map\") {\n const entries = tagged.entries as [unknown, unknown][];\n return new Map(entries.map(([k, v]) => [k, deserializeValue(v)]));\n }\n if (tagged.__type === \"Set\") {\n return new Set(tagged.values as unknown[]);\n }\n }\n return value;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids)\n .map((id) => this.items.get(id)!)\n .filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n\n snapshot(): CollectionSnapshot<T> {\n return {\n items: this.all(),\n autoId: this.autoId,\n indexFields: this.fieldNames,\n };\n }\n\n restore(snap: CollectionSnapshot<T>): void {\n this.clear();\n this.autoId = snap.autoId;\n for (const item of snap.items) {\n this.items.set(item.id, item);\n this.addToIndex(item);\n }\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`,\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n\n snapshot(): StoreSnapshot {\n const collections: Record<string, CollectionSnapshot> = {};\n for (const [name, col] of this.collections) {\n collections[name] = col.snapshot();\n }\n const data: Record<string, unknown> = {};\n for (const [key, value] of this._data) {\n data[key] = serializeValue(value);\n }\n return { collections, data };\n }\n\n restore(snap: StoreSnapshot): void {\n const snapshotNames = new Set(Object.keys(snap.collections));\n for (const name of this.collections.keys()) {\n if (!snapshotNames.has(name)) {\n this.collections.delete(name);\n }\n }\n for (const [name, colSnap] of Object.entries(snap.collections)) {\n const indexFields = colSnap.indexFields as (keyof Entity)[];\n const col = this.collection(name, indexFields);\n col.restore(colSnap as CollectionSnapshot<any>);\n }\n this._data.clear();\n for (const [key, value] of Object.entries(snap.data)) {\n this._data.set(key, deserializeValue(value));\n }\n }\n}\n","import { createServer as createNodeServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\n\ntype BodyInit = ConstructorParameters<typeof Response>[0];\ntype HeadersInit = ConstructorParameters<typeof Headers>[0];\ntype FormDataEntryValue = string | File;\n\nexport type ContentfulStatusCode = number;\nexport type Next = () => Promise<Response | void>;\n\ntype VariablesOf<E> = unknown extends E\n ? Record<string, any>\n : E extends { Variables: infer V }\n ? V\n : Record<string, any>;\ntype HandlerResult = Response | void | Promise<Response | void>;\n\nexport type Handler<E = unknown, P extends string = string> = (c: Context<E, P>, next: Next) => HandlerResult;\nexport type MiddlewareHandler<E = unknown> = Handler<E>;\nexport type ErrorHandler<E = unknown> = (err: unknown, c: Context<E>) => Response | Promise<Response>;\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\ninterface CompiledPath {\n pattern: string;\n regex: RegExp;\n paramNames: string[];\n}\n\ninterface Route<E> {\n method: string;\n compiled: CompiledPath;\n handlers: Handler<E>[];\n}\n\ninterface MatchedHandler<E> {\n handler: Handler<E>;\n params: Record<string, string>;\n}\n\nexport interface ServeOptions {\n fetch: FetchHandler;\n port?: number;\n hostname?: string;\n}\n\nexport interface CorsOptions {\n origin?: string;\n allowMethods?: string[];\n allowHeaders?: string[];\n credentials?: boolean;\n maxAge?: number;\n}\n\nexport class HonoRequest {\n readonly raw: Request;\n readonly url: string;\n readonly method: string;\n readonly path: string;\n /** The matched route pattern (e.g. /repos/:owner/:repo), when a route matched. */\n readonly routePath?: string;\n\n constructor(\n request: Request,\n private readonly params: Record<string, string>,\n routePath?: string,\n ) {\n this.raw = request;\n this.url = request.url;\n this.method = request.method;\n this.path = new URL(request.url).pathname;\n this.routePath = routePath;\n }\n\n header(): Record<string, string>;\n header(name: string): string | undefined;\n header(name?: string): Record<string, string> | string | undefined {\n if (name) return this.raw.headers.get(name) ?? undefined;\n const headers: Record<string, string> = {};\n this.raw.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return headers;\n }\n\n query(name: string): string | undefined {\n return new URL(this.url).searchParams.get(name) ?? undefined;\n }\n\n queries(name: string): string[] | undefined {\n const values = new URL(this.url).searchParams.getAll(name);\n return values.length > 0 ? values : undefined;\n }\n\n param(): Record<string, string>;\n param(name: string): string;\n param(name?: string): Record<string, string> | string {\n if (!name) return { ...this.params };\n return this.params[name] ?? \"\";\n }\n\n json<T = any>(): Promise<T> {\n return this.raw.json() as Promise<T>;\n }\n\n text(): Promise<string> {\n return this.raw.text();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.raw.arrayBuffer();\n }\n\n async parseBody(): Promise<Record<string, FormDataEntryValue | FormDataEntryValue[]>> {\n const contentType = this.header(\"Content-Type\") ?? \"\";\n if (contentType.includes(\"multipart/form-data\")) {\n return formDataToObject(await this.raw.formData());\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params = new URLSearchParams(await this.raw.text());\n const out: Record<string, string | string[]> = {};\n for (const [key, value] of params) {\n appendBodyValue(out, key, value);\n }\n return out;\n }\n if (contentType.includes(\"application/json\")) {\n const body = await this.raw.json().catch(() => ({}));\n return body && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, FormDataEntryValue | FormDataEntryValue[]>)\n : {};\n }\n return {};\n }\n}\n\nexport class Context<E = unknown, _P extends string = string> {\n readonly req: HonoRequest;\n private readonly vars = new Map<string, unknown>();\n private readonly responseHeaders = new Headers();\n private responseStatus = 200;\n\n constructor(\n request: Request,\n params: Record<string, string>,\n private readonly notFoundHandler: (c: Context<E>) => Response | Promise<Response>,\n routePath?: string,\n ) {\n this.req = new HonoRequest(request, params, routePath);\n }\n\n get<K extends keyof VariablesOf<E> & string>(key: K): VariablesOf<E>[K] | undefined {\n return this.vars.get(key) as VariablesOf<E>[K] | undefined;\n }\n\n set<K extends keyof VariablesOf<E> & string>(key: K, value: VariablesOf<E>[K]): void {\n this.vars.set(key, value);\n }\n\n header(name: string, value: string): void {\n this.responseHeaders.set(name, value);\n }\n\n status(status: number): void {\n this.responseStatus = status;\n }\n\n json(data: unknown, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(JSON.stringify(data), status, defaultContentType(headers, \"application/json; charset=UTF-8\"));\n }\n\n text(text: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(text, status, defaultContentType(headers, \"text/plain; charset=UTF-8\"));\n }\n\n html(html: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(html, status, defaultContentType(headers, \"text/html; charset=UTF-8\"));\n }\n\n body(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(body, status, headers);\n }\n\n redirect(location: string, status: ContentfulStatusCode = 302): Response {\n return this.response(null, status, { Location: location });\n }\n\n notFound(): Response | Promise<Response> {\n return this.notFoundHandler(this);\n }\n\n finalize(response: Response): Response {\n if (!hasHeaders(this.responseHeaders)) return response;\n const headers = new Headers(response.headers);\n this.responseHeaders.forEach((value, key) => {\n headers.set(key, value);\n });\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n private response(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n const merged = new Headers(headers);\n this.responseHeaders.forEach((value, key) => {\n merged.set(key, value);\n });\n return new Response(body, {\n status: status ?? this.responseStatus,\n headers: merged,\n });\n }\n}\n\nexport class Hono<E = unknown> {\n private readonly middleware: Route<E>[] = [];\n private readonly routes: Route<E>[] = [];\n private errorHandler: ErrorHandler<E> = (err) => {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return new Response(message, { status: 500 });\n };\n private notFoundHandler: (c: Context<E>) => Response | Promise<Response> = () =>\n new Response(\"404 Not Found\", { status: 404 });\n\n use<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;\n use(...handlers: Handler<E>[]): this;\n use<P extends string = string>(pathOrHandler: string | Handler<E>, ...handlers: Handler<E, P>[]): this {\n if (typeof pathOrHandler === \"string\") {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(pathOrHandler), handlers: handlers as Handler<E>[] });\n } else {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(\"*\"), handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n on<P extends string = string>(method: string, path: string, ...handlers: Handler<E, P>[]): this {\n this.routes.push({ method: method.toUpperCase(), compiled: compilePath(path), handlers: handlers as Handler<E>[] });\n return this;\n }\n\n get<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"GET\", path, ...handlers);\n }\n\n post<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"POST\", path, ...handlers);\n }\n\n put<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PUT\", path, ...handlers);\n }\n\n patch<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PATCH\", path, ...handlers);\n }\n\n delete<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"DELETE\", path, ...handlers);\n }\n\n onError(handler: ErrorHandler<E>): this {\n this.errorHandler = handler;\n return this;\n }\n\n notFound(handler: (c: Context<E>) => Response | Promise<Response>): this {\n this.notFoundHandler = handler;\n return this;\n }\n\n async request(input: string | Request, init?: RequestInit): Promise<Response> {\n if (input instanceof Request) return this.fetch(input);\n const url = input.startsWith(\"/\") ? `http://localhost${input}` : input;\n return this.fetch(new Request(url, init));\n }\n\n fetch = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const path = url.pathname;\n const method = request.method.toUpperCase();\n const matched = this.match(method, path);\n const context = new Context<E>(request, matched.params, this.notFoundHandler, matched.routePattern);\n\n try {\n const response = await this.dispatch(context, matched.handlers);\n return context.finalize(response ?? (await this.notFoundHandler(context)));\n } catch (err) {\n return context.finalize(await this.errorHandler(err, context));\n }\n };\n\n private match(\n method: string,\n path: string,\n ): { handlers: MatchedHandler<E>[]; params: Record<string, string>; routePattern?: string } {\n const handlers: MatchedHandler<E>[] = [];\n const params: Record<string, string> = {};\n\n for (const route of this.middleware) {\n const match = matchPath(route.compiled, path);\n if (!match) continue;\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n const route =\n this.routes.find((candidate) => candidate.method === method && matchPath(candidate.compiled, path) != null) ??\n (method === \"HEAD\"\n ? this.routes.find((candidate) => candidate.method === \"GET\" && matchPath(candidate.compiled, path) != null)\n : undefined);\n\n if (route) {\n const match = matchPath(route.compiled, path) ?? {};\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n return { handlers, params, routePattern: route?.compiled.pattern };\n }\n\n private async dispatch(context: Context<E>, handlers: MatchedHandler<E>[]): Promise<Response | void> {\n let index = -1;\n const run = async (nextIndex: number): Promise<Response | void> => {\n if (nextIndex <= index) throw new Error(\"next() called multiple times\");\n index = nextIndex;\n const matched = handlers[nextIndex];\n if (!matched) return undefined;\n\n const originalParams = context.req.param();\n Object.assign(originalParams, matched.params);\n\n let nextResponse: Response | void = undefined;\n let nextCalled = false;\n const next: Next = async () => {\n nextCalled = true;\n nextResponse = await run(nextIndex + 1);\n return nextResponse;\n };\n\n const response = await matched.handler(context, next);\n if (response instanceof Response) return response;\n if (nextCalled) return nextResponse;\n return response;\n };\n\n return run(0);\n }\n}\n\nexport function cors(options: CorsOptions = {}): MiddlewareHandler {\n const origin = options.origin ?? \"*\";\n const allowMethods = options.allowMethods ?? [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"];\n\n return async (c, next) => {\n c.header(\"Access-Control-Allow-Origin\", origin);\n if (options.credentials) c.header(\"Access-Control-Allow-Credentials\", \"true\");\n\n if (c.req.method.toUpperCase() === \"OPTIONS\") {\n c.header(\"Access-Control-Allow-Methods\", allowMethods.join(\",\"));\n const allowHeaders = options.allowHeaders?.join(\",\") ?? c.req.header(\"Access-Control-Request-Headers\");\n if (allowHeaders) c.header(\"Access-Control-Allow-Headers\", allowHeaders);\n if (options.maxAge != null) c.header(\"Access-Control-Max-Age\", String(options.maxAge));\n return c.body(null, 204);\n }\n\n await next();\n };\n}\n\nexport function serve(options: ServeOptions): Server {\n const port = options.port ?? 3000;\n const server = createNodeServer(async (req, res) => {\n try {\n const request = nodeRequestToFetchRequest(req);\n const response = await options.fetch(request);\n await writeFetchResponse(res, response, req.method?.toUpperCase() === \"HEAD\");\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=UTF-8\");\n res.end(message);\n }\n });\n server.listen(port, options.hostname);\n return server;\n}\n\nfunction compilePath(pattern: string): CompiledPath {\n if (pattern === \"*\" || pattern === \"/*\") {\n return { pattern, regex: /^.*$/, paramNames: [] };\n }\n\n const paramNames: string[] = [];\n let source = \"^\";\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n if (char !== \":\") {\n source += escapeRegex(char);\n continue;\n }\n\n let name = \"\";\n i++;\n while (i < pattern.length && /[A-Za-z0-9_]/.test(pattern[i])) {\n name += pattern[i];\n i++;\n }\n i--;\n paramNames.push(name);\n\n if (pattern[i + 1] === \"{\") {\n const close = pattern.indexOf(\"}\", i + 2);\n if (close < 0) throw new Error(`Invalid route pattern: ${pattern}`);\n const expr = pattern.slice(i + 2, close);\n source += `(${expr})`;\n i = close;\n } else {\n source += \"([^/]+)\";\n }\n }\n source += \"$\";\n return { pattern, regex: new RegExp(source), paramNames };\n}\n\nfunction matchPath(compiled: CompiledPath, path: string): Record<string, string> | null {\n const match = compiled.regex.exec(path);\n if (!match) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < compiled.paramNames.length; i++) {\n params[compiled.paramNames[i]] = decodePathParam(match[i + 1] ?? \"\");\n }\n return params;\n}\n\nfunction decodePathParam(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\nfunction hasHeaders(headers: Headers): boolean {\n for (const _ of headers) return true;\n return false;\n}\n\nfunction defaultContentType(headers: HeadersInit | undefined, contentType: string): Headers {\n const out = new Headers(headers);\n if (!out.has(\"Content-Type\")) {\n out.set(\"Content-Type\", contentType);\n }\n return out;\n}\n\nfunction formDataToObject(formData: FormData): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n const out: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n for (const [key, value] of formData) {\n appendBodyValue(out, key, value);\n }\n return out;\n}\n\nfunction appendBodyValue<T>(target: Record<string, T | T[]>, key: string, value: T): void {\n const existing = target[key];\n if (existing === undefined) {\n target[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n target[key] = [existing, value];\n }\n}\n\nfunction nodeRequestToFetchRequest(req: IncomingMessage): Request {\n const host = req.headers.host ?? \"localhost\";\n const url = new URL(req.url ?? \"/\", `http://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else {\n headers.set(key, value);\n }\n }\n\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n return new Request(url.toString(), {\n method,\n headers,\n body: hasBody ? (req as unknown as BodyInit) : undefined,\n duplex: \"half\",\n } as RequestInit & { duplex: string });\n}\n\nasync function writeFetchResponse(res: ServerResponse, response: Response, headOnly: boolean): Promise<void> {\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n\n const headersWithCookies = response.headers as Headers & { getSetCookie?: () => string[] };\n const cookies = headersWithCookies.getSetCookie?.();\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\" && cookies && cookies.length > 0) return;\n res.setHeader(key, value);\n });\n if (cookies && cookies.length > 0) {\n res.setHeader(\"Set-Cookie\", cookies);\n }\n\n if (headOnly || !response.body) {\n res.end();\n return;\n }\n\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!res.write(value)) {\n await new Promise<void>((resolve) => res.once(\"drain\", resolve));\n }\n }\n res.end();\n } catch (err) {\n res.destroy(err instanceof Error ? err : undefined);\n }\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>,\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(\n event: string,\n action: string | undefined,\n payload: unknown,\n owner: string,\n repo?: string,\n ): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return event === \"ping\" || s.events.includes(\"*\") || s.events.includes(event);\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ContentfulStatusCode, ErrorHandler, MiddlewareHandler } from \"../http.js\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Route handlers throw to the app error handler.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode,\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"../http.js\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport interface TokenEntry {\n token: string;\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function serializeTokenMap(tokenMap: TokenMap): TokenEntry[] {\n return [...tokenMap.entries()].map(([token, user]) => ({\n token,\n login: user.login,\n id: user.id,\n scopes: user.scopes,\n }));\n}\n\nexport function restoreTokenMap(tokenMap: TokenMap, tokens: TokenEntry[]): void {\n tokenMap.clear();\n for (const t of tokens) {\n tokenMap.set(t.token, { login: t.login, id: t.id, scopes: t.scopes });\n }\n}\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n /** Correlation id for the active request, set by the ledger middleware. */\n correlationId?: string;\n /** Provider operation id a handler can advertise for the ledger. */\n operationId?: string;\n /** Side effects a handler records onto the active request's ledger entry. */\n ledgerEffects?: import(\"../ledger.js\").LedgerSideEffect[];\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(Buffer.from(payloadB64, \"base64url\").toString());\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n","const isDebug =\n typeof process !== \"undefined\" &&\n (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\n// Read the cosmetic font/favicon assets lazily and defensively: on a real\n// filesystem (Node/Bun hosts) this serves them; on filesystem-less runtimes\n// (e.g. Cloudflare Workers) the read fails and the route 404s, but — crucially —\n// importing this module touches neither fs NOR import.meta.url at load time\n// (workerd leaves import.meta.url undefined, which would crash `fileURLToPath`),\n// so `createServer` boots everywhere. API emulation never needs these assets.\nconst assetCache = new Map<string, Buffer | null>();\nfunction loadAsset(name: string): Buffer | null {\n if (assetCache.has(name)) return assetCache.get(name)!;\n let buf: Buffer | null = null;\n try {\n const dir = dirname(fileURLToPath(import.meta.url));\n buf = readFileSync(join(dir, \"fonts\", name));\n } catch {\n buf = null;\n }\n assetCache.set(name, buf);\n return buf;\n}\n\nconst FONT_NAMES = new Set([\"geist-sans.woff2\", \"GeistPixel-Square.woff2\"]);\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n if (!FONT_NAMES.has(name)) return c.notFound();\n const buf = loadAsset(name);\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n\n app.get(\"/_emulate/favicon.ico\", (c) => {\n const buf = loadAsset(\"favicon.ico\");\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"image/x-icon\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n },\n });\n });\n}\n","import type { MiddlewareHandler } from \"./http.js\";\nimport type { AppEnv, AuthUser, AuthApp } from \"./middleware/auth.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\n\nexport interface LedgerIdentity {\n user?: Pick<AuthUser, \"login\" | \"id\" | \"scopes\">;\n app?: Pick<AuthApp, \"appId\" | \"slug\" | \"name\">;\n}\n\nexport interface LedgerSideEffect {\n type: \"create\" | \"update\" | \"delete\" | \"custom\";\n collection?: string;\n id?: string | number;\n summary?: string;\n}\n\nexport interface LedgerWebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n status_code: number | null;\n success: boolean;\n}\n\nexport interface LedgerEntry {\n id: string;\n /** Correlation id: honored from X-Correlation-Id / X-Request-Id or generated. */\n correlationId: string;\n timestamp: string;\n method: string;\n host: string;\n path: string;\n query: string;\n /** Matched route pattern, e.g. /repos/:owner/:repo/issues. */\n route?: string;\n /** Provider operation id, when the handler advertises one. */\n operationId?: string;\n request: {\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n identity: LedgerIdentity;\n response: {\n status: number;\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n /** Human/agent-readable one-liner, e.g. \"POST /repos/:owner/:repo -> 201\". */\n summary: string;\n sideEffects: LedgerSideEffect[];\n webhookDeliveries: LedgerWebhookDelivery[];\n durationMs: number;\n}\n\nexport interface LedgerOptions {\n maxEntries?: number;\n maxBodyChars?: number;\n /** When provided, webhook deliveries fired during a request are correlated onto its entry. */\n webhooks?: WebhookDispatcher;\n}\n\nexport interface LedgerSnapshot {\n entries: LedgerEntry[];\n counter: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 1000;\nconst DEFAULT_MAX_BODY_CHARS = 20000;\nconst REDACTED = \"[redacted]\";\nconst SENSITIVE_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"x-github-token\",\n \"stripe-signature\",\n]);\nconst SENSITIVE_KEYS = /token|secret|password|authorization|api[_-]?key|client[_-]?secret|private[_-]?key/i;\n\nexport class RequestLedger {\n private entries: LedgerEntry[] = [];\n private counter = 1;\n\n constructor(private readonly options: LedgerOptions = {}) {}\n\n add(entry: Omit<LedgerEntry, \"id\">): LedgerEntry {\n const saved = { ...entry, id: `req_${this.counter++}` };\n this.entries.push(saved);\n const max = this.options.maxEntries ?? DEFAULT_MAX_ENTRIES;\n if (this.entries.length > max) {\n this.entries.splice(0, this.entries.length - max);\n }\n return saved;\n }\n\n list(limit?: number): LedgerEntry[] {\n const all = [...this.entries].reverse();\n return limit != null ? all.slice(0, limit) : all;\n }\n\n clear(): void {\n this.entries.length = 0;\n this.counter = 1;\n }\n\n /** Serialize for durable persistence (e.g. a Cloudflare Durable Object). */\n serialize(): LedgerSnapshot {\n return { entries: [...this.entries], counter: this.counter };\n }\n\n restore(snapshot: LedgerSnapshot | undefined): void {\n if (!snapshot) return;\n this.entries = Array.isArray(snapshot.entries) ? [...snapshot.entries] : [];\n this.counter = typeof snapshot.counter === \"number\" ? snapshot.counter : this.entries.length + 1;\n }\n}\n\nfunction correlationIdFor(headers: Record<string, string>): string {\n const provided = headers[\"x-correlation-id\"] ?? headers[\"x-request-id\"];\n if (provided && provided.length <= 200) return provided;\n return `cor_${crypto.randomUUID().replace(/-/g, \"\")}`;\n}\n\nexport function createLedgerMiddleware(ledger: RequestLedger, options: LedgerOptions = {}): MiddlewareHandler<AppEnv> {\n const maxBodyChars = options.maxBodyChars ?? DEFAULT_MAX_BODY_CHARS;\n const webhooks = options.webhooks;\n\n return async (c, next) => {\n if (c.req.path.startsWith(\"/_emulate\")) {\n await next();\n return;\n }\n\n const started = Date.now();\n const url = new URL(c.req.url);\n const rawHeaders = c.req.header();\n const correlationId = correlationIdFor(rawHeaders);\n c.set(\"correlationId\", correlationId);\n c.set(\"ledgerEffects\", []);\n c.header(\"X-Correlation-Id\", correlationId);\n\n const requestBody = await readBody(c.req.raw.clone(), maxBodyChars);\n const requestHeaders = redactHeaders(rawHeaders);\n\n // Snapshot existing webhook delivery ids so we can correlate the ones this\n // request fires. Exact under the serialized execution of a Durable Object;\n // best-effort on the concurrent local dev server.\n const beforeDeliveryIds = webhooks ? new Set(webhooks.getDeliveries().map((d) => d.id)) : undefined;\n\n const response = await next();\n if (!response) return;\n\n const responseBody = await readBody(response.clone(), maxBodyChars);\n const route = c.req.routePath;\n const operationId = c.get(\"operationId\");\n const sideEffects = (c.get(\"ledgerEffects\") as LedgerSideEffect[] | undefined) ?? [];\n const webhookDeliveries: LedgerWebhookDelivery[] =\n webhooks && beforeDeliveryIds\n ? webhooks\n .getDeliveries()\n .filter((d) => !beforeDeliveryIds.has(d.id))\n .map((d) => ({\n id: d.id,\n hook_id: d.hook_id,\n event: d.event,\n action: d.action,\n status_code: d.status_code,\n success: d.success,\n }))\n : [];\n\n ledger.add({\n correlationId,\n timestamp: new Date().toISOString(),\n method: c.req.method.toUpperCase(),\n host: url.host,\n path: url.pathname,\n query: url.search,\n route,\n operationId,\n request: {\n headers: requestHeaders,\n ...requestBody,\n },\n identity: {\n user: c.get(\"authUser\"),\n app: c.get(\"authApp\"),\n },\n response: {\n status: response.status,\n headers: redactHeaders(headersToRecord(response.headers)),\n ...responseBody,\n },\n summary: `${c.req.method.toUpperCase()} ${route ?? url.pathname} -> ${response.status}`,\n sideEffects,\n webhookDeliveries,\n durationMs: Date.now() - started,\n });\n\n return response;\n };\n}\n\n/** Record a side effect onto the active request's ledger entry. */\nexport function recordSideEffect(\n c: { get: (key: \"ledgerEffects\") => LedgerSideEffect[] | undefined },\n effect: LedgerSideEffect,\n): void {\n const effects = c.get(\"ledgerEffects\");\n if (effects) effects.push(effect);\n}\n\nasync function readBody(\n responseOrRequest: Request | Response,\n maxChars: number,\n): Promise<{ body?: unknown; bodyTruncated?: boolean }> {\n const method = responseOrRequest instanceof Request ? responseOrRequest.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") return {};\n\n const contentType = responseOrRequest.headers.get(\"content-type\") ?? \"\";\n if (responseOrRequest instanceof Response && responseOrRequest.status === 204) return {};\n\n let text: string;\n try {\n text = await responseOrRequest.text();\n } catch {\n return {};\n }\n if (!text) return {};\n\n const truncated = text.length > maxChars;\n const clipped = truncated ? text.slice(0, maxChars) : text;\n if (contentType.includes(\"application/json\")) {\n try {\n return { body: redactValue(JSON.parse(clipped)), bodyTruncated: truncated || undefined };\n } catch {\n return { body: clipped, bodyTruncated: truncated || undefined };\n }\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params: Record<string, string> = {};\n for (const [key, value] of new URLSearchParams(clipped)) {\n params[key] = SENSITIVE_KEYS.test(key) ? REDACTED : value;\n }\n return { body: params, bodyTruncated: truncated || undefined };\n }\n return { body: clipped, bodyTruncated: truncated || undefined };\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nfunction redactHeaders(headers: Record<string, string>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n out[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? REDACTED : value;\n }\n return out;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactValue);\n if (!value || typeof value !== \"object\") return value;\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n out[key] = SENSITIVE_KEYS.test(key) ? REDACTED : redactValue(child);\n }\n return out;\n}\n","export type SpecKind = \"openapi\" | \"graphql\" | \"mcp\" | \"google-discovery\" | \"oauth-metadata\" | \"manual\";\nexport type SpecCoverage = \"generated\" | \"hand-authored\" | \"partial\" | \"unsupported\";\n\n/**\n * Per-operation coverage. The vision asks for honest, operation-level coverage\n * boundaries (generated / hand-authored / partial / unsupported) instead of a\n * single label stamped across an entire spec. A plugin declares the operations\n * it actually implements; `GET /_emulate/coverage` reports them with a summary.\n */\nexport interface OperationCoverage {\n operationId: string;\n method?: string;\n path?: string;\n status: SpecCoverage;\n summary?: string;\n}\n\nexport interface SpecManifest {\n kind: SpecKind;\n title: string;\n url?: string;\n coverage: SpecCoverage;\n operations?: OperationCoverage[];\n notes?: string;\n}\n\nexport interface SurfaceManifest {\n id: string;\n kind: \"rest\" | \"oauth\" | \"oidc\" | \"graphql\" | \"mcp\" | \"webhooks\" | \"ui\" | \"provider-specific\";\n title: string;\n basePath?: string;\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface AuthCapabilityManifest {\n id: string;\n title: string;\n type:\n | \"api-key\"\n | \"bearer-token\"\n | \"oauth-client-credentials\"\n | \"oauth-authorization-code\"\n | \"oidc\"\n | \"jwt-app\"\n | \"dynamic-client-registration\"\n | \"webhook-secret\"\n | \"provider-specific\";\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface ScenarioManifest {\n id: string;\n title: string;\n description?: string;\n}\n\n/** A seedable area of the instance, surfaced so agents can discover the seed shape. */\nexport interface SeedFieldManifest {\n key: string;\n title: string;\n description?: string;\n example?: unknown;\n}\n\nexport interface SeedSchemaManifest {\n description?: string;\n fields: SeedFieldManifest[];\n /** A full example seed body that can be POSTed to /_emulate/seed. */\n example?: unknown;\n}\n\nexport interface StateCollectionManifest {\n name: string;\n title?: string;\n description?: string;\n}\n\nexport interface StateModelManifest {\n description?: string;\n collections: StateCollectionManifest[];\n}\n\nexport interface ResetBehaviorManifest {\n description: string;\n reseeds: boolean;\n clearsLedger: boolean;\n clearsWebhooks: boolean;\n}\n\nexport type InspectorTabKind = \"landing\" | \"ledger\" | \"state\" | \"logs\" | \"credentials\" | \"seed\" | \"spec\" | \"custom\";\n\nexport interface InspectorTabManifest {\n id: string;\n title: string;\n kind: InspectorTabKind;\n description?: string;\n}\n\n/** Describes what the request ledger records and how durable it is. */\nexport interface LedgerCapabilitiesManifest {\n description?: string;\n recordsFields: string[];\n redactsSensitive: boolean;\n correlationId: boolean;\n webhookDeliveries: boolean;\n sideEffects: boolean;\n persistent: boolean;\n maxEntries?: number;\n}\n\nexport type ConnectionKind = \"sdk\" | \"cli\" | \"env\" | \"curl\" | \"config\" | \"mcp\";\n\n/**\n * A copyable connection snippet. The `template` uses {{placeholders}} that the\n * control plane resolves against the live instance ({{baseUrl}}, {{controlBaseUrl}},\n * {{service}}, {{instance}}, {{token}}, {{clientId}}, {{clientSecret}}). This is\n * how a human or agent copies ready-to-run SDK / CLI / app config without repo\n * context.\n */\nexport interface ConnectionSnippet {\n id: string;\n title: string;\n kind: ConnectionKind;\n language?: string;\n description?: string;\n template: string;\n}\n\nexport interface ServiceManifest {\n id: string;\n name: string;\n description: string;\n surfaces: SurfaceManifest[];\n auth: AuthCapabilityManifest[];\n specs: SpecManifest[];\n scenarios?: ScenarioManifest[];\n seedSchema?: SeedSchemaManifest;\n stateModel?: StateModelManifest;\n resetBehavior?: ResetBehaviorManifest;\n inspectorTabs?: InspectorTabManifest[];\n ledger?: LedgerCapabilitiesManifest;\n connections?: ConnectionSnippet[];\n docsUrl?: string;\n}\n\nexport interface EmulatorInstanceInfo {\n service: string;\n instance?: string;\n baseUrl: string;\n controlBaseUrl: string;\n providerBaseUrl: string;\n}\n\n/**\n * Reset, ledger capabilities, inspector tabs and base connection snippets are the\n * same for every emulator because they all run on the shared core control plane.\n * Defining them once here keeps per-plugin manifests focused on service-specific\n * surface, auth, seed, and SDK details, and guarantees the control plane never\n * lies about a capability it actually provides.\n */\nexport const CORE_RESET_BEHAVIOR: ResetBehaviorManifest = {\n description: \"Resets the instance to its seeded baseline.\",\n reseeds: true,\n clearsLedger: true,\n clearsWebhooks: true,\n};\n\nexport function coreLedgerCapabilities(persistent: boolean): LedgerCapabilitiesManifest {\n return {\n description: \"Recent provider requests with sensitive headers and fields redacted.\",\n recordsFields: [\n \"timestamp\",\n \"method\",\n \"host\",\n \"path\",\n \"route\",\n \"operationId\",\n \"correlationId\",\n \"identity\",\n \"request\",\n \"response\",\n \"summary\",\n \"sideEffects\",\n \"webhookDeliveries\",\n \"durationMs\",\n ],\n redactsSensitive: true,\n correlationId: true,\n webhookDeliveries: true,\n sideEffects: true,\n persistent,\n maxEntries: 1000,\n };\n}\n\nexport function coreInspectorTabs(manifest: ServiceManifest): InspectorTabManifest[] {\n const tabs: InspectorTabManifest[] = [\n {\n id: \"overview\",\n title: \"Overview\",\n kind: \"landing\",\n description: \"Service surfaces, base URLs, and connection snippets.\",\n },\n {\n id: \"ledger\",\n title: \"Ledger\",\n kind: \"ledger\",\n description: \"Recent provider requests recorded by the emulator.\",\n },\n { id: \"state\", title: \"State\", kind: \"state\", description: \"Current seeded and mutated instance state.\" },\n {\n id: \"credentials\",\n title: \"Credentials\",\n kind: \"credentials\",\n description: \"Mint tokens, API keys, or OAuth clients.\",\n },\n ];\n if (manifest.seedSchema || (manifest.scenarios && manifest.scenarios.length > 0)) {\n tabs.push({ id: \"seed\", title: \"Seed\", kind: \"seed\", description: \"Seed state or load a scenario.\" });\n }\n if (manifest.specs.some((s) => s.kind === \"openapi\" || s.kind === \"graphql\")) {\n tabs.push({ id: \"spec\", title: \"Spec\", kind: \"spec\", description: \"OpenAPI / GraphQL spec sources and coverage.\" });\n }\n if (manifest.surfaces.some((s) => s.kind === \"webhooks\")) {\n tabs.push({\n id: \"logs\",\n title: \"Webhooks\",\n kind: \"logs\",\n description: \"Webhook deliveries dispatched by the emulator.\",\n });\n }\n return tabs;\n}\n\n/** Connection snippets every emulator can offer (env + curl against the control plane). */\nexport function coreConnections(): ConnectionSnippet[] {\n return [\n {\n id: \"base-url\",\n title: \"Base URL (env)\",\n kind: \"env\",\n language: \"bash\",\n description: \"Point your SDK or app at the emulator instead of the real provider.\",\n template: \"{{SERVICE_UPPER}}_BASE_URL={{baseUrl}}\",\n },\n {\n id: \"create-credential\",\n title: \"Create a credential\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Mint a working credential for this instance.\",\n template:\n 'curl -s -X POST {{controlBaseUrl}}/credentials \\\\\\n -H \"content-type: application/json\" \\\\\\n -d \\'{\"type\":\"{{defaultAuthType}}\"}\\'',\n },\n {\n id: \"inspect-ledger\",\n title: \"Inspect requests\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Read the request ledger to validate how your app called the service.\",\n template: \"curl -s {{controlBaseUrl}}/ledger\",\n },\n ];\n}\n\n/**\n * Merge the shared core capabilities into a plugin manifest so every served\n * manifest fully describes reset behavior, ledger capabilities, inspector tabs,\n * and at least the base connection snippets, without each plugin repeating them.\n */\nexport function enrichManifest(manifest: ServiceManifest, opts: { ledgerPersistent?: boolean } = {}): ServiceManifest {\n return {\n ...manifest,\n resetBehavior: manifest.resetBehavior ?? CORE_RESET_BEHAVIOR,\n ledger: manifest.ledger ?? coreLedgerCapabilities(opts.ledgerPersistent ?? false),\n inspectorTabs: manifest.inspectorTabs ?? coreInspectorTabs(manifest),\n connections: [...(manifest.connections ?? []), ...coreConnections()],\n };\n}\n\nexport interface ConnectionVars {\n baseUrl: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n service: string;\n instance?: string;\n token?: string;\n clientId?: string;\n clientSecret?: string;\n defaultAuthType?: string;\n}\n\nexport interface ResolvedConnection extends ConnectionSnippet {\n body: string;\n}\n\n/** Interpolate a connection snippet template against live instance values. */\nexport function resolveConnections(connections: ConnectionSnippet[], vars: ConnectionVars): ResolvedConnection[] {\n const map: Record<string, string> = {\n baseUrl: vars.baseUrl,\n providerBaseUrl: vars.providerBaseUrl,\n controlBaseUrl: vars.controlBaseUrl,\n service: vars.service,\n SERVICE_UPPER: vars.service.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\"),\n instance: vars.instance ?? \"default\",\n token: vars.token ?? \"<token>\",\n clientId: vars.clientId ?? \"<client_id>\",\n clientSecret: vars.clientSecret ?? \"<client_secret>\",\n defaultAuthType: vars.defaultAuthType ?? \"bearer-token\",\n };\n return connections.map((snippet) => ({\n ...snippet,\n body: snippet.template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => map[key] ?? `{{${key}}}`),\n }));\n}\n\n/** A summary of declared per-operation coverage across a manifest's specs. */\nexport function coverageReport(manifest: ServiceManifest): {\n operations: OperationCoverage[];\n summary: Record<SpecCoverage, number>;\n specs: Array<{ kind: SpecKind; title: string; coverage: SpecCoverage; operationCount: number }>;\n} {\n const operations: OperationCoverage[] = [];\n const summary: Record<SpecCoverage, number> = {\n generated: 0,\n \"hand-authored\": 0,\n partial: 0,\n unsupported: 0,\n };\n const specs = manifest.specs.map((spec) => {\n const ops = spec.operations ?? [];\n for (const op of ops) {\n operations.push(op);\n summary[op.status] += 1;\n }\n return { kind: spec.kind, title: spec.title, coverage: spec.coverage, operationCount: ops.length };\n });\n return { operations, summary, specs };\n}\n\nexport function createDefaultManifest(service: string): ServiceManifest {\n return {\n id: service,\n name: service,\n description: `Stateful ${service} API emulator.`,\n surfaces: [{ id: \"rest\", kind: \"rest\", title: \"REST API\", status: \"partial\" }],\n auth: [{ id: \"bearer\", title: \"Bearer token\", type: \"bearer-token\", status: \"partial\" }],\n specs: [{ kind: \"manual\", title: \"Hand-authored emulator behavior\", coverage: \"partial\" }],\n };\n}\n","export function escapeHtml(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"'\");\n}\n\nconst CSS = `\n@font-face{\n font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;\n src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');\n}\n@font-face{\n font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;\n src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');\n}\n*{box-sizing:border-box;margin:0;padding:0}\nbody{\n font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;\n background:#000;color:#33ff00;min-height:100vh;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n}\n.emu-bar{\n border-bottom:1px solid #0a3300;padding:10px 20px;\n display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;\n}\n.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}\n.emu-bar-links{margin-left:auto;display:flex;gap:16px;}\n.emu-bar-links a{\n color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;\n}\n.emu-bar-links a:hover{color:#33ff00;}\n.emu-bar-links a .full{display:inline;}\n.emu-bar-links a .short{display:none;}\n@media(max-width:600px){\n .emu-bar-links a .full{display:none;}\n .emu-bar-links a .short{display:inline;}\n}\n\n.content{\n display:flex;align-items:center;justify-content:center;\n min-height:calc(100vh - 42px);padding:24px 16px;\n}\n.content-inner{width:100%;max-width:420px;}\n.card-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;\n}\n.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}\n.powered-by{\n position:fixed;bottom:0;left:0;right:0;\n text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;\n font-family:'Geist Pixel',monospace;\n}\n.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.powered-by a:hover{color:#33ff00;}\n\n.error-title{\n font-family:'Geist Pixel',monospace;\n color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;\n}\n.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}\n.error-card{text-align:center;}\n\n.user-form{margin-bottom:8px;}\n.user-form:last-of-type{margin-bottom:0;}\n.user-btn{\n width:100%;display:flex;align-items:center;gap:12px;\n padding:10px 12px;border:1px solid #0a3300;border-radius:8px;\n background:#000;color:inherit;cursor:pointer;text-align:left;\n font:inherit;transition:border-color .15s;\n}\n.user-btn:hover{border-color:#33ff00;}\n.avatar{\n width:36px;height:36px;border-radius:50%;\n background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.user-text{min-width:0;}\n.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}\n.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}\n.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}\n\n.settings-layout{\n max-width:920px;margin:0 auto;padding:28px 20px;\n display:flex;gap:28px;\n}\n.settings-sidebar{width:200px;flex-shrink:0;}\n.settings-sidebar a{\n display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;\n text-decoration:none;font-size:.8125rem;transition:color .15s;\n}\n.settings-sidebar a:hover{color:#33ff00;}\n.settings-sidebar a.active{color:#33ff00;font-weight:600;}\n.settings-main{flex:1;min-width:0;}\n\n.s-card{\n padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;\n}\n.s-card:last-child{border-bottom:none;}\n.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}\n.s-icon{\n width:42px;height:42px;border-radius:8px;\n background:#0a3300;display:flex;align-items:center;justify-content:center;\n font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.s-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.25rem;font-weight:600;color:#33ff00;\n}\n.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.section-heading{\n font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;\n display:flex;align-items:center;justify-content:space-between;\n}\n.perm-list{list-style:none;}\n.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}\n.check{color:#33ff00;}\n.org-row{\n display:flex;align-items:center;gap:8px;padding:7px 0;\n border-bottom:1px solid #0a3300;font-size:.8125rem;\n}\n.org-row:last-child{border-bottom:none;}\n.org-icon{\n width:22px;height:22px;border-radius:4px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;\n font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.org-name{font-weight:600;color:#33ff00;}\n.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}\n.badge-granted{background:#0a3300;color:#33ff00;}\n.badge-denied{background:#1a0a0a;color:#ff4444;}\n.badge-requested{background:#0a3300;color:#1a8c00;}\n.btn-revoke{\n display:inline-block;padding:5px 14px;border-radius:6px;\n border:1px solid #0a3300;background:transparent;color:#ff4444;\n font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;\n}\n.btn-revoke:hover{border-color:#ff4444;}\n.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}\n.info-text a,.section-heading a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.info-text a:hover,.section-heading a:hover{color:#33ff00;}\ncode{font-family:'Geist Mono','SF Mono',ui-monospace,monospace;font-size:.8125rem;color:#33ff00;word-break:break-all;}\n.code-block{\n background:#020;border:1px solid #0a3300;border-radius:6px;padding:10px 12px;\n margin:8px 0 12px;overflow-x:auto;\n}\n.code-block code{white-space:pre;word-break:normal;display:block;line-height:1.5;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n\n.inspector-layout{max-width:960px;margin:0 auto;padding:28px 20px;}\n.inspector-tabs{display:flex;gap:4px;margin-bottom:20px;}\n.inspector-tabs a{\n padding:7px 16px;border-radius:6px;text-decoration:none;\n font-size:.8125rem;color:#1a8c00;border:1px solid transparent;\n transition:color .15s,border-color .15s;\n}\n.inspector-tabs a:hover{color:#33ff00;}\n.inspector-tabs a.active{color:#33ff00;font-weight:600;border-color:#0a3300;background:#0a3300;}\n.inspector-section{margin-bottom:24px;}\n.inspector-section h2{\n font-family:'Geist Pixel',monospace;\n font-size:1rem;font-weight:600;color:#33ff00;margin-bottom:10px;\n}\n.inspector-section h3{\n font-family:'Geist Pixel',monospace;\n font-size:.875rem;font-weight:600;color:#1a8c00;margin:16px 0 8px;\n}\n.inspector-table{width:100%;border-collapse:collapse;margin-bottom:12px;}\n.inspector-table th,.inspector-table td{\n text-align:left;padding:8px 12px;border-bottom:1px solid #0a3300;\n font-size:.8125rem;\n}\n.inspector-table th{color:#1a8c00;font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;}\n.inspector-table td{color:#33ff00;}\n.inspector-table tbody tr{transition:background .1s;}\n.inspector-table tbody tr:hover{background:#0a3300;}\n.inspector-empty{color:#1a8c00;text-align:center;padding:20px 0;font-size:.8125rem;}\n\n.checkout-layout{\n display:flex;min-height:calc(100vh - 42px);\n}\n.checkout-summary{\n flex:1;background:#020;padding:48px 40px 48px 10%;\n display:flex;flex-direction:column;justify-content:center;\n border-right:1px solid #0a3300;\n}\n.checkout-form-side{\n flex:1;background:#000;padding:48px 10% 48px 40px;\n display:flex;flex-direction:column;justify-content:center;\n}\n.checkout-merchant{\n display:flex;align-items:center;gap:10px;margin-bottom:6px;\n}\n.checkout-merchant-name{\n font-family:'Geist Pixel',monospace;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-test-badge{\n font-size:.625rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n background:#0a3300;color:#1a8c00;padding:2px 8px;border-radius:4px;\n}\n.checkout-total{\n font-family:'Geist Pixel',monospace;\n font-size:2rem;font-weight:700;color:#33ff00;margin:8px 0 28px;\n}\n.checkout-line-item{\n display:flex;align-items:center;gap:14px;padding:14px 0;\n border-bottom:1px solid #0a3300;\n}\n.checkout-line-item:first-child{border-top:1px solid #0a3300;}\n.checkout-item-icon{\n width:42px;height:42px;border-radius:6px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;font-size:.875rem;font-weight:700;color:#116600;\n}\n.checkout-item-details{flex:1;min-width:0;}\n.checkout-item-name{font-size:.875rem;font-weight:600;color:#33ff00;}\n.checkout-item-qty{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.checkout-item-price{\n font-size:.875rem;font-weight:600;color:#33ff00;text-align:right;white-space:nowrap;\n}\n.checkout-item-unit{font-size:.6875rem;color:#1a8c00;text-align:right;margin-top:2px;}\n.checkout-totals{margin-top:20px;}\n.checkout-totals-row{\n display:flex;justify-content:space-between;padding:6px 0;\n font-size:.8125rem;color:#1a8c00;\n}\n.checkout-totals-row.total{\n border-top:1px solid #0a3300;margin-top:8px;padding-top:14px;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-form-section{margin-bottom:24px;}\n.checkout-form-label{\n font-size:.8125rem;font-weight:600;color:#33ff00;margin-bottom:8px;display:block;\n}\n.checkout-input{\n width:100%;padding:10px 12px;border:1px solid #0a3300;border-radius:6px;\n background:#020;color:#33ff00;font:inherit;font-size:.875rem;\n transition:border-color .15s;outline:none;\n}\n.checkout-input:focus{border-color:#33ff00;}\n.checkout-input::placeholder{color:#116600;}\n.checkout-card-box{\n border:1px solid #0a3300;border-radius:6px;padding:14px;\n background:#020;\n}\n.checkout-card-row{\n display:flex;gap:12px;margin-top:10px;\n}\n.checkout-card-row .checkout-input{flex:1;}\n.checkout-sim-note{\n font-size:.6875rem;color:#1a8c00;margin-top:10px;text-align:center;\n font-style:italic;\n}\n.checkout-pay-btn{\n width:100%;padding:14px;border:none;border-radius:8px;\n background:#33ff00;color:#000;font:inherit;font-size:.9375rem;font-weight:700;\n cursor:pointer;transition:background .15s;\n font-family:'Geist Pixel',monospace;\n}\n.checkout-pay-btn:hover{background:#44ff22;}\n.checkout-cancel{\n text-align:center;margin-top:14px;\n}\n.checkout-cancel a{\n color:#1a8c00;text-decoration:none;font-size:.8125rem;\n transition:color .15s;\n}\n.checkout-cancel a:hover{color:#33ff00;}\n@media(max-width:768px){\n .checkout-layout{flex-direction:column;}\n .checkout-summary{padding:32px 20px;border-right:none;border-bottom:1px solid #0a3300;}\n .checkout-form-side{padding:32px 20px;}\n}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <a href=\"https://github.com/vercel-labs/emulate/issues\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Report Issue</span><span class=\"short\">Report</span></a>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<link rel=\"icon\" href=\"/_emulate/favicon.ico\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(title: string, subtitle: string, body: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(title: string, sidebarHtml: string, bodyHtml: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface InspectorTab {\n id: string;\n label: string;\n href: string;\n}\n\nexport function renderInspectorPage(\n title: string,\n tabs: InspectorTab[],\n activeTab: string,\n body: string,\n service?: string,\n): string {\n const tabLinks = tabs\n .map(\n (t) => `<a href=\"${escapeAttr(t.href)}\" class=\"${t.id === activeTab ? \"active\" : \"\"}\">${escapeHtml(t.label)}</a>`,\n )\n .join(\"\");\n\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"inspector-layout\">\n <nav class=\"inspector-tabs\">${tabLinks}</nav>\n ${body}\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderFormPostPage(action: string, fields: Record<string, string>, service?: string): string {\n const hiddens = Object.entries(fields)\n .filter(([, v]) => v != null)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\\n\");\n\n return `${head(\"Redirecting\")}\n<body onload=\"document.forms[0].submit()\">\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\" style=\"text-align:center\">\n <div class=\"card-subtitle\">Redirecting…</div>\n <form method=\"POST\" action=\"${escapeAttr(action)}\">\n${hiddens}\n <noscript><button type=\"submit\" class=\"user-btn\" style=\"margin-top:12px;justify-content:center\">\n <span class=\"user-login\">Continue</span>\n </button></noscript>\n </form>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface CheckoutLineItem {\n name: string;\n quantity: number;\n unitPrice: number;\n totalPrice: number;\n currency: string;\n}\n\nexport interface CheckoutPageOptions {\n merchantName?: string;\n lineItems: CheckoutLineItem[];\n subtotal: number;\n total: number;\n currency: string;\n sessionId: string;\n cancelUrl?: string | null;\n}\n\nexport function renderCheckoutPage(opts: CheckoutPageOptions, service?: string): string {\n const fmt = (cents: number, cur: string) => `$${(cents / 100).toFixed(2)} ${cur.toUpperCase()}`;\n const fmtShort = (cents: number) => `$${(cents / 100).toFixed(2)}`;\n\n const itemsHtml =\n opts.lineItems.length > 0\n ? opts.lineItems\n .map((li) => {\n const initial = li.name.charAt(0).toUpperCase();\n const unitNote =\n li.quantity > 1 ? `<div class=\"checkout-item-unit\">${fmtShort(li.unitPrice)} each</div>` : \"\";\n return `<div class=\"checkout-line-item\">\n <div class=\"checkout-item-icon\">${escapeHtml(initial)}</div>\n <div class=\"checkout-item-details\">\n <div class=\"checkout-item-name\">${escapeHtml(li.name)}</div>\n <div class=\"checkout-item-qty\">Qty ${li.quantity}</div>\n </div>\n <div>\n <div class=\"checkout-item-price\">${fmtShort(li.totalPrice)}</div>\n ${unitNote}\n </div>\n</div>`;\n })\n .join(\"\")\n : '<p class=\"empty\">No line items</p>';\n\n const totalsHtml = `<div class=\"checkout-totals\">\n <div class=\"checkout-totals-row\">\n <span>Subtotal</span><span>${fmtShort(opts.subtotal)}</span>\n </div>\n <div class=\"checkout-totals-row total\">\n <span>Total due</span><span>${fmt(opts.total, opts.currency)}</span>\n </div>\n</div>`;\n\n const cancelHtml = opts.cancelUrl\n ? `<div class=\"checkout-cancel\"><a href=\"${escapeAttr(opts.cancelUrl)}\">Cancel</a></div>`\n : \"\";\n\n const merchant = opts.merchantName ? escapeHtml(opts.merchantName) : \"Checkout\";\n\n return `${head(\"Checkout\")}\n<body>\n${emuBar(service)}\n<div class=\"checkout-layout\">\n <div class=\"checkout-summary\">\n <div class=\"checkout-merchant\">\n <span class=\"checkout-merchant-name\">${merchant}</span>\n <span class=\"checkout-test-badge\">Test Mode</span>\n </div>\n <div class=\"checkout-total\">${fmtShort(opts.total)}</div>\n ${itemsHtml}\n ${totalsHtml}\n </div>\n <div class=\"checkout-form-side\">\n <form method=\"post\" action=\"/checkout/${escapeAttr(opts.sessionId)}/complete\">\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Email</label>\n <input type=\"email\" name=\"email\" class=\"checkout-input\" placeholder=\"you@example.com\"/>\n </div>\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Card information</label>\n <div class=\"checkout-card-box\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"1234 1234 1234 1234\" disabled/>\n <div class=\"checkout-card-row\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"MM / YY\" disabled/>\n <input type=\"text\" class=\"checkout-input\" placeholder=\"CVC\" disabled/>\n </div>\n </div>\n <div class=\"checkout-sim-note\">Card fields are simulated. Payment will be auto-approved.</div>\n </div>\n <button type=\"submit\" class=\"checkout-pay-btn\">Pay ${fmtShort(opts.total)}</button>\n </form>\n ${cancelHtml}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>` : \"\";\n const emailLine = opts.email ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>` : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import type { Context, Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\nimport type { Store } from \"./store.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\nimport type { RequestLedger } from \"./ledger.js\";\nimport type { ConnectionVars, EmulatorInstanceInfo, ResolvedConnection, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport type { TokenMap } from \"./middleware/auth.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\n\nexport interface CredentialRequest {\n type?: string;\n login?: string;\n name?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n [key: string]: unknown;\n}\n\nexport interface IssuedCredential {\n type: string;\n token?: string;\n login?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n token_url?: string;\n authorization_url?: string;\n notes?: string;\n [key: string]: unknown;\n}\n\nexport interface ControlPlaneOptions {\n manifest: ServiceManifest;\n instance: EmulatorInstanceInfo;\n store: Store;\n webhooks: WebhookDispatcher;\n ledger: RequestLedger;\n tokenMap?: TokenMap;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport const INSTANCE_NOTES = \"Hosted deployments create instances lazily when the returned URL is first used.\";\n\nexport interface InstanceCreation {\n service: string;\n instance: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n pathUrl: string;\n hostHint: string;\n notes: string;\n}\n\n/** The single, canonical shape for POST /_emulate/instances, shared by every host. */\nexport function buildInstanceCreation(args: {\n service: string;\n instance: string;\n providerBaseUrl: string;\n pathOrigin: string;\n hostSuffix: string;\n}): InstanceCreation {\n return {\n service: args.service,\n instance: args.instance,\n providerBaseUrl: args.providerBaseUrl,\n controlBaseUrl: `${args.providerBaseUrl}/_emulate`,\n pathUrl: `${args.pathOrigin}/${args.service}/${args.instance}`,\n hostHint: `${args.service}.${args.instance}.${args.hostSuffix}`,\n notes: INSTANCE_NOTES,\n };\n}\n\nfunction connectionVars(\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n overrides?: Partial<ConnectionVars>,\n): ConnectionVars {\n return {\n baseUrl: instance.providerBaseUrl,\n providerBaseUrl: instance.providerBaseUrl,\n controlBaseUrl: instance.controlBaseUrl,\n service: manifest.id,\n instance: instance.instance,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n ...overrides,\n };\n}\n\nexport function registerControlPlane(app: Hono<AppEnv>, options: ControlPlaneOptions): void {\n const { instance, store, webhooks, ledger } = options;\n const manifest = enrichManifest(options.manifest, { ledgerPersistent: options.ledgerPersistent });\n const hostSuffix = options.hostSuffix ?? \"emulators.dev\";\n\n app.get(\"/_emulate\", (c) => c.html(renderLandingPage(manifest, instance)));\n app.get(\"/_emulate/manifest\", (c) =>\n c.json({\n manifest,\n instance,\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance)),\n }),\n );\n app.get(\"/_emulate/quickstart\", (c) => c.text(renderQuickstart(manifest, instance)));\n app.get(\"/_emulate/specs\", (c) => c.json({ specs: manifest.specs, surfaces: manifest.surfaces }));\n app.get(\"/_emulate/coverage\", (c) => c.json(coverageReport(manifest)));\n app.get(\"/_emulate/connections\", (c) => {\n const overrides: Partial<ConnectionVars> = {};\n const token = c.req.query(\"token\");\n const clientId = c.req.query(\"client_id\");\n const clientSecret = c.req.query(\"client_secret\");\n if (token) overrides.token = token;\n if (clientId) overrides.clientId = clientId;\n if (clientSecret) overrides.clientSecret = clientSecret;\n return c.json({\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance, overrides)),\n });\n });\n app.get(\"/_emulate/openapi\", (c) => redirectToSpec(c, manifest, instance, \"openapi\"));\n app.get(\"/_emulate/graphql\", (c) => endpointForSurface(c, manifest, instance, \"graphql\"));\n app.get(\"/_emulate/mcp\", (c) => endpointForSurface(c, manifest, instance, \"mcp\"));\n app.get(\"/_emulate/state\", (c) => c.json(store.snapshot()));\n app.get(\"/_emulate/ledger\", (c) => {\n const limitParam = c.req.query(\"limit\");\n const limit = limitParam ? Number.parseInt(limitParam, 10) : undefined;\n return c.json({ entries: ledger.list(Number.isFinite(limit) ? limit : undefined) });\n });\n app.delete(\"/_emulate/ledger\", (c) => {\n ledger.clear();\n return c.json({ ok: true });\n });\n app.get(\"/_emulate/logs\", (c) => c.json({ webhooks: webhooks.getDeliveries(), requests: ledger.list(100) }));\n app.post(\"/_emulate/reset\", async (c) => {\n if (options.reset) {\n await options.reset();\n } else {\n store.reset();\n webhooks.clear();\n ledger.clear();\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/seed\", async (c) => {\n if (!options.seed) {\n return c.json({ error: \"unsupported\", message: \"This emulator does not support runtime seeding.\" }, 501);\n }\n const body = await c.req.json().catch(() => undefined);\n try {\n await options.seed(body);\n } catch (err) {\n return c.json({ error: \"invalid_seed\", message: err instanceof Error ? err.message : \"Seed failed.\" }, 400);\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/credentials\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as CredentialRequest;\n try {\n if (options.issueCredential) {\n const credential = await options.issueCredential(body);\n return c.json({ credential });\n }\n const credential = issueDefaultCredential(body, manifest, options.tokenMap);\n if (!credential) {\n return c.json({ error: \"unsupported\", message: \"This emulator cannot create that credential type.\" }, 501);\n }\n return c.json({ credential });\n } catch (err) {\n return c.json(\n { error: \"unsupported\", message: err instanceof Error ? err.message : \"Credential creation failed.\" },\n 400,\n );\n }\n });\n app.post(\"/_emulate/instances\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as { instance?: string; service?: string };\n const nextInstance = slug(body.instance ?? `${manifest.id}-${randomId().slice(0, 8)}`);\n const service = slug(body.service ?? manifest.id);\n const origin = new URL(instance.providerBaseUrl).origin;\n return c.json(\n buildInstanceCreation({\n service,\n instance: nextInstance,\n providerBaseUrl: `${origin}/${service}/${nextInstance}`,\n pathOrigin: origin,\n hostSuffix,\n }),\n );\n });\n}\n\nexport function renderLandingPage(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const surfaces = manifest.surfaces\n .map(\n (surface) =>\n `<tr><td>${escapeHtml(surface.title)}</td><td><span class=\"badge\">${escapeHtml(surface.status)}</span></td><td><code>${escapeHtml(surface.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const auth = manifest.auth\n .map((cap) => `<li><span class=\"badge\">${escapeHtml(cap.status)}</span> ${escapeHtml(cap.title)}</li>`)\n .join(\"\");\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const instanceLabel = instance.instance ? ` · instance <code>${escapeHtml(instance.instance)}</code>` : \"\";\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Base URLs${instanceLabel}</div>\n <p class=\"info-text\">Provider: <code>${escapeHtml(instance.providerBaseUrl)}</code></p>\n <p class=\"info-text\">Control: <code>${escapeHtml(instance.controlBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Credentials</div>\n <ul class=\"perm-list\">${auth}</ul>\n </div>\n ${renderConnectionsHtml(connections)}\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">${controlLinks()}</p>\n </div>\n `,\n manifest.id,\n );\n}\n\nfunction renderConnectionsHtml(connections: ResolvedConnection[]): string {\n if (connections.length === 0) return \"\";\n const blocks = connections\n .map(\n (c) =>\n `<div class=\"section-heading\">${escapeHtml(c.title)}</div><pre class=\"code-block\"><code>${escapeHtml(c.body)}</code></pre>`,\n )\n .join(\"\");\n return `<div class=\"s-card\"><div class=\"section-heading\">Connect</div>${blocks}</div>`;\n}\n\nfunction controlLinks(): string {\n const routes = [\"manifest\", \"quickstart\", \"specs\", \"coverage\", \"connections\", \"state\", \"ledger\", \"logs\"];\n return routes.map((r) => `<a href=\"/_emulate/${r}\">${r}</a>`).join(\" | \");\n}\n\nexport function renderQuickstart(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const lines = [\n `# ${manifest.name} Emulator`,\n \"\",\n manifest.description,\n \"\",\n `Provider base URL: ${instance.providerBaseUrl}`,\n `Control base URL: ${instance.controlBaseUrl}`,\n \"\",\n \"Supported surfaces:\",\n ...manifest.surfaces.map((s) => `- ${s.title}: ${s.status}${s.basePath ? ` at ${s.basePath}` : \"\"}`),\n \"\",\n \"Control endpoints:\",\n `- ${instance.controlBaseUrl}/manifest`,\n `- ${instance.controlBaseUrl}/coverage`,\n `- ${instance.controlBaseUrl}/connections`,\n `- ${instance.controlBaseUrl}/state`,\n `- ${instance.controlBaseUrl}/ledger`,\n `- POST ${instance.controlBaseUrl}/credentials`,\n `- POST ${instance.controlBaseUrl}/seed`,\n `- POST ${instance.controlBaseUrl}/reset`,\n \"\",\n \"Connect:\",\n ...connections.flatMap((c) => [\"\", `## ${c.title}`, c.body]),\n ];\n return lines.join(\"\\n\");\n}\n\nfunction issueDefaultCredential(\n request: CredentialRequest,\n manifest: ServiceManifest,\n tokenMap: TokenMap | undefined,\n): IssuedCredential | null {\n const type = request.type ?? manifest.auth[0]?.type ?? \"bearer-token\";\n if (type !== \"bearer-token\" && type !== \"api-key\") return null;\n if (!tokenMap) return null;\n const token = typeof request.token === \"string\" && request.token ? request.token : `emu_${manifest.id}_${randomId()}`;\n const login = request.login ?? \"admin\";\n const scopes = Array.isArray(request.scopes) ? request.scopes.filter((s): s is string => typeof s === \"string\") : [];\n tokenMap.set(token, { login, id: Date.now(), scopes });\n return { type, token, login, scopes };\n}\n\nfunction redirectToSpec(c: Context<AppEnv>, manifest: ServiceManifest, instance: EmulatorInstanceInfo, kind: string) {\n const spec = manifest.specs.find((s) => s.kind === kind && s.url);\n if (spec?.url) return c.redirect(resolveUrl(instance.providerBaseUrl, spec.url));\n const advertised = manifest.specs.some((s) => s.kind === kind);\n if (kind === \"openapi\" && advertised) return c.redirect(`${instance.providerBaseUrl}/openapi.json`);\n return c.json({ error: \"not_found\", message: `No ${kind} spec is advertised for this emulator.` }, 404);\n}\n\nfunction endpointForSurface(\n c: Context<AppEnv>,\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n kind: \"graphql\" | \"mcp\",\n) {\n const surface = manifest.surfaces.find((s) => s.kind === kind && s.basePath);\n if (!surface?.basePath) {\n return c.json({ error: \"not_found\", message: `No ${kind} surface is advertised for this emulator.` }, 404);\n }\n return c.json({ endpoint: resolveUrl(instance.providerBaseUrl, surface.basePath), surface });\n}\n\nfunction resolveUrl(baseUrl: string, pathOrUrl: string): string {\n if (/^https?:\\/\\//i.test(pathOrUrl)) return pathOrUrl;\n return `${baseUrl}${pathOrUrl.startsWith(\"/\") ? \"\" : \"/\"}${pathOrUrl}`;\n}\n\nfunction randomId(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction slug(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n","import { Hono, cors } from \"./http.js\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport {\n authMiddleware,\n type AuthFallback,\n type TokenMap,\n type AppKeyResolver,\n type AppEnv,\n} from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\nimport { RequestLedger, createLedgerMiddleware } from \"./ledger.js\";\nimport { registerControlPlane, type CredentialRequest, type IssuedCredential } from \"./control-plane.js\";\nimport { createDefaultManifest, type ServiceManifest } from \"./manifest.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n manifest?: ServiceManifest;\n instance?: string;\n enableControlPlane?: boolean;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form surfaced in control-plane responses. */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n const ledger = new RequestLedger();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://docs.emulators.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n if (options.enableControlPlane !== false) {\n const manifest = options.manifest ?? createDefaultManifest(plugin.name);\n registerControlPlane(app, {\n manifest,\n instance: {\n service: manifest.id,\n instance: options.instance,\n baseUrl,\n providerBaseUrl: baseUrl,\n controlBaseUrl: `${baseUrl}/_emulate`,\n },\n store,\n webhooks,\n ledger,\n tokenMap,\n ledgerPersistent: options.ledgerPersistent,\n hostSuffix: options.hostSuffix,\n reset: options.reset,\n seed: options.seed,\n issueCredential: options.issueCredential,\n });\n }\n\n app.use(\"*\", createLedgerMiddleware(ledger, { webhooks }));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403,\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404,\n ),\n );\n\n return { app, store, webhooks, ledger, port, baseUrl, tokenMap };\n}\n","import type { EmulatorInstanceInfo, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\nimport { renderQuickstart, INSTANCE_NOTES } from \"./control-plane.js\";\n\nexport interface ServiceHostContext {\n manifest: ServiceManifest;\n service: string;\n /** Apex origin for the path form, e.g. https://emulators.dev. */\n origin: string;\n /** Request protocol including the colon, e.g. \"https:\". */\n protocol: string;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix: string;\n /** Whether the deployed host persists the ledger across eviction. */\n ledgerPersistent?: boolean;\n}\n\nconst SAMPLE_INSTANCE = \"your-instance\";\n\nfunction sampleInstanceInfo(ctx: ServiceHostContext): EmulatorInstanceInfo {\n const providerBaseUrl = `${ctx.protocol}//${ctx.service}.${SAMPLE_INSTANCE}.${ctx.hostSuffix}`;\n return {\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n baseUrl: providerBaseUrl,\n providerBaseUrl,\n controlBaseUrl: `${providerBaseUrl}/_emulate`,\n };\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n\n/**\n * Serve the service-level control plane on a bare service host (e.g.\n * github.emulators.dev) so a human or agent can read the manifest, quickstart,\n * specs, coverage, and connection snippets WITHOUT first creating an instance.\n * Returns null for paths this should not handle (so the caller can fall through\n * to the interactive console SPA).\n */\nexport function serviceHostControlPlane(path: string, method: string, ctx: ServiceHostContext): Response | null {\n if (!path.startsWith(\"/_emulate\")) return null;\n if (method !== \"GET\" && method !== \"HEAD\") return null;\n\n const manifest = enrichManifest(ctx.manifest, { ledgerPersistent: ctx.ledgerPersistent });\n const sample = sampleInstanceInfo(ctx);\n const connections = resolveConnections(manifest.connections ?? [], {\n baseUrl: sample.providerBaseUrl,\n providerBaseUrl: sample.providerBaseUrl,\n controlBaseUrl: sample.controlBaseUrl,\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n });\n\n switch (path) {\n case \"/_emulate\":\n return new Response(renderServiceLanding(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n case \"/_emulate/manifest\":\n return json({ manifest, instance: null, sampleInstance: sample, connections });\n case \"/_emulate/quickstart\":\n return new Response(renderServiceQuickstart(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n });\n case \"/_emulate/specs\":\n return json({ specs: manifest.specs, surfaces: manifest.surfaces });\n case \"/_emulate/coverage\":\n return json(coverageReport(manifest));\n case \"/_emulate/connections\":\n return json({ connections });\n case \"/_emulate/openapi\": {\n const spec = manifest.specs.find((s) => s.kind === \"openapi\");\n if (!spec) return json({ error: \"not_found\", message: \"No OpenAPI spec is advertised for this emulator.\" }, 404);\n return json({\n openapi: `${sample.providerBaseUrl}${spec.url ?? \"/openapi.json\"}`,\n note: \"Create an instance, then fetch this URL for the live spec.\",\n });\n }\n default:\n return null;\n }\n}\n\nfunction renderServiceQuickstart(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const base = renderQuickstart(manifest, sample);\n const header = [\n `# ${manifest.name} Emulator (service host)`,\n \"\",\n \"Create an instance:\",\n `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances -H 'content-type: application/json' -d '{\"instance\":\"my-run\"}'`,\n `# ${INSTANCE_NOTES}`,\n \"\",\n \"Then use the returned providerBaseUrl / controlBaseUrl. Example below uses a sample instance.\",\n \"\",\n ];\n return header.join(\"\\n\") + base;\n}\n\nfunction renderServiceLanding(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const surfaces = manifest.surfaces\n .map(\n (s) =>\n `<tr><td>${escapeHtml(s.title)}</td><td><span class=\"badge\">${escapeHtml(s.status)}</span></td><td><code>${escapeHtml(s.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const createCurl = `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances \\\\\n -H \"content-type: application/json\" \\\\\n -d '{\"instance\":\"my-run\"}'`;\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Create an instance</div>\n <p class=\"info-text\">Each instance is isolated, stateful, and addressable at its own host.</p>\n <pre class=\"code-block\"><code>${escapeHtml(createCurl)}</code></pre>\n <p class=\"info-text\">${escapeHtml(INSTANCE_NOTES)}</p>\n <p class=\"info-text\">Sample instance host: <code>${escapeHtml(sample.providerBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">\n <a href=\"/_emulate/manifest\">manifest</a> | <a href=\"/_emulate/quickstart\">quickstart</a> |\n <a href=\"/_emulate/specs\">specs</a> | <a href=\"/_emulate/coverage\">coverage</a> |\n <a href=\"/_emulate/connections\">connections</a>\n </p>\n </div>\n `,\n manifest.id,\n );\n}\n\nexport interface ServiceCatalogEntry {\n id: string;\n name: string;\n description: string;\n}\n\n/**\n * Server-rendered catalog landing for the apex host. Readable by an agent over a\n * raw fetch (no JS): it lists every emulator with its host and manifest URL. The\n * interactive console SPA is served instead only for browser navigations.\n */\nexport function renderCatalogPage(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): string {\n const rows = entries\n .map((e) => {\n const host = `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`;\n return `<a class=\"app-link\" href=\"${escapeHtml(host)}\">\n <img src=\"/_emulate/icons/${escapeHtml(e.id)}\" alt=\"\" width=\"24\" height=\"24\" style=\"object-fit:contain\" />\n <span><span class=\"app-link-name\">${escapeHtml(e.name)}</span><span class=\"app-link-scopes\">${escapeHtml(host)}</span></span>\n </a>`;\n })\n .join(\"\");\n return renderCardPage(\n \"Emulate\",\n \"Stateful integration emulators for real developer APIs. Each emulator has its own host; open one or fetch its manifest.\",\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Emulators</div>\n ${rows}\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">For agents</div>\n <p class=\"info-text\">Machine-readable catalog: <a href=\"/_emulate/services\">/_emulate/services</a></p>\n <p class=\"info-text\">Each service host serves <code>/_emulate/manifest</code>, <code>/_emulate/quickstart</code>, and <code>/_emulate/connections</code>, and the provider API directly against a default instance.</p>\n </div>\n `,\n );\n}\n\n/** A machine-readable index of the services a host serves, with both URL forms. */\nexport function servicesCatalog(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): Response {\n const services = entries.map((e) => ({\n id: e.id,\n name: e.name,\n description: e.description,\n icon: `${ctx.origin}/_emulate/icons/${e.id}`,\n serviceHost: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`,\n instanceHostPattern: `${ctx.protocol}//${e.id}.<instance>.${ctx.hostSuffix}`,\n pathForm: `${ctx.origin}/${e.id}/<instance>`,\n manifest: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}/_emulate/manifest`,\n }));\n return new Response(JSON.stringify({ services }), {\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n","import type { Context } from \"../http.js\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(c: Context, totalCount: number, page: number, perPage: number): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nexport interface PersistenceAdapter {\n load(): Promise<string | null>;\n save(data: string): Promise<void>;\n}\n\nexport function filePersistence(path: string): PersistenceAdapter {\n return {\n async load() {\n try {\n return await readFile(path, \"utf-8\");\n } catch {\n return null;\n }\n },\n async save(data: string) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, data, \"utf-8\");\n },\n };\n}\n","// Typed client for the /_emulate control plane. One handle works against any\n// emulator wherever it runs — a local createEmulator() process, another\n// process on the same machine, or a hosted instance on emulators.dev — so\n// consumers never hand-roll fetch calls or re-cast response shapes the server\n// already types.\nimport type { CredentialRequest, IssuedCredential } from \"./control-plane.js\";\nimport type { LedgerEntry } from \"./ledger.js\";\nimport type {\n EmulatorInstanceInfo,\n OperationCoverage,\n ResolvedConnection,\n ServiceManifest,\n SpecCoverage,\n SpecKind,\n SpecManifest,\n SurfaceManifest,\n} from \"./manifest.js\";\nimport type { StoreSnapshot } from \"./store.js\";\nimport type { WebhookDelivery } from \"./webhooks.js\";\n\nexport interface ManifestResponse {\n manifest: ServiceManifest;\n instance: EmulatorInstanceInfo;\n connections: ResolvedConnection[];\n}\n\nexport interface SpecsResponse {\n specs: SpecManifest[];\n surfaces: SurfaceManifest[];\n}\n\nexport interface CoverageResponse {\n operations: OperationCoverage[];\n summary: Record<SpecCoverage, number>;\n specs: Array<{ kind: SpecKind; title: string; coverage: SpecCoverage; operationCount: number }>;\n}\n\nexport interface LogsResponse {\n webhooks: WebhookDelivery[];\n requests: LedgerEntry[];\n}\n\nexport interface ConnectionsQuery {\n token?: string;\n clientId?: string;\n clientSecret?: string;\n}\n\nexport class EmulatorControlError extends Error {\n constructor(\n readonly method: string,\n readonly url: string,\n readonly status: number,\n readonly body: string,\n ) {\n super(`${method} ${url} -> ${status}${body ? `: ${body.slice(0, 300)}` : \"\"}`);\n this.name = \"EmulatorControlError\";\n }\n}\n\n/** fetch-compatible function, injectable for tests (e.g. a Hono app.request). */\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\nexport class EmulatorClient {\n /** Provider base URL — what an SDK or app under test points at. */\n readonly baseUrl: string;\n readonly #fetch: FetchLike;\n\n constructor(baseUrl: string, options?: { fetch?: FetchLike }) {\n this.baseUrl = baseUrl.replace(/\\/+$/, \"\");\n this.#fetch = options?.fetch ?? ((input, init) => fetch(input, init));\n }\n\n /** The /_emulate/openapi URL — feed it to anything that ingests a spec. */\n get openapiUrl(): string {\n return `${this.baseUrl}/_emulate/openapi`;\n }\n\n async manifest(): Promise<ManifestResponse> {\n return this.#json(\"GET\", \"/_emulate/manifest\");\n }\n\n async quickstart(): Promise<string> {\n return this.#text(\"GET\", \"/_emulate/quickstart\");\n }\n\n async specs(): Promise<SpecsResponse> {\n return this.#json(\"GET\", \"/_emulate/specs\");\n }\n\n async coverage(): Promise<CoverageResponse> {\n return this.#json(\"GET\", \"/_emulate/coverage\");\n }\n\n async connections(query?: ConnectionsQuery): Promise<ResolvedConnection[]> {\n const params = new URLSearchParams();\n if (query?.token) params.set(\"token\", query.token);\n if (query?.clientId) params.set(\"client_id\", query.clientId);\n if (query?.clientSecret) params.set(\"client_secret\", query.clientSecret);\n const qs = params.size > 0 ? `?${params}` : \"\";\n const body = await this.#json<{ connections: ResolvedConnection[] }>(\n \"GET\",\n `/_emulate/connections${qs}`,\n );\n return body.connections;\n }\n\n async state(): Promise<StoreSnapshot> {\n return this.#json(\"GET\", \"/_emulate/state\");\n }\n\n async logs(): Promise<LogsResponse> {\n return this.#json(\"GET\", \"/_emulate/logs\");\n }\n\n readonly ledger = {\n list: async (limit?: number): Promise<LedgerEntry[]> => {\n const qs = limit !== undefined ? `?limit=${limit}` : \"\";\n const body = await this.#json<{ entries: LedgerEntry[] }>(\"GET\", `/_emulate/ledger${qs}`);\n return body.entries;\n },\n clear: async (): Promise<void> => {\n await this.#json(\"DELETE\", \"/_emulate/ledger\");\n },\n };\n\n readonly credentials = {\n mint: async (request: CredentialRequest = {}): Promise<IssuedCredential> => {\n const body = await this.#json<{ credential: IssuedCredential }>(\n \"POST\",\n \"/_emulate/credentials\",\n request,\n );\n return body.credential;\n },\n };\n\n async seed(seed: unknown): Promise<void> {\n await this.#json(\"POST\", \"/_emulate/seed\", seed);\n }\n\n async reset(): Promise<void> {\n await this.#json(\"POST\", \"/_emulate/reset\", {});\n }\n\n async #request(method: string, path: string, body?: unknown): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n const response = await this.#fetch(url, {\n method,\n ...(body === undefined\n ? {}\n : { headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) }),\n });\n if (!response.ok) {\n throw new EmulatorControlError(method, url, response.status, await response.text());\n }\n return response;\n }\n\n async #json<T>(method: string, path: string, body?: unknown): Promise<T> {\n return (await this.#request(method, path, body)).json() as Promise<T>;\n }\n\n async #text(method: string, path: string, body?: unknown): Promise<string> {\n return (await this.#request(method, path, body)).text();\n }\n}\n","import type {\n ServicePlugin,\n Store,\n AppKeyResolver,\n AuthFallback,\n WebhookDispatcher,\n ServiceManifest,\n CredentialRequest,\n IssuedCredential,\n TokenMap,\n} from \"@emulators/core\";\n\nexport interface LoadedService {\n plugin: ServicePlugin;\n // Each plugin owns its manifest (the single source of truth). load() resolves\n // it lazily alongside the plugin so the CLI never eager-loads every service.\n manifest: ServiceManifest;\n seedFromConfig?(store: Store, baseUrl: string, config: unknown, webhooks?: WebhookDispatcher): void;\n createAppKeyResolver?(store: Store): AppKeyResolver;\n ensureUser?(store: Store, baseUrl: string, login: string): number;\n issueCredential?(\n store: Store,\n baseUrl: string,\n tokenMap: TokenMap,\n request: CredentialRequest,\n webhooks?: WebhookDispatcher,\n ): IssuedCredential;\n}\n\nexport interface ServiceEntry {\n label: string;\n endpoints: string;\n load(): Promise<LoadedService>;\n defaultFallback(svcSeedConfig?: Record<string, unknown>): AuthFallback;\n initConfig: Record<string, unknown>;\n}\n\nconst SERVICE_NAME_LIST = [\n \"vercel\",\n \"github\",\n \"google\",\n \"slack\",\n \"apple\",\n \"microsoft\",\n \"okta\",\n \"aws\",\n \"resend\",\n \"stripe\",\n \"mongoatlas\",\n \"clerk\",\n \"spotify\",\n \"x\",\n \"workos\",\n \"autumn\",\n] as const;\nexport type ServiceName = (typeof SERVICE_NAME_LIST)[number];\nexport const SERVICE_NAMES: readonly ServiceName[] = SERVICE_NAME_LIST;\n\nexport function issueServiceCredential(\n service: ServiceName,\n loaded: LoadedService,\n store: Store,\n baseUrl: string,\n tokenMap: TokenMap,\n request: CredentialRequest,\n webhooks?: WebhookDispatcher,\n): IssuedCredential {\n if (loaded.issueCredential) {\n return loaded.issueCredential(store, baseUrl, tokenMap, request, webhooks);\n }\n const type = request.type ?? loaded.manifest.auth[0]?.type ?? \"bearer-token\";\n if (type === \"bearer-token\" || type === \"api-key\") {\n const login = request.login ?? \"admin\";\n const scopes = Array.isArray(request.scopes)\n ? request.scopes.filter((s): s is string => typeof s === \"string\")\n : [];\n const id = loaded.ensureUser?.(store, baseUrl, login) ?? Date.now();\n const token =\n typeof request.token === \"string\" && request.token.length > 0 ? request.token : defaultToken(service, type);\n tokenMap.set(token, { login, id, scopes });\n return { type, token, login, scopes };\n }\n\n if (\n type === \"oauth-authorization-code\" ||\n type === \"oauth-client-credentials\" ||\n type === \"dynamic-client-registration\"\n ) {\n if (!loaded.seedFromConfig) throw new Error(`Credential type ${type} is not supported by ${service}`);\n const clientId = request.client_id ?? defaultClientId(service);\n const clientSecret = request.client_secret ?? defaultClientSecret(service);\n const redirectUris = normalizeRedirectUris(request.redirect_uris);\n const name = request.name ?? `${SERVICE_REGISTRY[service].label.replace(/ emulator$/i, \"\")} Client`;\n const seed = credentialSeed(service, { clientId, clientSecret, redirectUris, name, request });\n if (!seed) throw new Error(`Credential type ${type} is not supported by ${service}`);\n loaded.seedFromConfig(store, baseUrl, seed, webhooks);\n return {\n type,\n client_id: clientId,\n client_secret: clientSecret,\n redirect_uris: redirectUris,\n authorization_url: authorizationUrlFor(service, baseUrl),\n token_url: tokenUrlFor(service, baseUrl),\n };\n }\n\n throw new Error(`Credential type ${type} is not supported by ${service}`);\n}\n\nfunction defaultToken(service: ServiceName, type: string): string {\n const prefix = type === \"api-key\" ? apiKeyPrefix(service) : `emu_${service}`;\n return `${prefix}_${randomId()}`;\n}\n\nfunction apiKeyPrefix(service: ServiceName): string {\n if (service === \"stripe\") return \"sk_test\";\n if (service === \"resend\") return \"re\";\n if (service === \"clerk\") return \"sk_test\";\n return `emu_${service}`;\n}\n\nfunction defaultClientId(service: ServiceName): string {\n if (service === \"spotify\") return `app_${randomId().slice(0, 18)}`;\n if (service === \"github\") return `Iv1.${randomId().slice(0, 16)}`;\n if (service === \"google\") return `${randomId().slice(0, 24)}.apps.googleusercontent.com`;\n return `${service}_${randomId().slice(0, 18)}`;\n}\n\nfunction defaultClientSecret(service: ServiceName): string {\n if (service === \"google\") return `GOCSPX-${randomId().slice(0, 24)}`;\n return `secret_${randomId()}`;\n}\n\nfunction normalizeRedirectUris(value: unknown): string[] {\n if (Array.isArray(value)) {\n const uris = value.filter((uri): uri is string => typeof uri === \"string\" && uri.length > 0);\n if (uris.length > 0) return uris;\n }\n return [\"http://localhost:3000/callback\"];\n}\n\nfunction credentialSeed(\n service: ServiceName,\n args: {\n clientId: string;\n clientSecret: string;\n redirectUris: string[];\n name: string;\n request: CredentialRequest;\n },\n): unknown | null {\n const { clientId, clientSecret, redirectUris, name, request } = args;\n if (service === \"github\") {\n return { oauth_apps: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }] };\n }\n if (service === \"google\" || service === \"apple\" || service === \"microsoft\") {\n return { oauth_clients: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }] };\n }\n if (service === \"okta\") {\n return {\n oauth_clients: [\n {\n client_id: clientId,\n client_secret: clientSecret,\n name,\n redirect_uris: redirectUris,\n auth_server_id: typeof request.auth_server_id === \"string\" ? request.auth_server_id : \"default\",\n },\n ],\n };\n }\n if (service === \"slack\") {\n return {\n oauth_apps: [\n {\n client_id: clientId,\n client_secret: clientSecret,\n name,\n redirect_uris: redirectUris,\n scopes: Array.isArray(request.scopes) ? request.scopes : [\"chat:write\", \"channels:read\", \"users:read\"],\n user_scopes: Array.isArray(request.user_scopes) ? request.user_scopes : [],\n },\n ],\n };\n }\n if (service === \"vercel\") {\n return { integrations: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }] };\n }\n if (service === \"spotify\") {\n return { clients: [{ client_id: clientId, client_secret: clientSecret, name }] };\n }\n if (service === \"clerk\") {\n return {\n oauth_applications: [{ client_id: clientId, client_secret: clientSecret, name, redirect_uris: redirectUris }],\n };\n }\n if (service === \"x\") {\n return {\n oauth_clients: [\n {\n client_id: clientId,\n client_secret: clientSecret,\n client_type: \"confidential\",\n name,\n redirect_uris: redirectUris,\n },\n ],\n };\n }\n return null;\n}\n\nfunction tokenUrlFor(service: ServiceName, baseUrl: string): string | undefined {\n const paths: Partial<Record<ServiceName, string>> = {\n github: \"/login/oauth/access_token\",\n google: \"/token\",\n apple: \"/auth/token\",\n microsoft: \"/oauth2/v2.0/token\",\n okta: \"/oauth2/default/v1/token\",\n slack: \"/api/oauth.v2.access\",\n vercel: \"/v2/oauth/access_token\",\n spotify: \"/api/token\",\n clerk: \"/oauth/token\",\n x: \"/2/oauth2/token\",\n };\n const path = paths[service];\n return path ? `${baseUrl}${path}` : undefined;\n}\n\nfunction authorizationUrlFor(service: ServiceName, baseUrl: string): string | undefined {\n const paths: Partial<Record<ServiceName, string>> = {\n github: \"/login/oauth/authorize\",\n google: \"/o/oauth2/v2/auth\",\n apple: \"/auth/authorize\",\n microsoft: \"/oauth2/v2.0/authorize\",\n okta: \"/oauth2/default/v1/authorize\",\n slack: \"/oauth/v2/authorize\",\n vercel: \"/integrations/oauth/authorize\",\n clerk: \"/oauth/authorize\",\n x: \"/2/oauth2/authorize\",\n };\n const path = paths[service];\n return path ? `${baseUrl}${path}` : undefined;\n}\n\nfunction randomId(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nexport const SERVICE_REGISTRY: Record<ServiceName, ServiceEntry> = {\n vercel: {\n label: \"Vercel REST API emulator\",\n endpoints: \"projects, deployments, domains, env vars, users, teams, file uploads, protection bypass\",\n async load() {\n const mod = await import(\"@emulators/vercel\");\n return {\n plugin: mod.vercelPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ username: login }] });\n return mod.getVercelStore(store).users.findOneBy(\"username\", login)?.id ?? 1;\n },\n };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ username?: string }> | undefined)?.[0]?.username ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [] };\n },\n initConfig: {\n vercel: {\n users: [{ username: \"developer\", name: \"Developer\", email: \"dev@example.com\" }],\n teams: [{ slug: \"my-team\", name: \"My Team\" }],\n projects: [{ name: \"my-app\", team: \"my-team\", framework: \"nextjs\" }],\n integrations: [\n {\n client_id: \"oac_example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My Vercel App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/vercel\"],\n },\n ],\n },\n },\n },\n\n github: {\n label: \"GitHub REST API emulator\",\n endpoints:\n \"users, repos, issues, PRs, comments, reviews, labels, milestones, branches, git data, orgs, teams, releases, webhooks, search, actions, checks, rate limit\",\n async load() {\n const mod = await import(\"@emulators/github\");\n return {\n plugin: mod.githubPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n createAppKeyResolver(store: Store): AppKeyResolver {\n return (appId: number) => {\n try {\n const gh = mod.getGitHubStore(store);\n const ghApp = gh.apps.all().find((a) => a.app_id === appId);\n if (!ghApp) return null;\n return { privateKey: ghApp.private_key, slug: ghApp.slug, name: ghApp.name };\n } catch {\n return null;\n }\n };\n },\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ login }] });\n return mod.getGitHubStore(store).users.findOneBy(\"login\", login)?.id ?? 1;\n },\n };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ login?: string }> | undefined)?.[0]?.login ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n },\n initConfig: {\n github: {\n users: [\n {\n login: \"octocat\",\n name: \"The Octocat\",\n email: \"octocat@github.com\",\n bio: \"I am the Octocat\",\n company: \"GitHub\",\n location: \"San Francisco\",\n },\n ],\n orgs: [{ login: \"my-org\", name: \"My Organization\", description: \"A test organization\" }],\n repos: [\n {\n owner: \"octocat\",\n name: \"hello-world\",\n description: \"My first repository\",\n language: \"JavaScript\",\n topics: [\"hello\", \"world\"],\n auto_init: true,\n },\n {\n owner: \"my-org\",\n name: \"org-repo\",\n description: \"An organization repository\",\n language: \"TypeScript\",\n auto_init: true,\n },\n ],\n oauth_apps: [\n {\n client_id: \"Iv1.example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/github\"],\n },\n ],\n },\n },\n },\n\n google: {\n label: \"Google OAuth 2.0 / OpenID Connect + Gmail, Calendar, and Drive emulator\",\n endpoints:\n \"OAuth authorize, token exchange, userinfo, OIDC discovery, token revocation, Gmail messages/drafts/threads/labels/history/settings, Calendar lists/events/freebusy, Drive files/uploads\",\n async load() {\n const mod = await import(\"@emulators/google\");\n return { plugin: mod.googlePlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@gmail.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\"] };\n },\n initConfig: {\n google: {\n users: [\n {\n email: \"testuser@example.com\",\n name: \"Test User\",\n picture: \"https://lh3.googleusercontent.com/a/default-user\",\n email_verified: true,\n },\n ],\n oauth_clients: [\n {\n client_id: \"example-client-id.apps.googleusercontent.com\",\n client_secret: \"GOCSPX-example_secret\",\n name: \"Code App (Google)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/google\"],\n },\n ],\n labels: [\n {\n id: \"Label_ops\",\n user_email: \"testuser@example.com\",\n name: \"Ops/Review\",\n color_background: \"#DDEEFF\",\n color_text: \"#111111\",\n },\n ],\n messages: [\n {\n id: \"msg_welcome\",\n user_email: \"testuser@example.com\",\n from: \"welcome@example.com\",\n to: \"testuser@example.com\",\n subject: \"Welcome to the Gmail emulator\",\n body_text: \"You can now test Gmail, Calendar, and Drive flows locally.\",\n label_ids: [\"INBOX\", \"UNREAD\", \"CATEGORY_UPDATES\"],\n date: \"2025-01-04T10:00:00.000Z\",\n },\n ],\n calendars: [\n {\n id: \"primary\",\n user_email: \"testuser@example.com\",\n summary: \"testuser@example.com\",\n primary: true,\n selected: true,\n time_zone: \"UTC\",\n },\n ],\n calendar_events: [\n {\n id: \"evt_kickoff\",\n user_email: \"testuser@example.com\",\n calendar_id: \"primary\",\n summary: \"Project Kickoff\",\n start_date_time: \"2025-01-10T09:00:00.000Z\",\n end_date_time: \"2025-01-10T09:30:00.000Z\",\n },\n ],\n drive_items: [\n {\n id: \"drv_docs\",\n user_email: \"testuser@example.com\",\n name: \"Docs\",\n mime_type: \"application/vnd.google-apps.folder\",\n parent_ids: [\"root\"],\n },\n ],\n },\n },\n },\n\n slack: {\n label: \"Slack API emulator\",\n endpoints:\n \"auth, chat, conversations, users, profiles, presence, files, pins, bookmarks, views, reactions, team, OAuth, incoming webhooks, inspector\",\n async load() {\n const mod = await import(\"@emulators/slack\");\n return { plugin: mod.slackPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return {\n login: \"U000000001\",\n id: 1,\n scopes: [],\n };\n },\n initConfig: {\n slack: {\n team: { name: \"My Workspace\", domain: \"my-workspace\" },\n users: [\n {\n name: \"developer\",\n real_name: \"Developer\",\n email: \"dev@example.com\",\n profile: {\n title: \"Local Developer\",\n status_text: \"Testing locally\",\n status_emoji: \":computer:\",\n },\n presence: \"active\",\n },\n ],\n channels: [\n { name: \"general\", topic: \"General discussion\" },\n { name: \"random\", topic: \"Random stuff\" },\n ],\n bots: [{ name: \"my-bot\" }],\n oauth_apps: [\n {\n client_id: \"12345.67890\",\n client_secret: \"example_client_secret\",\n app_id: \"A000000001\",\n name: \"My Slack App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/slack\"],\n scopes: [\n \"chat:write\",\n \"channels:read\",\n \"channels:history\",\n \"channels:join\",\n \"channels:manage\",\n \"channels:write\",\n \"groups:read\",\n \"groups:history\",\n \"groups:write\",\n \"im:read\",\n \"im:history\",\n \"im:write\",\n \"mpim:read\",\n \"mpim:history\",\n \"mpim:write\",\n \"users:read\",\n \"users:read.email\",\n \"users.profile:read\",\n \"users.profile:write\",\n \"users:write\",\n \"files:read\",\n \"files:write\",\n \"pins:read\",\n \"pins:write\",\n \"bookmarks:read\",\n \"bookmarks:write\",\n \"reactions:read\",\n \"reactions:write\",\n \"team:read\",\n ],\n user_scopes: [\"users:read\", \"users.profile:read\"],\n bot_name: \"my-bot\",\n },\n ],\n strict_scopes: false,\n },\n },\n },\n\n apple: {\n label: \"Apple Sign In / OAuth emulator\",\n endpoints: \"OAuth authorize, token exchange, JWKS\",\n async load() {\n const mod = await import(\"@emulators/apple\");\n return { plugin: mod.applePlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@icloud.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"name\"] };\n },\n initConfig: {\n apple: {\n users: [{ email: \"testuser@icloud.com\", name: \"Test User\" }],\n oauth_clients: [\n {\n client_id: \"com.example.app\",\n team_id: \"TEAM001\",\n name: \"My Apple App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/apple\"],\n },\n ],\n },\n },\n },\n\n microsoft: {\n label: \"Microsoft Entra ID OAuth 2.0 / OpenID Connect emulator\",\n endpoints: \"OAuth authorize, token exchange, userinfo, OIDC discovery, Graph /me, logout, token revocation\",\n async load() {\n const mod = await import(\"@emulators/microsoft\");\n return { plugin: mod.microsoftPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@outlook.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\", \"User.Read\"] };\n },\n initConfig: {\n microsoft: {\n users: [{ email: \"testuser@outlook.com\", name: \"Test User\" }],\n oauth_clients: [\n {\n client_id: \"example-client-id\",\n client_secret: \"example-client-secret\",\n name: \"My Microsoft App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/microsoft-entra-id\"],\n },\n ],\n },\n },\n },\n\n okta: {\n label: \"Okta OAuth 2.0 / OpenID Connect + management API emulator\",\n endpoints:\n \"OIDC discovery, JWKS, OAuth authorize/token/userinfo/introspect/revoke/logout, users, groups, apps, authorization servers\",\n async load() {\n const mod = await import(\"@emulators/okta\");\n return { plugin: mod.oktaPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstLogin =\n (cfg?.users as Array<{ login?: string; email?: string }> | undefined)?.[0]?.login ??\n (cfg?.users as Array<{ login?: string; email?: string }> | undefined)?.[0]?.email ??\n \"testuser@okta.local\";\n return { login: firstLogin, id: 1, scopes: [\"openid\", \"profile\", \"email\", \"groups\"] };\n },\n initConfig: {\n okta: {\n users: [{ login: \"testuser@okta.local\", email: \"testuser@okta.local\", first_name: \"Test\", last_name: \"User\" }],\n groups: [{ name: \"Everyone\", description: \"All users\", type: \"BUILT_IN\", okta_id: \"00g_everyone\" }],\n authorization_servers: [{ id: \"default\", name: \"default\", audiences: [\"api://default\"] }],\n oauth_clients: [\n {\n client_id: \"okta-test-client\",\n client_secret: \"okta-test-secret\",\n name: \"Sample OIDC Client\",\n redirect_uris: [\"http://localhost:3000/callback\"],\n auth_server_id: \"default\",\n },\n ],\n },\n },\n },\n\n aws: {\n label: \"AWS cloud service emulator\",\n endpoints:\n \"S3 (buckets, objects), SQS (queues, messages), IAM (users, roles, access keys), STS (assume role, caller identity)\",\n async load() {\n const mod = await import(\"@emulators/aws\");\n return {\n plugin: mod.awsPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n issueCredential(\n store: Store,\n baseUrl: string,\n _tokenMap: TokenMap,\n request: CredentialRequest,\n ): IssuedCredential {\n const userName = request.login ?? \"developer\";\n mod.seedFromConfig(store, baseUrl, { iam: { users: [{ user_name: userName, create_access_key: true }] } });\n const user = mod.getAwsStore(store).iamUsers.findOneBy(\"user_name\", userName);\n const key = user?.access_keys.find((candidate) => candidate.status === \"Active\");\n if (!user || !key) throw new Error(\"Failed to create AWS access key\");\n return {\n type: \"provider-specific\",\n provider: \"aws\",\n user_name: user.user_name,\n access_key_id: key.access_key_id,\n secret_access_key: key.secret_access_key,\n region: \"us-east-1\",\n };\n },\n };\n },\n defaultFallback() {\n return { login: \"admin\", id: 1, scopes: [\"s3:*\", \"sqs:*\", \"iam:*\", \"sts:*\"] };\n },\n initConfig: {\n aws: {\n region: \"us-east-1\",\n s3: { buckets: [{ name: \"my-app-bucket\" }, { name: \"my-app-uploads\" }] },\n sqs: { queues: [{ name: \"my-app-events\" }, { name: \"my-app-dlq\" }] },\n iam: {\n users: [{ user_name: \"developer\", create_access_key: true }],\n roles: [{ role_name: \"lambda-execution-role\", description: \"Role for Lambda function execution\" }],\n },\n },\n },\n },\n resend: {\n label: \"Resend email API emulator\",\n endpoints: \"emails, domains, contacts, API keys, inbox UI\",\n async load() {\n const mod = await import(\"@emulators/resend\");\n return { plugin: mod.resendPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"re_test_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n resend: {\n domains: [{ name: \"example.com\", region: \"us-east-1\" }],\n contacts: [{ email: \"test@example.com\", first_name: \"Test\", last_name: \"User\" }],\n },\n },\n },\n stripe: {\n label: \"Stripe payments emulator\",\n endpoints:\n \"customers, payment methods, customer sessions, payment intents, charges, products, prices, checkout sessions, webhooks\",\n async load() {\n const mod = await import(\"@emulators/stripe\");\n return { plugin: mod.stripePlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"sk_test_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n stripe: {\n customers: [{ email: \"test@example.com\", name: \"Test Customer\" }],\n products: [{ name: \"Pro Plan\", description: \"Monthly pro subscription\" }],\n prices: [{ product_name: \"Pro Plan\", currency: \"usd\", unit_amount: 2000 }],\n },\n },\n },\n mongoatlas: {\n label: \"MongoDB Atlas service emulator\",\n endpoints:\n \"Atlas Admin API v2 (projects, clusters, database users, databases, collections), Atlas Data API v1 (findOne, find, insertOne, insertMany, updateOne, updateMany, deleteOne, deleteMany, aggregate)\",\n async load() {\n const mod = await import(\"@emulators/mongoatlas\");\n return { plugin: mod.mongoatlasPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"admin\", id: 1, scopes: [] };\n },\n initConfig: {\n mongoatlas: {\n projects: [{ name: \"Project0\" }],\n clusters: [{ name: \"Cluster0\", project: \"Project0\" }],\n database_users: [{ username: \"admin\", project: \"Project0\" }],\n databases: [{ cluster: \"Cluster0\", name: \"test\", collections: [\"items\"] }],\n },\n },\n },\n clerk: {\n label: \"Clerk authentication and user management emulator\",\n endpoints:\n \"OIDC discovery, JWKS, OAuth authorize/token/userinfo, users, email addresses, organizations, memberships, invitations, sessions\",\n async load() {\n const mod = await import(\"@emulators/clerk\");\n return { plugin: mod.clerkPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail =\n (cfg?.users as Array<{ email_addresses?: string[] }> | undefined)?.[0]?.email_addresses?.[0] ??\n \"test@example.com\";\n return { login: firstEmail, id: 1, scopes: [] };\n },\n initConfig: {\n clerk: {\n users: [\n {\n first_name: \"Test\",\n last_name: \"User\",\n email_addresses: [\"test@example.com\"],\n password: \"clerk_test_password\",\n },\n ],\n organizations: [\n {\n name: \"My Company\",\n slug: \"my-company\",\n members: [{ email: \"test@example.com\", role: \"admin\" }],\n },\n ],\n oauth_applications: [\n {\n client_id: \"clerk_emulate_client\",\n client_secret: \"clerk_emulate_secret\",\n name: \"Emulate App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/clerk\"],\n },\n ],\n },\n },\n },\n spotify: {\n label: \"Spotify Web API emulator\",\n endpoints: \"client credentials token endpoint, catalog search, artists, albums, and tracks\",\n async load() {\n const mod = await import(\"@emulators/spotify\");\n return { plugin: mod.spotifyPlugin, manifest: mod.manifest, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"spotify-app\", id: 1, scopes: [] };\n },\n initConfig: {\n spotify: {\n clients: [{ client_id: \"demo-client-id\", client_secret: \"demo-client-secret\", name: \"Demo App\" }],\n },\n },\n },\n x: {\n label: \"X (Twitter) API v2 emulator\",\n endpoints:\n \"OAuth 2.0 authorize/token/revoke (Authorization Code with PKCE + app-only client credentials), users, tweets\",\n async load() {\n const mod = await import(\"@emulators/x\");\n return {\n plugin: mod.xPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ username: login }] });\n return mod.getXStore(store).users.findOneBy(\"username\", login.toLowerCase().replace(/^@/, \"\"))?.id ?? 1;\n },\n };\n },\n defaultFallback(cfg) {\n const firstUsername = (cfg?.users as Array<{ username?: string }> | undefined)?.[0]?.username ?? \"developer\";\n return { login: firstUsername, id: 1, scopes: [\"tweet.read\", \"users.read\"] };\n },\n initConfig: {\n x: {\n users: [\n {\n username: \"developer\",\n name: \"Developer\",\n description: \"Building with the X API v2 emulator.\",\n verified: true,\n followers_count: 1200,\n following_count: 320,\n },\n ],\n oauth_clients: [\n {\n client_id: \"x-confidential-client\",\n client_secret: \"x-confidential-secret\",\n client_type: \"confidential\",\n name: \"My X App (confidential)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n {\n client_id: \"x-public-client\",\n client_type: \"public\",\n name: \"My X App (public)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n ],\n tweets: [{ text: \"Hello from the X API v2 emulator.\", author: \"developer\", like_count: 42, retweet_count: 7 }],\n },\n },\n },\n workos: {\n label: \"WorkOS emulator\",\n endpoints:\n \"AuthKit user management (hosted login, code/refresh grants, sealed-session JWKS), organizations, memberships, invitations, API keys, Vault KV, OAuth authorization server\",\n async load() {\n const mod = await import(\"@emulators/workos\");\n return {\n plugin: mod.workosPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n ensureUser(store: Store, baseUrl: string, login: string): number {\n mod.seedFromConfig(store, baseUrl, { users: [{ email: login }] });\n return mod.getWorkosStore(store).users.findOneBy(\"email\", login)?.id ?? 1;\n },\n };\n },\n defaultFallback() {\n return { login: \"sk_emulate_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n workos: {\n users: [{ email: \"admin@example.com\", first_name: \"Admin\", last_name: \"User\" }],\n organizations: [{ name: \"Acme\", members: [\"admin@example.com\"] }],\n },\n },\n },\n autumn: {\n label: \"Autumn billing emulator\",\n endpoints: \"customers (get_or_create with seedable subscriptions), usage tracking, plans/features/events lists\",\n async load() {\n const mod = await import(\"@emulators/autumn\");\n return {\n plugin: mod.autumnPlugin,\n manifest: mod.manifest,\n seedFromConfig: mod.seedFromConfig,\n };\n },\n defaultFallback() {\n return { login: \"am_emulate_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n autumn: {\n customers: [{ id: \"org_paid_example\", subscriptions: [{ plan_id: \"pro\", status: \"active\" }] }],\n },\n },\n },\n};\n\nexport const DEFAULT_TOKENS = {\n tokens: {\n test_token_admin: {\n login: \"admin\",\n scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n },\n test_token_user1: {\n login: \"octocat\",\n scopes: [\"repo\", \"user\"],\n },\n },\n};\n","import { createServer, serve, type AppKeyResolver, type Store } from \"@emulators/core\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES, issueServiceCredential, type ServiceName } from \"../registry.js\";\nimport { readFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { parse as parseYaml } from \"yaml\";\nimport pc from \"picocolors\";\nimport { ensurePortless, registerAliases, removeAliases, portlessBaseUrl, type PortlessAlias } from \"../portless.js\";\nimport { resolveBaseUrl } from \"../base-url.js\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nexport interface StartOptions {\n port: number;\n service?: string;\n seed?: string;\n baseUrl?: string;\n portless?: boolean;\n}\n\ninterface SeedConfig {\n tokens?: Record<string, { login: string; scopes?: string[] }>;\n [service: string]: unknown;\n}\n\ninterface LoadResult {\n config: SeedConfig;\n source: string;\n}\n\nfunction loadSeedConfig(seedPath?: string): LoadResult | null {\n if (seedPath) {\n const fullPath = resolve(seedPath);\n if (!existsSync(fullPath)) {\n console.error(`Seed file not found: ${fullPath}`);\n process.exit(1);\n }\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: seedPath };\n } catch (err) {\n console.error(`Failed to parse ${seedPath}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n\n const autoFiles = [\n \"emulate.config.yaml\",\n \"emulate.config.yml\",\n \"emulate.config.json\",\n \"service-emulator.config.yaml\",\n \"service-emulator.config.yml\",\n \"service-emulator.config.json\",\n ];\n\n for (const file of autoFiles) {\n const fullPath = resolve(file);\n if (existsSync(fullPath)) {\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: file };\n } catch (err) {\n console.error(`Failed to parse ${file}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n }\n\n return null;\n}\n\nfunction inferServicesFromConfig(config: SeedConfig): ServiceName[] | null {\n const found = SERVICE_NAMES.filter((k) => k in config);\n return found.length > 0 ? [...found] : null;\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const { port: basePort } = options;\n\n if (options.portless && options.baseUrl) {\n console.error(\"--portless and --base-url are mutually exclusive.\");\n process.exit(1);\n }\n\n const loaded = loadSeedConfig(options.seed);\n const seedConfig = loaded?.config ?? null;\n const configSource = loaded?.source ?? null;\n\n let services: ServiceName[];\n if (options.service) {\n services = options.service.split(\",\").map((s) => s.trim()) as ServiceName[];\n } else if (seedConfig) {\n services = inferServicesFromConfig(seedConfig) ?? [...SERVICE_NAMES];\n } else {\n services = [...SERVICE_NAMES];\n }\n\n for (const svc of services) {\n if (!SERVICE_REGISTRY[svc]) {\n console.error(`Unknown service: ${svc}`);\n process.exit(1);\n }\n }\n\n const tokens: Record<string, { login: string; id: number; scopes?: string[] }> = {};\n if (seedConfig?.tokens) {\n let tokenId = 100;\n for (const [token, user] of Object.entries(seedConfig.tokens)) {\n tokens[token] = { login: user.login, id: tokenId++, scopes: user.scopes };\n }\n } else {\n tokens[\"test_token_admin\"] = { login: \"admin\", id: 2, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n }\n\n if (options.portless) {\n await ensurePortless();\n }\n\n interface PreparedService {\n svc: ServiceName;\n entry: (typeof SERVICE_REGISTRY)[ServiceName];\n loadedSvc: Awaited<ReturnType<(typeof SERVICE_REGISTRY)[ServiceName][\"load\"]>>;\n svcSeedConfig: Record<string, unknown> | undefined;\n port: number;\n baseUrl: string;\n }\n\n const portlessAliases: PortlessAlias[] = [];\n const prepared: PreparedService[] = [];\n\n for (let i = 0; i < services.length; i++) {\n const svc = services[i];\n const entry = SERVICE_REGISTRY[svc];\n const loadedSvc = await entry.load();\n\n const svcSeedConfig = seedConfig?.[svc] as Record<string, unknown> | undefined;\n const port = (svcSeedConfig?.port as number | undefined) ?? basePort + i;\n\n if (options.portless) {\n portlessAliases.push({ name: `${svc}.emulate`, port });\n }\n\n const seedBaseUrl =\n typeof svcSeedConfig?.baseUrl === \"string\" && svcSeedConfig.baseUrl.length > 0\n ? svcSeedConfig.baseUrl\n : undefined;\n const effectiveBaseUrl = options.portless ? portlessBaseUrl(svc) : options.baseUrl;\n const baseUrl = resolveBaseUrl({ service: svc, port, baseUrl: effectiveBaseUrl, seedBaseUrl });\n\n prepared.push({ svc, entry, loadedSvc, svcSeedConfig, port, baseUrl });\n }\n\n if (portlessAliases.length > 0) {\n registerAliases(portlessAliases);\n }\n\n const serviceUrls: Array<{ name: string; url: string }> = [];\n const stores: Store[] = [];\n const httpServers: ReturnType<typeof serve>[] = [];\n\n for (const { svc, entry, loadedSvc, svcSeedConfig, port, baseUrl } of prepared) {\n serviceUrls.push({ name: svc, url: baseUrl });\n\n // eslint-disable-next-line prefer-const -- reassigned after closure captures it\n let cachedResolver: AppKeyResolver | undefined;\n const appKeyResolver: AppKeyResolver | undefined = loadedSvc.createAppKeyResolver\n ? (appId) => cachedResolver!(appId)\n : undefined;\n\n const fallbackUser = entry.defaultFallback(svcSeedConfig);\n\n let resetService = () => {};\n let applyRuntimeSeed = (_seed: unknown) => {};\n const { app, store, webhooks, ledger, tokenMap } = createServer(loadedSvc.plugin, {\n port,\n baseUrl,\n tokens,\n appKeyResolver,\n fallbackUser,\n manifest: loadedSvc.manifest,\n instance: svc,\n reset: () => resetService(),\n seed: (seed) => applyRuntimeSeed(seed),\n issueCredential: (request) => issueServiceCredential(svc, loadedSvc, store, baseUrl, tokenMap, request, webhooks),\n });\n cachedResolver = loadedSvc.createAppKeyResolver?.(store);\n stores.push(store);\n\n resetService = () => {\n store.reset();\n webhooks.clear();\n ledger.clear();\n loadedSvc.plugin.seed?.(store, baseUrl);\n if (svcSeedConfig && loadedSvc.seedFromConfig) {\n loadedSvc.seedFromConfig(store, baseUrl, svcSeedConfig, webhooks);\n }\n };\n applyRuntimeSeed = (seed) => {\n if (seed && loadedSvc.seedFromConfig) {\n loadedSvc.seedFromConfig(store, baseUrl, seed, webhooks);\n }\n };\n resetService();\n\n const httpServer = serve({ fetch: app.fetch, port });\n httpServers.push(httpServer);\n }\n\n printBanner(serviceUrls, tokens, configSource);\n\n const shutdown = () => {\n console.log(`\\n${pc.dim(\"Shutting down...\")}`);\n if (portlessAliases.length > 0) {\n removeAliases(portlessAliases);\n }\n for (const store of stores) {\n store.reset();\n }\n for (const srv of httpServers) {\n srv.close();\n }\n process.exit(0);\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n}\n\nfunction printBanner(\n services: Array<{ name: string; url: string }>,\n tokens: Record<string, { login: string; id: number; scopes?: string[] }>,\n configSource: string | null,\n): void {\n const lines: string[] = [];\n lines.push(\"\");\n lines.push(` ${pc.bold(\"emulate\")} ${pc.dim(`v${pkg.version}`)}`);\n lines.push(\"\");\n\n const maxNameLen = Math.max(...services.map((s) => s.name.length));\n for (const { name, url } of services) {\n lines.push(` ${pc.cyan(name.padEnd(maxNameLen + 2))}${pc.bold(url)}`);\n }\n lines.push(\"\");\n\n const tokenEntries = Object.entries(tokens);\n if (tokenEntries.length > 0) {\n lines.push(` ${pc.dim(\"Tokens\")}`);\n for (const [token, user] of tokenEntries) {\n lines.push(` ${pc.dim(token)} ${pc.dim(\"->\")} ${user.login}`);\n }\n lines.push(\"\");\n }\n\n if (configSource) {\n lines.push(` ${pc.dim(\"Config:\")} ${configSource}`);\n } else {\n lines.push(` ${pc.dim(\"Config:\")} defaults ${pc.dim(\"(run\")} npx emulate init ${pc.dim(\"to customize)\")}`);\n }\n lines.push(\"\");\n\n console.log(lines.join(\"\\n\"));\n}\n","import { execSync, spawnSync } from \"child_process\";\nimport { createInterface } from \"readline\";\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nfunction hasPortless(): boolean {\n const result = spawnSync(\"portless\", [\"--version\"], { stdio: \"ignore\" });\n return result.status === 0;\n}\n\nfunction promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer) => {\n rl.close();\n const normalized = answer.trim().toLowerCase();\n resolve(normalized === \"\" || normalized === \"y\" || normalized === \"yes\");\n });\n });\n}\n\nfunction isProxyRunning(): boolean {\n const result = spawnSync(\"portless\", [\"list\"], { stdio: \"ignore\" });\n return result.status === 0;\n}\n\nexport async function ensurePortless(): Promise<void> {\n if (!hasPortless()) {\n if (!isInteractive()) {\n console.error(\"portless is required but not installed. Run: npm i -g portless\");\n process.exit(1);\n }\n\n const yes = await promptYesNo(\"portless is not installed. Install it now? (npm i -g portless) [Y/n] \");\n if (!yes) {\n console.error(\"Cannot continue without portless.\");\n process.exit(1);\n }\n\n try {\n execSync(\"npm i -g portless\", { stdio: \"inherit\" });\n } catch {\n console.error(\"Failed to install portless.\");\n process.exit(1);\n }\n\n if (!hasPortless()) {\n console.error(\"portless was installed but could not be found on PATH.\");\n process.exit(1);\n }\n }\n\n if (!isProxyRunning()) {\n console.error(\"portless proxy is not running. Start it with: portless proxy start\");\n process.exit(1);\n }\n}\n\nexport interface PortlessAlias {\n name: string;\n port: number;\n}\n\nexport function registerAliases(aliases: PortlessAlias[]): void {\n const registered: PortlessAlias[] = [];\n for (const { name, port } of aliases) {\n const result = spawnSync(\"portless\", [\"alias\", name, String(port), \"--force\"], {\n stdio: \"inherit\",\n });\n if (result.status !== 0) {\n if (registered.length > 0) {\n removeAliases(registered);\n }\n throw new Error(`Failed to register portless alias: ${name} -> ${port}`);\n }\n registered.push({ name, port });\n }\n}\n\nexport function removeAliases(aliases: PortlessAlias[]): void {\n for (const { name } of aliases) {\n const result = spawnSync(\"portless\", [\"alias\", \"--remove\", name], { stdio: \"ignore\" });\n if (result.status !== 0) {\n console.error(`Warning: failed to remove portless alias: ${name}`);\n }\n }\n}\n\nexport function portlessBaseUrl(serviceName: string): string {\n return `https://${serviceName}.emulate.localhost`;\n}\n","export interface ResolveBaseUrlOptions {\n service: string;\n port: number;\n baseUrl?: string;\n seedBaseUrl?: string;\n}\n\n/**\n * Fallback chain:\n * 1. Per-service baseUrl from seed config\n * 2. Explicit baseUrl (CLI flag or programmatic option)\n * 3. EMULATE_BASE_URL env var (with {service} interpolation)\n * 4. PORTLESS_URL env var (with {service} interpolation)\n * 5. http://localhost:<port>\n */\nexport function resolveBaseUrl(opts: ResolveBaseUrlOptions): string {\n if (opts.seedBaseUrl) {\n return opts.seedBaseUrl.replace(/\\{service\\}/g, opts.service);\n }\n if (opts.baseUrl) {\n return opts.baseUrl.replace(/\\{service\\}/g, opts.service);\n }\n const envBaseUrl = process.env.EMULATE_BASE_URL;\n if (envBaseUrl) {\n return envBaseUrl.replace(/\\{service\\}/g, opts.service);\n }\n const portlessUrl = process.env.PORTLESS_URL;\n if (portlessUrl) {\n return portlessUrl.replace(/\\{service\\}/g, opts.service);\n }\n return `http://localhost:${opts.port}`;\n}\n","import { writeFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { stringify as yamlStringify } from \"yaml\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES, DEFAULT_TOKENS, type ServiceName } from \"../registry.js\";\n\ninterface InitOptions {\n service: string;\n}\n\nexport function initCommand(options: InitOptions): void {\n const filename = \"emulate.config.yaml\";\n const fullPath = resolve(filename);\n\n if (existsSync(fullPath)) {\n console.error(`Config file already exists: ${filename}`);\n process.exit(1);\n }\n\n let config: Record<string, unknown>;\n if (options.service === \"all\") {\n config = { ...DEFAULT_TOKENS };\n for (const name of SERVICE_NAMES) {\n Object.assign(config, SERVICE_REGISTRY[name].initConfig);\n }\n } else {\n const entry = SERVICE_REGISTRY[options.service as ServiceName];\n if (!entry) {\n console.error(`Unknown service: ${options.service}. Available: ${SERVICE_NAMES.join(\", \")}, all`);\n process.exit(1);\n }\n config = { ...DEFAULT_TOKENS, ...entry.initConfig };\n }\n\n const content = yamlStringify(config);\n writeFileSync(fullPath, content, \"utf-8\");\n\n console.log(`Created ${filename}`);\n console.log(`\\nRun 'npx emulate' to start the emulator.`);\n}\n","import { SERVICE_REGISTRY } from \"../registry.js\";\n\nexport function listCommand(): void {\n console.log(\"\\nAvailable services:\\n\");\n for (const [name, entry] of Object.entries(SERVICE_REGISTRY)) {\n console.log(` ${name.padEnd(10)}${entry.label}`);\n console.log(` Endpoints: ${entry.endpoints}`);\n console.log();\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,eAAe;;;AEAxB,SAAS,gBAAgB,wBAAgF;ACAzG,SAAS,kBAAkB;AIA3B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;ANoCvB,SAAS,eAAe,OAAyB;AACtD,MAAI,iBAAiB,KAAK;AACxB,WAAO,EAAE,QAAQ,OAAgB,SAAS,CAAC,GAAG,MAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,eAAe,CAAC,CAA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AM,aAAa;AAAA,IACjB;AAAA,IACA,SAAS,KAAK;AAAA,IACd,MAAM,KAAK;AAAA,IACX,SAAS,KAAK;AAAA,IACd,UAAU,KAAK;AAAA,EACjB,CAAC;AACH,CAAC;AAEH,QACG,QAAQ,MAAM,EACd,YAAY,gCAAgC,EAC5C,OAAO,2BAA2B,kCAAkC,KAAK,EACzE,OAAO,CAAC,SAAS;AAChB,cAAY,EAAE,SAAS,KAAK,QAAQ,CAAC;AACvC,CAAC;AAEH,QACG,QAAQ,MAAM,EACd,MAAM,eAAe,EACrB,YAAY,yBAAyB,EACrC,OAAO,MAAM;AACZ,cAAY;AACd,CAAC;AAEH,QAAQ,MAAM;","names":["route","resolve","credential","randomId","readFileSync","resolve","readFileSync","existsSync","resolve","resolve","existsSync","pkg"]}
|