@brickkit/core 0.10.0 → 0.11.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["defaultLogger","DEFAULT_REQUEST","RESOLVED_SYMBOL","EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty","EMPTY_SERVICES","DEFAULT_REQUEST","sqliteInteger","sqliteTable","sqliteText","sqliteIndex","pgText","pgInteger","pgIndex","and","eq","or","lte","lt","asc","inArray","getTableName","getTableName","getTableColumns","sql","getTableColumns"],"sources":["../src/compiler/ir.ts","../src/registry.ts","../src/telemetry.ts","../src/error-response.ts","../src/typebox.ts","../src/logger.ts","../src/action.ts","../src/plugin.ts","../src/compiler/runtime.ts","../src/action-handler.ts","../src/compiler/handler.ts","../src/app-entry.ts","../src/compiler.ts","../src/access.ts","../src/openapi.ts","../src/secrets.ts","../src/request-logger.ts","../src/docs.ts","../src/dashboard.ts","../src/endpoints.ts","../src/events/outbox.ts","../src/events/transaction.ts","../src/events/dispatcher.ts","../src/events/id.ts","../src/events/workflows.ts","../src/events/hub.ts","../src/socket.ts","../src/server.ts","../src/compiler/emit.ts","../src/tool.ts","../src/db/sqlite.ts","../src/db/postgres.ts","../src/db/define.ts","../src/db/index.ts","../src/resource.ts","../src/context.ts","../src/service.ts","../src/rpc.ts","../src/events/listener.ts","../src/events/emit.ts","../src/mcp.ts"],"sourcesContent":["import { type Service, type Action } from \"../types\";\nimport { getPluginActionRoute } from \"../plugin\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\" | \"array\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly preparations: readonly {\n service: string;\n name: string;\n metadata: unknown;\n }[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n for (const service of services) service.build();\n return analyzeDeclaredApplication(services, prefix);\n}\n\n/** Inspect current declarations without closing service/plugin setup. */\nexport function analyzeDeclaredApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, { name: string; plugin: boolean }>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const plugin = getPluginActionRoute(action, prefix) !== undefined;\n const key = `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n const previous = registered.get(key);\n if (previous) {\n if (plugin || previous.plugin)\n throw new Error(\n `Brick compiler: duplicate plugin route '${method} ${path}'`,\n );\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, { name: `${service.name}.${action.name}`, plugin });\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" | \"array\" }[] =\n [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\")\n coercions.push({ key, type: \"boolean\" });\n else if (prop.type === \"array\") coercions.push({ key, type: \"array\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\n bindings.push({ service, action });\n };\n for (const service of services) {\n for (const action of service.listActions()) {\n const pluginRoute = getPluginActionRoute(action, prefix);\n if (pluginRoute === false) continue;\n const path =\n pluginRoute?.path ??\n action.config.path ??\n `${prefix}/${service.name}/${action.name}`;\n add(\n service,\n action,\n pluginRoute?.method ?? action.config.method ?? \"POST\",\n path,\n \"action\",\n );\n }\n }\n const preparations = services.flatMap((service) =>\n service.listPreparations().map((contribution) => ({\n service: service.name,\n name: contribution.name,\n metadata: schemaSnapshot(contribution.describe?.()),\n })),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n preparations,\n diagnostics,\n });\n return { ir, bindings };\n}\n","import type { Service, ArchitectureSchema } from \"./types\";\nimport { analyzeDeclaredApplication, type RouteIR } from \"./compiler/ir\";\nimport type { EventsDefinition } from \"./events/hub\";\nimport type { BrickSocketSchema } from \"./socket-types\";\n\nexport interface ArchitectureApplication {\n services: readonly Service[];\n routes: readonly RouteIR[];\n events?: EventsDefinition;\n sockets?: readonly (BrickSocketSchema & { service: string; path: string })[];\n}\n\nexport class ServiceRegistry {\n private _revision = 0;\n /** Definition revision for invalidating serialized architecture snapshots. */\n get revision(): number {\n return this._revision;\n }\n touch(): void {\n this._revision++;\n }\n\n private services = new Map<string, Service>();\n private routes = new Map<Service, readonly RouteIR[]>();\n\n /** Remember the actual registered routes for subsequent registry exports. */\n setApplicationRoutes(application: ArchitectureApplication): void {\n for (const service of application.services) {\n this.routes.set(\n service,\n application.routes.filter((route) => route.service === service.name),\n );\n }\n this.touch();\n }\n\n register(service: Service): void {\n if (this.services.has(service.name)) {\n console.warn(\n `[Brick-TS] Service '${service.name}' is already registered. Overwriting.`,\n );\n }\n const previous = this.services.get(service.name);\n if (previous) this.routes.delete(previous);\n this.services.set(service.name, service);\n this.touch();\n }\n\n get(name: string): Service | undefined {\n return this.services.get(name);\n }\n\n has(name: string): boolean {\n return this.services.has(name);\n }\n\n list(): Service[] {\n return Array.from(this.services.values());\n }\n\n clear(): void {\n this.services.clear();\n this.routes.clear();\n this.touch();\n }\n\n exportArchitecture(\n application?: ArchitectureApplication,\n ): ArchitectureSchema {\n return {\n version: \"1.0.0\",\n ...(application?.events ? { events: application.events } : {}),\n services: (application?.services ?? this.list()).map((service) => {\n const routes = application\n ? application.routes.filter((route) => route.service === service.name)\n : (this.routes.get(service) ??\n analyzeDeclaredApplication([service]).ir.routes);\n const byAction = new Map(routes.map((route) => [route.action, route]));\n const schema = service.introspect();\n return {\n ...schema,\n ...(application?.sockets\n ? {\n sockets: application.sockets.filter(\n (socket) => socket.service === service.name,\n ),\n }\n : {}),\n actions: schema.actions.map((action) => {\n const route = byAction.get(action.name);\n return route\n ? { ...action, method: route.method, path: route.path }\n : action;\n }),\n };\n }),\n };\n }\n}\n\n// Global registry instance\nlet globalRegistry = new ServiceRegistry();\n\n/**\n * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI\n * generator, `createServiceProxy`, and the dashboard find services by name.\n *\n * @returns The current global registry.\n */\nexport function getGlobalRegistry(): ServiceRegistry {\n return globalRegistry;\n}\n\n/**\n * Start over with an empty global registry. For tests, which define the same\n * services again in each case; an application never needs it.\n */\nexport function resetGlobalRegistry(): void {\n globalRegistry = new ServiceRegistry();\n}\n","import {\n context,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n type Attributes,\n type Span,\n} from \"@opentelemetry/api\";\n\nconst INSTRUMENTATION_SCOPE = \"@brickkit/core\";\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STATEMENT_LENGTH = 2000;\nconst DATABASE_INSTRUMENTED = Symbol.for(\"brickkit.telemetry.database\");\nconst SQLITE_STATEMENT_METHODS = [\"all\", \"get\", \"run\", \"values\"] as const;\n\ntype Outcome =\n | { failed: false; value: unknown }\n | { failed: true; error: unknown };\n\n/** Run `fn` as a child of the active span, ending the span when its result settles. */\nexport function withSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n kind: SpanKind = SpanKind.INTERNAL,\n): T {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(name, { kind, attributes }, (span) =>\n settle(fn, (outcome) => {\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n }),\n );\n}\n\n/**\n * Add a child span for an in-process call, but only inside a request that is\n * already traced. Calls made outside instrumented requests run unchanged.\n */\nexport function withCallSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n): T {\n return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();\n}\n\ninterface HttpContext {\n request?: Request;\n headers?: Record<string, string | undefined>;\n set?: { status?: unknown; headers?: Record<string, unknown> };\n}\n\n/** What a raw route handler receives from `traceRoute`. Read the body from `request`. */\nexport interface RawRouteContext {\n request: Request;\n headers: Record<string, string | undefined>;\n set: { status?: unknown; headers?: Record<string, unknown> };\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n}\n\n/**\n * Wrap a raw route handler so each of its requests gets a server span. Use it\n * for routes registered directly on the app, outside actions and endpoints,\n * such as auth or webhook routes. Spans are recorded whenever a tracer provider\n * is registered; `brick({ telemetry })` does not apply to these routes.\n *\n * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia\n * decides what to parse from the handler's destructuring, and forwarding the\n * whole context would parse the body and leave `request.json()` with nothing.\n */\nexport function traceRoute<T>(\n route: string,\n handler: (context: RawRouteContext) => T,\n): (context: RawRouteContext) => T {\n return ({ request, headers, set, params, query }) =>\n traceHttpRequest({ request, headers, set }, request.method, route, () =>\n handler({ request, headers, set, params, query }),\n );\n}\n\n/**\n * Wrap one HTTP request in a server span. The span continues the caller's\n * trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the\n * request id Brick returns is the span's trace id, so clients can find the\n * request in the dashboard.\n */\nexport function traceHttpRequest<T>(\n request: HttpContext,\n method: string,\n route: string,\n fn: () => T,\n): T {\n const attributes: Attributes = {\n \"http.request.method\": method,\n \"http.route\": route,\n };\n if (request.request) {\n attributes[\"url.path\"] = new URL(request.request.url).pathname;\n }\n const headers = request.headers ?? {};\n const parent = propagation.extract(context.active(), headers);\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(\n `${method} ${route}`,\n { kind: SpanKind.SERVER, attributes },\n parent,\n (span) => {\n if (!headers[\"x-trace-id\"]) {\n headers[\"x-trace-id\"] = span.spanContext().traceId;\n }\n const outgoing: Record<string, string> = {};\n propagation.inject(context.active(), outgoing);\n if (request.set?.headers) Object.assign(request.set.headers, outgoing);\n return settle(fn, (outcome) => {\n // Raw handlers often return a Response, whose status Elysia's `set` never sees.\n const status = outcome.failed\n ? 500\n : outcome.value instanceof Response\n ? outcome.value.status\n : responseStatus(request.set?.status);\n if (outcome.failed) recordThrown(span, outcome.error);\n span.setAttribute(\"http.response.status_code\", status);\n const traceId = headers[\"x-trace-id\"];\n if (traceId) span.setAttribute(\"brick.trace_id\", traceId);\n if (status >= 500) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${status}`,\n });\n }\n span.end();\n });\n },\n );\n}\n\n/**\n * Attach a handled failure to the active span. Brick returns these as\n * responses rather than throwing, so only server faults (5xx) mark the span\n * as errored; client errors keep their code as an attribute.\n */\nexport function recordFailure(\n error: unknown,\n failure: { status: number; code: string; message: string },\n): void {\n const span = trace.getActiveSpan();\n if (!span) return;\n span.setAttributes({\n \"brick.error.code\": failure.code,\n \"brick.error.status\": failure.status,\n \"brick.error.message\": truncate(failure.message),\n });\n if (failure.status >= 500) recordThrown(span, error);\n}\n\n/**\n * Record SQL statements as client spans for the database behind a service.\n * Drizzle's logger has no timing, so the hook sits on the driver: each\n * statement is timed where the driver runs it. Statements outside traced\n * requests are not recorded. Calling this again on the same client is a no-op.\n */\nexport function instrumentDatabase(db: unknown): void {\n const client = (db as { $client?: unknown } | undefined)?.$client;\n // postgres.js clients are callable functions, so accept both shapes.\n if (\n (typeof client !== \"object\" && typeof client !== \"function\") ||\n client === null\n ) {\n return;\n }\n const driver = client as Record<PropertyKey, unknown>;\n if (driver[DATABASE_INSTRUMENTED]) return;\n if (typeof driver.prepare === \"function\") {\n instrumentBunSqlite(driver as unknown as BunSqliteClient);\n } else if (typeof driver.unsafe === \"function\") {\n instrumentPostgres(driver as unknown as PostgresClient);\n } else {\n return;\n }\n driver[DATABASE_INSTRUMENTED] = true;\n}\n\ntype BunSqliteStatement = Record<\n (typeof SQLITE_STATEMENT_METHODS)[number],\n (...args: unknown[]) => unknown\n>;\n\ninterface BunSqliteClient {\n prepare: (sql: string) => BunSqliteStatement;\n}\n\nfunction instrumentBunSqlite(client: BunSqliteClient): void {\n const prepare = client.prepare.bind(client);\n client.prepare = (sql: string) => {\n const statement = prepare(sql);\n for (const method of SQLITE_STATEMENT_METHODS) {\n const original = statement[method];\n if (typeof original !== \"function\") continue;\n statement[method] = (...args: unknown[]) =>\n recordStatement(sql, \"sqlite\", () => original.apply(statement, args));\n }\n return statement;\n };\n}\n\ninterface PostgresQuery {\n then: (\n onFulfilled?: (value: unknown) => unknown,\n onRejected?: (reason: unknown) => unknown,\n ) => Promise<unknown>;\n}\n\ninterface PostgresClient {\n unsafe: (sql: string, ...rest: unknown[]) => PostgresQuery;\n}\n\n/**\n * postgres.js returns a query that runs when awaited, and `values()` returns\n * that same object, so overriding `then` on it times the whole round trip.\n */\nfunction instrumentPostgres(client: PostgresClient): void {\n const unsafe = client.unsafe.bind(client);\n client.unsafe = (sql: string, ...rest: unknown[]) => {\n const query = unsafe(sql, ...rest);\n if (!trace.getActiveSpan() || typeof query?.then !== \"function\") {\n return query;\n }\n const span = startStatementSpan(sql, \"postgresql\");\n let finished = false;\n const finish = (outcome: Outcome) => {\n if (finished) return;\n finished = true;\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n };\n const then = query.then.bind(query);\n // The query is already thenable; this wraps its own `then` to time the\n // round trip, so the no-thenable rule does not apply.\n // oxlint-disable-next-line unicorn/no-thenable\n query.then = (onFulfilled, onRejected) =>\n then(\n (value) => {\n finish({ failed: false, value });\n return onFulfilled ? onFulfilled(value) : value;\n },\n (error: unknown) => {\n finish({ failed: true, error });\n if (onRejected) return onRejected(error);\n throw error;\n },\n );\n return query;\n };\n}\n\nfunction recordStatement<T>(sql: string, system: string, fn: () => T): T {\n if (!trace.getActiveSpan()) return fn();\n return withSpan(\n statementName(sql),\n statementAttributes(sql, system),\n fn,\n SpanKind.CLIENT,\n );\n}\n\nfunction startStatementSpan(sql: string, system: string): Span {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startSpan(\n statementName(sql),\n { kind: SpanKind.CLIENT, attributes: statementAttributes(sql, system) },\n context.active(),\n );\n}\n\nfunction statementName(sql: string): string {\n return `SQL ${operationOf(sql)}`;\n}\n\nfunction statementAttributes(sql: string, system: string): Attributes {\n return {\n \"db.system\": system,\n \"db.operation\": operationOf(sql),\n \"db.statement\": truncate(sql, MAX_STATEMENT_LENGTH),\n };\n}\n\nfunction operationOf(sql: string): string {\n return sql.trim().split(/\\s+/, 1)[0]?.toUpperCase() || \"SQL\";\n}\n\nfunction settle<T>(fn: () => T, done: (outcome: Outcome) => void): T {\n let result: T;\n try {\n result = fn();\n } catch (error) {\n done({ failed: true, error });\n throw error;\n }\n if (isPromiseLike(result)) {\n return result.then(\n (value) => {\n done({ failed: false, value });\n return value;\n },\n (error: unknown) => {\n done({ failed: true, error });\n throw error;\n },\n ) as unknown as T;\n }\n done({ failed: false, value: result });\n return result;\n}\n\nfunction recordThrown(span: Span, error: unknown): void {\n span.recordException(error instanceof Error ? error : String(error));\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncate(messageOf(error)),\n });\n}\n\nfunction responseStatus(value: unknown): number {\n const status = typeof value === \"number\" ? value : Number(value ?? 200);\n return Number.isInteger(status) ? status : 200;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n","import { ActionExecutionError, ValidationError, type Logger } from \"./types\";\nimport { recordFailure } from \"./telemetry\";\n\nexport interface ErrorEnvelope {\n name: string;\n code: string;\n message: string;\n status: number;\n requestId: string;\n details?: unknown;\n errors?: ValidationError[\"errors\"];\n}\n\ntype ErrorContext = { logger: Pick<Logger, \"error\">; requestId: string };\n\n/** Preserve declared failures, log and wrap unexpected throws without exposing internals. */\nexport function normalizeActionError(\n err: unknown,\n { logger, requestId }: ErrorContext,\n): ActionExecutionError | ValidationError {\n if (err instanceof ActionExecutionError || err instanceof ValidationError)\n return err;\n logger.error(\"Unexpected action error\", { requestId }, err);\n const failure = new ActionExecutionError(\n \"INTERNAL_SERVER_ERROR\",\n \"Internal Server Error\",\n 500,\n undefined,\n { cause: err },\n );\n failure.name = \"InternalServerError\";\n return failure;\n}\n\n/**\n * Turn what an action threw into the JSON body of its HTTP response, and record\n * the failure on the active trace. Declared failures and validation errors keep\n * their code, status, and details; anything else is logged and answered as a\n * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.\n *\n * @param err - Whatever was thrown.\n * @param context - A `logger` with `error()`, and the `requestId` to put in the body.\n * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and\n * `details` or `errors` when there are any.\n */\nexport function toErrorResponse(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const envelope = buildErrorEnvelope(err, context);\n recordFailure(err, envelope);\n return envelope;\n}\n\nfunction buildErrorEnvelope(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const failure = normalizeActionError(err, context);\n if (\n failure.status >= 500 &&\n (err instanceof ActionExecutionError || err instanceof ValidationError)\n ) {\n context.logger.error(\n \"Server action error\",\n { requestId: context.requestId },\n err,\n );\n }\n if (failure instanceof ValidationError && failure.status >= 500) {\n return {\n name: failure.name,\n code: failure.code,\n message: failure.message,\n status: failure.status,\n requestId: context.requestId,\n };\n }\n return { ...failure.toJSON(), requestId: context.requestId };\n}\n","import { Type, type TSchema, type Static } from \"@sinclair/typebox\";\nimport { TypeCompiler, type TypeCheck } from \"@sinclair/typebox/compiler\";\nimport type { ValidationErrorItem } from \"./types\";\n\nexport { Type, Type as t };\nexport type { TSchema, Static };\n\nconst compilerCache = new WeakMap<TSchema, TypeCheck<TSchema>>();\n\n/**\n * The compiled validator for a TypeBox schema. Compiling is slow and checking\n * is fast, so each schema is compiled once and kept for as long as the schema\n * object lives.\n *\n * @param schema - A TypeBox schema.\n * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.\n */\nexport function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T> {\n let compiled = compilerCache.get(schema) as TypeCheck<T> | undefined;\n if (!compiled) {\n compiled = TypeCompiler.Compile(schema);\n compilerCache.set(schema, compiled);\n }\n return compiled;\n}\n\n/**\n * Check a value against a schema, the way actions check their input and output.\n *\n * @param schema - A TypeBox schema, or `undefined` to accept anything.\n * @param value - The value to check.\n * @returns `{ success: true, data }`, or `{ success: false, errors }` with a\n * `path`, `message`, `type`, and the offending `value` for each problem.\n */\nexport function validateWithSchema<T extends TSchema>(\n schema: T | undefined,\n value: unknown,\n):\n | { success: true; data: Static<T> }\n | { success: false; errors: ValidationErrorItem[] } {\n if (!schema) {\n return { success: true, data: value as Static<T> };\n }\n\n const check = getCompiledCheck(schema);\n if (check.Check(value)) {\n return { success: true, data: value as Static<T> };\n }\n\n const errors: ValidationErrorItem[] = [];\n for (const error of check.Errors(value)) {\n errors.push({\n path: error.path,\n message: error.message,\n value: error.value,\n type: error.type,\n });\n }\n\n return { success: false, errors };\n}\n","import { formatWithOptions } from \"node:util\";\nimport { trace, type Span } from \"@opentelemetry/api\";\nimport type { Logger } from \"./types\";\n\ntype Level = keyof Logger;\n\n/**\n * Set by the CLI when a dashboard is collecting logs, in `brick dev` or in\n * `brick start` with the `dashboard` option. A shared symbol, not an option or\n * an export: the CLI and the app may each hold their own copy of this package,\n * and nothing but a dashboard turns it on.\n */\nconst CAPTURE = Symbol.for(\"brickkit.logs.capture\");\n\n/** The span event a log line becomes; the dashboard reads these. */\nconst LOG_EVENT = \"log\";\nconst MAX_MESSAGE_LENGTH = 4000;\n/**\n * Logs one span keeps. OpenTelemetry keeps 128 events per span by default,\n * exceptions among them, so a chatty action must not use them all up and\n * lose the stack trace of the error that ends it.\n */\nconst MAX_LOGS_PER_SPAN = 100;\n\nconst logged = new WeakMap<Span, number>();\n\n/**\n * Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and\n * titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their\n * console output, which in a web page shows as stray characters.\n */\n// oxlint-disable no-control-regex\nconst ANSI =\n /\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\))/g;\n// oxlint-enable no-control-regex\n\n/** `text` without terminal formatting. */\nexport function stripAnsi(text: string): string {\n return text.includes(\"\\u001b\") ? text.replace(ANSI, \"\") : text;\n}\n\n/**\n * What `console.log` would print, without terminal colors, with objects cut off\n * at a sensible size.\n */\nfunction render(args: unknown[]): string {\n const text = stripAnsi(\n formatWithOptions(\n { depth: 3, breakLength: 120, maxArrayLength: 50, maxStringLength: 1000 },\n ...args,\n ),\n );\n return text.length > MAX_MESSAGE_LENGTH\n ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…`\n : text;\n}\n\nfunction record(span: Span, level: Level, args: unknown[]): void {\n const count = (logged.get(span) ?? 0) + 1;\n logged.set(span, count);\n if (count > MAX_LOGS_PER_SPAN) {\n // Counted, so the dashboard can say how many it left out.\n span.setAttribute(\"brick.logs.dropped\", count - MAX_LOGS_PER_SPAN);\n return;\n }\n span.addEvent(LOG_EVENT, {\n \"log.level\": level,\n \"log.message\": render(args),\n });\n}\n\n/**\n * Record a line on the running span, if a recording one is running. Returns\n * whether it did, so the caller prints only when it did not.\n */\nfunction recordActive(level: Level, args: unknown[]): boolean {\n const span = trace.getActiveSpan();\n if (!span?.isRecording()) return false;\n record(span, level, args);\n return true;\n}\n\n// The dev server's console capture calls this by name, for the same reason\n// `CAPTURE` is a shared symbol: it may hold a different copy of this package.\n(globalThis as Record<symbol, unknown>)[Symbol.for(\"brickkit.logs.record\")] =\n recordActive;\n\n/**\n * A logger for actions, tools, and endpoints. While a dashboard is on, a line\n * logged while a request is being traced becomes an event on the span that is\n * running, which the dashboard shows with that request (and in its Logs tab);\n * it is not printed. Everywhere else, and for lines logged outside a request,\n * it prints to the console, prefixed by `prefix`: one for all levels, or one\n * per level.\n *\n * Capturing costs one context lookup and a span event per line, and nothing\n * is serialized for the dashboard until the span ends, so it is cheaper than\n * a console write. Lines are cut at 4,000 characters and a span keeps 100.\n */\nexport function createLogger(prefix: string | Record<Level, string>): Logger {\n const level =\n (name: Level, print: (...args: unknown[]) => void) =>\n (...args: unknown[]): void => {\n if (\n (globalThis as Record<symbol, unknown>)[CAPTURE] === true &&\n recordActive(name, args)\n )\n return;\n print(typeof prefix === \"string\" ? prefix : prefix[name], ...args);\n };\n return {\n info: level(\"info\", (...args) => console.log(...args)),\n warn: level(\"warn\", (...args) => console.warn(...args)),\n error: level(\"error\", (...args) => console.error(...args)),\n debug: level(\"debug\", (...args) => console.debug(...args)),\n };\n}\n\n/** The prefixes of loggers a caller did not supply. */\nexport const DEFAULT_LOG_PREFIXES: Record<Level, string> = {\n info: \"[INFO]\",\n warn: \"[WARN]\",\n error: \"[ERROR]\",\n debug: \"[DEBUG]\",\n};\n","import type { TSchema } from \"@sinclair/typebox\";\nimport {\n type Action,\n type ActionConfigWithAuthorize,\n type ActionConfigWithoutAuthorize,\n type ActionContext,\n type ActionErrorDefinition,\n type ErrorBuilder,\n type BaseContext,\n ActionExecutionError,\n ValidationError,\n type Logger,\n} from \"./types\";\nimport { normalizeActionError } from \"./error-response\";\nimport { validateWithSchema } from \"./typebox\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\n\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet _defaultCtxSeq = 0;\n\n// Symbol to tie context resolution to a specific service instance and invocation\nconst RESOLVED_SYMBOL = Symbol(\"resolved\");\n\nconst standardErrorDefaults: Record<\n string,\n { status: number; message: string }\n> = {\n BAD_REQUEST: { status: 400, message: \"Bad Request\" },\n UNAUTHORIZED: { status: 401, message: \"Unauthorized\" },\n FORBIDDEN: { status: 403, message: \"Forbidden\" },\n NOT_FOUND: { status: 404, message: \"Not Found\" },\n CONFLICT: { status: 409, message: \"Conflict\" },\n INTERNAL_SERVER_ERROR: { status: 500, message: \"Internal Server Error\" },\n};\n\nfunction createDefaultContext(partial?: any): BaseContext & any {\n // Only accept pre-resolved context with a service-specific marker or when service will handle resolution\n if (partial?.[RESOLVED_SYMBOL]) return partial;\n const seq = (++_defaultCtxSeq).toString(36);\n const req = partial?.request ?? DEFAULT_REQUEST;\n return {\n request: req,\n traceId: partial?.traceId || `tr_${seq}`,\n requestId: partial?.requestId || `req_${seq}`,\n db: partial?.db,\n user: partial?.user,\n logger: partial?.logger || defaultLogger,\n services: partial?.services || {},\n metadata: partial?.metadata || {},\n ...partial,\n [RESOLVED_SYMBOL]: true,\n };\n}\n\n/**\n * The `error` helpers an action receives: one function per error code that\n * throws an `ActionExecutionError` with that code and status. The standard HTTP\n * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,\n * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to\n * them or replace one.\n *\n * @param errorsDef - The action's `errors`: for each code, its `message` and\n * `status` (default 400).\n * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,\n * and always throw.\n */\nexport function buildErrorHelpers<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(errorsDef?: TErrors): ErrorBuilder<TErrors> {\n const helpers: Record<string, any> = {};\n\n // 1. Populate standard HTTP error helpers\n for (const [code, def] of Object.entries(standardErrorDefaults)) {\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n const message = overrideMessage || def.message;\n const status = def.status;\n throw new ActionExecutionError(code, message, status, details, options);\n };\n }\n\n // 2. Populate or override with user-defined action errors\n if (errorsDef) {\n for (const [code, def] of Object.entries(errorsDef)) {\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n const message = overrideMessage || def.message;\n const status = def.status || 400;\n throw new ActionExecutionError(code, message, status, details, options);\n };\n }\n }\n\n return helpers as ErrorBuilder<TErrors>;\n}\n\n/**\n * Define an action: a typed, validated function that Brick serves over HTTP,\n * runs in-process, and exposes to the typed client and OpenAPI.\n *\n * A call runs in order: the input is validated against `input` (an invalid one\n * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;\n * `execute` runs; and its result is validated against `output` (a mismatch is a\n * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared\n * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value\n * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response\n * and in the log.\n *\n * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`\n * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.\n * Where it is given, `execute` can rely on what it checked.\n *\n * @param config - `name`, `execute`, and optionally `description`, `input` and\n * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to\n * change the route (POST by default), `tags`, and `emits`.\n * @returns The action. Register it with `service.action(action)`; call it\n * directly with `action.run(input, ctx)`.\n * @example\n * import { defineAction, t } from \"@brickkit/core\";\n *\n * export const getPage = defineAction({\n * name: \"get\",\n * method: \"GET\",\n * input: t.Object({ id: t.String() }),\n * output: t.Object({ id: t.String(), title: t.String() }),\n * errors: { PAGE_GONE: { message: \"That page was removed\", status: 410 } },\n * authorize: ({ user }) => user != null,\n * execute: async ({ input, ctx, error }) => {\n * const page = await findPage(ctx.db, input.id);\n * if (!page) throw error.NOT_FOUND(\"No such page\");\n * return page;\n * },\n * });\n */\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction(config: any): any {\n const errorHelpers = buildErrorHelpers(config.errors);\n\n const actionFn = (async (params: { input?: any; ctx?: any }) => {\n return actionFn.execute(params);\n }) as any;\n\n Object.defineProperty(actionFn, \"name\", {\n value: config.name,\n configurable: true,\n });\n\n actionFn.config = config;\n actionFn.errorHelpers = errorHelpers;\n\n actionFn.validateInput = (input: unknown) => {\n return validateWithSchema(config.input, input);\n };\n\n actionFn.validateOutput = (output: unknown) => {\n const runtimeSchema =\n (actionFn as { outputValidationSchema?: TSchema })\n .outputValidationSchema ?? config.output;\n return validateWithSchema(runtimeSchema, output);\n };\n\n actionFn.run = async (input?: any, ctx?: any) => {\n return actionFn.execute({ input, ctx });\n };\n\n actionFn.execute = async (params: { input?: any; ctx?: any }) => {\n const boundService = actionFn.service;\n // The bound service resolves the context once per request, and recognizes\n // one it already resolved.\n const fullCtx: any = boundService?.resolveContext\n ? await boundService.resolveContext(params?.ctx)\n : createDefaultContext(params?.ctx);\n\n try {\n // Fill ctx.db from the bound service or the registry when the call has none.\n if (!fullCtx.db) {\n const service =\n boundService ??\n (actionFn.serviceName\n ? getGlobalRegistry().get(actionFn.serviceName)\n : undefined);\n if (service?.getDb()) fullCtx.db = service.getDb();\n }\n\n // 1. Validate Input\n if (config.input) {\n const inputValidation = actionFn.validateInput(params?.input);\n if (!inputValidation.success) {\n throw new ValidationError(\n `Validation failed for action '${config.name}' input` as string,\n inputValidation.errors,\n );\n }\n }\n\n // 2. Authorize\n if (config.authorize) {\n const allowed = await config.authorize({\n user: fullCtx.user,\n input: params?.input,\n ctx: fullCtx,\n });\n if (!allowed) {\n throw new ActionExecutionError(\n fullCtx.user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${config.name}'`,\n fullCtx.user == null ? 401 : 403,\n );\n }\n }\n\n // 3. Execute implementation\n const result = await config.execute({\n input: params?.input,\n ctx: fullCtx,\n error: errorHelpers,\n });\n\n // 4. Validate Output\n const runtimeOutputSchema =\n (actionFn as { outputValidationSchema?: TSchema })\n .outputValidationSchema ?? config.output;\n if (runtimeOutputSchema) {\n const outputValidation = actionFn.validateOutput(result);\n if (!outputValidation.success) {\n throw new ValidationError(\n `Validation failed for action '${config.name}' output` as string,\n outputValidation.errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err) {\n throw normalizeActionError(err, fullCtx);\n }\n };\n\n return actionFn;\n}\n","import type { TSchema } from \"@sinclair/typebox\";\nimport type {\n Action,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionContext,\n ActionErrorDefinition,\n BaseContext,\n Resource,\n Service,\n} from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { defineAction } from \"./action\";\n\nexport type PluginRouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport type PluginRouteScope = \"app\" | \"service\" | \"resource\";\nexport type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =\n | false\n | Readonly<Record<string, false | { path?: string; scope?: S }>>;\n\ntype ContextOf<S> =\n S extends Service<infer D, infer C> ? BaseContext<D> & C : never;\n\nexport interface PluginEndpointContext<\n C extends ActionContext = ActionContext,\n> {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n set: { status?: number; headers: Record<string, string> };\n ctx: C;\n}\n\nexport interface PluginRouteRegistrar<\n C extends ActionContext = ActionContext,\n S extends PluginRouteScope = PluginRouteScope,\n> {\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<I, O, E, C> & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<I, O, E, C> & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n endpoint(config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n }): void;\n}\n\nexport interface ServicePluginContext<\n S extends Service<any, any> = Service<any, any>,\n> {\n service: S;\n routes: PluginRouteRegistrar<ContextOf<S>, \"app\" | \"service\">;\n}\nexport interface ResourcePluginContext<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n> {\n service: S;\n resource: R;\n routes: PluginRouteRegistrar<ContextOf<S>>;\n}\n\n/** Plugins may specialize their returned API for the installation host. */\nexport interface ResourcePluginTypes {\n readonly table: unknown;\n readonly context: unknown;\n readonly resource: unknown;\n readonly api: object;\n}\nexport type ResourcePluginAPI<P, T, C, R = unknown> = P extends {\n readonly types: infer H extends ResourcePluginTypes;\n}\n ? (H & {\n readonly table: T;\n readonly context: C;\n readonly resource: R;\n })[\"api\"]\n : P extends ResourcePlugin<any, any, infer A>\n ? A\n : never;\n\n// Process-global like actionBindingKey, so descriptors survive a second core copy.\nconst pluginKind: unique symbol = Symbol.for(\"brickkit.plugin.kind\");\nexport interface ServicePlugin<S extends Service<any, any>, A> {\n readonly [pluginKind]: \"service\";\n readonly name: string;\n readonly routes?: PluginRoutes<\"app\" | \"service\">;\n readonly setup: (context: ServicePluginContext<S>) => A;\n}\nexport interface ResourcePlugin<\n S extends Service<any, any>,\n R extends Resource<any, any, any>,\n A extends object,\n> {\n readonly [pluginKind]: \"resource\";\n readonly name: string;\n readonly routes?: PluginRoutes;\n readonly setup: (context: ResourcePluginContext<S, R>) => A;\n}\n\n/**\n * Define a plugin that installs onto a service with `service.use(plugin)`. Its\n * `setup` receives the service and a `routes` registrar for adding actions and\n * raw HTTP endpoints, and returns the typed API that `service.use` hands back.\n *\n * @param definition - A unique `name`, optional `routes` controls that let the\n * user move or switch off the plugin's routes, and `setup`, which must be\n * synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n * @example\n * import { defineServicePlugin, t } from \"@brickkit/core\";\n *\n * export const greeting = (salutation = \"Hello\") =>\n * defineServicePlugin({\n * name: \"example/greeting\",\n * setup({ routes }) {\n * const hello = routes.action({\n * name: \"hello\",\n * input: t.Object({ name: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `${salutation}, ${input.name}!`,\n * });\n * return { hello };\n * },\n * });\n *\n * const api = greeterService.use(greeting(\"Welcome\"));\n * await api.hello({ input: { name: \"Ada\" } });\n */\nexport function defineServicePlugin<\n S extends Service<any, any> = Service<any, any>,\n A = unknown,\n>(\n definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & {\n setup: (\n context: ServicePluginContext<S>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ServicePlugin<S, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [pluginKind]: \"service\" as const,\n });\n}\n/**\n * Define a plugin that installs onto a resource (a table and its entity) with\n * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a\n * `routes` registrar, whose routes are scoped under the resource's name, and\n * returns the typed API that `resource.use` hands back. `crud` is built this way.\n *\n * @param definition - A unique `name`, optional `routes` controls, and `setup`,\n * which must be synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n */\nexport function defineResourcePlugin<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n A extends object = object,\n>(\n definition: Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & {\n setup: (\n context: ResourcePluginContext<S, R>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ResourcePlugin<S, R, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [pluginKind]: \"resource\" as const,\n });\n}\n\nfunction validateName(name: string) {\n if (!name || name.trim() !== name)\n throw new Error(\n \"Plugin and route names must be nonempty and have no surrounding whitespace\",\n );\n}\nfunction validatePath(path: string) {\n if (\n !path.startsWith(\"/\") ||\n path.includes(\"?\") ||\n path.includes(\"#\") ||\n path.includes(\"//\") ||\n path.split(\"/\").some((part) => part === \".\" || part === \"..\")\n ) {\n throw new Error(`Invalid plugin route path '${path}'`);\n }\n}\nfunction copyControls<S extends PluginRouteScope>(\n controls: PluginRoutes<S> | undefined,\n): PluginRoutes<S> | undefined {\n if (controls === undefined || controls === false) return controls;\n const result: Record<string, false | { path?: string; scope?: S }> =\n Object.create(null);\n for (const [name, value] of Object.entries(controls)) {\n validateName(name);\n if (value === false) {\n result[name] = false;\n continue;\n }\n if (value.path !== undefined) validatePath(value.path);\n if (\n value.scope !== undefined &&\n ![\"app\", \"service\", \"resource\"].includes(value.scope)\n )\n throw new Error(`Invalid plugin route scope '${value.scope}'`);\n result[name] = Object.freeze({ ...value });\n }\n return Object.freeze(result);\n}\n\ninterface Binding {\n service: Service<any, any>;\n resource?: Resource<any, any, any>;\n /** Owning plugin descriptor name (e.g. `@brickkit/crud`). Kept separate from the public action name. */\n plugin: string;\n path: string;\n method: PluginRouteMethod;\n scope: PluginRouteScope;\n enabled: boolean;\n clientPath?: string[];\n}\ninterface RawBinding extends Binding {\n handler: (context: PluginEndpointContext<any>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\ninterface Installation {\n descriptor: object;\n status: \"installing\" | \"installed\";\n api?: unknown;\n}\ninterface PluginState {\n hosts: Map<object, Map<string, Installation>>;\n actions: Map<Action<any, any, any, any>, Binding>;\n endpoints: RawBinding[];\n}\nconst states = new WeakMap<object, PluginState>();\nconst actionBindings = new WeakMap<Action<any, any, any, any>, Binding>();\n/**\n * Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)\n * may load a second copy of core that owns a different WeakMap, while the\n * action objects themselves cross the boundary by reference. The binding\n * travels on the action under a process-global symbol so route lookups\n * (including disabled-route suppression) keep working there.\n */\nconst actionBindingKey = Symbol.for(\"brickkit.plugin.actionBinding\");\nfunction stateOf(service: Service<any, any>): PluginState {\n let state = states.get(service);\n if (!state) {\n state = { hosts: new Map(), actions: new Map(), endpoints: [] };\n states.set(service, state);\n }\n return state;\n}\nexport function isInstallingPlugin(service: Service<any, any>): boolean {\n return [...(states.get(service)?.hosts.values() ?? [])].some(\n (installations) =>\n [...installations.values()].some((item) => item.status === \"installing\"),\n );\n}\n\nfunction pathOf(binding: Binding, prefix: string) {\n const scope =\n binding.scope === \"app\"\n ? \"\"\n : `/${binding.scope === \"resource\" ? binding.resource!.name : binding.service.name}`;\n return (\n `${prefix.replace(/\\/$/, \"\")}${scope}${binding.path === \"/\" ? \"\" : binding.path}` ||\n \"/\"\n );\n}\n/**\n * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the\n * compiler, and the typed client.\n *\n * @param action - An action.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns `undefined` when no plugin bound the action (it uses its own route),\n * `false` when the plugin's route was switched off, otherwise the route's\n * `path` and `method`, the `clientPath` the typed client uses, and the owning\n * `plugin` and `resource`.\n */\nexport function getPluginActionRoute(\n action: Action<any, any, any, any>,\n prefix = \"/api\",\n) {\n const binding =\n (action as unknown as Record<symbol, Binding | undefined>)[\n actionBindingKey\n ] ?? actionBindings.get(action);\n if (!binding) return undefined;\n if (!binding.enabled) return false;\n return {\n path: pathOf(binding, prefix),\n method: binding.method,\n clientPath: binding.clientPath,\n plugin: binding.plugin,\n resource: binding.resource?.name,\n };\n}\n/**\n * The raw HTTP endpoints plugins registered on a service, ready to mount on the\n * application. Each handler resolves the service's context before it runs.\n *\n * @param service - The service plugins were installed on.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns The enabled endpoints: `path`, `method`, `handler`, and the\n * `summary`, `description`, and `tags` for OpenAPI.\n */\nexport function getPluginEndpoints(\n service: Service<any, any>,\n prefix = \"/api\",\n) {\n return stateOf(service)\n .endpoints.filter((binding) => binding.enabled)\n .map((binding) => ({\n path: pathOf(binding, prefix),\n method: binding.method,\n service,\n summary: binding.summary,\n description: binding.description,\n tags: binding.tags,\n handler: async (context: Omit<PluginEndpointContext, \"ctx\">) =>\n binding.handler({\n ...context,\n ctx: await service.resolveContext({ request: context.request }),\n }),\n }));\n}\n\n/** Descriptor identity is scoped to the service or resource installation host. */\nexport function installPlugin(\n service: Service<any, any>,\n resource: Resource<any, any, any> | undefined,\n descriptor: ServicePlugin<any, any> | ResourcePlugin<any, any, any>,\n) {\n if (service.isBuilt)\n throw new Error(\"Plugins must be installed before service build\");\n if (descriptor[pluginKind] !== (resource ? \"resource\" : \"service\"))\n throw new Error(\"Plugin does not support this installation host\");\n const state = stateOf(service);\n const host = resource ?? service;\n const existing = state.hosts.get(host)?.get(descriptor.name);\n if (existing) {\n if (existing.status === \"installing\")\n throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);\n if (existing.descriptor !== descriptor)\n throw new Error(\n `Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`,\n );\n return resource ?? existing.api;\n }\n const snapshots = {\n actions: new Map(service.actions),\n tools: new Map(service.tools),\n tables: new Map(service.tables),\n resources: new Map(service.resources),\n preparations: new Map(service.preparations),\n hosts: new Map(\n [...state.hosts].map(([key, installations]) => [\n key,\n new Map(installations),\n ]),\n ),\n bindings: new Map(state.actions),\n endpoints: [...state.endpoints],\n properties: new Map(\n [...service.resources.values()].map((item) => [\n item,\n Object.getOwnPropertyDescriptors(item),\n ]),\n ),\n };\n const installations =\n state.hosts.get(host) ?? new Map<string, Installation>();\n state.hosts.set(host, installations);\n installations.set(descriptor.name, { descriptor, status: \"installing\" });\n const names = new Set<string>();\n const ownedActions = new Set<Action<any, any, any, any>>();\n let active = true;\n const bindingFor = (config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: PluginRouteScope;\n }): Binding => {\n if (!active || service.isBuilt)\n throw new Error(\"Plugin routes can only be registered during setup\");\n validateName(config.name);\n validatePath(config.path);\n if (names.has(config.name))\n throw new Error(`Duplicate plugin route name '${config.name}'`);\n names.add(config.name);\n const control =\n descriptor.routes === false ? false : descriptor.routes?.[config.name];\n const scope =\n (control && control.scope) ||\n config.scope ||\n (resource ? \"resource\" : \"service\");\n if (scope === \"resource\" && !resource)\n throw new Error(\"Service plugin routes cannot use resource scope\");\n if (![\"app\", \"service\", \"resource\"].includes(scope))\n throw new Error(`Invalid plugin route scope '${scope}'`);\n if (![\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(config.method))\n throw new Error(`Invalid plugin route method '${config.method}'`);\n const path = (control && control.path) || config.path;\n validatePath(path);\n return {\n service,\n resource,\n plugin: descriptor.name,\n path,\n method: config.method,\n scope,\n enabled: control !== false,\n };\n };\n const routes: PluginRouteRegistrar<any> = {\n action(config: any) {\n const binding = bindingFor(config);\n for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) {\n if (\n !config.input?.properties ||\n !Object.hasOwn(config.input.properties, match[1]!)\n )\n throw new Error(\n `Plugin action path parameter '${match[1]}' must be declared in its input schema`,\n );\n }\n // Public contract name: resource/operation only (e.g. `page.list`).\n // The owning plugin stays in binding metadata (`plugin`) and on the\n // action (`plugin`/`resource`) so it never leaks into exported names,\n // OpenAPI, or client contracts.\n const name = `${resource ? `${resource.name}.` : \"\"}${config.name}`;\n if (service.actions.has(name))\n throw new Error(\n `Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`,\n );\n const { scope: _scope, ...actionConfig } = config;\n const action = defineAction({ ...actionConfig, name });\n (action as unknown as Record<string, unknown>).plugin = descriptor.name;\n if (resource)\n (action as unknown as Record<string, unknown>).resource = resource.name;\n service.action(action);\n ownedActions.add(action);\n state.actions.set(action, binding);\n actionBindings.set(action, binding);\n // Same object travels across bundler module copies; see actionBindingKey.\n (action as unknown as Record<symbol, Binding>)[actionBindingKey] =\n binding;\n return action;\n },\n endpoint(config) {\n const binding = bindingFor(config);\n state.endpoints.push({\n ...binding,\n handler: config.handler,\n summary: config.summary,\n description: config.description,\n tags: config.tags,\n });\n },\n };\n try {\n const api = resource\n ? (descriptor as ResourcePlugin<any, any, any>).setup({\n service,\n resource,\n routes,\n })\n : (descriptor as ServicePlugin<any, any>).setup({ service, routes });\n if (api && typeof api === \"object\" && \"then\" in api)\n throw new Error(\"Plugin setup must be synchronous\");\n if (\n descriptor.routes &&\n Object.keys(descriptor.routes).some((name) => !names.has(name))\n )\n throw new Error(\n `Plugin '${descriptor.name}' has an override for an unknown route`,\n );\n const walk = (value: unknown, path: string[], ancestors: Set<object>) => {\n if (typeof value === \"function\") {\n const binding = state.actions.get(value as Action<any, any, any, any>);\n if (binding && ownedActions.has(value as Action<any, any, any, any>)) {\n if (binding.clientPath)\n throw new Error(\"Plugin actions must have one returned API path\");\n binding.clientPath = [resource?.name ?? service.name, ...path];\n }\n } else if (value && typeof value === \"object\" && !ancestors.has(value)) {\n const next = new Set(ancestors).add(value);\n for (const [key, child] of Object.entries(value))\n walk(child, [...path, key], next);\n }\n };\n walk(api, [], new Set());\n if (resource) {\n if (!api || typeof api !== \"object\" || Array.isArray(api))\n throw new Error(\"Resource plugins must return named API contributions\");\n for (const key of Object.keys(api)) {\n if (\n key in resource ||\n [\"__proto__\", \"prototype\", \"constructor\"].includes(key)\n )\n throw new Error(\n `Resource plugin contribution '${key}' collides with an existing property`,\n );\n }\n Object.assign(resource, api);\n }\n state.hosts.get(host)!.set(descriptor.name, {\n descriptor,\n status: \"installed\",\n api,\n });\n getGlobalRegistry().touch();\n return resource ?? api;\n } catch (error) {\n for (const action of state.actions.keys())\n if (!snapshots.bindings.has(action)) {\n actionBindings.delete(action);\n delete (action as unknown as Record<symbol, unknown>)[actionBindingKey];\n }\n restoreMap(service.actions, snapshots.actions);\n restoreMap(service.tools, snapshots.tools);\n restoreMap(service.tables, snapshots.tables);\n restoreMap(service.resources, snapshots.resources);\n restoreMap(service.preparations, snapshots.preparations);\n state.hosts = snapshots.hosts;\n state.actions = snapshots.bindings;\n state.endpoints = snapshots.endpoints;\n for (const [item, properties] of snapshots.properties) {\n for (const key of Reflect.ownKeys(item))\n if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);\n Object.defineProperties(item, properties);\n }\n getGlobalRegistry().touch();\n throw error;\n } finally {\n active = false;\n }\n}\nfunction restoreMap<K, V>(target: Map<K, V>, snapshot: Map<K, V>) {\n target.clear();\n for (const [key, value] of snapshot) target.set(key, value);\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"../types\";\n\nimport { toErrorResponse } from \"../error-response\";\nimport type { Logger } from \"../types\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n // Early return on the first key: an allocation-free emptiness check.\n for (const _ in value) return true; // NOSONAR\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\n// Generic pre-validation nesting cap for parsed HTTP input. Compiled input\n// validators recurse, so unbounded nesting (e.g. a 20k-deep filter object)\n// would throw RangeError (HTTP 500) instead of failing validation with a\n// 400. The walk is iterative and far above legitimate depths (a max-depth\n// CRUD filter is ~45 levels of JSON).\nconst MAX_INPUT_DEPTH = 128;\nexport function inputTooDeep(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const stack: { node: unknown; depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (depth > MAX_INPUT_DEPTH) return true;\n if (node && typeof node === \"object\") {\n const children = Array.isArray(node) ? node : Object.values(node);\n for (const child of children)\n if (child && typeof child === \"object\")\n stack.push({ node: child, depth: depth + 1 });\n }\n }\n return false;\n}\n\nfunction checkDepth(value: unknown, action: string) {\n if (!inputTooDeep(value)) return;\n throw new ValidationError(`Validation failed for action '${action}' input`, [\n { path: \"\", message: \"Input exceeds maximum nesting depth\" },\n ]);\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction mapError(\n err: unknown,\n set: any,\n options: { logger: Logger; requestId: string },\n) {\n const response = toErrorResponse(err, options);\n set.status = response.status;\n return response;\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n checkDepth,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n deny: (action: string, user: unknown): never => {\n throw new ActionExecutionError(\n user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${action}'`,\n user == null ? 401 : 403,\n );\n },\n});\n","import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n} from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { buildErrorHelpers } from \"./action\";\nimport { toErrorResponse } from \"./error-response\";\nimport { inputTooDeep } from \"./compiler/runtime\";\nimport { createLogger } from \"./logger\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n // Early return on the first key: an allocation-free emptiness check.\n for (const _ in obj) return true; // NOSONAR\n return false;\n}\n\n/**\n * Work out, once at startup, everything an action's route needs to answer a\n * request: where its input comes from (body, query, or path), the validators,\n * the authorization and execute functions, and its logger. Low level: `brick()`\n * does this for every route.\n *\n * @param service - The service the action belongs to.\n * @param action - The action.\n * @param routePath - The route's path.\n * @param method - The HTTP method (POST by default).\n * @returns The plan `executeCompiledRoute` runs.\n */\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n // Prefer a runtime-only output schema when the action provides one (CRUD\n // subset projections validate loosely at runtime while `config.output`\n // stays strict for contracts/OpenAPI).\n const runtimeOutputSchema =\n (action as { outputValidationSchema?: typeof outputSchema })\n .outputValidationSchema ?? outputSchema;\n const outputChecker = runtimeOutputSchema\n ? (getCompiledCheck(runtimeOutputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{\n key: string;\n isNumber: boolean;\n isBoolean: boolean;\n isArray?: boolean;\n }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{\n key: string;\n isNumber: boolean;\n isBoolean: boolean;\n isArray?: boolean;\n }> = [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n } else if (type === \"array\") {\n list.push({ key, isNumber: false, isBoolean: false, isArray: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = createLogger(tag);\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\n/**\n * Answer one request for a compiled route: read the input, run the action, and\n * return its output or the error response, with the `x-trace-id` and\n * `x-request-id` headers set. Low level: `brick()` mounts this for every route.\n *\n * @param plan - From `compileRoutePlan`.\n * @param elysiaCtx - The Elysia request context: `params`, `body`, `query`,\n * `headers`, `request`, and `set`.\n * @returns The action's output, or an error envelope with the status set on `set`.\n */\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isArray) {\n const values = request\n ? new URL(request.url).searchParams.getAll(c.key)\n : [];\n coercedQuery[c.key] = values.length\n ? values\n : Array.isArray(val)\n ? val\n : [val];\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n const hasP = isNonEmpty(params);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = params;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, params, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = params;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, params, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (inputTooDeep(input)) {\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n [{ path: \"\", message: \"Input exceeds maximum nesting depth\" }],\n );\n }\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n ctx.user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${plan.actionName}'`,\n ctx.user == null ? 401 : 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err) {\n const response = toErrorResponse(err, { logger: ctx.logger, requestId });\n set.status = response.status;\n return response;\n }\n}\n\n/**\n * An Elysia handler for one action: `compileRoutePlan` and\n * `executeCompiledRoute` together. Use it to mount an action on your own\n * Elysia app; `brick()` does it for you.\n *\n * @param service - The service the action belongs to.\n * @param action - The action.\n * @param routePath - The route's path.\n * @param method - The HTTP method (POST by default).\n * @returns A function from the Elysia context to the response.\n */\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import type { RouteIR } from \"./ir\";\nimport type { HandlerFactory } from \"./runtime\";\nimport type { ActionContext } from \"../types\";\n\nfunction coerceQueryValue(\n value: unknown,\n type: RouteIR[\"coercions\"][number][\"type\"],\n request: Request | undefined,\n key: string,\n) {\n if (type === \"number\" && value !== undefined) {\n const number = Number(value);\n return Number.isNaN(number) ? value : number;\n }\n if (type === \"array\") {\n const values = request ? new URL(request.url).searchParams.getAll(key) : [];\n return values.length ? values : Array.isArray(value) ? value : [value];\n }\n if (type === \"boolean\") {\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n }\n return value;\n}\n\n/** Bind route metadata with ordinary closures; emitted factories remain build-only. */\nexport function createHandlerFactory(route: RouteIR): HandlerFactory {\n return (binding, runtime) => {\n const {\n execute,\n contextHook,\n authorize,\n inputChecker,\n outputChecker,\n errorBuilder,\n logger,\n cachedDb,\n service,\n } = binding;\n const readLike = route.inputPrecedence[0] === \"query\";\n const objectInput = binding.action.config.input?.type === \"object\";\n const readInput = route.input\n ? ({ params, body, query, request }: any) => {\n let coercedQuery = query;\n if (query && route.coercions.length) {\n coercedQuery = { ...query };\n for (const { key, type } of route.coercions) {\n if (query[key] !== undefined)\n coercedQuery[key] = coerceQueryValue(\n query[key],\n type,\n request,\n key,\n );\n }\n }\n let input = readLike\n ? runtime.mergeInput(coercedQuery, params, body)\n : runtime.mergeInput(params, body, coercedQuery);\n if (objectInput) input ??= {};\n return input;\n }\n : () => undefined;\n const validateInput = (input: unknown) => {\n if (inputChecker) {\n runtime.checkDepth(input, route.action);\n runtime.validate(inputChecker, input, route.action, \"input\");\n }\n };\n const validateOutput = (result: unknown) => {\n if (route.output && outputChecker)\n runtime.validate(outputChecker, result, route.action, \"output\");\n return result;\n };\n const createContext = ({\n headers,\n request,\n set,\n }: any): ActionContext & { requestId: string } => {\n const seq = runtime.nextSequence();\n const traceId = headers?.[\"x-trace-id\"] || \"tr_\" + seq;\n const requestId = headers?.[\"x-request-id\"] || \"req_\" + seq;\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n return {\n request: request instanceof Request ? request : runtime.defaultRequest,\n traceId,\n requestId,\n db: cachedDb ?? service.getDb(),\n logger,\n services: runtime.emptyServices,\n metadata: { headers },\n _resolved: true,\n };\n };\n if (contextHook || authorize) {\n return async function brickAction(context) {\n const input = readInput(context);\n const ctx = createContext(context);\n try {\n if (contextHook) {\n const extra = await contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n }\n validateInput(input);\n if (authorize && !(await authorize({ ctx, input, user: ctx.user })))\n runtime.deny(route.action, ctx.user);\n return validateOutput(\n await execute({ input, ctx, error: errorBuilder }),\n );\n } catch (err) {\n return runtime.mapError(err, context.set, ctx);\n }\n };\n }\n return function brickAction(context) {\n const input = readInput(context);\n const ctx = createContext(context);\n try {\n validateInput(input);\n const result = execute({ input, ctx, error: errorBuilder });\n if (runtime.isThenable(result))\n return Promise.resolve(result)\n .then(validateOutput)\n .catch((err) => runtime.mapError(err, context.set, ctx));\n return validateOutput(result);\n } catch (err) {\n return runtime.mapError(err, context.set, ctx);\n }\n };\n };\n}\n","import type { BrickApp } from \"./endpoints\";\n\n/**\n * Whether a value is an application made by `brick()`. It checks for the\n * methods and `definition` a `BrickApp` has, so it also recognizes one built by\n * another copy of the package.\n *\n * @param app - Anything, such as the default export of an entry file.\n * @returns `true` for a `BrickApp`, narrowing its type.\n */\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\n/**\n * Check that a module's default export is an application ready to be served,\n * for tools that load an entry file.\n *\n * @param app - The default export of an entry file.\n * @returns The app.\n * @throws When it is not a `BrickApp`, or it already called `.listen()`: the\n * entry must only build the app, and leave listening to the server bootstrap.\n */\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n","import type { Service } from \"./types\";\nimport { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport { createHandlerFactory } from \"./compiler/handler\";\nimport {\n compilerRuntime,\n type CompiledHandler,\n type HandlerFactory,\n} from \"./compiler/runtime\";\nimport { requireBrickApp } from \"./app-entry\";\n\ntype ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;\nconst buildBindings = new Map<string, ApplicationBinder>();\n\nfunction applicationKey(\n services: readonly Service<any, any>[],\n prefix = \"/api\",\n) {\n return JSON.stringify([prefix, services.map((service) => service.name)]);\n}\n\n/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n ir: BrickIR,\n bind: ApplicationBinder,\n) {\n const key = JSON.stringify([ir.prefix, ir.services]);\n if (buildBindings.has(key))\n throw new Error(\"Brick compiler: overlapping compiled app imports\");\n buildBindings.set(key, bind);\n try {\n const app = requireBrickApp((await load()).default);\n if (applicationKey(app.definition.services, app.definition.prefix) !== key)\n throw new Error(\n \"Brick compiler: app services/prefix changed; rebuild the application\",\n );\n return app;\n } finally {\n buildBindings.delete(key);\n }\n}\n\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(\n compileRoutePlan(service, action, route.path, route.method),\n );\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const bind = buildBindings.get(\n applicationKey(options.services, options.prefix),\n );\n if (bind && options.mode !== \"generic\") return bind(options.services);\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] =\n options.mode === \"generic\"\n ? ir.routes.map(\n () => (plan) => (context) => executeCompiledRoute(plan, context),\n )\n : ir.routes.map(createHandlerFactory);\n if (options.mode !== \"generic\")\n for (const service of options.services) {\n service.prepareContributions();\n }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n for (const service of services) {\n service.prepareContributions();\n }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n","import type { Action, ActionAccessPolicy } from \"./types\";\n\nexport type { ActionAccessPolicy };\nexport interface ActionAccessInfo {\n hasAuthorize: boolean;\n hasScope: boolean;\n policy: ActionAccessPolicy;\n}\n\n/**\n * Cross-copy access metadata protocol. CRUD enforces its access policy\n * inside `execute`, so `config.authorize` is absent and introspection\n * can't see it. The plugin stamps each action under this process-global\n * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so\n * the binding survives a second copy of core (bundler SSR, Vitest),\n * same as the plugin action-binding key.\n */\nexport const ACTION_ACCESS_KEY = Symbol.for(\"brickkit.action.access\");\n\n/**\n * Record how an action is protected, for tools that cannot read it from the\n * configuration: plugins such as `crud` enforce access inside `execute`, so the\n * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard\n * read what is recorded here.\n *\n * @param action - The action to describe.\n * @param info - Whether it checks authorization and whether it scopes queries,\n * and the resulting policy.\n */\nexport function setActionAccess(action: object, info: ActionAccessInfo): void {\n (action as Record<symbol, ActionAccessInfo>)[ACTION_ACCESS_KEY] = {\n hasAuthorize: info.hasAuthorize,\n hasScope: info.hasScope,\n policy: info.policy,\n };\n}\n\n/**\n * How an action is protected: `\"public\"` when nothing checks the caller,\n * `\"authorized\"` when an `authorize` does, and `\"scoped\"` when the action also\n * limits what rows the caller can reach. It reads what a plugin recorded with\n * `setActionAccess`, else the action's own `authorize`, and keeps the policy\n * consistent with the flags.\n *\n * @param action - An action, or any object a plugin described.\n * @returns `hasAuthorize`, `hasScope`, and `policy`.\n */\nexport function getActionAccess(action: Action | object): ActionAccessInfo {\n const meta = (action as Record<symbol, unknown>)[ACTION_ACCESS_KEY] as\n | Partial<ActionAccessInfo>\n | undefined;\n const configAuthorize = Boolean(\n (action as Action)?.config &&\n typeof (action as Action).config === \"object\" &&\n \"authorize\" in (action as Action).config &&\n typeof (action as Action).config.authorize === \"function\",\n );\n if (!meta) {\n return {\n hasAuthorize: configAuthorize,\n hasScope: false,\n policy: configAuthorize ? \"authorized\" : \"public\",\n };\n }\n const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);\n const hasScope = Boolean(meta.hasScope);\n let policy: ActionAccessPolicy =\n meta.policy ??\n (hasAuthorize ? (hasScope ? \"scoped\" : \"authorized\") : \"public\");\n // Normalize conflicting metadata so the policy always agrees with the\n // effective flags (e.g. metadata stamped \"public\" on an action that also\n // declares config.authorize must not report policy \"public\").\n if (policy === \"public\" && hasAuthorize)\n policy = hasScope ? \"scoped\" : \"authorized\";\n else if (policy !== \"public\" && !hasAuthorize) policy = \"public\";\n else if (policy === \"scoped\" && !hasScope) policy = \"authorized\";\n return { hasAuthorize, hasScope, policy };\n}\n","import { getPluginActionRoute } from \"./plugin\";\nimport { getActionAccess } from \"./access\";\nimport type { ServiceRegistry } from \"./registry\";\nimport { getGlobalRegistry } from \"./registry\";\nimport type { Service, ActionErrorDefinition } from \"./types\";\n\nexport interface OpenApiGeneratorOptions {\n title?: string;\n version?: string;\n description?: string;\n prefix?: string;\n services?: Service<any, any>[];\n registry?: ServiceRegistry;\n}\n\nfunction isAnchor(\n node: unknown,\n): node is { $id: string } & Record<string, any> {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$id === \"string\"\n );\n}\n\nfunction isBareRef(node: unknown): node is { $ref: string } {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$ref === \"string\" &&\n !(node as { $ref: string }).$ref.startsWith(\"#\")\n );\n}\n\nfunction toComponentKey(id: string): string {\n return id.replace(/[^A-Za-z0-9.\\-_]+/g, \"_\");\n}\n\n/**\n * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors\n * (`{ $id: \"T0\", ..., { $ref: \"T0\" } }`). OpenAPI interprets a bare `$ref`\n * as an external file reference, so downstream tooling tries to load a\n * file named `T0` and fails. Hoist every anchored subschema into\n * `#/components/schemas/` and rewrite the refs to local pointers.\n * First definition wins when one `$id` is declared twice.\n */\nexport function hoistAnchoredSchemas(spec: Record<string, any>): string[] {\n const anchored = new Map<string, any>();\n const conflicts: string[] = [];\n\n const collect = (node: any): any => {\n if (Array.isArray(node)) return node.map(collect);\n if (typeof node !== \"object\" || node === null) return node;\n if (isAnchor(node)) {\n const id = node.$id;\n const { $id: _dropped, ...rest } = node;\n const collected = collect(rest);\n if (anchored.has(id)) {\n if (JSON.stringify(anchored.get(id)) !== JSON.stringify(collected)) {\n conflicts.push(id);\n }\n } else {\n anchored.set(id, collected);\n }\n return { $ref: `#/components/schemas/${toComponentKey(id)}` };\n }\n for (const key of Object.keys(node)) {\n node[key] = collect(node[key]);\n }\n return node;\n };\n\n const rewrite = (node: any): void => {\n if (Array.isArray(node)) {\n for (const child of node) rewrite(child);\n return;\n }\n if (typeof node !== \"object\" || node === null) return;\n if (isBareRef(node)) {\n node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;\n }\n for (const key of Object.keys(node)) rewrite(node[key]);\n };\n\n collect(spec);\n\n const components = (spec.components ??= {}) as Record<string, any>;\n const schemas = (components.schemas ??= {}) as Record<string, any>;\n for (const [id, schema] of anchored) {\n schemas[toComponentKey(id)] = schema;\n }\n\n // Second pass covers refs inside the hoisted copies themselves\n // (e.g. the self-recursive JSON-value schema).\n rewrite(spec);\n\n return [...anchored.keys()];\n}\n\n/**\n * Build the OpenAPI 3.1 document for the services: one path per action route,\n * with request and response schemas from the actions' TypeBox schemas, their\n * declared errors, tags by service, and a bearer security scheme where any\n * action needs authorization.\n *\n * `brick()` calls this for `/openapi.json`; call it yourself to write the\n * document to a file or feed another tool.\n *\n * @param options - `title`, `version`, and `description` for the `info` block,\n * `prefix` (default `/api`), and the `services` or `registry` to describe\n * (the global registry by default).\n * @returns The document as a plain object.\n */\nexport function generateOpenApiSpec(\n options: OpenApiGeneratorOptions = {},\n): Record<string, any> {\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const description =\n options.description ??\n \"Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.\";\n const prefix = options.prefix ?? \"/api\";\n\n const services =\n options.services ??\n (options.registry ? options.registry.list() : getGlobalRegistry().list());\n\n const paths: Record<string, any> = {};\n const tagsSet = new Set<string>();\n let hasAnyAuthorizedAction = false;\n\n for (const service of services) {\n tagsSet.add(service.name);\n\n for (const action of service.listActions()) {\n const pluginRoute = getPluginActionRoute(action, prefix);\n if (pluginRoute === false) continue;\n const routePath =\n pluginRoute?.path ??\n action.config.path ??\n `${prefix}/${service.name}/${action.name}`;\n const method = (\n pluginRoute?.method ??\n action.config.method ??\n \"POST\"\n ).toLowerCase();\n const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map(\n (match) => match[1]!,\n );\n const actionPath = routePath.replace(/:([^/]+)/g, \"{$1}\");\n if (!paths[actionPath]) paths[actionPath] = {};\n // Match the compiler's first-registration-wins policy for route collisions.\n if (paths[actionPath][method]) continue;\n\n const hasAuth = getActionAccess(action).hasAuthorize;\n if (hasAuth) {\n hasAnyAuthorizedAction = true;\n }\n\n // Build responses map\n const responses: Record<string, any> = {};\n\n // 200 Success Response\n if (action.config.output) {\n responses[\"200\"] = {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: action.config.output,\n },\n },\n };\n } else {\n responses[\"200\"] = {\n description: \"Successful response\",\n };\n }\n\n const errorAlternatives = new Set<string>();\n const addError = (code: string, status: number, message: string) => {\n const key = `${status}:${code}`;\n if (errorAlternatives.has(key)) return;\n errorAlternatives.add(key);\n const schema = {\n allOf: [\n { $ref: \"#/components/schemas/ErrorEnvelope\" },\n {\n type: \"object\",\n properties: { code: { const: code }, status: { const: status } },\n },\n ],\n };\n const existing = responses[String(status)];\n if (existing) {\n existing.description += \"; \" + message;\n existing.content[\"application/json\"].schema.oneOf.push(schema);\n } else {\n responses[String(status)] = {\n description: message,\n content: { \"application/json\": { schema: { oneOf: [schema] } } },\n };\n }\n };\n if (action.config.input)\n addError(\"VALIDATION_FAILED\", 400, \"Validation error\");\n if (hasAuth) {\n addError(\"UNAUTHORIZED\", 401, \"Authentication required\");\n addError(\"FORBIDDEN\", 403, \"Access denied\");\n }\n if (action.config.errors) {\n for (const [code, errorDef] of Object.entries(action.config.errors)) {\n const def = errorDef as ActionErrorDefinition;\n addError(code, def.status || 400, def.message || code);\n }\n }\n addError(\"INTERNAL_SERVER_ERROR\", 500, \"Internal server error\");\n if (action.config.output)\n addError(\"VALIDATION_FAILED\", 500, \"Output validation error\");\n\n const operation: Record<string, any> = {\n operationId: `${service.name}_${action.name}_${method}`,\n summary: `${service.name}.${action.name}`,\n description:\n action.config.description ??\n `Execute action '${action.name}' on service '${service.name}'`,\n tags:\n action.config.tags && action.config.tags.length > 0\n ? action.config.tags\n : [service.name],\n ...((action as { plugin?: string }).plugin\n ? { \"x-brick-plugin\": (action as { plugin?: string }).plugin }\n : {}),\n ...((action as { resource?: string }).resource\n ? { \"x-brick-resource\": (action as { resource?: string }).resource }\n : {}),\n responses,\n };\n\n const inputSchema = action.config.input;\n const properties = inputSchema?.properties ?? {};\n const parameters: any[] = [...new Set(pathParams)].map((key) => ({\n name: key,\n in: \"path\",\n required: true,\n schema: properties[key] ?? { type: \"string\" },\n }));\n const queryOnly = method === \"get\" || method === \"delete\";\n if (queryOnly) {\n for (const [key, schema] of Object.entries(properties)) {\n if (pathParams.includes(key)) continue;\n parameters.push({\n name: key,\n in: \"query\",\n required: inputSchema?.required?.includes(key) ?? false,\n schema,\n });\n }\n } else if (inputSchema) {\n const bodySchema =\n pathParams.length && inputSchema.properties\n ? {\n ...inputSchema,\n properties: Object.fromEntries(\n Object.entries(properties).filter(\n ([key]) => !pathParams.includes(key),\n ),\n ),\n required: (inputSchema.required ?? []).filter(\n (key: string) => !pathParams.includes(key),\n ),\n }\n : inputSchema;\n operation.requestBody = {\n required: true,\n content: { \"application/json\": { schema: bodySchema } },\n };\n }\n if (parameters.length) operation.parameters = parameters;\n if (hasAuth) operation.security = [{ bearerAuth: [] }];\n paths[actionPath][method] = operation;\n }\n }\n\n const spec: Record<string, any> = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n description,\n },\n paths,\n tags: Array.from(tagsSet).map((name) => ({\n name,\n description: `Actions exposed by '${name}' service`,\n })),\n };\n\n spec.components = {\n schemas: {\n ErrorEnvelope: {\n type: \"object\",\n required: [\"name\", \"code\", \"message\", \"status\", \"requestId\"],\n properties: {\n name: { type: \"string\" },\n code: { type: \"string\" },\n message: { type: \"string\" },\n status: { type: \"integer\" },\n requestId: { type: \"string\" },\n details: {},\n errors: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"path\", \"message\"],\n properties: {\n path: { type: \"string\" },\n message: { type: \"string\" },\n value: {},\n },\n },\n },\n },\n },\n },\n };\n if (hasAnyAuthorizedAction) {\n Object.assign(spec.components, {\n securitySchemes: {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description: \"Enter your Bearer authentication token\",\n },\n },\n });\n }\n\n // Operations reference live TypeBox schemas. Rewrite only the serialized\n // document so OpenAPI pointers cannot corrupt runtime validation schemas.\n const document: Record<string, any> = JSON.parse(JSON.stringify(spec));\n hoistAnchoredSchemas(document);\n\n return document;\n}\n","/**\n * Type-safe secrets & environment variables.\n *\n * Declare each secret once at module scope instead of scattering untyped\n * `process.env.FOO` reads:\n *\n * const port = secret(\"PORT\").default(\"3333\").transform(Number).require();\n * const baseUrl = secret(\"BASE_URL\").url().require();\n * const key = secret(\"STRIPE_KEY\").validate((v) =>\n * v.startsWith(\"sk_\") || \"must start with sk_\"\n * ).require();\n *\n * Values resolve from the environment (Bun populates `process.env` from\n * `.env` locally; in prod the same env source applies — a future\n * `SecretSource` such as AWS can slot in without touching call sites).\n *\n * Resolution order per secret: test/session override → source (`process.env`\n * by default) → declared `default`. `resolveSecrets()` validates every\n * registered secret at boot and throws listing all missing required ones.\n */\n\nexport interface SecretSource {\n get(name: string): string | undefined;\n}\n\n/** Default source: `process.env` (Bun loads `.env` into it automatically). */\nexport const envSource: SecretSource = {\n get: (name: string) => process.env[name],\n};\n\nexport interface SecretOptions {\n /** Fallback when the source has no value. Secrets without a default are required. */\n default?: string;\n}\n\n/** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */\nexport type SecretValidator<T> = (value: T) => void | boolean | string;\n\nconst registry = new Map<string, SecretRef<any>>();\nconst overrides = new Map<string, string | undefined>();\n\nexport class SecretRef<T = string> {\n readonly name: string;\n readonly options: SecretOptions;\n private transformFn?: (raw: string) => T;\n private validators: SecretValidator<T>[] = [];\n\n constructor(name: string, options: SecretOptions = {}) {\n this.name = name;\n this.options = options;\n }\n\n /** True when a default was declared (i.e. the secret is optional). */\n get hasDefault(): boolean {\n return this.options.default !== undefined;\n }\n\n /** Fallback used when the source has no value. Makes the secret optional. */\n default(value: string): this {\n this.options.default = value;\n return this;\n }\n\n /**\n * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === \"true\"`).\n * Runs before validators; a throwing transform fails resolution.\n */\n transform<U>(fn: (raw: string) => U): SecretRef<U> {\n this.transformFn = fn as unknown as (raw: string) => T;\n return this as unknown as SecretRef<U>;\n }\n\n /** Run a custom check on the (transformed) value at every resolution. */\n validate(fn: SecretValidator<T>): this {\n this.validators.push(fn);\n return this;\n }\n\n /** Shorthand validator: value must parse as a URL. String refs only. */\n url(this: SecretRef<string>): SecretRef<string> {\n this.validators.push((v) => {\n try {\n new URL(v);\n } catch {\n return \"must be a valid URL\";\n }\n });\n return this;\n }\n\n private resolveRaw(source: SecretSource): string | undefined {\n if (overrides.has(this.name)) {\n const v = overrides.get(this.name);\n if (v !== undefined) return v;\n }\n return source.get(this.name) ?? this.options.default;\n }\n\n private coerce(raw: string): T {\n let value: T;\n if (this.transformFn) {\n try {\n value = this.transformFn(raw);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": transform failed (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n } else {\n value = raw as unknown as T;\n }\n for (const fn of this.validators) {\n let result: void | boolean | string;\n try {\n result = fn(value);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (result === false) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": validation failed`,\n );\n }\n if (typeof result === \"string\") {\n throw new Error(`Invalid value for secret \"${this.name}\": ${result}`);\n }\n }\n return value;\n }\n\n /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */\n value(source: SecretSource = envSource): T | undefined {\n const raw = this.resolveRaw(source);\n if (raw === undefined) return undefined;\n return this.coerce(raw);\n }\n\n /** Resolved value, or throws naming the missing/invalid secret. */\n require(source: SecretSource = envSource): T {\n const raw = this.resolveRaw(source);\n if (raw === undefined) {\n throw new Error(\n `Missing required secret \"${this.name}\": set it in .env (local) or the environment (prod)`,\n );\n }\n return this.coerce(raw);\n }\n\n /** True when a value would resolve (override, source, or default). */\n isSet(source: SecretSource = envSource): boolean {\n return this.resolveRaw(source) !== undefined;\n }\n}\n\n/**\n * Declare a secret. Idempotent: re-declaring the same name returns the\n * original ref (first declaration wins) so module re-evaluation is safe.\n */\nexport function secret(\n name: string,\n options: SecretOptions = {},\n): SecretRef<string> {\n const existing = registry.get(name);\n if (existing) return existing;\n const ref = new SecretRef<string>(name, options);\n registry.set(name, ref);\n return ref;\n}\n\n/**\n * Validate every registered secret at boot. Throws a single error listing\n * all missing required secrets. Returns the resolved values.\n */\nexport function resolveSecrets(\n opts: { source?: SecretSource } = {},\n): Record<string, unknown> {\n const source = opts.source ?? envSource;\n const missing: string[] = [];\n const resolved: Record<string, unknown> = {};\n for (const ref of registry.values()) {\n const v = ref.value(source);\n if (v === undefined) missing.push(ref.name);\n else resolved[ref.name] = v;\n }\n if (missing.length > 0) {\n throw new Error(\n `Missing required secrets: ${missing.join(\", \")}. Set them in .env (local) or the environment (prod)`,\n );\n }\n return resolved;\n}\n\n/** Metadata for introspection (values never exposed — future dashboard use). */\nexport function listSecrets(\n opts: { source?: SecretSource } = {},\n): Array<{ name: string; hasDefault: boolean; isSet: boolean }> {\n const source = opts.source ?? envSource;\n return [...registry.values()].map((ref) => ({\n hasDefault: ref.hasDefault,\n isSet: ref.isSet(source),\n name: ref.name,\n }));\n}\n\n/** Test/session override for one secret (`undefined` clears the override). */\nexport function overrideSecret(name: string, value: string | undefined): void {\n overrides.set(name, value);\n}\n\n/** Bulk overrides (test/session scoped). */\nexport function overrideSecrets(\n values: Record<string, string | undefined>,\n): void {\n for (const [name, value] of Object.entries(values)) {\n overrides.set(name, value);\n }\n}\n\n/** Clear registry and overrides. Test-only. */\nexport function resetSecrets(): void {\n registry.clear();\n overrides.clear();\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved. Logging only —\n * no CORS headers are set here.\n *\n * Hooks are registered with the \"global\" scope so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in beforeHandle\n * because request hooks are not propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({\n request,\n set,\n }: Pick<Context, \"request\" | \"set\">): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n logger(\n formatLog(request.method, path, set.status ?? 200, Date.now() - start),\n );\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.beforeHandle(\"global\", markStarted);\n plugin.afterHandle(\"global\", logSuccess);\n plugin.error(\"global\", logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\n\n/** An OpenAPI document as plain JSON. */\nexport type OpenApiDocument = Record<string, unknown>;\n\n/** An extra OpenAPI document for the API reference, such as Better Auth's. */\nexport interface ReferenceDocument {\n /** Name in the reference's list of documents. */\n title: string;\n /** The document, or a function returning it; called each time the app starts. */\n document:\n | OpenApiDocument\n | (() => OpenApiDocument | Promise<OpenApiDocument>);\n}\n\n/** A named OpenAPI document ready to render. */\nexport interface ApiDocument {\n title: string;\n document: OpenApiDocument;\n}\n\n/** Developer documentation for the `brick dev` dashboard. */\nexport interface DocumentationOptions {\n /**\n * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the\n * app entry, as it reads in the file that sets it.\n */\n dir: string;\n /**\n * Module whose exports are React components for MDX, added to the built-in\n * ones; a relative path starts where `dir` does. A default export or a\n * `components` export holds the name-to-component map. The dashboard bundles\n * it, so it may import anything the project has.\n */\n components?: string;\n}\n\nexport interface ReferenceOptions {\n /** Also serve a standalone Scalar page here. Without a path, no page is served. */\n path?: string;\n title?: string;\n specUrl?: string;\n /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */\n documents?: ReferenceDocument[];\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/** Mounts the Scalar reference route onto an existing app. */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","/** Who may open the dashboard that `brick start` serves for monitoring. */\nexport interface DashboardAuth {\n /**\n * Secrets that let a request in. A browser asks for one in its sign-in\n * prompt (any user name, the secret as the password), and monitors and\n * scripts send `Authorization: Bearer <secret>`. Give several to rotate one\n * while the other still works. Each is at least 16 characters long;\n * `openssl rand -base64 32` makes a good one.\n */\n token?: string | readonly string[];\n /**\n * Your own check, to sign people in with the auth the app already has: read\n * a session cookie, verify a Better Auth or Clerk session, look at a header\n * a proxy adds. It receives the request (method, URL, and headers; no body)\n * and returns `true` to let it in, `false` to refuse it with 401, or a\n * `Response` to send instead, such as a redirect to your login page. If it\n * throws or takes longer than five seconds, the request is refused with 503.\n *\n * A request is let in when it carries a valid `token`, or when this\n * returns `true`; give both to let monitors in by token and people in by\n * sign-in.\n */\n authorize?: (\n request: Request,\n ) => boolean | Response | Promise<boolean | Response>;\n}\n\n/**\n * The monitoring dashboard `brick start` serves beside the app, on a port of\n * its own: live requests, logs, errors, and the shape of the service, so it\n * stays reachable when the app's own routes are not. `brick dev` has its own\n * dashboard, set by command line options, and ignores this.\n *\n * Setting it turns on `telemetry`, since the dashboard shows what is traced.\n * While it is on, `ctx.logger` and `console` lines written during a request\n * go to the dashboard instead of the console.\n */\nexport interface DashboardOptions {\n /** Default 9400. */\n port?: number;\n /**\n * The address to listen on. Default `127.0.0.1`, reachable only from the same\n * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard\n * will not start on any other address without it.\n */\n host?: string;\n auth?: DashboardAuth;\n /**\n * Days of finished requests to keep on disk, in `.brick/` of the working\n * folder. Default 0: only what happened since the process started, which is\n * lost when it restarts. Needs a folder that outlives the container.\n */\n historyDays?: number;\n}\n\nconst MIN_TOKEN_LENGTH = 16;\n\n/**\n * Check what `brick()` was given, and freeze it. The secrets sit behind a getter\n * that is not enumerable, so logging or serializing the application definition\n * does not print them.\n */\nexport function normalizeDashboard(\n options: DashboardOptions | undefined,\n): DashboardOptions | undefined {\n if (options === undefined) return undefined;\n const { port, host, auth, historyDays } = options;\n if (\n port !== undefined &&\n (!Number.isInteger(port) || port < 1 || port > 65535)\n )\n throw new Error(\n `Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`,\n );\n if (host !== undefined && (typeof host !== \"string\" || host.trim() === \"\"))\n throw new Error(\n \"Brick: dashboard host must be an address, such as '0.0.0.0'.\",\n );\n if (\n historyDays !== undefined &&\n (!Number.isInteger(historyDays) || historyDays < 0)\n )\n throw new Error(\n `Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`,\n );\n const normalized: DashboardOptions = {\n ...(port !== undefined ? { port } : {}),\n ...(host !== undefined ? { host: host.trim() } : {}),\n ...(historyDays !== undefined ? { historyDays } : {}),\n };\n if (auth !== undefined) {\n const tokens =\n auth.token === undefined\n ? undefined\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n if (\n tokens?.some(\n (token) => typeof token !== \"string\" || token.length < MIN_TOKEN_LENGTH,\n )\n )\n throw new Error(\n `Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`,\n );\n if (auth.authorize !== undefined && typeof auth.authorize !== \"function\")\n throw new Error(\"Brick: dashboard authorize must be a function.\");\n if ((tokens === undefined || tokens.length === 0) && !auth.authorize)\n throw new Error(\n \"Brick: dashboard auth needs a token or an authorize function.\",\n );\n const secrets = Object.freeze({\n ...(tokens ? { token: Object.freeze(tokens) } : {}),\n ...(auth.authorize ? { authorize: auth.authorize } : {}),\n });\n // A getter, so inspecting the object (Bun prints hidden fields too) shows\n // `[Getter]` and not the secrets.\n Object.defineProperty(normalized, \"auth\", {\n enumerable: false,\n get: () => secrets,\n });\n }\n return Object.freeze(normalized);\n}\n","import type { RouteIR } from \"./compiler/ir\";\nimport type { Elysia } from \"elysia\";\nimport type { Service } from \"./types\";\nimport type { DatabaseHandle } from \"./db/define\";\nimport type { ApiDocument, DocumentationOptions } from \"./docs\";\nimport type { DashboardOptions } from \"./dashboard\";\nimport type { EventsDefinition, EventsHub } from \"./events/hub\";\nimport { toErrorResponse } from \"./error-response\";\nimport { createLogger } from \"./logger\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\nimport type { BrickSocketSchema } from \"./socket-types\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb() ?? undefined;\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n const tag = `endpoint:${def.method} ${def.path}`;\n const logger = createLogger(`[${tag}]`);\n return async ({ params, body, query, headers, request, set }: any) => {\n const traceId = headers?.[\"x-trace-id\"] || `tr_${crypto.randomUUID()}`;\n const requestId = headers?.[\"x-request-id\"] || `req_${crypto.randomUUID()}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger,\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err) {\n const failure =\n !(\n err instanceof ActionExecutionError || err instanceof ValidationError\n ) &&\n err !== null &&\n typeof err === \"object\" &&\n \"status\" in err &&\n typeof err.status === \"number\" &&\n Number.isInteger(err.status) &&\n err.status >= 400 &&\n err.status < 500\n ? new ActionExecutionError(\n \"HTTP_ERROR\",\n \"message\" in err && typeof err.message === \"string\"\n ? err.message\n : \"Endpoint error\",\n err.status,\n undefined,\n { cause: err },\n )\n : err;\n const response = toErrorResponse(failure, {\n logger: ctx.logger,\n requestId,\n });\n set.status = response.status;\n return response;\n }\n };\n}\n\n/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions, prefix, and telemetry setting chosen at construction. */\n readonly definition: {\n readonly routes: readonly RouteIR[];\n readonly sockets: readonly (BrickSocketSchema & {\n service: string;\n path: string;\n })[];\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n readonly telemetry: boolean;\n readonly documentation?: DocumentationOptions;\n /** What `brick start` serves for monitoring; its `auth` is not enumerable. */\n readonly dashboard?: DashboardOptions;\n /** The listeners and settings of `events`, as plain data. */\n readonly events?: EventsDefinition;\n };\n /**\n * The events of this app, when `events` is set: start and stop delivery, drain\n * what is due, and see or retry what is parked. `brick dev` and `brick start`\n * start it for you.\n */\n readonly events?: EventsHub;\n /** Register a raw endpoint (outside the JSON action mesh). */\n endpoint(def: EndpointDefinition): void;\n /**\n * The OpenAPI documents behind the dashboard's APIs view: this app's own\n * unless `docs` is false, then those from `reference.documents`.\n */\n referenceDocuments(): Promise<ApiDocument[]>;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","import {\n bigserial,\n index as pgIndex,\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp,\n} from \"drizzle-orm/pg-core\";\nimport {\n index as sqliteIndex,\n integer as sqliteInteger,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\n\nconst OUTBOX = Symbol.for(\"brick.outbox\");\n\n/** What the outbox rows are in, by state. */\nexport type OutboxStatus = \"pending\" | \"claimed\" | \"delivered\" | \"dead\";\n\nfunction sqliteOutbox(name: string) {\n const timestampMs = (column: string) =>\n sqliteInteger(column, { mode: \"timestamp_ms\" });\n return sqliteTable(\n name,\n {\n seq: sqliteInteger(\"seq\").primaryKey({ autoIncrement: true }),\n id: sqliteText(\"id\").notNull().unique(),\n eventId: sqliteText(\"event_id\").notNull(),\n listener: sqliteText(\"listener\").notNull(),\n name: sqliteText(\"name\").notNull(),\n payload: sqliteText(\"payload\", { mode: \"json\" }).notNull(),\n traceId: sqliteText(\"trace_id\"),\n source: sqliteText(\"source\"),\n occurredAt: timestampMs(\"occurred_at\").notNull(),\n status: sqliteText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: sqliteInteger(\"attempts\").notNull().default(0),\n lastError: sqliteText(\"last_error\"),\n availableAt: timestampMs(\"available_at\").notNull(),\n claimedAt: timestampMs(\"claimed_at\"),\n deliveredAt: timestampMs(\"delivered_at\"),\n },\n (table) => [\n sqliteIndex(`${name}_due`).on(table.status, table.availableAt),\n sqliteIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\nfunction postgresOutbox(name: string) {\n const at = (column: string) => timestamp(column, { withTimezone: true });\n return pgTable(\n name,\n {\n seq: bigserial(\"seq\", { mode: \"number\" }).primaryKey(),\n id: pgText(\"id\").notNull().unique(),\n eventId: pgText(\"event_id\").notNull(),\n listener: pgText(\"listener\").notNull(),\n name: pgText(\"name\").notNull(),\n payload: jsonb(\"payload\").notNull(),\n traceId: pgText(\"trace_id\"),\n source: pgText(\"source\"),\n occurredAt: at(\"occurred_at\").notNull(),\n status: pgText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: pgInteger(\"attempts\").notNull().default(0),\n lastError: pgText(\"last_error\"),\n availableAt: at(\"available_at\").notNull(),\n claimedAt: at(\"claimed_at\"),\n deliveredAt: at(\"delivered_at\"),\n },\n (table) => [\n pgIndex(`${name}_due`).on(table.status, table.availableAt),\n pgIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\n/** The outbox table of a SQLite database. */\nexport type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;\n/** The outbox table of a Postgres database. */\nexport type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;\n/** An outbox table, made by `outboxTable`. */\nexport type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;\n\n/**\n * The outbox table: where recorded events wait, one row per listener, until they\n * are delivered. A write and the events it causes are inserted in one transaction,\n * so an event is neither lost when the process dies after the write nor sent for a\n * write that was rolled back.\n *\n * Brick does not create tables for you. Put this in the schema of the database\n * whose writes emit events, and your migration tool (such as drizzle-kit) creates\n * it. A service whose database holds the table records events; one without it does\n * not.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_outbox`.\n * @returns A Drizzle table.\n * @example\n * import { defineDatabase, outboxTable } from \"@brickkit/core\";\n *\n * export const outbox = outboxTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { users, outbox },\n * });\n */\nexport function outboxTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteOutboxTable;\nexport function outboxTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresOutboxTable;\nexport function outboxTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): OutboxTable {\n const name = options.name ?? \"brick_outbox\";\n const table = engine === \"sqlite\" ? sqliteOutbox(name) : postgresOutbox(name);\n Object.defineProperty(table, OUTBOX, { value: { engine } });\n return table;\n}\n\n/**\n * Whether a value is an outbox table made by `outboxTable`.\n *\n * @param value - Anything.\n * @returns `true` for an outbox table, narrowing its type.\n */\nexport function isOutboxTable(value: unknown): value is OutboxTable {\n return typeof value === \"object\" && value !== null && OUTBOX in value;\n}\n\nexport function outboxEngine(table: OutboxTable): \"sqlite\" | \"postgres\" {\n return (\n table as unknown as Record<symbol, { engine: \"sqlite\" | \"postgres\" }>\n )[OUTBOX].engine;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst sqliteQueues = new WeakMap<object, Promise<unknown>>();\n\ninterface OpenTransaction {\n /** The handles a nested call can pass to join this transaction. */\n handles: Set<unknown>;\n commits: (() => unknown)[];\n open: boolean;\n savepoints: number;\n}\nconst active = new AsyncLocalStorage<OpenTransaction>();\n\nfunction joined(db: unknown): OpenTransaction | undefined {\n const open = active.getStore();\n return open?.open && open.handles.has(db) ? open : undefined;\n}\n\nexport function isSqliteDatabase(db: any): boolean {\n return (\n typeof db?.$client?.prepare === \"function\" &&\n typeof db?.$client?.run === \"function\"\n );\n}\n\nfunction rollbackQuietly(db: any, statement = \"ROLLBACK\"): void {\n try {\n db.$client.run(statement);\n } catch {\n return;\n }\n}\n\nasync function nested<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const commits = open.commits.length;\n try {\n if (!isSqliteDatabase(db))\n // Drizzle runs a nested transaction as a savepoint.\n return await db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n const name = `brick_${++open.savepoints}`;\n db.$client.run(`SAVEPOINT ${name}`);\n try {\n const result = await fn(db);\n db.$client.run(`RELEASE ${name}`);\n return result;\n } catch (error) {\n rollbackQuietly(db, `ROLLBACK TO ${name}`);\n rollbackQuietly(db, `RELEASE ${name}`);\n throw error;\n }\n } catch (error) {\n // Work that was rolled back must not run its commit callbacks.\n open.commits.length = commits;\n throw error;\n }\n}\n\n/**\n * Run `fn` in a database transaction: everything it writes through the `tx` it is\n * given is committed together when it returns, or undone if it throws.\n *\n * Postgres uses a real transaction on one connection. SQLite has one connection\n * and a synchronous driver, which Drizzle's own `transaction` cannot use with an\n * async callback (it would commit before the callback finished). So transactions\n * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.\n * A write made elsewhere in the process during that time, outside this helper,\n * would join the transaction; use Postgres where that matters.\n *\n * A call made inside `fn` with the `tx` it was given (on SQLite, the database\n * itself) joins the open transaction as a savepoint instead of waiting for it: a\n * nested failure undoes only the nested work, and the outer transaction decides\n * the commit. Nested calls must run one at a time.\n *\n * @param db - A Drizzle database, from `service.getDb()`.\n * @param fn - Receives the transaction handle to run queries on.\n * @returns What `fn` returned.\n * @throws What `fn` threw, after rolling back.\n */\nexport async function runInTransaction<T>(\n db: any,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const outer = joined(db);\n if (outer) return nested(db, outer, fn);\n const open: OpenTransaction = {\n handles: new Set(),\n commits: [],\n open: true,\n savepoints: 0,\n };\n let result: T;\n try {\n result = await active.run(open, () => begin(db, open, fn));\n } finally {\n open.open = false;\n }\n for (const commit of open.commits) await commit();\n return result;\n}\n\nasync function begin<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n if (!isSqliteDatabase(db)) {\n return db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n }\n\n open.handles.add(db);\n const previous = sqliteQueues.get(db) ?? Promise.resolve();\n let release!: () => void;\n const turn = new Promise<void>((resolve) => {\n release = resolve;\n });\n sqliteQueues.set(\n db,\n previous.then(() => turn),\n );\n await previous;\n try {\n db.$client.run(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn(db);\n db.$client.run(\"COMMIT\");\n return result;\n } catch (error) {\n rollbackQuietly(db);\n throw error;\n }\n } finally {\n release();\n }\n}\n\n/**\n * Run `fn` once the transaction that `db` belongs to has committed, or now when\n * `db` is not in one opened by `runInTransaction`. It never runs when that\n * transaction, or the savepoint it was queued in, rolls back. An error it throws\n * reaches the caller of the outermost `runInTransaction`, after the commit.\n *\n * @param db - The handle the work ran on: a `tx`, or a database.\n * @param fn - The side effect, such as clearing a cache.\n */\nexport async function onTransactionCommit(\n db: unknown,\n fn: () => unknown,\n): Promise<void> {\n const open = joined(db);\n if (open) open.commits.push(fn);\n else await fn();\n}\n","import { and, asc, eq, inArray, lt, lte, or, sql } from \"drizzle-orm\";\nimport { type OutboxStatus, type OutboxTable, outboxEngine } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type { Deliverable } from \"./hub\";\nimport type { DispatchOptions, EventDelivery } from \"./types\";\n\nexport type ResolvedDispatchOptions = Required<DispatchOptions>;\n\nexport function resolveDispatchOptions(\n options: DispatchOptions = {},\n): ResolvedDispatchOptions {\n return {\n timer: options.timer ?? true,\n intervalMs: options.intervalMs ?? 1_000,\n batchSize: options.batchSize ?? 50,\n maxAttempts: options.maxAttempts ?? 8,\n claimTimeoutMs: options.claimTimeoutMs ?? 60_000,\n maxBackoffMs: options.maxBackoffMs ?? 300_000,\n retainDeliveredMs: options.retainDeliveredMs ?? 86_400_000,\n };\n}\n\n/** How many outbox rows are in each state. */\nexport type OutboxCounts = Record<OutboxStatus, number>;\n\ninterface OutboxRow {\n seq: number;\n id: string;\n eventId: string;\n listener: string;\n name: string;\n payload: unknown;\n traceId: string | null;\n source: string | null;\n occurredAt: Date;\n status: OutboxStatus;\n attempts: number;\n lastError: string | null;\n}\n\nconst PURGE_INTERVAL_MS = 60_000;\n\nexport function backoffMs(attempt: number, maxBackoffMs: number): number {\n return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);\n}\n\n/**\n * Delivers the events recorded in one outbox table to the app's listeners.\n *\n * It claims a batch of due rows, runs each listener, and marks the row delivered.\n * A listener that throws is retried later with a growing delay, and parked as\n * dead after its attempts run out. Several dispatchers can share a table: on\n * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not\n * finished within `claimTimeoutMs` (the process died) is taken by another.\n * Delivery is at least once, so a listener should tolerate running twice for the\n * same `deliveryId`.\n */\nexport class Dispatcher {\n private readonly engine: \"sqlite\" | \"postgres\";\n private readonly options: ResolvedDispatchOptions;\n private readonly inFlight = new Set<Promise<void>>();\n private timer?: ReturnType<typeof setInterval>;\n private tickQueue?: Promise<number>;\n private lastPurge = 0;\n\n constructor(\n private readonly db: any,\n private readonly table: OutboxTable,\n private readonly listeners: (name: string) => Deliverable | undefined,\n options: DispatchOptions = {},\n private readonly onError: (error: unknown) => void = (error) =>\n console.error(\"[Brick-TS events]\", error),\n ) {\n this.engine = outboxEngine(table);\n this.options = resolveDispatchOptions(options);\n }\n\n /** Whether the dispatcher is looking for work on a timer. */\n get running(): boolean {\n return this.timer !== undefined;\n }\n\n /** Start looking for due deliveries on a timer. Does nothing if it already is. */\n start(): void {\n if (this.timer || !this.options.timer) return;\n this.timer = setInterval(() => void this.tick(), this.options.intervalMs);\n this.timer.unref?.();\n void this.tick();\n }\n\n /**\n * Stop the timer and wait for the deliveries that are running to finish.\n */\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.tickQueue;\n await Promise.allSettled(this.inFlight);\n }\n\n /** Look for work soon, without waiting for the timer. Safe to call often. */\n notify(): void {\n if (!this.timer) return;\n setTimeout(() => void this.tick(), 0).unref?.();\n }\n\n /**\n * Claim what is due and run it, once. Used by the timer, and by tests and\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries it started.\n */\n tick(): Promise<number> {\n this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(\n () => this.claimAndRun(),\n () => this.claimAndRun(),\n );\n return this.tickQueue;\n }\n\n /**\n * Deliver everything that is due now and wait until those deliveries are done.\n * Deliveries that fail and are rescheduled are not waited for again.\n *\n * @returns How many deliveries it ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (;;) {\n const started = await this.tick();\n await Promise.allSettled(this.inFlight);\n if (started === 0) return total;\n total += started;\n }\n }\n\n /**\n * How many rows are in each state.\n */\n async counts(): Promise<OutboxCounts> {\n const t = this.table as any;\n const rows: { status: OutboxStatus; count: number }[] = await this.db\n .select({ status: t.status, count: sql<number>`count(*)` })\n .from(t)\n .groupBy(t.status);\n const counts: OutboxCounts = {\n pending: 0,\n claimed: 0,\n delivered: 0,\n dead: 0,\n };\n for (const row of rows) counts[row.status] = Number(row.count);\n return counts;\n }\n\n /**\n * Put parked deliveries back in line, with their attempts reset.\n *\n * @param deliveryId - One delivery to retry. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n const t = this.table as any;\n const rows: { id: string }[] = await this.db\n .update(t)\n .set({ status: \"pending\", attempts: 0, availableAt: new Date() })\n .where(\n deliveryId\n ? and(eq(t.status, \"dead\"), eq(t.id, deliveryId))\n : eq(t.status, \"dead\"),\n )\n .returning({ id: t.id });\n if (rows.length) this.notify();\n return rows.length;\n }\n\n private async claimAndRun(): Promise<number> {\n try {\n const room = this.options.batchSize - this.inFlight.size;\n if (room <= 0) return 0;\n const rows = await this.claim(room);\n for (const row of rows) {\n const run = this.deliver(row).finally(() => {\n this.inFlight.delete(run);\n });\n this.inFlight.add(run);\n }\n await this.purgeDelivered();\n return rows.length;\n } catch (error) {\n this.onError(error);\n return 0;\n }\n }\n\n private async claim(limit: number): Promise<OutboxRow[]> {\n const t = this.table as any;\n const now = new Date();\n const stale = new Date(now.getTime() - this.options.claimTimeoutMs);\n const due = or(\n and(eq(t.status, \"pending\"), lte(t.availableAt, now)),\n and(eq(t.status, \"claimed\"), lt(t.claimedAt, stale)),\n );\n const claimIn = async (tx: any): Promise<OutboxRow[]> => {\n let select = tx\n .select()\n .from(t)\n .where(due)\n .orderBy(asc(t.seq))\n .limit(limit);\n if (this.engine === \"postgres\")\n select = select.for(\"update\", { skipLocked: true });\n const picked: OutboxRow[] = await select;\n if (!picked.length) return [];\n await tx\n .update(t)\n .set({\n status: \"claimed\",\n claimedAt: now,\n attempts: sql`${t.attempts} + 1`,\n })\n .where(\n inArray(\n t.seq,\n picked.map((row) => row.seq),\n ),\n );\n return picked.map((row) => ({ ...row, attempts: row.attempts + 1 }));\n };\n return this.engine === \"postgres\"\n ? this.db.transaction(claimIn)\n : runInTransaction(this.db, claimIn);\n }\n\n private async deliver(row: OutboxRow): Promise<void> {\n const listener = this.listeners(row.listener);\n if (!listener) {\n await this.park(row, `No listener named '${row.listener}' is registered`);\n return;\n }\n const delivery: EventDelivery = {\n id: row.eventId,\n name: row.name,\n payload: row.payload,\n occurredAt: row.occurredAt.toISOString(),\n ...(row.traceId ? { traceId: row.traceId } : {}),\n ...(row.source ? { source: row.source } : {}),\n listener: row.listener,\n deliveryId: row.id,\n attempt: row.attempts,\n };\n try {\n await listener.run(delivery);\n } catch (error) {\n await this.fail(\n row,\n error,\n listener.maxAttempts ?? this.options.maxAttempts,\n );\n return;\n }\n await this.markDelivered(row);\n }\n\n private async markDelivered(row: OutboxRow): Promise<void> {\n const t = this.table as any;\n try {\n if (this.options.retainDeliveredMs === 0)\n await this.db.delete(t).where(eq(t.seq, row.seq));\n else\n await this.db\n .update(t)\n .set({\n status: \"delivered\",\n deliveredAt: new Date(),\n lastError: null,\n })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.onError(error);\n }\n }\n\n private async fail(\n row: OutboxRow,\n error: unknown,\n maxAttempts: number,\n ): Promise<void> {\n const message = error instanceof Error ? error.message : String(error);\n if (row.attempts >= maxAttempts) {\n await this.park(row, message);\n return;\n }\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({\n status: \"pending\",\n lastError: message,\n claimedAt: null,\n availableAt: new Date(\n Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs),\n ),\n })\n .where(eq(t.seq, row.seq));\n } catch (writeError) {\n this.onError(writeError);\n }\n }\n\n private async park(row: OutboxRow, message: string): Promise<void> {\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({ status: \"dead\", lastError: message, claimedAt: null })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.onError(error);\n }\n }\n\n private async purgeDelivered(): Promise<void> {\n const keep = this.options.retainDeliveredMs;\n const now = Date.now();\n if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;\n this.lastPurge = now;\n const t = this.table as any;\n await this.db\n .delete(t)\n .where(\n and(eq(t.status, \"delivered\"), lt(t.deliveredAt, new Date(now - keep))),\n );\n }\n}\n","const ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport function newEventId(now: number = Date.now()): string {\n let time = \"\";\n let remaining = now;\n for (let index = 0; index < 10; index++) {\n time = ALPHABET[remaining % 32] + time;\n remaining = Math.floor(remaining / 32);\n }\n let random = \"\";\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n random += ALPHABET[byte % 32];\n }\n return `evt_${time}${random}`;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type {\n EventDelivery,\n EventListener,\n EventsWorld,\n WorkflowEvent,\n WorkflowsOptions,\n} from \"./types\";\n\n/** `getQueueTopicPrefix(\"workflow\")` from `@workflow/world`: the queue the runtime reads. */\nconst WORKFLOW_QUEUE_PREFIX = \"__wkf_workflow_\";\nconst BUNDLE_DIR = \".well-known/workflow/v1\";\nconst STOPPED = \"The events were stopped, so workflows can no longer run\";\n/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */\nexport const WEBHOOK_ROUTE = \"/.well-known/workflow/v1/webhook/*\";\n/** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */\nconst STEP_REGISTRY = Symbol.for(\"@workflow/core//registeredSteps\");\n\ninterface WorkflowSdk {\n start(\n workflow: unknown,\n args: unknown[],\n options: Record<string, unknown>,\n ): Promise<{ runId: string }>;\n setWorld(world: unknown): void;\n}\n\ninterface BundleManifest {\n steps?: Record<string, unknown>;\n workflows?: Record<string, Record<string, { workflowId?: string }>>;\n}\n\n/**\n * Where the workflow bundle is read from, and the project it is built from.\n *\n * @param options - The `events.workflows` option.\n * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the\n * builder finds the SDK from where it writes, and skips only this directory when it\n * looks for workflows.\n */\nexport function resolveWorkflowPaths(options: WorkflowsOptions = {}): {\n root: string;\n dir: string;\n} {\n const root = resolve(options.root ?? process.cwd());\n return { root, dir: join(root, BUNDLE_DIR) };\n}\n\n/**\n * Runs workflow listeners: wires the world into the Workflow SDK, serves the\n * built bundle from this process, and starts one run for each delivery.\n *\n * Nothing is loaded until it is needed, so an app without workflow listeners\n * never imports the SDK.\n */\nexport class WorkflowRuntime {\n readonly root: string;\n readonly dir: string;\n private ready: Promise<WorkflowSdk> | undefined;\n private connected: Promise<WorkflowSdk> | undefined;\n private closed = false;\n\n constructor(\n readonly world: EventsWorld,\n options: WorkflowsOptions | undefined,\n private readonly listeners: readonly EventListener[],\n ) {\n ({ root: this.root, dir: this.dir } = resolveWorkflowPaths(options));\n }\n\n /** Begin loading the runtime now rather than at the first delivery. */\n warmUp(): void {\n this.ensure().catch((error) =>\n console.error(\n `[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n\n /**\n * Start the run for a delivery.\n *\n * The run is named after the delivery id, so a delivery that is tried again\n * finds the run it already started instead of starting another.\n *\n * @param listener - The workflow listener the delivery is for.\n * @param delivery - The delivery.\n * @returns The run id.\n */\n async startRun(\n listener: EventListener,\n delivery: EventDelivery,\n ): Promise<string> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...event } = delivery;\n const run = await sdk.start(\n listener.workflow,\n [event satisfies WorkflowEvent],\n {\n world: this.world,\n runKey: delivery.deliveryId,\n runKeyTime: Date.parse(delivery.occurredAt),\n },\n );\n return run.runId;\n }\n\n /**\n * Answer a request to a webhook a workflow created with `createWebhook`, by\n * resuming the workflow that waits on it. Needs the world but not the queue\n * consumer, so a process that only records events (`dispatch: false`) serves\n * webhooks too.\n *\n * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.\n * @returns The response the bundle's webhook handler gives.\n */\n async handleWebhook(request: Request): Promise<Response> {\n await this.connect();\n const file = join(this.dir, \"webhook.mjs\");\n if (!existsSync(file))\n throw new Error(\n `No webhook bundle at ${file}. brick dev and brick start build it; ` +\n \"in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\",\n );\n const handlers = await import(pathToFileURL(file).href);\n const handler = handlers[request.method];\n if (typeof handler !== \"function\")\n return new Response(null, { status: 405 });\n return handler(request);\n }\n\n /** Stop the world. The runtime cannot be started again afterwards. */\n async close(): Promise<void> {\n this.closed = true;\n await this.ready?.catch(() => {});\n await this.connected?.catch(() => {});\n await this.world.close?.();\n }\n\n private ensure(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.ready ??= this.initialize().catch((error) => {\n this.ready = undefined;\n throw error;\n });\n return this.ready;\n }\n\n /** Load the SDK and give it the world: all a webhook needs. */\n private connect(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.connected ??= this.loadSdk()\n .then((sdk) => {\n sdk.setWorld(this.world);\n return sdk;\n })\n .catch((error) => {\n this.connected = undefined;\n throw error;\n });\n return this.connected;\n }\n\n private async initialize(): Promise<WorkflowSdk> {\n if (typeof this.world.createRunId !== \"function\")\n throw new Error(\n \"This world cannot name a run after its key, so an event delivered twice would start two runs. \" +\n \"Use the world from @brickkit/redis-world or @brickkit/bullmq-world.\",\n );\n const sdk = await this.connect();\n const flow = join(this.dir, \"flow.mjs\");\n if (!existsSync(flow))\n throw new Error(\n `No workflow bundle at ${flow}. brick dev and brick start build it; ` +\n \"in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\",\n );\n const manifest = this.readManifest();\n this.checkListeners(manifest);\n const bundle = await this.loadBundle(flow);\n if (typeof bundle.POST !== \"function\")\n throw new Error(`${flow} does not export a POST handler`);\n this.world.registerHandler?.(WORKFLOW_QUEUE_PREFIX, bundle.POST);\n await this.world.start?.();\n return sdk;\n }\n\n private async loadSdk(): Promise<WorkflowSdk> {\n const from = createRequire(join(this.root, \"package.json\"));\n const load = async (specifier: string) => {\n let path: string;\n try {\n path = from.resolve(specifier);\n } catch {\n throw new Error(\n `The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`,\n );\n }\n return import(pathToFileURL(path).href);\n };\n const [api, runtime] = await Promise.all([\n load(\"workflow/api\"),\n load(\"workflow/runtime\"),\n ]);\n return { start: api.start, setWorld: runtime.setWorld };\n }\n\n /**\n * The bundle holds its own copy of every step and registers them all when it\n * loads, replacing the ones the app registered. A copy has its own module state:\n * a step would find no database connection, no config, none of what the app set\n * up. So the app's steps are put back, and the bundle's copies serve only the\n * steps the app never loaded.\n */\n private async loadBundle(\n flow: string,\n ): Promise<{ POST?: (request: Request) => Promise<Response> }> {\n const registry = () =>\n (globalThis as Record<symbol, unknown>)[STEP_REGISTRY] as\n | Map<string, unknown>\n | undefined;\n const app = new Map(registry());\n const bundle = await import(pathToFileURL(flow).href);\n const registered = registry();\n if (registered) for (const [id, step] of app) registered.set(id, step);\n return bundle;\n }\n\n private readManifest(): BundleManifest | undefined {\n const path = join(this.dir, \"manifest.json\");\n if (!existsSync(path)) return undefined;\n return JSON.parse(readFileSync(path, \"utf8\")) as BundleManifest;\n }\n\n /**\n * A listener's workflow must carry the id the transform gives it, and the bundle\n * must know that id: a function that was never transformed, or a bundle built\n * before the workflow existed, would fail on its first delivery with a less\n * helpful message.\n */\n private checkListeners(manifest: BundleManifest | undefined): void {\n const known = new Set<string>();\n for (const file of Object.values(manifest?.workflows ?? {}))\n for (const entry of Object.values(file))\n if (entry.workflowId) known.add(entry.workflowId);\n for (const listener of this.listeners) {\n const id = (listener.workflow as { workflowId?: unknown } | undefined)\n ?.workflowId;\n if (typeof id !== \"string\")\n throw new Error(\n `The workflow of listener '${listener.name}' was not transformed. ` +\n \"Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.\",\n );\n if (manifest && !known.has(id))\n throw new Error(\n `The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`,\n );\n }\n }\n}\n","import { Dispatcher, type OutboxCounts } from \"./dispatcher\";\nimport { newEventId } from \"./id\";\nimport type { OutboxTable } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type {\n DispatchOptions,\n EventDelivery,\n EventListener,\n EventRecorder,\n EventsOptions,\n EventsWorld,\n ServiceEvents,\n} from \"./types\";\nimport { WorkflowRuntime } from \"./workflows\";\n\ninterface EventsHost {\n readonly name: string;\n getDb(): unknown;\n getOutbox?(): OutboxTable | undefined;\n setEvents?(events: ServiceEvents | undefined): void;\n}\n\nexport function matchesEvent(pattern: string, name: string): boolean {\n if (pattern === \"*\") return true;\n if (pattern.endsWith(\"*\")) return name.startsWith(pattern.slice(0, -1));\n return pattern === name;\n}\n\n/** The recorder of each service database, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */\nexport const recorders = new WeakMap<object, ServiceEvents>();\n\n// Shared by name: the CLI that stops the hubs may hold another copy of this package.\nconst startedHubs = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(\"brickkit.events.started\")\n] ??= new Set()) as Set<Pick<EventsHub, \"stop\">>;\n\n/**\n * Stop every events hub started in this process, by any copy of `@brickkit/core`,\n * and wait for their deliveries. A hub that fails to stop does not cut the wait\n * for the others: the first failure is thrown once every hub is done.\n */\nexport async function stopAllEvents(): Promise<void> {\n const results = await Promise.allSettled(\n [...startedHubs].map((hub) => hub.stop()),\n );\n const failed = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (failed) throw failed.reason;\n}\n\n/**\n * What an app's `events` option describes, as plain data. It goes in the app\n * definition, which is sent to the dev dashboard, so it holds no functions.\n */\nexport interface EventsDefinition {\n listeners: { name: string; on: string[]; kind: \"handler\" | \"workflow\" }[];\n dispatch: boolean;\n /** Names of the services whose writes record events. */\n recorders: string[];\n}\n\n/** What the dispatcher runs for a delivery. */\nexport interface Deliverable {\n readonly maxAttempts?: number;\n run(delivery: EventDelivery): void | Promise<void>;\n}\n\n/**\n * The events of one app: who listens, where events are recorded, and the\n * dispatchers that deliver them. `brick({ events })` makes one and puts it on\n * `app.events`.\n */\nexport class EventsHub {\n private readonly byName = new Map<string, EventListener>();\n private readonly dispatchers = new Map<OutboxTable, Dispatcher>();\n private readonly deliverables = new Map<string, Deliverable>();\n private readonly dispatchOptions: DispatchOptions | false;\n private readonly runtime: WorkflowRuntime | undefined;\n private readonly recorderNames: string[] = [];\n private started = false;\n private stopping: Promise<void> | undefined;\n\n constructor(options: EventsOptions) {\n for (const listener of options.listeners ?? []) {\n if (typeof listener.name !== \"string\" || !listener.name)\n throw new Error(\"An event listener needs a name\");\n if (listener.name.includes(\":\"))\n throw new Error(\n `Event listener name '${listener.name}' must not contain ':'`,\n );\n if (!listener.on?.length)\n throw new Error(\n `Event listener '${listener.name}' listens for nothing`,\n );\n if (this.byName.has(listener.name))\n throw new Error(`Duplicate event listener '${listener.name}'`);\n if (!listener.run === !listener.workflow)\n throw new Error(\n `Event listener '${listener.name}' needs exactly one of run and workflow`,\n );\n this.byName.set(listener.name, listener);\n }\n const workflowListeners = [...this.byName.values()].filter(\n (listener) => listener.workflow,\n );\n if (workflowListeners.length) {\n if (!options.world)\n throw new Error(\n `Event listener '${workflowListeners[0]!.name}' runs a workflow, so events needs a world: ` +\n \"brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.\",\n );\n this.runtime = new WorkflowRuntime(\n options.world,\n options.workflows,\n workflowListeners,\n );\n }\n this.dispatchOptions =\n options.dispatch === false\n ? false\n : options.dispatch === true || options.dispatch === undefined\n ? {}\n : options.dispatch;\n }\n\n /**\n * Give each service whose database holds an outbox table a recorder, and a\n * dispatcher for that table. Call it before the first request: a service has no\n * recorder until then.\n *\n * @param services - The app's services.\n * @returns The hub, for chaining.\n */\n attach(services: readonly EventsHost[]): this {\n let attached = 0;\n for (const service of services) {\n const table = service.getOutbox?.();\n if (!table) continue;\n attached++;\n this.recorderNames.push(service.name);\n const bound = this.bind(table);\n service.setEvents?.(bound);\n const db = service.getDb();\n if (db && typeof db === \"object\") recorders.set(db, bound);\n }\n if (attached === 0 && this.byName.size > 0) {\n console.warn(\n \"[Brick-TS] events are configured, but no service database has an outbox table. \" +\n \"Add outboxTable() to a database's tables so its writes can record events.\",\n );\n }\n for (const service of services) {\n const table = service.getOutbox?.();\n if (table && !this.dispatchers.has(table)) {\n this.dispatchers.set(\n table,\n new Dispatcher(\n service.getDb(),\n table,\n (name) => this.deliverable(name),\n this.dispatchOptions || {},\n ),\n );\n }\n }\n return this;\n }\n\n /** The listeners that want an event. */\n matching(name: string): EventListener[] {\n const found: EventListener[] = [];\n for (const listener of this.byName.values())\n if (listener.on.some((pattern) => matchesEvent(pattern, name)))\n found.push(listener);\n return found;\n }\n\n /** The listeners and settings, as plain data. */\n describe(): EventsDefinition {\n return {\n listeners: [...this.byName.values()].map((listener) => ({\n name: listener.name,\n on: [...listener.on],\n kind: listener.workflow ? (\"workflow\" as const) : (\"handler\" as const),\n })),\n dispatch: this.dispatchOptions !== false,\n recorders: [...this.recorderNames],\n };\n }\n\n /**\n * Where the workflow bundle is read from, the project it is built from, and\n * the world the workflows run on. Only set when a listener runs a workflow.\n * The CLI builds the bundle there before events start, and shows the world's\n * runs in the dev dashboard.\n */\n get workflows():\n | { root: string; dir: string; world: EventsWorld }\n | undefined {\n return (\n this.runtime && {\n root: this.runtime.root,\n dir: this.runtime.dir,\n world: this.runtime.world,\n }\n );\n }\n\n /**\n * Resume the workflow that waits on a webhook. The server mounts this on the\n * route the Workflow SDK puts in webhook URLs.\n */\n webhook(request: Request): Promise<Response> {\n if (!this.runtime)\n throw new Error(\"No listener of this app runs a workflow\");\n return this.runtime.handleWebhook(request);\n }\n\n /**\n * Start delivering recorded events from this process, and start the world that\n * runs workflow listeners. Does nothing if this process only records events\n * (`dispatch: false`), already started, or a stop is still waiting.\n */\n start(): void {\n // A process being stopped exits when the stop is done, and would drop what\n // this start claims. A startup that finishes late, or a commit, lands here.\n if (this.dispatchOptions === false || this.started || this.stopping) return;\n this.started = true;\n startedHubs.add(this);\n this.runtime?.warmUp();\n for (const dispatcher of this.dispatchers.values()) dispatcher.start();\n }\n\n /**\n * Stop delivering, wait for the deliveries that are running, and close the\n * world. A world cannot be started again, so workflow listeners stop for good.\n * A stop that arrives while another runs waits for that one.\n */\n stop(): Promise<void> {\n return (this.stopping ??= this.shutDown().finally(() => {\n // Removed only when done, so a stop-all waits for a stop already running.\n this.stopping = undefined;\n startedHubs.delete(this);\n }));\n }\n\n private async shutDown(): Promise<void> {\n this.started = false;\n await Promise.all(\n [...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()),\n );\n await this.runtime?.close();\n }\n\n /**\n * Deliver everything that is due now and wait for it. For tests and for\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.drain();\n return total;\n }\n\n /** How many rows are in each state, across the app's outbox tables. */\n async counts(): Promise<OutboxCounts> {\n const total: OutboxCounts = {\n pending: 0,\n claimed: 0,\n delivered: 0,\n dead: 0,\n };\n for (const dispatcher of this.dispatchers.values()) {\n const counts = await dispatcher.counts();\n for (const status of Object.keys(total) as (keyof OutboxCounts)[])\n total[status] += counts[status];\n }\n return total;\n }\n\n /**\n * Put parked deliveries back in line.\n *\n * @param deliveryId - One delivery. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.retryDead(deliveryId);\n return total;\n }\n\n private deliverable(name: string): Deliverable | undefined {\n const listener = this.byName.get(name);\n if (!listener) return undefined;\n let found = this.deliverables.get(name);\n if (!found) {\n const runtime = this.runtime;\n found = listener.workflow\n ? {\n ...(listener.maxAttempts !== undefined\n ? { maxAttempts: listener.maxAttempts }\n : {}),\n run: async (delivery) => {\n await runtime!.startRun(listener, delivery);\n },\n }\n : (listener as Deliverable);\n this.deliverables.set(name, found);\n }\n return found;\n }\n\n private bind(table: OutboxTable): ServiceEvents {\n const startAndNotify = () => {\n this.start();\n this.dispatchers.get(table)?.notify();\n };\n const insert = async (\n tx: any,\n context: { traceId?: string; source?: string },\n name: string,\n payload: unknown,\n ): Promise<boolean> => {\n const listeners = this.matching(name);\n if (!listeners.length) return false;\n const eventId = newEventId();\n const occurredAt = new Date();\n await tx.insert(table as any).values(\n listeners.map((listener) => ({\n id: `${eventId}:${listener.name}`,\n eventId,\n listener: listener.name,\n name,\n payload,\n traceId: context.traceId ?? null,\n source: context.source ?? null,\n occurredAt,\n status: \"pending\",\n attempts: 0,\n availableAt: occurredAt,\n })),\n );\n return true;\n };\n return {\n wants: (name) => this.matching(name).length > 0,\n transaction: async (db, context, fn) => {\n let recorded = false;\n const result = await runInTransaction(db, async (tx) => {\n const record: EventRecorder = async (name, payload) => {\n if (await insert(tx, context, name, payload)) recorded = true;\n };\n return fn(tx, record);\n });\n if (recorded) startAndNotify();\n return result;\n },\n record: async (tx, context, name, payload) => {\n await insert(tx, context, name, payload);\n },\n };\n }\n}\n","import type { Elysia } from \"elysia\";\nimport { websocket } from \"elysia/websocket\";\nimport { createLogger } from \"./logger\";\nimport type { BaseContext } from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport {\n serializeSocketSchema,\n isSocketEnvelope,\n SOCKET_MAX_BYTES,\n SOCKET_BUFFER_BYTES,\n} from \"./socket-schema\";\nimport type {\n BrickSocketConfig,\n BrickSocketSchema,\n BrickSocketSender,\n SocketPayloads,\n SocketSchemas,\n} from \"./socket-types\";\n\ninterface SocketSender {\n readonly isOpen: boolean;\n send(event: string, payload: unknown): void;\n close(): void;\n}\ninterface SocketSession {\n open(socket: SocketSender): Promise<void>;\n message(event: string, data: unknown, socket: SocketSender): Promise<void>;\n close(socket: SocketSender, code: number, reason: string): Promise<void>;\n}\nexport interface RegisteredSocket {\n schema: BrickSocketSchema;\n input: SocketSchemas;\n output: SocketSchemas;\n allowedOrigins?: readonly string[];\n allowMissingOrigin?: boolean;\n connect(request: Request): Promise<SocketSession>;\n}\n\nclass SocketDenied extends Error {}\n\nexport function defineServiceSocket<\n I extends SocketSchemas,\n O extends SocketSchemas,\n Ctx extends BaseContext,\n>(\n config: BrickSocketConfig<I, O, Ctx>,\n resolve: (request: Request) => Promise<Ctx>,\n): RegisteredSocket {\n if (\n !config.name ||\n config.name.split(\".\").some((part) => !/^[a-zA-Z_][\\w-]*$/.test(part))\n )\n throw new Error(\"Invalid socket name\");\n if (\n config.path !== undefined &&\n (!config.path.startsWith(\"/\") ||\n /[?#*]/.test(config.path) ||\n config.path.split(\"/\").some((segment) => segment.startsWith(\":\")))\n )\n throw new Error(\n \"Socket path must be a static absolute route without a query or fragment\",\n );\n const input = Object.freeze({ ...config.input });\n const output = Object.freeze({ ...config.output });\n const handlers = { ...config.handlers };\n if (\n Object.keys(input).length !== Object.keys(handlers).length ||\n Object.keys(input).some(\n (key) =>\n !Object.hasOwn(handlers, key) || typeof handlers[key] !== \"function\",\n )\n )\n throw new Error(\"Every socket input event needs exactly one handler\");\n for (const schema of [...Object.values(input), ...Object.values(output)]) {\n serializeSocketSchema(schema);\n getCompiledCheck(schema);\n }\n const typed = (socket: SocketSender): BrickSocketSender<SocketPayloads<O>> =>\n socket;\n const context = async (request: Request) => {\n const ctx = await resolve(request);\n if (config.authorize && !(await config.authorize({ ctx })))\n throw new SocketDenied();\n return ctx;\n };\n return {\n schema: {\n name: config.name,\n path: config.path,\n description: config.description,\n input: Object.keys(input),\n output: Object.keys(output),\n hasAuthorize: !!config.authorize,\n },\n input,\n output,\n allowedOrigins: config.allowedOrigins\n ? [...config.allowedOrigins]\n : undefined,\n allowMissingOrigin: config.allowMissingOrigin,\n async connect(request) {\n const initial = await context(request);\n return {\n async open(socket) {\n await config.open?.({ ctx: initial, socket: typed(socket) });\n },\n async message(event, data, socket) {\n const schema = Object.hasOwn(input, event) ? input[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new SocketDenied();\n const ctx = await context(request);\n if (!socket.isOpen) return;\n // The schema and event were checked together before dispatch.\n const handler = handlers[event as keyof I];\n await handler({\n input: data as SocketPayloads<I>[keyof I],\n ctx,\n socket: typed(socket),\n });\n },\n async close(socket, code, reason) {\n await config.close?.({\n ctx: initial,\n socket: typed(socket),\n code,\n reason,\n });\n },\n };\n },\n };\n}\n\nexport function socketPath(\n prefix: string,\n service: string,\n socket: RegisteredSocket,\n): string {\n return (\n socket.schema.path ??\n `${prefix.replace(/\\/$/, \"\")}/${service}/${socket.schema.name}`\n );\n}\n\n/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */\nfunction publicOrigin(request: Request): string {\n // Browsers cannot set X-Forwarded-* on a WebSocket handshake, so a cross-site page cannot forge a match.\n const forwarded = (name: string) =>\n request.headers.get(name)?.split(\",\")[0]?.trim() || undefined;\n const url = new URL(request.url);\n const proto = forwarded(\"x-forwarded-proto\");\n return `${proto ? `${proto}:` : url.protocol}//${forwarded(\"x-forwarded-host\") ?? url.host}`;\n}\n\n/** Mounts native adapters. Each connection owns its queue and service session. */\nexport function mountSockets(\n app: Elysia,\n sockets: { service: string; path: string; definition: RegisteredSocket }[],\n): void {\n if (!sockets.length) return;\n app.use(\n websocket({\n maxPayloadLength: SOCKET_MAX_BYTES,\n backpressureLimit: SOCKET_BUFFER_BYTES,\n closeOnBackpressureLimit: true,\n }),\n );\n for (const { service, path, definition } of sockets) {\n const logger = createLogger(\n `[Brick socket ${service}.${definition.schema.name}]`,\n );\n const sessions = new WeakMap<Request, SocketSession>();\n type Peer = {\n request: Request;\n send(data: string): number;\n close(code?: number, reason?: string): void;\n readonly readyState: number;\n };\n const connections = new WeakMap<\n Request,\n {\n session: SocketSession;\n sender: SocketSender;\n tail: Promise<void>;\n pending: number;\n bytes: number;\n closed: boolean;\n }\n >();\n const fail = (ws: Peer, error: unknown) => {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n if (ws.readyState !== 1) return;\n ws.close(\n error instanceof SocketDenied ? 1008 : 1011,\n error instanceof SocketDenied\n ? \"Message refused\"\n : \"Socket handler failed\",\n );\n };\n app.ws(path, {\n async beforeHandle({ request }) {\n if (sessions.has(request)) return;\n const origin = request.headers.get(\"origin\");\n if (\n origin\n ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(\n origin,\n )\n : !definition.allowMissingOrigin\n )\n return new Response(\"Socket origin refused\", { status: 403 });\n try {\n sessions.set(request, await definition.connect(request));\n } catch (error) {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n return new Response(\"Socket connection refused\", {\n status: error instanceof SocketDenied ? 403 : 500,\n });\n }\n },\n async open(ws) {\n const session = sessions.get(ws.request);\n if (!session) {\n ws.close(1011, \"Missing socket session\");\n return;\n }\n const sender: SocketSender = {\n get isOpen() {\n return !state.closed && ws.readyState === 1;\n },\n close() {\n ws.close(1000, \"\");\n },\n send(event, data) {\n if (!sender.isOpen) throw new Error(\"Socket is closed\");\n const schema = Object.hasOwn(definition.output, event)\n ? definition.output[event]\n : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new Error(\"Invalid socket output\");\n const frame = JSON.stringify({ event, data });\n if (new TextEncoder().encode(frame).byteLength > SOCKET_MAX_BYTES)\n throw new Error(\"Socket output too large\");\n // Check the JSON representation too, so values lost during serialization cannot break the contract.\n if (!getCompiledCheck(schema).Check(JSON.parse(frame).data))\n throw new Error(\"Socket output is not JSON-compatible\");\n const result = ws.send(frame);\n if (result === 0) {\n ws.close(1013, \"Socket buffer full\");\n throw new Error(\"Socket buffer full\");\n }\n },\n };\n const state = {\n session,\n sender,\n tail: Promise.resolve(),\n pending: 0,\n bytes: 0,\n closed: false,\n };\n connections.set(ws.request, state);\n try {\n await session.open(sender);\n } catch (error) {\n fail(ws, error);\n }\n },\n message(ws, value: unknown) {\n const state = connections.get(ws.request);\n if (!state || state.closed || ws.readyState !== 1) return;\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n ws.close(1003, \"Only JSON text is supported\");\n return;\n }\n if (typeof value === \"string\") {\n ws.close(1007, \"Expected JSON envelope\");\n return;\n }\n if (!isSocketEnvelope(value)) {\n ws.close(1008, \"Invalid socket envelope\");\n return;\n }\n const size = new TextEncoder().encode(JSON.stringify(value)).byteLength;\n if (size > SOCKET_MAX_BYTES) {\n ws.close(1009, \"Message too large\");\n return;\n }\n if (state.pending >= 32 || state.bytes + size > SOCKET_BUFFER_BYTES) {\n ws.close(1013, \"Socket queue full\");\n return;\n }\n state.pending++;\n state.bytes += size;\n state.tail = state.tail\n .then(async () => {\n if (state.closed || ws.readyState !== 1) return;\n await state.session.message(value.event, value.data, state.sender);\n })\n .catch((error: unknown) => fail(ws, error))\n .finally(() => {\n state.pending--;\n state.bytes -= size;\n });\n // Brick owns the queue. Returning the tail here makes native close wait on application work.\n },\n async close(ws, code = 1006, reason = \"\") {\n const state = connections.get(ws.request);\n sessions.delete(ws.request);\n if (!state || state.closed) return;\n state.closed = true;\n try {\n await state.session.close(state.sender, code, reason);\n } catch (error) {\n logger.error({\n error,\n service,\n socket: definition.schema.name,\n phase: \"cleanup\",\n });\n }\n connections.delete(ws.request);\n },\n });\n }\n}\n","import { Elysia } from \"elysia\";\nimport {\n compileBrickApplication,\n type CompiledApplication,\n type RouteIR,\n} from \"./compiler\";\nimport type { Service } from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getPluginActionRoute, getPluginEndpoints } from \"./plugin\";\nimport { generateOpenApiSpec } from \"./openapi\";\nimport { resolveSecrets, type SecretSource } from \"./secrets\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n registerReferenceRoute,\n type ApiDocument,\n type DocumentationOptions,\n type OpenApiDocument,\n type ReferenceOptions,\n} from \"./docs\";\nimport { normalizeDashboard, type DashboardOptions } from \"./dashboard\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\nimport { instrumentDatabase, traceHttpRequest, withSpan } from \"./telemetry\";\nimport { EventsHub } from \"./events/hub\";\nimport { WEBHOOK_ROUTE } from \"./events/workflows\";\nimport type { EventsOptions } from \"./events/types\";\nimport { mountSockets, socketPath } from \"./socket\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Generate specialized handlers once at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n /**\n * `true` serves a Scalar page at /reference. Options serve one only with a\n * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.\n */\n reference?: boolean | ReferenceOptions; // default false\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (outside the JSON action mesh), mounted at startup. */\n endpoints?: EndpointDefinition[];\n /**\n * Record request, action, and RPC spans with OpenTelemetry (default false).\n * Spans go to the globally registered tracer provider; without one they are\n * no-ops. `brick dev` shows them in its dashboard.\n */\n telemetry?: boolean;\n /**\n * Developer documentation for the `brick dev` dashboard (its Docs tab): a\n * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and\n * `meta.json` for ordering. A string is the folder. Relative paths start at\n * the folder of the app entry, as they read in the file that sets them (from\n * `src/app.ts`, `\"../docs\"` is `docs/` at the project root). Needs\n * `fumadocs-core` and `@mdx-js/mdx` installed.\n */\n documentation?: string | DocumentationOptions;\n /**\n * Monitoring dashboard for `brick start`, on a port of its own and behind\n * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.\n */\n dashboard?: DashboardOptions;\n /**\n * Record events in the same database transaction as the writes that cause them,\n * and deliver them to listeners after the commit. Generated CRUD writes emit\n * `<resource>.create`, `<resource>.update` and `<resource>.delete`. A service\n * records events once its database holds an `outboxTable()`. Reads emit nothing,\n * and an app without this option behaves exactly as before. See `EventsOptions`.\n */\n events?: EventsOptions;\n}\n\nexport {\n compileRoutePlan,\n executeCompiledRoute,\n createActionHandler,\n} from \"./action-handler\";\n\n/**\n * Create the HTTP application: an Elysia app that serves every service's\n * actions (and the tools that opt in with `http: true`) as routes, with\n * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,\n * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.\n *\n * Services come from the global registry unless `services` is given. The app\n * does not listen by itself: export it from your entry file, where `brick dev`,\n * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your\n * own server bootstrap.\n *\n * @param options - `prefix` for action routes (default `/api`), `services`,\n * `title`, `version`, and `description` for the OpenAPI document, `docs` and the\n * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,\n * `telemetry`, `documentation`, and `dashboard`. See `CreateServerOptions`.\n * @returns The app, with `definition` (its services, prefix, and routes),\n * `endpoint()` to add raw routes, and `listEndpoints()` to list them.\n * @throws When a required secret is missing, or `documentation` or `dashboard`\n * is invalid.\n * @example\n * import { brick } from \"@brickkit/core\";\n * import { pagesService } from \"./services/pages\";\n *\n * export default brick({\n * services: [pagesService],\n * title: \"Pages API\",\n * telemetry: true,\n * });\n */\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n const prefix = options.prefix ?? options.compilation?.ir.prefix ?? \"/api\";\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const compiled = options.compiler !== false;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? \"/openapi.json\";\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n const dashboard = normalizeDashboard(options.dashboard);\n // The dashboard shows what is traced, so having one means tracing.\n const telemetry = options.telemetry === true || dashboard !== undefined;\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n // Diagnostics & health\n app.get(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false) {\n const pluginOpts = requestLogging === true ? {} : requestLogging;\n if (pluginOpts.enabled !== false) {\n app.use(requestLoggingPlugin(pluginOpts));\n }\n }\n\n // Scalar API reference page (opt-in): `reference: true`, or options with a path.\n const reference = options.reference ?? false;\n const referenceOptions: ReferenceOptions =\n typeof reference === \"object\" ? reference : {};\n const referencePath =\n reference === true ? \"/reference\" : referenceOptions.path;\n if (referencePath !== undefined) {\n const settings = {\n path: referencePath,\n title: referenceOptions.title ?? title,\n specUrl: referenceOptions.specUrl ?? openApiPath,\n };\n if (compiled)\n app.get(\n settings.path,\n htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)),\n );\n else registerReferenceRoute(app, settings);\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n const events = options.events\n ? new EventsHub(options.events).attach(services)\n : undefined;\n if (events?.workflows)\n app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));\n if (telemetry) {\n for (const service of services) instrumentDatabase(service.getDb());\n }\n\n // Precompute plans and freeze immutable plans across all services\n for (const service of services) {\n if (typeof (service as any).build === \"function\") {\n (service as any).build();\n }\n }\n\n // Raw endpoints declared via options or app.endpoint() (declaration order).\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n const paths = { ...spec.paths };\n for (const [path, operations] of Object.entries(\n endpointPaths(endpointDefs),\n ))\n paths[path] = { ...paths[path], ...operations };\n return { ...spec, paths };\n };\n\n // OpenAPI 3.1 & Interactive Documentation Endpoints\n if (enableDocs) {\n app.get(\n openApiPath,\n compiled\n ? cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n )\n : buildSpec,\n );\n\n if (compiled) {\n app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n } else {\n app.get(docsPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(openApiPath, title);\n });\n\n app.get(swaggerPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return swaggerDocsHTML(openApiPath, title);\n });\n }\n }\n\n // Dedicated Route Registry\n const registeredRoutes = new Map<string, boolean>();\n const routeKey = (method: string, path: string) =>\n `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n registeredRoutes.set(routeKey(\"GET\", \"/_health\"), false);\n registeredRoutes.set(routeKey(\"GET\", \"/_brick/services\"), false);\n if (enableDocs) {\n for (const path of [openApiPath, docsPath, swaggerPath])\n registeredRoutes.set(routeKey(\"GET\", path), false);\n }\n if (referencePath !== undefined)\n registeredRoutes.set(routeKey(\"GET\", referencePath), false);\n\n const sockets = services.flatMap((service) =>\n service.listSockets().map((definition) => ({\n service: service.name,\n path: socketPath(prefix, service.name, definition),\n definition,\n })),\n );\n const socketRoutes = new Set<string>();\n for (const socket of sockets) {\n const key = routeKey(\"GET\", socket.path);\n if (registeredRoutes.has(key) || socketRoutes.has(key))\n throw new Error(`Brick: duplicate socket route '${socket.path}'`);\n socketRoutes.add(key);\n }\n\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any,\n plugin = false,\n ) => {\n const key = routeKey(method, path);\n if (socketRoutes.has(key))\n throw new Error(\n `Brick: route '${method} ${path}' conflicts with a socket`,\n );\n if (registeredRoutes.has(key)) {\n if (plugin || registeredRoutes.get(key))\n throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);\n return false;\n }\n switch (method) {\n case \"GET\":\n app.get(path, handler);\n break;\n case \"POST\":\n app.post(path, handler);\n break;\n case \"PUT\":\n app.put(path, handler);\n break;\n case \"PATCH\":\n app.patch(path, handler);\n break;\n case \"DELETE\":\n app.delete(path, handler);\n break;\n }\n registeredRoutes.set(key, plugin);\n return true;\n };\n\n // Raw endpoints (outside the JSON action mesh).\n const mountEndpoint = (def: EndpointDefinition, plugin = false) => {\n const handler = createEndpointHandler(def, services);\n mountRoute(\n def.method,\n def.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, def.method, def.path, () =>\n handler(context),\n )\n : handler,\n plugin,\n );\n endpointDefs.push(def);\n endpointRevision++;\n };\n\n for (const service of services) {\n for (const def of getPluginEndpoints(service, prefix))\n mountEndpoint(def, true);\n }\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n brickApp.referenceDocuments = async () => {\n const documents: ApiDocument[] = enableDocs\n ? [{ title, document: buildSpec() as unknown as OpenApiDocument }]\n : [];\n for (const extra of referenceOptions.documents ?? []) {\n try {\n const document =\n typeof extra.document === \"function\"\n ? await extra.document()\n : extra.document;\n documents.push({ title: extra.title, document });\n } catch (error) {\n console.warn(\n `[Brick-TS] Skipping the \"${extra.title}\" API document: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return documents;\n };\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n const mountedRoutes: RouteIR[] = [];\n for (const route of compilation.routes) {\n const service = services.find(\n (candidate) => candidate.name === route.ir.service,\n )!;\n const action = service\n .listActions()\n .find((candidate) => candidate.name === route.ir.action)!;\n const invoke = (context: any) => {\n const result = telemetry\n ? withSpan(\n `action ${route.ir.service}.${route.ir.action}`,\n {\n \"brick.service\": route.ir.service,\n \"brick.action\": route.ir.action,\n },\n () => route.handler(context),\n )\n : route.handler(context);\n return result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ? Promise.resolve(result).then(jsonActionResult)\n : jsonActionResult(result);\n };\n const mounted = mountRoute(\n route.ir.method,\n route.ir.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, route.ir.method, route.ir.path, () =>\n invoke(context),\n )\n : invoke,\n getPluginActionRoute(action, prefix) !== undefined,\n );\n if (mounted) mountedRoutes.push(route.ir);\n }\n\n mountSockets(app, sockets);\n const definition = Object.freeze({\n services: Object.freeze([...services]),\n prefix,\n routes: Object.freeze(mountedRoutes),\n sockets: Object.freeze(\n sockets.map(({ service, path, definition }) => ({\n ...definition.schema,\n service,\n path,\n })),\n ),\n telemetry,\n documentation: normalizeDocumentation(options.documentation),\n dashboard,\n ...(events ? { events: events.describe() } : {}),\n });\n Object.defineProperty(brickApp, \"definition\", { value: definition });\n Object.defineProperty(brickApp, \"events\", { value: events });\n getGlobalRegistry().setApplicationRoutes(definition);\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n app.get(\n \"/_brick/services\",\n compiled\n ? cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(definition),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n )\n : () => getGlobalRegistry().exportArchitecture(definition),\n );\n\n return brickApp;\n}\n\nfunction normalizeDocumentation(\n documentation: string | DocumentationOptions | undefined,\n): DocumentationOptions | undefined {\n if (documentation === undefined) return undefined;\n const options =\n typeof documentation === \"string\" ? { dir: documentation } : documentation;\n if (typeof options.dir !== \"string\" || options.dir === \"\")\n throw new Error(\"Brick: documentation needs a folder, such as './docs'.\");\n return Object.freeze({\n dir: options.dir,\n ...(options.components ? { components: options.components } : {}),\n });\n}\n\nfunction jsonActionResult(value: unknown): unknown {\n return value === null\n ? new Response(\"null\", { headers: { \"content-type\": \"application/json\" } })\n : value;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n","import type { RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input\n ? \"params, body, query, headers, request, set\"\n : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\")\n input.push(\n `if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`,\n );\n else if (coercion.type === \"array\")\n input.push(\n `if (v${index} !== undefined) { const values${index} = request ? new URL(request.url).searchParams.getAll(${key}) : []; coercedQuery[${key}] = values${index}.length ? values${index} : Array.isArray(v${index}) ? v${index} : [v${index}]; }`,\n );\n else\n input.push(\n `if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`,\n );\n }\n input.push(\"}\");\n }\n input.push(\n `input = mergeInput(${route.inputPrecedence.map((source) => (source === \"query\" ? \"coercedQuery\" : source)).join(\", \")});`,\n );\n if ((route.inputSchema as { type?: string } | undefined)?.type === \"object\")\n input.push(\"input ??= {};\");\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context\n ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\"\n : \"\";\n const validation = route.input\n ? `checkDepth(input, ${name}); validate(inputChecker, input, ${name}, \"input\");`\n : \"\";\n const authorization = route.authorize\n ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name}, ctx.user);`\n : \"\";\n const output = route.output\n ? `validate(outputChecker, result, ${name}, \"output\");`\n : \"\";\n const execute = asyncStages\n ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;`\n : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set, ctx));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, checkDepth, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set, ctx); }\n};\n}`;\n}\n","import type { TSchema } from \"@sinclair/typebox\";\nimport { defineAction } from \"./action\";\nimport type {\n Tool,\n ToolConfigWithAuthorize,\n ToolConfigWithoutAuthorize,\n ActionErrorDefinition,\n ActionContext,\n} from \"./types\";\n\n/**\n * Define a tool: an action that AI agents can call through MCP. It takes the\n * same configuration as `defineAction` (validation, `authorize`, errors), plus\n * `title`, `annotations` (the MCP hints about what the tool does), and `http`\n * to also serve it over HTTP and in OpenAPI (off by default).\n *\n * @param config - An action configuration and tool options. `input` must be an\n * object schema, since MCP passes arguments by name.\n * @returns The tool, which is also an action. Register it with `service.tool(tool)`.\n * @throws When `input` is not an object schema.\n * @example\n * import { defineTool, t } from \"@brickkit/core\";\n *\n * export const echoTool = defineTool({\n * name: \"echo\",\n * title: \"Echo a message\",\n * description: \"Returns the message it is given.\",\n * input: t.Object({ message: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `Echo: ${input.message}`,\n * });\n */\nexport function defineTool<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ToolConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ToolConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool(config: any): any {\n if (config.input && config.input.type !== \"object\") {\n throw new Error(`Tool '${config.name}' input must be an object schema`);\n }\n const tool = defineAction(config);\n Object.defineProperty(tool, \"kind\", { value: \"tool\" });\n return tool;\n}\n\n/**\n * Whether a value was made with `defineTool`, as opposed to `defineAction`.\n *\n * @param value - Anything.\n * @returns `true` for a tool, narrowing its type.\n */\nexport function isTool(value: unknown): value is Tool<any, any, any, any> {\n return typeof value === \"function\" && (value as Tool).kind === \"tool\";\n}\n","import type { Database } from \"bun:sqlite\";\nimport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nimport { createRequire } from \"node:module\";\n\nconst requireSQLite = createRequire(import.meta.url);\n\nexport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nexport {\n sqliteTable,\n text,\n integer,\n real,\n blob,\n index,\n uniqueIndex,\n primaryKey,\n foreignKey,\n} from \"drizzle-orm/sqlite-core\";\n\nexport interface SQLiteDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Database file path or ':memory:' (default: ':memory:') */\n path?: string;\n /** Alias for path */\n filename?: string;\n /** Whether to enable WAL journal mode for file-based DBs (default: true) */\n wal?: boolean;\n /** Whether to enforce foreign key constraints (default: true) */\n foreignKeys?: boolean;\n /** Optional existing bun:sqlite Database instance */\n client?: Database;\n /** Optional Drizzle schema object for typed relational queries */\n schema?: TSchema;\n}\n\nexport type BrickSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = BunSQLiteDatabase<TSchema> & {\n $client: Database;\n};\n\n/**\n * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine\n * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).\n *\n * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on\n * other runtimes (e.g. Node) stays safe until this function is actually\n * called.\n */\nexport function createSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: SQLiteDatabaseConfig<TSchema> = {}): BunSQLiteDatabase<TSchema> {\n let Database: new (path: string) => Database;\n let drizzle: (\n client: Database,\n config?: { schema?: TSchema },\n ) => BunSQLiteDatabase<TSchema>;\n try {\n ({ Database } = requireSQLite(\"bun:sqlite\"));\n // Keep the adapter lazy for Node imports, but visible to Bun's bundler.\n ({ drizzle } = require(\"drizzle-orm/bun-sqlite\"));\n } catch (err: any) {\n throw new Error(\n `[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`,\n );\n }\n const filePath = config.filename ?? config.path ?? \":memory:\";\n const client = config.client ?? new Database(filePath);\n\n if (config.foreignKeys !== false) {\n client.run(\"PRAGMA foreign_keys = ON;\");\n }\n\n if (config.wal !== false && filePath !== \":memory:\") {\n client.run(\"PRAGMA journal_mode = WAL;\");\n }\n\n const db = (\n config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client)\n ) as BunSQLiteDatabase<TSchema>;\n\n if (!(db as any).$client) {\n (db as any).$client = client;\n }\n\n return db;\n}\n","import postgres, { type Sql } from \"postgres\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\n\nexport interface PostgresDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */\n client?: Sql;\n /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */\n url?: string;\n /** Connection string alias */\n connectionString?: string;\n host?: string;\n port?: number;\n user?: string;\n password?: string;\n database?: string;\n ssl?: boolean | \"require\" | \"allow\" | \"prefer\" | \"verify-full\";\n max?: number;\n /**\n * Disable prepared statements (required for transaction-mode poolers such\n * as Supabase's Supavisor on :6543, which cannot hold named prepared\n * statements across transactions).\n */\n prepare?: boolean;\n /** Optional Drizzle schema for relational queries */\n schema?: TSchema;\n /** Custom schema name for Encore-style isolated schemas */\n schemaName?: string;\n}\n\nexport type PostgresDatabase<\n _TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = any;\n\nexport interface DatabaseAdapter<TDb = any, TConfig = any> {\n createDatabase(config?: TConfig): TDb;\n}\n\n/**\n * Creates a PostgreSQL Drizzle instance using postgres-js.\n * Static imports (both are hard dependencies in package.json) so bundlers\n * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in\n * `sqlite.ts` since it only exists under Bun.\n */\nexport function createPostgresDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: PostgresDatabaseConfig<TSchema> = {}): PostgresDatabase<TSchema> {\n const connectionUrl =\n config.url ??\n config.connectionString ??\n (typeof process !== \"undefined\" ? process.env?.DATABASE_URL : undefined);\n\n const client =\n config.client ??\n (connectionUrl\n ? postgres(connectionUrl, {\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n })\n : postgres({\n host: config.host ?? \"localhost\",\n port: config.port ?? 5432,\n user: config.user,\n password: config.password,\n database: config.database,\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n }));\n\n return drizzle(client, {\n schema: config.schema,\n ...(config.schemaName ? { schemaFilter: [config.schemaName] } : {}),\n });\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { type Table, getTableName } from \"drizzle-orm\";\nimport type { PostgresJsDatabase } from \"drizzle-orm/postgres-js\";\nimport type { Sql } from \"postgres\";\nimport { SecretRef } from \"../secrets\";\nimport {\n createSQLiteDatabase,\n type SQLiteDatabaseConfig,\n type BunSQLiteDatabase,\n type BrickSQLiteDatabase,\n} from \"./sqlite\";\nimport {\n createPostgresDatabase,\n type PostgresDatabaseConfig,\n} from \"./postgres\";\n\nexport type EnvInput<T> = T | SecretRef<T>;\ntype EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>> };\n\ninterface DefinitionOptions<TSchema extends Record<string, unknown>> {\n name?: string;\n /** Drizzle tables retained for schema tooling. Never applied at runtime. */\n tables?: (TSchema & Record<string, Table>) | readonly Table[];\n schema?: TSchema;\n}\n\nexport type SQLiteDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine?: \"sqlite\";\n client?: SQLiteDatabaseConfig<TSchema>[\"client\"];\n url?: never;\n connectionString?: never;\n };\n\nexport type PostgresDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine: \"postgres\";\n path?: never;\n filename?: never;\n wal?: never;\n foreignKeys?: never;\n client?: PostgresDatabaseConfig<TSchema>[\"client\"];\n };\n\nexport type DatabaseDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;\n\nexport interface DatabaseHandle<\n TDb,\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n readonly kind: \"brick-database\";\n readonly name?: string;\n readonly engine: \"sqlite\" | \"postgres\";\n readonly tables: Readonly<Record<string, Table>>;\n readonly schema: TSchema;\n getDb(): TDb;\n close?(): void | Promise<void>;\n}\n\n/**\n * Whether a value is a database handle made by `defineDatabase`.\n *\n * @param value - Anything.\n * @returns `true` for a handle, narrowing its type.\n */\nexport function isDatabaseHandle(\n value: unknown,\n): value is DatabaseHandle<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n value.kind === \"brick-database\"\n );\n}\n\n/**\n * Declare a service's database: its engine, its Drizzle tables, and how to\n * reach it. Nothing connects until the handle is used (`getDb()`), so defining\n * one has no side effects.\n *\n * SQLite is the default and needs no options. Pass `engine: \"postgres\"` with a\n * `url` for Postgres. Options that belong to the other engine (such as `url` for\n * SQLite, or `path` for Postgres) are refused.\n *\n * @param options - `engine` (`\"sqlite\"` or `\"postgres\"`), `tables`, an optional\n * `name`, and the engine's connection settings.\n * @returns A handle to give to `defineService({ database })`. `getDb()` returns\n * the Drizzle database.\n * @throws When the engine is unsupported, or an option does not suit the engine.\n * @example\n * import { defineDatabase } from \"@brickkit/core\";\n * import { sqliteTable, text } from \"drizzle-orm/sqlite-core\";\n *\n * const pages = sqliteTable(\"pages\", {\n * id: text(\"id\").primaryKey(),\n * title: text(\"title\").notNull(),\n * });\n *\n * export const database = defineDatabase({ tables: { pages } });\n */\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options?: SQLiteDefinition<TSchema>,\n): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>;\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options: PostgresDefinition<TSchema>,\n): DatabaseHandle<PostgresJsDatabase<TSchema> & { $client: Sql }, TSchema>;\nexport function defineDatabase(\n options: DatabaseDefinition = {},\n): DatabaseHandle<unknown> {\n const engine = options.engine ?? \"sqlite\";\n if (engine !== \"sqlite\" && engine !== \"postgres\") {\n throw new Error(`Unsupported database engine: ${engine}`);\n }\n const forbidden =\n engine === \"sqlite\"\n ? [\n \"url\",\n \"connectionString\",\n \"host\",\n \"port\",\n \"user\",\n \"password\",\n \"database\",\n \"ssl\",\n \"max\",\n \"schemaName\",\n ]\n : [\"path\", \"filename\", \"wal\", \"foreignKeys\"];\n for (const key of forbidden) {\n if (key in options)\n throw new Error(`Database option \"${key}\" is not valid for ${engine}`);\n }\n const declared = options.tables ?? {};\n const tables: Record<string, Table> = Array.isArray(declared)\n ? Object.fromEntries(declared.map((table) => [getTableName(table), table]))\n : { ...declared };\n const schema = options.schema ?? tables;\n let db: unknown;\n let closeClient: (() => void | Promise<void>) | undefined;\n let closed = false;\n let closing: void | Promise<void>;\n\n return {\n kind: \"brick-database\",\n name: options.name,\n engine,\n tables: Object.freeze(tables),\n schema,\n close() {\n if (closed) return closing;\n closed = true;\n closing = closeClient?.();\n return closing;\n },\n getDb() {\n if (closed) throw new Error(\"Brick database handle is closed\");\n if (db !== undefined) return db;\n const config: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if ([\"tables\", \"schema\", \"name\", \"engine\"].includes(key)) continue;\n // An injected Postgres client already owns all connection settings.\n if (\n engine === \"postgres\" &&\n options.client &&\n key !== \"client\" &&\n key !== \"schemaName\"\n )\n continue;\n config[key] = value instanceof SecretRef ? value.require() : value;\n }\n if (engine === \"sqlite\") {\n const path = (config.filename ?? config.path ?? \":memory:\") as string;\n if (!config.client && path !== \":memory:\")\n mkdirSync(dirname(path), { recursive: true });\n const instance = createSQLiteDatabase({ ...config, schema });\n db = instance;\n if (!options.client)\n closeClient = () => (instance as BrickSQLiteDatabase).$client.close();\n } else {\n const instance: PostgresJsDatabase & { $client: Sql } =\n createPostgresDatabase({ ...config, schema });\n db = instance;\n if (!options.client) closeClient = () => instance.$client.end();\n }\n return db;\n },\n };\n}\n","import type { Service } from \"../types\";\nimport type { DatabaseHandle } from \"./define\";\nimport {\n createSQLiteDatabase,\n type SQLiteDatabaseConfig,\n type BunSQLiteDatabase,\n} from \"./sqlite\";\nimport {\n createPostgresDatabase,\n type PostgresDatabaseConfig,\n type PostgresDatabase,\n} from \"./postgres\";\nimport { getTableColumns, getTableName, sql } from \"drizzle-orm\";\n\nexport * from \"./sqlite\";\nexport * from \"./postgres\";\nexport * from \"./define\";\n\n// Re-export core Drizzle SQL expressions & operators for convenience\nexport {\n sql,\n eq,\n ne,\n gt,\n gte,\n lt,\n lte,\n and,\n or,\n not,\n desc,\n asc,\n inArray,\n notInArray,\n isNull,\n isNotNull,\n like,\n ilike,\n relations,\n getTableColumns,\n getTableName,\n Table,\n is,\n} from \"drizzle-orm\";\n\nexport interface DatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>\n extends\n Omit<SQLiteDatabaseConfig<TSchema>, \"client\">,\n Omit<PostgresDatabaseConfig<TSchema>, \"client\"> {\n client?:\n | SQLiteDatabaseConfig<TSchema>[\"client\"]\n | PostgresDatabaseConfig<TSchema>[\"client\"];\n /** Database engine. Default: 'sqlite' */\n engine?: \"sqlite\" | \"postgres\" | \"clickhouse\";\n /** Optional service name associated with this database */\n name?: string;\n}\n\nexport type BrickDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;\n\n/**\n * Creates a database instance based on the provided configuration.\n * Zero-config: calling `createDatabase()` returns an ultra-fast Bun-native SQLite\n * database in `:memory:` mode wrapped with Drizzle ORM.\n */\nexport function createDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n config: DatabaseConfig<TSchema> = {},\n): BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema> {\n const engine = config.engine ?? \"sqlite\";\n\n if (engine === \"sqlite\") {\n return createSQLiteDatabase<TSchema>(\n config as SQLiteDatabaseConfig<TSchema>,\n );\n }\n\n if (engine === \"postgres\") {\n return createPostgresDatabase<TSchema>(\n config as PostgresDatabaseConfig<TSchema>,\n );\n }\n\n throw new Error(`[Brick-TS DB] Unsupported database engine: '${engine}'`);\n}\n\n/** Attach a defined database. Schema changes remain the caller's responsibility. */\nexport function attachDatabase<TDb>(\n service: Service<TDb, any>,\n database: DatabaseHandle<TDb>,\n): TDb {\n service.setDb(database);\n return database.getDb();\n}\n\n/**\n * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition\n * directly from a Drizzle table schema.\n */\nexport function generateSQLiteTableDdl(table: any): string {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colDefs: string[] = [];\n\n for (const [, col] of Object.entries(columns) as [string, any][]) {\n let def = `\"${col.name}\" ${col.getSQLType().toUpperCase()}`;\n if (col.primary) def += \" PRIMARY KEY\";\n if (col.notNull) def += \" NOT NULL\";\n if (col.isUnique) def += \" UNIQUE\";\n if (col.hasDefault) {\n if (typeof col.default === \"string\") {\n def += ` DEFAULT '${col.default.replace(/'/g, \"''\")}'`;\n } else if (typeof col.default === \"boolean\") {\n def += ` DEFAULT ${col.default ? 1 : 0}`;\n } else if (typeof col.default === \"number\") {\n def += ` DEFAULT ${col.default}`;\n } else if (col.default !== undefined) {\n def += ` DEFAULT ${col.default}`;\n }\n }\n colDefs.push(def);\n }\n\n return `CREATE TABLE IF NOT EXISTS \"${tableName}\" (\\n ${colDefs.join(\",\\n \")}\\n);`;\n}\n\n/**\n * Generates idempotent secondary index DDL for a Drizzle table.\n * Covers owner scoping, sort columns, and exact-match filters.\n * UNIQUE columns already carry an implicit index — skipped here.\n * FTS/trigram indexes are handled separately by the search layer.\n */\nexport function generateSQLiteIndexDdl(\n table: any,\n opts: { ownerField?: string; sortFields?: string[] } = {},\n): string[] {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const stmts: string[] = [];\n const seen = new Set<string>();\n const push = (name: string, cols: string[]) => {\n const clean = cols.filter(Boolean);\n if (clean.length === 0) return;\n const key = `${name}(${clean.join(\",\")})`;\n if (seen.has(key)) return;\n seen.add(key);\n const colList = clean.map((c) => `\"${c}\"`).join(\", \");\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"${name}\" ON \"${tableName}\" (${colList});`,\n );\n };\n\n const colNameOf = (field: string): string | undefined => {\n if ((columns as any)[field]) return (columns as any)[field].name ?? field;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === field) return col.name;\n }\n return undefined;\n };\n\n // Owner scope index: WHERE user_id = ? (+ sort composite below).\n let ownerCol: string | undefined;\n if (opts.ownerField) {\n const oc = colNameOf(opts.ownerField);\n if (oc) {\n ownerCol = oc;\n push(`idx_${tableName}_${oc}`, [oc]);\n }\n }\n\n // Sort column indexes (updated_at / created_at drive default ORDER BY).\n const sorts = opts.sortFields ?? [\"updated_at\", \"created_at\"];\n const sortCols: string[] = [];\n for (const f of sorts) {\n const c = colNameOf(f);\n if (c) {\n sortCols.push(c);\n push(`idx_${tableName}_${c}`, [c]);\n }\n }\n\n // Composite owner+sort — the hot path for scoped sorted lists.\n if (ownerCol && sortCols.length > 0) {\n push(`idx_${tableName}_${ownerCol}_${sortCols[0]}`, [\n ownerCol,\n sortCols[0],\n ]);\n }\n\n return stmts;\n}\n\n/**\n * Ensures secondary indexes exist for a resource table.\n * SQLite: B-tree indexes for owner scope + sort + composite hot path.\n * Postgres: same B-trees plus pg_trgm GIN indexes for substring search.\n * Best-effort: failures warn and continue (e.g. read-only replicas).\n */\nexport function ensureResourceIndexes(\n db: any,\n table: any,\n opts: {\n ownerField?: string;\n sortFields?: string[];\n searchFields?: string[];\n } = {},\n): void {\n if (!db) return;\n const isPostgres =\n typeof (db as any).execute === \"function\" && !(db as any).$client?.run;\n const stmts = generateSQLiteIndexDdl(table, opts);\n // Postgres trigram support for LIKE %term% (requires superuser for extension;\n // failure is silently ignored — LIKE still works, just slower).\n if (isPostgres && opts.searchFields && opts.searchFields.length > 0) {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n for (const f of opts.searchFields) {\n const c = colNameOf(f);\n if (c) {\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"idx_${tableName}_${c}_trgm\" ON \"${tableName}\" USING gin (\"${c}\" gin_trgm_ops);`,\n );\n }\n }\n }\n if (stmts.length === 0) return;\n const run = (stmt: string) => {\n try {\n if ((db as any).$client?.run) {\n (db as any).$client.run(stmt);\n } else if (typeof (db as any).execute === \"function\") {\n void (db as any).execute(sql.raw(stmt)).catch(() => {});\n } else if ((db as any).run) {\n (db as any).run(stmt);\n }\n } catch {\n // best-effort\n }\n };\n if (isPostgres) {\n run(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);\n }\n for (const s of stmts) run(s);\n}\n\n/**\n * SQLite FTS5 search layer for resource list (?search=).\n * B-tree indexes cannot serve LIKE '%term%' (leading wildcard forces a full\n * scan). FTS5 gives indexed substring/prefix search on title/slug-scale text.\n * Postgres uses ilike + pg_trgm GIN indexes instead (see ensureResourceIndexes).\n */\n\nfunction ftsTableName(table: any): string {\n return `${getTableName(table)}_fts`;\n}\n\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.\n * Idempotent; safe to call on every resource registration.\n * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.\n */\nexport function ensureSQLiteFts(\n db: any,\n table: any,\n searchCols: string[],\n): void {\n if (!db || searchCols.length === 0) return;\n // SQLite only: Postgres has execute() but no $client.run.\n const client = (db as any).$client;\n const runRaw = (db as any).run;\n if (!client?.run && !runRaw) return;\n const run = (stmt: string) => {\n if (client?.run) client.run(stmt);\n else runRaw(stmt);\n };\n try {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n // Resolve to DB column names, drop unknowns.\n const dbCols = searchCols.map(colNameOf).filter((c): c is string => !!c);\n if (dbCols.length === 0) return;\n const idCol =\n colNameOf(\"id\") ??\n (Object.values(columns) as any[]).find((c) => c.primary)?.name ??\n \"id\";\n const fts = ftsTableName(table);\n const ftsCols = [\n `\"id\" UNINDEXED`,\n ...dbCols.map((c) => quoteIdent(c)),\n ].join(\", \");\n run(\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${quoteIdent(fts)} USING fts5(${ftsCols}, tokenize='porter');`,\n );\n const colList = dbCols.map(quoteIdent).join(\", \");\n const newVals = dbCols.map((c) => `new.${quoteIdent(c)}`).join(\", \");\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ai`)} AFTER INSERT ON ${quoteIdent(tableName)} BEGIN INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_au`)} AFTER UPDATE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n // Backfill rows predating the FTS table (dedupe via NOT IN).\n run(\n `INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT \"id\" FROM ${quoteIdent(fts)});`,\n );\n } catch {\n // best-effort: LIKE fallback in the list path covers FTS absence.\n }\n}\n\n/**\n * Builds an FTS5 MATCH condition for a resource search term.\n * Returns null when the term has no usable tokens or FTS errors.\n * Caller falls back to LIKE in that case.\n */\nexport function buildFtsMatchQuery(search: string): string | null {\n const terms = search\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean)\n .slice(0, 10);\n if (terms.length === 0) return null;\n const escaped = terms\n .map((term) => {\n const clean = term.replace(/\"/g, \"\").trim();\n if (!clean) return null;\n return `\"${clean.replace(/\"/g, '\"\"')}\"*`;\n })\n .filter((x): x is string => !!x);\n if (escaped.length === 0) return null;\n return escaped.join(\" AND \");\n}\n\n/**\n * Explicit SQLite development/test schema preparation helper.\n * Never called by services, resources, auth, or server startup.\n * Not a migration runner; PostgreSQL schema management is caller-owned.\n */\nexport function syncSchema(\n tablesOrService: Map<string, any> | any[] | Record<string, any> | Service,\n dbInstance?: any,\n): Promise<void> | void {\n let db = dbInstance;\n let tables: any[] = [];\n\n if (\n tablesOrService &&\n typeof (tablesOrService as any).listActions === \"function\" &&\n (tablesOrService as any).tables\n ) {\n const service = tablesOrService as Service;\n tables = Array.from(service.tables.values());\n if (!db) {\n db = service.getDb();\n }\n } else if (tablesOrService instanceof Map) {\n tables = Array.from(tablesOrService.values());\n } else if (Array.isArray(tablesOrService)) {\n tables = tablesOrService;\n } else if (tablesOrService && typeof tablesOrService === \"object\") {\n tables = Object.values(tablesOrService);\n }\n\n if (!db || tables.length === 0) return;\n\n // Bun SQLite\n if ((db as any).$client?.run || (db as any).run) {\n for (const table of tables) {\n try {\n const ddl = generateSQLiteTableDdl(table);\n if ((db as any).$client?.run) {\n (db as any).$client.run(ddl);\n } else if ((db as any).run) {\n (db as any).run(sql.raw(ddl));\n }\n } catch (err: any) {\n console.warn(`[Brick-TS DB] Failed to create table:`, err.message);\n }\n }\n return;\n }\n\n // Postgres async mode\n return (async () => {\n for (const table of tables) {\n try {\n const _tableName = getTableName(table);\n // Postgres sync or migration runner if configured\n } catch (err: any) {\n console.warn(`[Brick-TS DB] Postgres syncSchema error:`, err.message);\n }\n }\n })();\n}\n","import { getTableColumns, type Column } from \"drizzle-orm\";\nimport { installPlugin } from \"./plugin\";\nimport type {\n ActionContext,\n Resource,\n ResourceConfig,\n ResourceTypeOptions,\n ResourceIdentity,\n Service,\n} from \"./types\";\n\n/** Declares a plugin host without registering actions or changing the schema. */\nexport function defineResource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n const O extends ResourceTypeOptions = ResourceTypeOptions,\n>(\n service: Service<any, any>,\n config: ResourceConfig<TTable, TCtx> & O,\n): Resource<TTable, TCtx, ResourceIdentity<TTable, O>> {\n const columns = getTableColumns(\n config.table as Parameters<typeof getTableColumns>[0],\n );\n const primary = Object.entries(columns).filter(\n ([, column]) => column.primary,\n );\n const id: Column | undefined =\n config.id ?? (primary.length === 1 ? primary[0]?.[1] : undefined);\n const entry = Object.entries(columns).find(([, column]) => column === id);\n if (!entry || !id)\n throw new Error(\n `Resource '${config.name}' requires an id column belonging to its table`,\n );\n if (\n !config.name ||\n config.name.includes(\"/\") ||\n [\"__proto__\", \"constructor\", \"prototype\"].includes(config.name)\n )\n throw new Error(`Invalid resource name '${config.name}'`);\n service.registerTable(config.table);\n const resource = {\n name: config.name,\n serviceName: service.name,\n table: config.table,\n id,\n idField: entry[0],\n config: Object.freeze({ ...config, id }),\n use(plugin: import(\"./plugin\").ResourcePlugin<any, any, any>) {\n return installPlugin(\n service,\n resource as Resource<TTable, TCtx, ResourceIdentity<TTable, O>>,\n plugin,\n );\n },\n };\n return resource as Resource<TTable, TCtx, ResourceIdentity<TTable, O>>;\n}\n","import type { BaseContext } from \"./types\";\n\ntype ContextEnvelope = Pick<\n BaseContext,\n \"caller\" | \"traceId\" | \"requestId\" | \"tenantId\"\n> & { user?: unknown };\n\nexport function pickContextEnvelope(\n context?: Partial<BaseContext> & { user?: unknown },\n): Partial<ContextEnvelope> {\n if (!context) return {};\n const envelope: Partial<ContextEnvelope> = {};\n if (context.caller !== undefined) envelope.caller = context.caller;\n if (context.user !== undefined) envelope.user = context.user;\n if (context.traceId !== undefined) envelope.traceId = context.traceId;\n if (context.requestId !== undefined) envelope.requestId = context.requestId;\n if (context.tenantId !== undefined) envelope.tenantId = context.tenantId;\n return envelope;\n}\n","import {\n installPlugin,\n isInstallingPlugin,\n type ServicePlugin,\n} from \"./plugin\";\nimport type { TSchema } from \"@sinclair/typebox\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type {\n Service,\n ServiceOptions,\n Action,\n Tool,\n ToolConfigWithAuthorize,\n ToolConfigWithoutAuthorize,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionErrorDefinition,\n ServiceSchema,\n BaseContext,\n Logger,\n Resource,\n ResourceConfig,\n ResourceTypeOptions,\n ResourceIdentity,\n PreparationContribution,\n} from \"./types\";\nimport { defineTool, isTool } from \"./tool\";\nimport { defineAction } from \"./action\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getTableName, isDatabaseHandle, type DatabaseHandle } from \"./db\";\nimport { defineResource } from \"./resource\";\nimport { isOutboxTable, type OutboxTable } from \"./events/outbox\";\nimport type { ServiceEvents } from \"./events/types\";\nimport { getActionAccess } from \"./access\";\nimport { pickContextEnvelope } from \"./context\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\nimport { defineServiceSocket, type RegisteredSocket } from \"./socket\";\nimport type { BrickSocketConfig, SocketSchemas } from \"./socket-types\";\n\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nconst EMPTY_SERVICES = Object.freeze({});\nconst EMPTY_METADATA = Object.freeze({});\nlet _ctxSeq = 0;\n\n// Symbol to tie context resolution to a specific service instance and invocation\nconst RESOLVED_SYMBOL = Symbol(\"resolved\");\n\nexport class ServiceImpl<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> implements Service<TDb, TServiceContext> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n readonly actions = new Map<string, Action<any, any, any, any>>();\n readonly tools = new Map<string, Tool<any, any, any, any>>();\n readonly tables = new Map<string, any>();\n private readonly sockets = new Map<string, RegisteredSocket>();\n readonly resources = new Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >();\n readonly preparations = new Map<string, PreparationContribution>();\n private database?: DatabaseHandle<TDb>;\n private _isBuilt = false;\n\n constructor(\n name: string,\n options: ServiceOptions<TServiceContext, TDb> = {},\n ) {\n this.name = name;\n this.options = options;\n if (options.database !== undefined && !isDatabaseHandle(options.database)) {\n throw new Error(\"Service database must be created with defineDatabase()\");\n }\n this.database = options.database;\n }\n\n use<A>(plugin: ServicePlugin<this, A>): A {\n return installPlugin(this, undefined, plugin) as A;\n }\n\n get db(): TDb | undefined {\n return this.getDb();\n }\n\n get isBuilt(): boolean {\n return this._isBuilt;\n }\n\n /**\n * Closes declarations after plugins have registered their actions and preparations.\n */\n build(): this {\n if (isInstallingPlugin(this))\n throw new Error(\"Cannot build a service during plugin setup\");\n if (this._isBuilt) return this;\n this._isBuilt = true;\n return this;\n }\n\n contributePreparation(contribution: PreparationContribution): void {\n if (this._isBuilt)\n throw new Error(\"Preparations must be registered before service build\");\n if (this.preparations.has(contribution.name))\n throw new Error(`Duplicate preparation '${contribution.name}'`);\n this.preparations.set(contribution.name, contribution);\n getGlobalRegistry().touch();\n }\n\n listPreparations(): PreparationContribution[] {\n return [...this.preparations.values()];\n }\n prepareContributions(): void {\n for (const contribution of this.preparations.values())\n contribution.prepare();\n }\n\n registerTable(table: any): this {\n try {\n const tableName = getTableName(table);\n this.tables.set(tableName, table);\n } catch {\n const fallbackName =\n (table as any)._?.name ?? `table_${this.tables.size + 1}`;\n this.tables.set(fallbackName, table);\n }\n\n return this;\n }\n\n // The public signature preserves config literals; runtime registration stores\n // resources with different tables in the same map.\n resource = <\n TTable = any,\n const TOptions extends ResourceTypeOptions = ResourceTypeOptions,\n >(\n config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> &\n TOptions &\n Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>,\n ): Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n > => {\n if (this._isBuilt)\n throw new Error(\"Resources must be registered before service build\");\n if (this.resources.has(config.name))\n throw new Error(`Duplicate plugin resource: ${config.name}`);\n const resourceInstance = defineResource(this, config);\n this.resources.set(resourceInstance.name, resourceInstance);\n getGlobalRegistry().touch();\n return resourceInstance as Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n >;\n };\n\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined {\n return this.resources.get(name);\n }\n\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[] {\n return Array.from(this.resources.values());\n }\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n action(actionOrConfig: any): any {\n let actionInstance: Action<any, any, any, any>;\n const isActionFunction =\n typeof actionOrConfig === \"function\" && \"config\" in actionOrConfig;\n\n if (isActionFunction) {\n actionInstance = actionOrConfig;\n } else {\n actionInstance = defineAction(actionOrConfig);\n }\n\n if (\n isInstallingPlugin(this) &&\n this.actions.has(actionInstance.name) &&\n this.actions.get(actionInstance.name) !== actionInstance\n )\n throw new Error(`Duplicate plugin action: ${actionInstance.name}`);\n if (isTool(actionInstance)) actionInstance.config.http = true;\n actionInstance.serviceName = this.name;\n (actionInstance as any).service = this;\n this.actions.set(actionInstance.name, actionInstance);\n getGlobalRegistry().touch();\n\n if (isActionFunction) {\n return this;\n }\n return actionInstance;\n }\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n tool(toolOrConfig: any): any {\n const existing = isTool(toolOrConfig);\n const tool = existing ? toolOrConfig : defineTool(toolOrConfig);\n if (this.tools.has(tool.name))\n throw new Error(`Duplicate tool: ${tool.name}`);\n tool.serviceName = this.name;\n (tool as any).service = this;\n this.tools.set(tool.name, tool);\n if (tool.config.http) this.action(tool);\n getGlobalRegistry().touch();\n return existing ? this : tool;\n }\n\n getTool(name: string): Tool<any, any, any, any> | undefined {\n return this.tools.get(name);\n }\n\n socket<const I extends SocketSchemas, const O extends SocketSchemas>(\n config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext>,\n ): this {\n if (this._isBuilt)\n throw new Error(\"Sockets must be declared before service build\");\n if (this.sockets.has(config.name))\n throw new Error(`Duplicate socket: ${config.name}`);\n this.sockets.set(\n config.name,\n defineServiceSocket(config, (request) =>\n resolveServiceContext(this, { request }),\n ),\n );\n getGlobalRegistry().touch();\n return this;\n }\n\n listSockets(): RegisteredSocket[] {\n return [...this.sockets.values()];\n }\n\n listTools(): Tool<any, any, any, any>[] {\n return Array.from(this.tools.values());\n }\n\n getAction(name: string): Action<any, any, any, any> | undefined {\n return this.actions.get(name);\n }\n\n listActions(): Action<any, any, any, any>[] {\n return Array.from(new Set(this.actions.values()));\n }\n\n getDb(): TDb | undefined {\n return this.database?.getDb();\n }\n\n /** What a write needs to record events. Set by `brick({ events })`. */\n events?: ServiceEvents;\n\n getOutbox(): OutboxTable | undefined {\n return Object.values(this.database?.tables ?? {}).find(isOutboxTable);\n }\n\n setEvents(events: ServiceEvents | undefined): void {\n this.events = events;\n }\n\n setDb(database: DatabaseHandle<TDb>): void {\n if (!isDatabaseHandle(database))\n throw new Error(\"Use defineDatabase() to set a service database\");\n this.database = database;\n getGlobalRegistry().touch();\n }\n\n /**\n * Resolves the complete service execution context once per incoming request.\n * Merges framework BaseContext with the service's custom context hook.\n * Always rebuilds context for this service to prevent caller context from overriding.\n */\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n ): Promise<BaseContext<TDb> & TServiceContext> {\n return resolveServiceContext(this, callCtx);\n }\n\n introspect(): ServiceSchema {\n const databaseConfig = this.database\n ? {\n name: this.database.name,\n engine: this.database.engine,\n tables: Object.keys(this.database.tables),\n }\n : undefined;\n // The schema is data. A function among the options (context, an auth policy,\n // lifecycle hooks) cannot cross to the dev dashboard: structured clone\n // refuses the whole architecture. JSON keeps the data and drops the rest.\n const { database: _database, ...config } = this.options;\n const options: ServiceSchema[\"options\"] = JSON.parse(\n JSON.stringify(config),\n );\n return {\n name: this.name,\n options,\n hasDatabase: Boolean(this.database),\n sockets: this.listSockets().map((socket) => socket.schema),\n databaseConfig,\n actions: this.listActions().map((act) => {\n const access = getActionAccess(act);\n return {\n name: act.name,\n serviceName: this.name,\n ...((act as { plugin?: string }).plugin\n ? { plugin: (act as { plugin?: string }).plugin }\n : {}),\n ...((act as { resource?: string }).resource\n ? { resource: (act as { resource?: string }).resource }\n : {}),\n description: act.config.description,\n inputSchema: act.config.input,\n outputSchema: act.config.output,\n hasAuthorize: access.hasAuthorize,\n hasScope: access.hasScope,\n accessPolicy: access.policy,\n errors: act.config.errors,\n emits: act.config.emits,\n tags: act.config.tags,\n };\n }),\n tools: this.listTools().map((tool) => ({ name: tool.name })),\n resources: this.listResources().map((res) => ({\n name: res.name,\n })),\n };\n }\n}\n\nasync function resolveServiceContext<\n TDb,\n TServiceContext extends Record<string, any>,\n>(\n service: ServiceImpl<TDb, TServiceContext>,\n callCtx?: Partial<BaseContext<TDb>> & { user?: unknown },\n): Promise<BaseContext<TDb> & TServiceContext> {\n // Only a context this service resolved itself is accepted as it is.\n if ((callCtx as any)?.[RESOLVED_SYMBOL] === service) {\n return callCtx as BaseContext<TDb> & TServiceContext;\n }\n const seq = ++_ctxSeq;\n const req = callCtx?.request ?? DEFAULT_REQUEST;\n // Always use this service's own database, never the caller's\n const db = service.getDb() as TDb;\n const logger = callCtx?.logger ?? defaultLogger;\n const traceId = callCtx?.traceId ?? `tr_${seq.toString(36)}`;\n const requestId = callCtx?.requestId ?? `req_${seq.toString(36)}`;\n const services = callCtx?.services ?? EMPTY_SERVICES;\n const metadata = callCtx?.metadata ?? EMPTY_METADATA;\n\n const fullBaseCtx: BaseContext<TDb> = {\n request: req,\n db,\n logger,\n traceId,\n requestId,\n services,\n metadata,\n // Only the envelope fields a caller may set, never the framework's own.\n ...pickContextEnvelope(callCtx),\n };\n\n const resolvedExtra = service.options.context\n ? await service.options.context(fullBaseCtx)\n : {};\n const finalCtx: any = {\n ...fullBaseCtx,\n ...resolvedExtra,\n [RESOLVED_SYMBOL]: service,\n };\n return finalCtx;\n}\n\n/**\n * Declare a service: a named group of actions, tools, and resources with its own\n * database and request context. It is registered globally, so `brick()`, the\n * OpenAPI generator, and `createServiceProxy` find it by name.\n *\n * Add actions with `service.action(...)`, tools with `service.tool(...)`,\n * resources with `service.resource(...)`, and plugins with `service.use(...)`.\n *\n * @param name - Unique name. It is the service's segment of every action route\n * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining a\n * second service with the same name replaces the first and logs a warning.\n * @param options - `database` (a handle from `defineDatabase`), `context` (adds\n * fields such as the signed-in user to every action's `ctx`), and `auth`,\n * `rateLimit`, `cache`, `resilience`, `telemetry`, and `lifecycle`.\n * @returns The service.\n * @example\n * import { defineDatabase, defineService, t } from \"@brickkit/core\";\n *\n * const database = defineDatabase({ tables: { pages } });\n *\n * export const pagesService = defineService(\"pages\", {\n * database,\n * // Added to `ctx` in every action of this service.\n * context: async ({ request }) => ({ user: await readUser(request) }),\n * });\n *\n * pagesService.action({\n * name: \"list\",\n * input: t.Object({ limit: t.Optional(t.Number()) }),\n * output: t.Array(t.Object({ id: t.String(), title: t.String() })),\n * execute: ({ input, ctx }) =>\n * ctx.db.select().from(pages).limit(input.limit ?? 20),\n * });\n */\nexport function defineService<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n>(\n name: string,\n options?: ServiceOptions<TServiceContext, TDb>,\n): Service<TDb, TServiceContext> {\n const service = new ServiceImpl<TDb, TServiceContext>(name, options);\n getGlobalRegistry().register(service as any);\n return service;\n}\n","import type { ActionContext, ProxyOptions } from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { pickContextEnvelope } from \"./context\";\nimport { withCallSpan } from \"./telemetry\";\n\n/**\n * A typed way to call another service's actions in-process. Each property of\n * the proxy is an action of that service: call it with the action's input, and\n * optionally a call context.\n *\n * The call runs through the target's own validation and authorization, with the\n * target's database and context (never the caller's), and shows as an `rpc`\n * span in the trace. Only in-process dispatch exists: with `isMonolith: false`\n * a call throws. Use the typed client to call a service over HTTP.\n *\n * @param serviceName - The registered name of the service to call.\n * @param options - `from` (the calling service's name, which becomes `ctx.caller`\n * in the target and cannot be spoofed), `context` (defaults for every call), and\n * `isMonolith`.\n * @returns A proxy typed as `T`, usually the target's actions.\n * @throws On a call, when the service or the action is not registered.\n * @example\n * import { createServiceProxy } from \"@brickkit/core\";\n *\n * const pages = createServiceProxy<{ get(input: { id: string }): Promise<Page> }>(\n * \"pages\",\n * { from: \"billing\" },\n * );\n * const page = await pages.get({ id: \"p_1\" });\n */\nexport function createServiceProxy<T extends Record<string, any>>(\n serviceName: string,\n options: ProxyOptions = {},\n): T {\n const isMonolith = options.isMonolith ?? true;\n\n return new Proxy({} as T, {\n get(_, actionName: string) {\n return async (payload: any, callCtx?: Partial<ActionContext>) => {\n if (isMonolith) {\n const registry = getGlobalRegistry();\n const service = registry.get(serviceName);\n if (!service) {\n throw new Error(\n `[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`,\n );\n }\n\n const action = service.getAction(actionName);\n if (!action) {\n throw new Error(\n `[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`,\n );\n }\n\n const envelopeCtx = createRpcEnvelope(\n options.from,\n options.context,\n callCtx,\n );\n\n const execute = () =>\n action.execute({\n input: payload,\n ctx: envelopeCtx,\n });\n return withCallSpan(\n `rpc ${serviceName}.${actionName}`,\n {\n \"brick.service\": serviceName,\n \"brick.action\": actionName,\n },\n execute,\n );\n } else {\n throw new Error(\n `[Brick-TS RPC] Remote microservice dispatch for '${serviceName}.${actionName}' is not configured. Use createClient({ baseUrl, contract }) for HTTP calls to remote services.`,\n );\n }\n };\n },\n });\n}\n\n/** Build the trusted envelope for a proxy call.\n *\n * When `from` is provided, it identifies the service that created the proxy\n * and always sets `caller` — any `caller` supplied via `options.context` or\n * the per-call context is ignored so it cannot be spoofed. When `from` is\n * omitted, an explicitly supplied `caller` still passes through for backward\n * compatibility; otherwise `caller` stays unset (never the target service).\n */\nexport function createRpcEnvelope(\n from: string | undefined,\n defaultContext?: Partial<ActionContext>,\n callContext?: Partial<ActionContext>,\n): Partial<ActionContext> {\n const envelope = {\n ...pickContextEnvelope(defaultContext),\n ...pickContextEnvelope(callContext),\n } as Partial<ActionContext> & { caller?: string };\n // `caller` identifies the service that created this proxy, never the target.\n // A configured `from` wins over any supplied value; without `from` we keep\n // an explicitly supplied caller (legacy) and otherwise leave it unset.\n if (from !== undefined) {\n envelope.caller = from;\n }\n return envelope;\n}\n","import type { EventDelivery, EventListener, EventWorkflow } from \"./types\";\n\ntype ListenerConfig<TPayload> = {\n name: string;\n on: string | readonly string[];\n maxAttempts?: number;\n} & (\n | {\n run: (delivery: EventDelivery<TPayload>) => void | Promise<void>;\n workflow?: never;\n }\n | { workflow: EventWorkflow<TPayload>; run?: never }\n);\n\n/**\n * Define a listener: code that runs for each event it listens for, after the write\n * that caused the event has been committed. Pass it to `brick({ events: {\n * listeners } })`.\n *\n * It either runs a handler (`run`) in the process that delivers events, or starts\n * a durable workflow (`workflow`) on the app's `events.world`. Delivery is at\n * least once. A handler that throws is retried later with a growing delay, then\n * parked as dead, so it can run again for the same event: use\n * `delivery.deliveryId` to make its work idempotent. A workflow needs no such\n * care: a delivery starts one run however often it is tried, and the workflow\n * retries its own steps.\n *\n * @param config - `name` (unique; it is part of each delivery's id), `on` (an\n * event name or a list of them; a trailing `*` matches a prefix, as in\n * `user.*`), `run` or `workflow`, and optionally `maxAttempts`.\n * @returns The listener.\n * @throws When the name is empty or contains `:`, `on` is empty, or the listener\n * has both or neither of `run` and `workflow`.\n * @example\n * import { brick, defineListener } from \"@brickkit/core\";\n *\n * const welcome = defineListener({\n * name: \"welcome-email\",\n * on: \"user.create\",\n * run: async ({ payload, deliveryId }) => {\n * await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });\n * },\n * });\n *\n * export default brick({ services, events: { listeners: [welcome] } });\n * @example\n * // src/workflows/onboard.ts\n * export async function onboard(event: WorkflowEvent<CrudEventPayload>) {\n * \"use workflow\";\n * await sendWelcome(event.payload.row.email);\n * }\n *\n * defineListener({ name: \"onboard\", on: \"user.create\", workflow: onboard });\n */\nexport function defineListener<TPayload = any>(\n config: ListenerConfig<TPayload>,\n): EventListener<TPayload> {\n if (typeof config.name !== \"string\" || !config.name)\n throw new Error(\"An event listener needs a name\");\n if (config.name.includes(\":\"))\n throw new Error(\n `Event listener name '${config.name}' must not contain ':'`,\n );\n const on = typeof config.on === \"string\" ? [config.on] : [...config.on];\n if (!on.length || on.some((pattern) => !pattern))\n throw new Error(`Event listener '${config.name}' listens for nothing`);\n if (\n config.maxAttempts !== undefined &&\n (!Number.isInteger(config.maxAttempts) || config.maxAttempts < 1)\n )\n throw new Error(\n `Event listener '${config.name}': maxAttempts must be a positive integer`,\n );\n const { name, run, workflow } = config as {\n name: string;\n run?: unknown;\n workflow?: unknown;\n };\n if (run !== undefined && workflow !== undefined)\n throw new Error(\n `Event listener '${name}' has both run and workflow; give it one`,\n );\n if (run === undefined && workflow === undefined)\n throw new Error(\n `Event listener '${name}' needs a run handler or a workflow`,\n );\n if (run !== undefined && typeof run !== \"function\")\n throw new Error(`Event listener '${name}': run must be a function`);\n if (workflow !== undefined && typeof workflow !== \"function\")\n throw new Error(\n `Event listener '${name}': workflow must be a function marked \"use workflow\"`,\n );\n return Object.freeze({\n name: config.name,\n on: Object.freeze(on),\n ...(config.run !== undefined ? { run: config.run } : {}),\n ...(config.workflow !== undefined ? { workflow: config.workflow } : {}),\n ...(config.maxAttempts !== undefined\n ? { maxAttempts: config.maxAttempts }\n : {}),\n });\n}\n","import { recorders } from \"./hub\";\n\n/**\n * Record an event of your own from an action, a tool or a hook. Listeners get it\n * as they get a generated CRUD event, with the payload you give.\n *\n * By default the event is committed in a transaction of its own. Pass the `tx`\n * of a transaction you have open to commit it with your writes instead: then it\n * is delivered at the dispatcher's next poll, because Brick does not see your\n * commit. Nothing is recorded when no listener wants the event.\n *\n * @param ctx - The action context: its `db` finds the service's outbox, and its\n * `traceId` follows the event to its listeners.\n * @param name - The event name, such as `order.refunded`.\n * @param payload - JSON data for the listeners.\n * @param options - `tx`: an open transaction on the service's database. `source`:\n * what emitted it, shown to listeners.\n * @throws When the context's database has no outbox table, or the app has no\n * `events`.\n * @example\n * refund: service.action({\n * name: \"refund\",\n * execute: async ({ ctx, input }) => {\n * await ctx.db.update(orders).set({ status: \"refunded\" }).where(eq(orders.id, input.id));\n * await emitEvent(ctx, \"order.refunded\", { id: input.id });\n * },\n * });\n */\nexport async function emitEvent(\n ctx: { db?: unknown; traceId?: string },\n name: string,\n payload: unknown,\n options: { tx?: unknown; source?: string } = {},\n): Promise<void> {\n const events =\n ctx.db && typeof ctx.db === \"object\" ? recorders.get(ctx.db) : undefined;\n if (!events)\n throw new Error(\n `Cannot emit '${name}': ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database, not a transaction)`,\n );\n const context = { traceId: ctx.traceId, source: options.source };\n if (options.tx !== undefined)\n return events.record(options.tx, context, name, payload);\n await events.transaction(ctx.db, context, async (_tx, record) => {\n await record(name, payload);\n });\n}\n","import type { ActionContext, Service, Tool, ToolAnnotations } from \"./types\";\n\nexport interface McpToolDefinition {\n name: string;\n title?: string;\n description: string;\n inputSchema: unknown;\n annotations: ToolAnnotations;\n}\n\nexport interface McpRegistryOptions {\n services?: readonly Pick<Service<any, any>, \"listTools\">[];\n tools?: readonly Tool<any, any, any, any>[];\n}\n\nexport interface McpRegistry {\n listTools(): McpToolDefinition[];\n callTool(\n name: string,\n args?: Record<string, unknown>,\n ctx?: Partial<ActionContext>,\n ): Promise<unknown>;\n}\n\nexport class UnknownToolError extends Error {\n constructor(name: string) {\n super(`unknown tool: ${name}`);\n this.name = \"UnknownToolError\";\n }\n}\n\n/** Collect only explicitly defined tools, without exposing ordinary actions. */\nexport function createMcpRegistry(options: McpRegistryOptions): McpRegistry {\n function toolsByName() {\n const tools = new Map<string, Tool<any, any, any, any>>();\n for (const tool of [\n ...(options.tools ?? []),\n ...(options.services ?? []).flatMap((service) => service.listTools()),\n ]) {\n const existing = tools.get(tool.name);\n if (existing && existing !== tool)\n throw new Error(`Duplicate MCP tool: ${tool.name}`);\n tools.set(tool.name, tool);\n }\n return tools;\n }\n toolsByName();\n return {\n listTools: () =>\n Array.from(toolsByName().values(), (tool) => ({\n name: tool.name,\n ...((tool.config.title ?? tool.config.annotations?.title)\n ? { title: tool.config.title ?? tool.config.annotations?.title }\n : {}),\n description: tool.config.description ?? \"\",\n inputSchema: tool.config.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n annotations: tool.config.annotations ?? {},\n })),\n async callTool(name, args = {}, ctx) {\n const tool = toolsByName().get(name);\n if (!tool) throw new UnknownToolError(name);\n return tool({ input: args, ctx });\n },\n };\n}\n\nexport interface McpHandlerOptions {\n registry: McpRegistry;\n serverInfo: { name: string; version: string; title?: string };\n /** Versions supported by this transport, newest first. */\n protocolVersions?: readonly string[];\n}\n\nfunction result(id: unknown, value: unknown) {\n return Response.json({ jsonrpc: \"2.0\", id, result: value });\n}\nfunction rpcError(id: unknown, code: number, message: string) {\n return Response.json({ jsonrpc: \"2.0\", id, error: { code, message } });\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */\nexport function createMcpHandler(options: McpHandlerOptions) {\n const versions = options.protocolVersions ?? [\"2025-06-18\"];\n if (!versions.length)\n throw new Error(\"At least one MCP protocol version is required\");\n return async (\n request: Request,\n ctx?: Partial<ActionContext>,\n ): Promise<Response> => {\n if (request.method !== \"POST\")\n return new Response(null, { status: 405, headers: { Allow: \"POST\" } });\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return rpcError(null, -32700, \"parse error\");\n }\n if (\n !isRecord(body) ||\n body.jsonrpc !== \"2.0\" ||\n typeof body.method !== \"string\" ||\n (body.id !== undefined &&\n body.id !== null &&\n typeof body.id !== \"string\" &&\n typeof body.id !== \"number\") ||\n (body.params !== undefined && !isRecord(body.params))\n ) {\n return rpcError(null, -32600, \"invalid request\");\n }\n if (body.id === undefined) return new Response(null, { status: 202 });\n const { id, method } = body;\n const params = body.params as Record<string, unknown> | undefined;\n switch (method) {\n case \"initialize\": {\n const requested = params?.protocolVersion;\n return result(id, {\n capabilities: { tools: {} },\n protocolVersion:\n typeof requested === \"string\" && versions.includes(requested)\n ? requested\n : versions[0],\n serverInfo: options.serverInfo,\n });\n }\n case \"ping\":\n return result(id, {});\n case \"tools/list\":\n try {\n return result(id, { tools: options.registry.listTools() });\n } catch {\n return rpcError(id, -32603, \"internal error\");\n }\n case \"tools/call\": {\n if (\n typeof params?.name !== \"string\" ||\n (params.arguments !== undefined && !isRecord(params.arguments))\n ) {\n return rpcError(id, -32602, \"invalid tool parameters\");\n }\n try {\n const value = await options.registry.callTool(\n params.name,\n params.arguments as Record<string, unknown> | undefined,\n { ...ctx, request },\n );\n return result(id, {\n content: [\n {\n type: \"text\",\n text:\n typeof value === \"string\"\n ? value\n : (JSON.stringify(value, null, 2) ?? \"null\"),\n },\n ],\n });\n } catch (error) {\n if (error instanceof UnknownToolError)\n return rpcError(id, -32602, error.message);\n return result(id, {\n content: [\n {\n type: \"text\",\n text: error instanceof Error ? error.message : String(error),\n },\n ],\n isError: true,\n });\n }\n }\n default:\n return rpcError(id, -32601, `method not found: ${method}`);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,SAAY,OAAa;CACvC,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG;EACjE,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GAAG,SAAS,KAAK;EACxD,OAAO,OAAO,KAAK;CACrB;CACA,OAAO;AACT;AAEA,SAAS,eAAe,QAA0B;CAChD,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC;AAC7E;AAEA,SAAgB,mBACd,UACA,SAAS,QACT;CACA,KAAK,MAAM,WAAW,UAAU,QAAQ,MAAM;CAC9C,OAAO,2BAA2B,UAAU,MAAM;AACpD;;AAGA,SAAgB,2BACd,UACA,SAAS,QACT;CACA,IAAI,CAAC,OAAO,WAAW,GAAG,GACxB,MAAM,IAAI,MAAM,4CAA4C;CAC9D,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,WAAW,UAAU;EAC9B,IAAI,MAAM,IAAI,QAAQ,IAAI,GACxB,MAAM,IAAI,MAAM,sCAAsC,QAAQ,KAAK,EAAE;EACvE,MAAM,IAAI,QAAQ,IAAI;CACxB;CACA,MAAM,SAAoB,CAAC;CAC3B,MAAM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U,OAAO,KAAK;MAC7D,CACF;MACA,SAAS;KACX,CAAC;IACH;GAEF,SACE,OAAO,SAAS,IAAI,QAAQ,qBAAqB,QAAQ;EAC7D;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["defaultLogger","DEFAULT_REQUEST","RESOLVED_SYMBOL","sqliteTable","sqliteText","sqliteInteger","sqliteReal","pgText","pgInteger","pgBoolean","pgTimestamp","getTableName","EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty","EMPTY_SERVICES","DEFAULT_REQUEST","sqliteInteger","sqliteTable","sqliteText","sqliteIndex","pgText","pgInteger","pgIndex","and","eq","or","lte","lt","asc","inArray","getTableName","getTableName","getTableColumns","sql","and","eq","getTableColumns","inArray"],"sources":["../src/routes.ts","../src/compiler/ir.ts","../src/registry.ts","../src/telemetry.ts","../src/error-response.ts","../src/typebox.ts","../src/logger.ts","../src/action.ts","../src/plugin.ts","../src/deps.ts","../src/define-plugin.ts","../src/compiler/runtime.ts","../src/action-handler.ts","../src/compiler/handler.ts","../src/app-entry.ts","../src/compiler.ts","../src/access.ts","../src/openapi.ts","../src/secrets.ts","../src/request-logger.ts","../src/docs.ts","../src/dashboard.ts","../src/endpoints.ts","../src/events/outbox.ts","../src/events/transaction.ts","../src/events/dispatcher.ts","../src/events/id.ts","../src/events/workflows.ts","../src/events/hub.ts","../src/socket.ts","../src/server.ts","../src/compiler/emit.ts","../src/tool.ts","../src/db/sqlite.ts","../src/db/postgres.ts","../src/db/define.ts","../src/db/index.ts","../src/resource.ts","../src/events/catalog.ts","../src/context.ts","../src/service.ts","../src/socket-redis.ts","../src/rpc.ts","../src/events/listener.ts","../src/events/emit.ts","../src/mcp.ts"],"sourcesContent":["import type { Action, ResourceActionAccess } from \"./types\";\nimport { getPluginActionRoute } from \"./plugin\";\nimport { kebabCase } from \"./kebab\";\n\nexport { kebabCase };\n\n/**\n * The route every name of an owner mounts under: `${prefix}`,\n * `${prefix}/${service}`, or `${prefix}/${service}/${resource}`, in kebab-case.\n */\nexport function ownerPath(\n prefix: string,\n service?: string,\n resource?: string,\n): string {\n let path = prefix.replace(/\\/$/, \"\");\n if (service !== undefined) path += `/${kebabCase(service)}`;\n if (resource !== undefined) path += `/${kebabCase(resource)}`;\n return path;\n}\n\n/** Joins a path relative to its owner. `/` is the owner's own route. */\nexport function joinRoute(base: string, path: string): string {\n return `${base}${path === \"/\" ? \"\" : path}` || \"/\";\n}\n\nexport interface ActionRoute {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n /** The v0.10 path, served too by `brick({ legacyRoutes: true })`. */\n legacyPath?: string;\n}\n\n/**\n * Where an action is served over HTTP: its method and its path under the owner\n * tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource\n * action's `${prefix}/${service}/${resource}[/:id]/${action}`).\n *\n * @param action - An action registered on a service.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns `false` when a plugin switched the route off, otherwise the route.\n */\nexport function getActionRoute(\n action: Action<any, any, any, any>,\n prefix = \"/api\",\n): ActionRoute | false {\n const plugin = getPluginActionRoute(action, prefix);\n if (plugin === false) return false;\n if (plugin)\n return {\n method: plugin.method,\n path: plugin.path,\n legacyPath: plugin.legacyPath,\n };\n const service = action.serviceName ?? \"\";\n const method = action.config.method ?? \"POST\";\n const { resourceAction } = action as { resourceAction?: ResourceActionInfo };\n if (resourceAction) {\n const base = ownerPath(prefix, service, resourceAction.resource);\n return {\n method,\n path:\n action.config.path !== undefined\n ? joinRoute(base, action.config.path)\n : `${base}${resourceAction.record ? \"/:id\" : \"\"}/${kebabCase(resourceAction.name)}`,\n };\n }\n const base = ownerPath(prefix, service);\n return {\n method,\n path:\n action.config.path !== undefined\n ? joinRoute(base, action.config.path)\n : `${base}/${kebabCase(action.name)}`,\n legacyPath: legacyPath(prefix, service, action.name, action.config.path),\n };\n}\n\n/**\n * The v0.10 route of a service action or socket: the names as declared, or an\n * explicit path that still reads as absolute (it starts with the prefix). A\n * path already rewritten as relative has no v0.10 form.\n */\nexport function legacyPath(\n prefix: string,\n service: string,\n name: string,\n path: string | undefined,\n): string | undefined {\n const root = prefix.replace(/\\/$/, \"\");\n if (path === undefined) return `${root}/${service}/${name}`;\n return path.startsWith(`${root}/`) ? path : undefined;\n}\n\n/** Stamped on actions declared with `resource.action(...)`. */\nexport interface ResourceActionInfo {\n resource: string;\n /** The declared name, without the `resource.` prefix. */\n name: string;\n record: boolean;\n /** A record action's own access rule. */\n access?: ResourceActionAccess;\n}\n","import { type Service, type Action } from \"../types\";\nimport { getPluginActionRoute } from \"../plugin\";\nimport { getActionRoute, kebabCase } from \"../routes\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\" | \"array\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly preparations: readonly {\n service: string;\n name: string;\n metadata: unknown;\n }[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n for (const service of services) service.build();\n return analyzeDeclaredApplication(services, prefix);\n}\n\n/** Inspect current declarations without closing service/plugin setup. */\nexport function analyzeDeclaredApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, { name: string; plugin: boolean }>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const plugin = getPluginActionRoute(action, prefix) !== undefined;\n const key = `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n const previous = registered.get(key);\n if (previous) {\n if (plugin || previous.plugin)\n throw new Error(\n `Brick compiler: duplicate plugin route '${method} ${path}'`,\n );\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, { name: `${service.name}.${action.name}`, plugin });\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" | \"array\" }[] =\n [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\")\n coercions.push({ key, type: \"boolean\" });\n else if (prop.type === \"array\") coercions.push({ key, type: \"array\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\n bindings.push({ service, action });\n };\n for (const service of services) {\n checkSegments(service);\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n add(service, action, route.method, route.path, \"action\");\n }\n }\n const preparations = services.flatMap((service) =>\n service.listPreparations().map((contribution) => ({\n service: service.name,\n name: contribution.name,\n metadata: schemaSnapshot(contribution.describe?.()),\n })),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n preparations,\n diagnostics,\n });\n return { ir, bindings };\n}\n\n/** A service action, resource, and socket own the URL segment after the service. */\nfunction checkSegments(service: Service<any, any>) {\n const owners = new Map<string, string>();\n const claim = (segment: string, owner: string) => {\n const previous = owners.get(segment);\n if (previous)\n throw new Error(\n `Brick: duplicate name \"${segment}\" in service \"${service.name}\": ${previous} and ${owner} share the URL segment`,\n );\n owners.set(segment, owner);\n };\n for (const resource of service.listResources())\n claim(kebabCase(resource.name), `resource \"${resource.name}\"`);\n for (const socket of service.listSockets())\n if (socket.schema.path === undefined)\n claim(kebabCase(socket.schema.name), `socket \"${socket.schema.name}\"`);\n for (const action of service.listActions())\n if (\n action.config.path === undefined &&\n !(action as { resourceAction?: unknown }).resourceAction &&\n getPluginActionRoute(action) === undefined\n )\n claim(kebabCase(action.name), `action \"${action.name}\"`);\n}\n","import type { InstalledPlugin } from \"./define-plugin\";\nimport type { Service, ArchitectureSchema } from \"./types\";\nimport { analyzeDeclaredApplication, type RouteIR } from \"./compiler/ir\";\nimport type { EventsDefinition } from \"./events/hub\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport { fileURLToPath } from \"node:url\";\n\n// The package root (src/ or dist/ is beneath it), so Brick's own frames are skipped.\nconst brickRoot = fileURLToPath(new URL(\"..\", import.meta.url));\n\n/**\n * The first `file:line` outside Brick on the current stack: where a name is\n * being defined. Best-effort: `undefined` when there is no stack.\n */\nexport function definitionSite(): string | undefined {\n // Plugins nest several Brick frames above the caller's.\n const limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 50;\n const stack = new Error().stack;\n Error.stackTraceLimit = limit;\n for (const line of stack?.split(\"\\n\").slice(1) ?? []) {\n const match =\n /(?:\\(|at )(?:file:\\/\\/)?([^\\s()?]+)(?:\\?[^\\s():]*)?:(\\d+):\\d+\\)?$/.exec(\n line,\n );\n if (!match) continue;\n const [, file, row] = match;\n if (\n file!.startsWith(`${brickRoot}src/`) ||\n file!.startsWith(`${brickRoot}dist/`)\n )\n continue;\n return `${file}:${row}`;\n }\n return undefined;\n}\n\n/**\n * Records where `name` is defined. The same file defining it again (a dev\n * reload) replaces the old definition.\n *\n * @throws When a different file already defined `name`.\n */\nexport function claimName(\n sites: Map<string, string | undefined>,\n label: string,\n name: string,\n site: string | undefined,\n): void {\n const file = (at: string | undefined) => at?.replace(/:\\d+$/, \"\");\n if (sites.has(name) && file(sites.get(name)) !== file(site))\n throw new Error(\n `Brick: duplicate ${label}\\n ${sites.get(name) ?? \"unknown\"}\\n ${site ?? \"unknown\"}`,\n );\n sites.set(name, site);\n}\n\nexport interface ArchitectureApplication {\n services: readonly Service[];\n routes: readonly RouteIR[];\n events?: EventsDefinition;\n sockets?: readonly (BrickSocketSchema & { service: string; path: string })[];\n plugins?: readonly InstalledPlugin[];\n}\n\nexport class ServiceRegistry {\n private _revision = 0;\n /** Definition revision for invalidating serialized architecture snapshots. */\n get revision(): number {\n return this._revision;\n }\n touch(): void {\n this._revision++;\n }\n\n private services = new Map<string, Service>();\n private sites = new Map<string, string | undefined>();\n private routes = new Map<Service, readonly RouteIR[]>();\n\n /** Remember the actual registered routes for subsequent registry exports. */\n setApplicationRoutes(application: ArchitectureApplication): void {\n for (const service of application.services) {\n this.routes.set(\n service,\n application.routes.filter((route) => route.service === service.name),\n );\n }\n this.touch();\n }\n\n /** @throws When a different file already registered a service with this name. */\n register(service: Service, site = definitionSite()): void {\n claimName(this.sites, `service \"${service.name}\"`, service.name, site);\n const previous = this.services.get(service.name);\n if (previous) this.routes.delete(previous);\n this.services.set(service.name, service);\n this.touch();\n }\n\n get(name: string): Service | undefined {\n return this.services.get(name);\n }\n\n has(name: string): boolean {\n return this.services.has(name);\n }\n\n list(): Service[] {\n return Array.from(this.services.values());\n }\n\n clear(): void {\n this.services.clear();\n this.sites.clear();\n this.routes.clear();\n this.touch();\n }\n\n exportArchitecture(\n application?: ArchitectureApplication,\n ): ArchitectureSchema {\n return {\n version: \"1.0.0\",\n ...(application?.events ? { events: application.events } : {}),\n ...(application?.plugins?.length\n ? { plugins: [...application.plugins] }\n : {}),\n services: (application?.services ?? this.list()).map((service) => {\n const routes = application\n ? application.routes.filter((route) => route.service === service.name)\n : (this.routes.get(service) ??\n analyzeDeclaredApplication([service]).ir.routes);\n const byAction = new Map(routes.map((route) => [route.action, route]));\n const schema = service.introspect();\n return {\n ...schema,\n ...(application?.sockets\n ? {\n sockets: application.sockets.filter(\n (socket) => socket.service === service.name,\n ),\n }\n : {}),\n actions: schema.actions.map((action) => {\n const route = byAction.get(action.name);\n return route\n ? { ...action, method: route.method, path: route.path }\n : action;\n }),\n };\n }),\n };\n }\n}\n\n// Global registry instance\nlet globalRegistry = new ServiceRegistry();\n\n/**\n * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI\n * generator, `useService`, and the dashboard find services by name.\n *\n * @returns The current global registry.\n */\nexport function getGlobalRegistry(): ServiceRegistry {\n return globalRegistry;\n}\n\n/**\n * Start over with an empty global registry. For tests, which define the same\n * services again in each case; an application never needs it.\n */\nexport function resetGlobalRegistry(): void {\n globalRegistry = new ServiceRegistry();\n}\n","import {\n context,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n type Attributes,\n type Span,\n} from \"@opentelemetry/api\";\n\nconst INSTRUMENTATION_SCOPE = \"@brickkit/core\";\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STATEMENT_LENGTH = 2000;\nconst DATABASE_INSTRUMENTED = Symbol.for(\"brickkit.telemetry.database\");\nconst SQLITE_STATEMENT_METHODS = [\"all\", \"get\", \"run\", \"values\"] as const;\n\ntype Outcome =\n | { failed: false; value: unknown }\n | { failed: true; error: unknown };\n\n/** Run `fn` as a child of the active span, ending the span when its result settles. */\nexport function withSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n kind: SpanKind = SpanKind.INTERNAL,\n): T {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(name, { kind, attributes }, (span) =>\n settle(fn, (outcome) => {\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n }),\n );\n}\n\n/**\n * Add a child span for an in-process call, but only inside a request that is\n * already traced. Calls made outside instrumented requests run unchanged.\n */\nexport function withCallSpan<T>(\n name: string,\n attributes: Attributes,\n fn: () => T,\n): T {\n return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();\n}\n\ninterface HttpContext {\n request?: Request;\n headers?: Record<string, string | undefined>;\n set?: { status?: unknown; headers?: Record<string, unknown> };\n}\n\n/** What a raw route handler receives from `traceRoute`. Read the body from `request`. */\nexport interface RawRouteContext {\n request: Request;\n headers: Record<string, string | undefined>;\n set: { status?: unknown; headers?: Record<string, unknown> };\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n}\n\n/**\n * Wrap a raw route handler so each of its requests gets a server span. Use it\n * for routes registered directly on the app, outside actions and endpoints,\n * such as auth or webhook routes. Spans are recorded whenever a tracer provider\n * is registered; `brick({ telemetry })` does not apply to these routes.\n *\n * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia\n * decides what to parse from the handler's destructuring, and forwarding the\n * whole context would parse the body and leave `request.json()` with nothing.\n */\nexport function traceRoute<T>(\n route: string,\n handler: (context: RawRouteContext) => T,\n): (context: RawRouteContext) => T {\n return ({ request, headers, set, params, query }) =>\n traceHttpRequest({ request, headers, set }, request.method, route, () =>\n handler({ request, headers, set, params, query }),\n );\n}\n\n/**\n * Wrap one HTTP request in a server span. The span continues the caller's\n * trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the\n * request id Brick returns is the span's trace id, so clients can find the\n * request in the dashboard. `extra` adds attributes, such as\n * `brick.legacy_route` on a v0.10 path.\n */\nexport function traceHttpRequest<T>(\n request: HttpContext,\n method: string,\n route: string,\n fn: () => T,\n extra?: Attributes,\n): T {\n const attributes: Attributes = {\n \"http.request.method\": method,\n \"http.route\": route,\n ...extra,\n };\n if (request.request) {\n attributes[\"url.path\"] = new URL(request.request.url).pathname;\n }\n const headers = request.headers ?? {};\n const parent = propagation.extract(context.active(), headers);\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startActiveSpan(\n `${method} ${route}`,\n { kind: SpanKind.SERVER, attributes },\n parent,\n (span) => {\n if (!headers[\"x-trace-id\"]) {\n headers[\"x-trace-id\"] = span.spanContext().traceId;\n }\n const outgoing: Record<string, string> = {};\n propagation.inject(context.active(), outgoing);\n if (request.set?.headers) Object.assign(request.set.headers, outgoing);\n return settle(fn, (outcome) => {\n // Raw handlers often return a Response, whose status Elysia's `set` never sees.\n const status = outcome.failed\n ? 500\n : outcome.value instanceof Response\n ? outcome.value.status\n : responseStatus(request.set?.status);\n if (outcome.failed) recordThrown(span, outcome.error);\n span.setAttribute(\"http.response.status_code\", status);\n const traceId = headers[\"x-trace-id\"];\n if (traceId) span.setAttribute(\"brick.trace_id\", traceId);\n if (status >= 500) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `HTTP ${status}`,\n });\n }\n span.end();\n });\n },\n );\n}\n\n/**\n * Attach a handled failure to the active span. Brick returns these as\n * responses rather than throwing, so only server faults (5xx) mark the span\n * as errored; client errors keep their code as an attribute.\n */\nexport function recordFailure(\n error: unknown,\n failure: { status: number; code: string; message: string },\n): void {\n const span = trace.getActiveSpan();\n if (!span) return;\n span.setAttributes({\n \"brick.error.code\": failure.code,\n \"brick.error.status\": failure.status,\n \"brick.error.message\": truncate(failure.message),\n });\n if (failure.status >= 500) recordThrown(span, error);\n}\n\n/**\n * Record SQL statements as client spans for the database behind a service.\n * Drizzle's logger has no timing, so the hook sits on the driver: each\n * statement is timed where the driver runs it. Statements outside traced\n * requests are not recorded. Calling this again on the same client is a no-op.\n */\nexport function instrumentDatabase(db: unknown): void {\n const client = (db as { $client?: unknown } | undefined)?.$client;\n // postgres.js clients are callable functions, so accept both shapes.\n if (\n (typeof client !== \"object\" && typeof client !== \"function\") ||\n client === null\n ) {\n return;\n }\n const driver = client as Record<PropertyKey, unknown>;\n if (driver[DATABASE_INSTRUMENTED]) return;\n if (typeof driver.prepare === \"function\") {\n instrumentBunSqlite(driver as unknown as BunSqliteClient);\n } else if (typeof driver.unsafe === \"function\") {\n instrumentPostgres(driver as unknown as PostgresClient);\n } else {\n return;\n }\n driver[DATABASE_INSTRUMENTED] = true;\n}\n\ntype BunSqliteStatement = Record<\n (typeof SQLITE_STATEMENT_METHODS)[number],\n (...args: unknown[]) => unknown\n>;\n\ninterface BunSqliteClient {\n prepare: (sql: string) => BunSqliteStatement;\n}\n\nfunction instrumentBunSqlite(client: BunSqliteClient): void {\n const prepare = client.prepare.bind(client);\n client.prepare = (sql: string) => {\n const statement = prepare(sql);\n for (const method of SQLITE_STATEMENT_METHODS) {\n const original = statement[method];\n if (typeof original !== \"function\") continue;\n statement[method] = (...args: unknown[]) =>\n recordStatement(sql, \"sqlite\", () => original.apply(statement, args));\n }\n return statement;\n };\n}\n\ninterface PostgresQuery {\n then: (\n onFulfilled?: (value: unknown) => unknown,\n onRejected?: (reason: unknown) => unknown,\n ) => Promise<unknown>;\n}\n\ninterface PostgresClient {\n unsafe: (sql: string, ...rest: unknown[]) => PostgresQuery;\n}\n\n/**\n * postgres.js returns a query that runs when awaited, and `values()` returns\n * that same object, so overriding `then` on it times the whole round trip.\n */\nfunction instrumentPostgres(client: PostgresClient): void {\n const unsafe = client.unsafe.bind(client);\n client.unsafe = (sql: string, ...rest: unknown[]) => {\n const query = unsafe(sql, ...rest);\n if (!trace.getActiveSpan() || typeof query?.then !== \"function\") {\n return query;\n }\n const span = startStatementSpan(sql, \"postgresql\");\n let finished = false;\n const finish = (outcome: Outcome) => {\n if (finished) return;\n finished = true;\n if (outcome.failed) recordThrown(span, outcome.error);\n span.end();\n };\n const then = query.then.bind(query);\n // The query is already thenable; this wraps its own `then` to time the\n // round trip, so the no-thenable rule does not apply.\n // oxlint-disable-next-line unicorn/no-thenable\n query.then = (onFulfilled, onRejected) =>\n then(\n (value) => {\n finish({ failed: false, value });\n return onFulfilled ? onFulfilled(value) : value;\n },\n (error: unknown) => {\n finish({ failed: true, error });\n if (onRejected) return onRejected(error);\n throw error;\n },\n );\n return query;\n };\n}\n\nfunction recordStatement<T>(sql: string, system: string, fn: () => T): T {\n if (!trace.getActiveSpan()) return fn();\n return withSpan(\n statementName(sql),\n statementAttributes(sql, system),\n fn,\n SpanKind.CLIENT,\n );\n}\n\nfunction startStatementSpan(sql: string, system: string): Span {\n return trace\n .getTracer(INSTRUMENTATION_SCOPE)\n .startSpan(\n statementName(sql),\n { kind: SpanKind.CLIENT, attributes: statementAttributes(sql, system) },\n context.active(),\n );\n}\n\nfunction statementName(sql: string): string {\n return `SQL ${operationOf(sql)}`;\n}\n\nfunction statementAttributes(sql: string, system: string): Attributes {\n return {\n \"db.system\": system,\n \"db.operation\": operationOf(sql),\n \"db.statement\": truncate(sql, MAX_STATEMENT_LENGTH),\n };\n}\n\nfunction operationOf(sql: string): string {\n return sql.trim().split(/\\s+/, 1)[0]?.toUpperCase() || \"SQL\";\n}\n\nfunction settle<T>(fn: () => T, done: (outcome: Outcome) => void): T {\n let result: T;\n try {\n result = fn();\n } catch (error) {\n done({ failed: true, error });\n throw error;\n }\n if (isPromiseLike(result)) {\n return result.then(\n (value) => {\n done({ failed: false, value });\n return value;\n },\n (error: unknown) => {\n done({ failed: true, error });\n throw error;\n },\n ) as unknown as T;\n }\n done({ failed: false, value: result });\n return result;\n}\n\nfunction recordThrown(span: Span, error: unknown): void {\n span.recordException(error instanceof Error ? error : String(error));\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncate(messageOf(error)),\n });\n}\n\nfunction responseStatus(value: unknown): number {\n const status = typeof value === \"number\" ? value : Number(value ?? 200);\n return Number.isInteger(status) ? status : 200;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n","import { ActionExecutionError, ValidationError, type Logger } from \"./types\";\nimport { recordFailure } from \"./telemetry\";\n\nexport interface ErrorEnvelope {\n name: string;\n code: string;\n message: string;\n status: number;\n requestId: string;\n details?: unknown;\n errors?: ValidationError[\"errors\"];\n}\n\ntype ErrorContext = { logger: Pick<Logger, \"error\">; requestId: string };\n\n/** Preserve declared failures, log and wrap unexpected throws without exposing internals. */\nexport function normalizeActionError(\n err: unknown,\n { logger, requestId }: ErrorContext,\n): ActionExecutionError | ValidationError {\n if (err instanceof ActionExecutionError || err instanceof ValidationError)\n return err;\n logger.error(\"Unexpected action error\", { requestId }, err);\n const failure = new ActionExecutionError(\n \"INTERNAL_SERVER_ERROR\",\n \"Internal Server Error\",\n 500,\n undefined,\n { cause: err },\n );\n failure.name = \"InternalServerError\";\n return failure;\n}\n\n/**\n * Turn what an action threw into the JSON body of its HTTP response, and record\n * the failure on the active trace. Declared failures and validation errors keep\n * their code, status, and details; anything else is logged and answered as a\n * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.\n *\n * @param err - Whatever was thrown.\n * @param context - A `logger` with `error()`, and the `requestId` to put in the body.\n * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and\n * `details` or `errors` when there are any.\n */\nexport function toErrorResponse(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const envelope = buildErrorEnvelope(err, context);\n recordFailure(err, envelope);\n return envelope;\n}\n\nfunction buildErrorEnvelope(\n err: unknown,\n context: ErrorContext,\n): ErrorEnvelope {\n const failure = normalizeActionError(err, context);\n if (\n failure.status >= 500 &&\n (err instanceof ActionExecutionError || err instanceof ValidationError)\n ) {\n context.logger.error(\n \"Server action error\",\n { requestId: context.requestId },\n err,\n );\n }\n if (failure instanceof ValidationError && failure.status >= 500) {\n return {\n name: failure.name,\n code: failure.code,\n message: failure.message,\n status: failure.status,\n requestId: context.requestId,\n };\n }\n return { ...failure.toJSON(), requestId: context.requestId };\n}\n","import { Type, type TSchema, type Static } from \"@sinclair/typebox\";\nimport { TypeCompiler, type TypeCheck } from \"@sinclair/typebox/compiler\";\nimport type { ValidationErrorItem } from \"./types\";\n\nexport { Type, Type as t };\nexport type { TSchema, Static };\n\nconst compilerCache = new WeakMap<TSchema, TypeCheck<TSchema>>();\n\n/**\n * The compiled validator for a TypeBox schema. Compiling is slow and checking\n * is fast, so each schema is compiled once and kept for as long as the schema\n * object lives.\n *\n * @param schema - A TypeBox schema.\n * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.\n */\nexport function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T> {\n let compiled = compilerCache.get(schema) as TypeCheck<T> | undefined;\n if (!compiled) {\n compiled = TypeCompiler.Compile(schema);\n compilerCache.set(schema, compiled);\n }\n return compiled;\n}\n\n/**\n * Check a value against a schema, the way actions check their input and output.\n *\n * @param schema - A TypeBox schema, or `undefined` to accept anything.\n * @param value - The value to check.\n * @returns `{ success: true, data }`, or `{ success: false, errors }` with a\n * `path`, `message`, `type`, and the offending `value` for each problem.\n */\nexport function validateWithSchema<T extends TSchema>(\n schema: T | undefined,\n value: unknown,\n):\n | { success: true; data: Static<T> }\n | { success: false; errors: ValidationErrorItem[] } {\n if (!schema) {\n return { success: true, data: value as Static<T> };\n }\n\n const check = getCompiledCheck(schema);\n if (check.Check(value)) {\n return { success: true, data: value as Static<T> };\n }\n\n const errors: ValidationErrorItem[] = [];\n for (const error of check.Errors(value)) {\n errors.push({\n path: error.path,\n message: error.message,\n value: error.value,\n type: error.type,\n });\n }\n\n return { success: false, errors };\n}\n","import { formatWithOptions } from \"node:util\";\nimport { trace, type Span } from \"@opentelemetry/api\";\nimport type { Logger } from \"./types\";\n\ntype Level = keyof Logger;\n\n/**\n * Set by the CLI when a dashboard is collecting logs, in `brick dev` or in\n * `brick start` with the `dashboard` option. A shared symbol, not an option or\n * an export: the CLI and the app may each hold their own copy of this package,\n * and nothing but a dashboard turns it on.\n */\nconst CAPTURE = Symbol.for(\"brickkit.logs.capture\");\n\n/** The span event a log line becomes; the dashboard reads these. */\nconst LOG_EVENT = \"log\";\nconst MAX_MESSAGE_LENGTH = 4000;\n/**\n * Logs one span keeps. OpenTelemetry keeps 128 events per span by default,\n * exceptions among them, so a chatty action must not use them all up and\n * lose the stack trace of the error that ends it.\n */\nconst MAX_LOGS_PER_SPAN = 100;\n\nconst logged = new WeakMap<Span, number>();\n\n/**\n * Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and\n * titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their\n * console output, which in a web page shows as stray characters.\n */\n// oxlint-disable no-control-regex\nconst ANSI =\n /\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\))/g;\n// oxlint-enable no-control-regex\n\n/** `text` without terminal formatting. */\nexport function stripAnsi(text: string): string {\n return text.includes(\"\\u001b\") ? text.replace(ANSI, \"\") : text;\n}\n\n/**\n * What `console.log` would print, without terminal colors, with objects cut off\n * at a sensible size.\n */\nfunction render(args: unknown[]): string {\n const text = stripAnsi(\n formatWithOptions(\n { depth: 3, breakLength: 120, maxArrayLength: 50, maxStringLength: 1000 },\n ...args,\n ),\n );\n return text.length > MAX_MESSAGE_LENGTH\n ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…`\n : text;\n}\n\nfunction record(span: Span, level: Level, args: unknown[]): void {\n const count = (logged.get(span) ?? 0) + 1;\n logged.set(span, count);\n if (count > MAX_LOGS_PER_SPAN) {\n // Counted, so the dashboard can say how many it left out.\n span.setAttribute(\"brick.logs.dropped\", count - MAX_LOGS_PER_SPAN);\n return;\n }\n span.addEvent(LOG_EVENT, {\n \"log.level\": level,\n \"log.message\": render(args),\n });\n}\n\n/**\n * Record a line on the running span, if a recording one is running. Returns\n * whether it did, so the caller prints only when it did not.\n */\nfunction recordActive(level: Level, args: unknown[]): boolean {\n const span = trace.getActiveSpan();\n if (!span?.isRecording()) return false;\n record(span, level, args);\n return true;\n}\n\n// The dev server's console capture calls this by name, for the same reason\n// `CAPTURE` is a shared symbol: it may hold a different copy of this package.\n(globalThis as Record<symbol, unknown>)[Symbol.for(\"brickkit.logs.record\")] =\n recordActive;\n\n/**\n * A logger for actions, tools, and endpoints. While a dashboard is on, a line\n * logged while a request is being traced becomes an event on the span that is\n * running, which the dashboard shows with that request (and in its Logs tab);\n * it is not printed. Everywhere else, and for lines logged outside a request,\n * it prints to the console, prefixed by `prefix`: one for all levels, or one\n * per level.\n *\n * Capturing costs one context lookup and a span event per line, and nothing\n * is serialized for the dashboard until the span ends, so it is cheaper than\n * a console write. Lines are cut at 4,000 characters and a span keeps 100.\n */\nexport function createLogger(prefix: string | Record<Level, string>): Logger {\n const level =\n (name: Level, print: (...args: unknown[]) => void) =>\n (...args: unknown[]): void => {\n if (\n (globalThis as Record<symbol, unknown>)[CAPTURE] === true &&\n recordActive(name, args)\n )\n return;\n print(typeof prefix === \"string\" ? prefix : prefix[name], ...args);\n };\n return {\n info: level(\"info\", (...args) => console.log(...args)),\n warn: level(\"warn\", (...args) => console.warn(...args)),\n error: level(\"error\", (...args) => console.error(...args)),\n debug: level(\"debug\", (...args) => console.debug(...args)),\n };\n}\n\n/** The prefixes of loggers a caller did not supply. */\nexport const DEFAULT_LOG_PREFIXES: Record<Level, string> = {\n info: \"[INFO]\",\n warn: \"[WARN]\",\n error: \"[ERROR]\",\n debug: \"[DEBUG]\",\n};\n","import type { TSchema } from \"@sinclair/typebox\";\nimport {\n type Action,\n type ActionConfigWithAuthorize,\n type ActionConfigWithoutAuthorize,\n type ActionContext,\n type ActionErrorDefinition,\n type ErrorBuilder,\n type BaseContext,\n ActionExecutionError,\n ValidationError,\n type Logger,\n} from \"./types\";\nimport { normalizeActionError } from \"./error-response\";\nimport { validateWithSchema } from \"./typebox\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\n\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet _defaultCtxSeq = 0;\n\n// Symbol to tie context resolution to a specific service instance and invocation\nconst RESOLVED_SYMBOL = Symbol(\"resolved\");\n\nconst standardErrorDefaults: Record<\n string,\n { status: number; message: string }\n> = {\n BAD_REQUEST: { status: 400, message: \"Bad Request\" },\n UNAUTHORIZED: { status: 401, message: \"Unauthorized\" },\n FORBIDDEN: { status: 403, message: \"Forbidden\" },\n NOT_FOUND: { status: 404, message: \"Not Found\" },\n CONFLICT: { status: 409, message: \"Conflict\" },\n INTERNAL_SERVER_ERROR: { status: 500, message: \"Internal Server Error\" },\n};\n\nfunction createDefaultContext(partial?: any): BaseContext & any {\n // Only accept pre-resolved context with a service-specific marker or when service will handle resolution\n if (partial?.[RESOLVED_SYMBOL]) return partial;\n const seq = (++_defaultCtxSeq).toString(36);\n const req = partial?.request ?? DEFAULT_REQUEST;\n return {\n request: req,\n traceId: partial?.traceId || `tr_${seq}`,\n requestId: partial?.requestId || `req_${seq}`,\n db: partial?.db,\n user: partial?.user,\n logger: partial?.logger || defaultLogger,\n services: partial?.services || {},\n metadata: partial?.metadata || {},\n ...partial,\n [RESOLVED_SYMBOL]: true,\n };\n}\n\n/**\n * The `error` helpers an action receives: one function per error code that\n * throws an `ActionExecutionError` with that code and status. The standard HTTP\n * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,\n * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to\n * them or replace one.\n *\n * @param errorsDef - The action's `errors`: for each code, its `message` and\n * `status` (default 400).\n * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,\n * and always throw.\n */\nexport function buildErrorHelpers<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(errorsDef?: TErrors): ErrorBuilder<TErrors> {\n const helpers: Record<string, any> = {};\n\n // 1. Populate standard HTTP error helpers\n for (const [code, def] of Object.entries(standardErrorDefaults)) {\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n const message = overrideMessage || def.message;\n const status = def.status;\n throw new ActionExecutionError(code, message, status, details, options);\n };\n }\n\n // 2. Populate or override with user-defined action errors\n if (errorsDef) {\n for (const [code, def] of Object.entries(errorsDef)) {\n helpers[code] = (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => {\n const message = overrideMessage || def.message;\n const status = def.status || 400;\n throw new ActionExecutionError(code, message, status, details, options);\n };\n }\n }\n\n return helpers as ErrorBuilder<TErrors>;\n}\n\n/**\n * Define a reusable error. Spread it into the `errors` of any action, listener or\n * command; give it a `details` schema and `error.CODE(message, details)` checks\n * the details against it in types. The details are not validated at runtime.\n *\n * @example\n * const SlugExists = defineError(\"SLUG_EXISTS\", {\n * status: 409,\n * message: \"Slug is already taken\",\n * details: t.Object({ slug: t.String() }),\n * });\n * // errors: { ...SlugExists } then error.SLUG_EXISTS(undefined, { slug })\n */\nexport function defineError<\n const TCode extends string,\n TDetails extends TSchema | undefined = undefined,\n>(\n code: TCode,\n definition: { status?: number; message: string; details?: TDetails },\n): {\n [K in TCode]: { status?: number; message: string } & (TDetails extends TSchema\n ? { details: TDetails }\n : {});\n} {\n return { [code]: definition } as any;\n}\n\n/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */\nexport function errorsOf<\n TErrors extends Record<string, ActionErrorDefinition>,\n>(action: { config: { errors?: TErrors } }): TErrors {\n return (action.config.errors ?? {}) as TErrors;\n}\n\n/**\n * Define an action: a typed, validated function that Brick serves over HTTP,\n * runs in-process, and exposes to the typed client and OpenAPI.\n *\n * A call runs in order: the input is validated against `input` (an invalid one\n * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;\n * `execute` runs; and its result is validated against `output` (a mismatch is a\n * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared\n * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value\n * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response\n * and in the log.\n *\n * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`\n * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.\n * Where it is given, `execute` can rely on what it checked.\n *\n * @param config - `name`, `execute`, and optionally `description`, `input` and\n * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to\n * change the route (POST by default), `tags`, and `emits`.\n * @returns The action. Register it with `service.action(action)`; call it\n * directly with `action.run(input, ctx)`.\n * @example\n * import { defineAction, t } from \"@brickkit/core\";\n *\n * export const getPage = defineAction({\n * name: \"get\",\n * method: \"GET\",\n * input: t.Object({ id: t.String() }),\n * output: t.Object({ id: t.String(), title: t.String() }),\n * errors: { PAGE_GONE: { message: \"That page was removed\", status: 410 } },\n * authorize: ({ user }) => user != null,\n * execute: async ({ input, ctx, error }) => {\n * const page = await findPage(ctx.db, input.id);\n * if (!page) throw error.NOT_FOUND(\"No such page\");\n * return page;\n * },\n * });\n */\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Action<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineAction(config: any): any {\n const errorHelpers = buildErrorHelpers(config.errors);\n\n const actionFn = (async (params: { input?: any; ctx?: any }) => {\n return actionFn.execute(params);\n }) as any;\n\n Object.defineProperty(actionFn, \"name\", {\n value: config.name,\n configurable: true,\n });\n\n actionFn.config = config;\n actionFn.errorHelpers = errorHelpers;\n\n actionFn.validateInput = (input: unknown) => {\n return validateWithSchema(config.input, input);\n };\n\n actionFn.validateOutput = (output: unknown) => {\n const runtimeSchema =\n (actionFn as { outputValidationSchema?: TSchema })\n .outputValidationSchema ?? config.output;\n return validateWithSchema(runtimeSchema, output);\n };\n\n actionFn.run = async (input?: any, ctx?: any) => {\n return actionFn.execute({ input, ctx });\n };\n\n actionFn.execute = async (params: { input?: any; ctx?: any }) => {\n const boundService = actionFn.service;\n // The bound service resolves the context once per request, and recognizes\n // one it already resolved.\n const fullCtx: any = boundService?.resolveContext\n ? await boundService.resolveContext(params?.ctx)\n : createDefaultContext(params?.ctx);\n\n try {\n // Fill ctx.db from the bound service or the registry when the call has none.\n if (!fullCtx.db) {\n const service =\n boundService ??\n (actionFn.serviceName\n ? getGlobalRegistry().get(actionFn.serviceName)\n : undefined);\n if (service?.getDb()) fullCtx.db = service.getDb();\n }\n\n // 1. Validate Input\n if (config.input) {\n const inputValidation = actionFn.validateInput(params?.input);\n if (!inputValidation.success) {\n throw new ValidationError(\n `Validation failed for action '${config.name}' input` as string,\n inputValidation.errors,\n );\n }\n }\n\n // 2. Authorize\n if (config.authorize) {\n const allowed = await config.authorize({\n user: fullCtx.user,\n input: params?.input,\n ctx: fullCtx,\n });\n if (!allowed) {\n throw new ActionExecutionError(\n fullCtx.user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${config.name}'`,\n fullCtx.user == null ? 401 : 403,\n );\n }\n }\n\n // 3. Execute implementation\n const result = await config.execute({\n input: params?.input,\n ctx: fullCtx,\n error: errorHelpers,\n });\n\n // 4. Validate Output\n const runtimeOutputSchema =\n (actionFn as { outputValidationSchema?: TSchema })\n .outputValidationSchema ?? config.output;\n if (runtimeOutputSchema) {\n const outputValidation = actionFn.validateOutput(result);\n if (!outputValidation.success) {\n throw new ValidationError(\n `Validation failed for action '${config.name}' output` as string,\n outputValidation.errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err) {\n throw normalizeActionError(err, fullCtx);\n }\n };\n\n return actionFn;\n}\n","import type { TSchema } from \"@sinclair/typebox\";\nimport type {\n Action,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionContext,\n ActionErrorDefinition,\n BaseContext,\n Resource,\n Service,\n} from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { defineAction } from \"./action\";\nimport { joinRoute, ownerPath } from \"./routes\";\n\nexport type PluginRouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport type PluginRouteScope = \"app\" | \"service\" | \"resource\";\nexport type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =\n | false\n | Readonly<Record<string, false | { path?: string; scope?: S }>>;\n\ntype ContextOf<S> =\n S extends Service<infer D, infer C> ? BaseContext<D> & C : never;\n\nexport interface PluginEndpointContext<\n C extends ActionContext = ActionContext,\n> {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n set: { status?: number; headers: Record<string, string> };\n ctx: C;\n}\n\nexport interface PluginRouteRegistrar<\n C extends ActionContext = ActionContext,\n S extends PluginRouteScope = PluginRouteScope,\n> {\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<I, O, E, C> & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n action<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<I, O, E, C> & {\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n },\n ): Action<I, O, E, C>;\n endpoint(config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: S;\n handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n }): void;\n}\n\nexport interface ServicePluginContext<\n S extends Service<any, any> = Service<any, any>,\n> {\n service: S;\n routes: PluginRouteRegistrar<ContextOf<S>, \"app\" | \"service\">;\n}\nexport interface ResourcePluginContext<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n> {\n service: S;\n resource: R;\n routes: PluginRouteRegistrar<ContextOf<S>>;\n}\n\n/** Plugins may specialize their returned API for the installation host. */\nexport interface ResourcePluginTypes {\n readonly table: unknown;\n readonly context: unknown;\n readonly resource: unknown;\n readonly api: object;\n}\nexport type ResourcePluginAPI<P, T, C, R = unknown> = P extends {\n readonly types: infer H extends ResourcePluginTypes;\n}\n ? (H & {\n readonly table: T;\n readonly context: C;\n readonly resource: R;\n })[\"api\"]\n : P extends import(\"./define-plugin\").PluginInstance<\n infer A extends object,\n any\n >\n ? A\n : P extends ResourcePlugin<any, any, infer A>\n ? A\n : never;\n\n// Process-global like actionBindingKey, so descriptors survive a second core copy.\nconst pluginKind: unique symbol = Symbol.for(\"brickkit.plugin.kind\");\n/** `definePlugin` instances install on either host; see `define-plugin.ts`. */\nexport const pluginFinish: unique symbol = Symbol.for(\"brickkit.plugin.finish\");\nexport interface ServicePlugin<S extends Service<any, any>, A> {\n readonly [pluginKind]: \"service\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes<\"app\" | \"service\">;\n readonly setup: (context: ServicePluginContext<S>) => A;\n}\nexport interface ResourcePlugin<\n S extends Service<any, any>,\n R extends Resource<any, any, any>,\n A extends object,\n> {\n readonly [pluginKind]: \"resource\" | \"plugin\";\n readonly name: string;\n readonly routes?: PluginRoutes;\n readonly setup: (context: ResourcePluginContext<S, R>) => A;\n}\n\n/**\n * Define a plugin that installs onto a service with `service.use(plugin)`. Its\n * `setup` receives the service and a `routes` registrar for adding actions and\n * raw HTTP endpoints, and returns the typed API that `service.use` hands back.\n *\n * @param definition - A unique `name`, optional `routes` controls that let the\n * user move or switch off the plugin's routes, and `setup`, which must be\n * synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n * @example\n * import { defineServicePlugin, t } from \"@brickkit/core\";\n *\n * export const greeting = (salutation = \"Hello\") =>\n * defineServicePlugin({\n * name: \"example/greeting\",\n * setup({ routes }) {\n * const hello = routes.action({\n * name: \"hello\",\n * input: t.Object({ name: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `${salutation}, ${input.name}!`,\n * });\n * return { hello };\n * },\n * });\n *\n * const api = greeterService.use(greeting(\"Welcome\"));\n * await api.hello({ input: { name: \"Ada\" } });\n */\nexport function defineServicePlugin<\n S extends Service<any, any> = Service<any, any>,\n A = unknown,\n>(\n definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & {\n setup: (\n context: ServicePluginContext<S>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ServicePlugin<S, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [pluginKind]: \"service\" as const,\n });\n}\n/**\n * Define a plugin that installs onto a resource (a table and its entity) with\n * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a\n * `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and\n * returns the typed API that `resource.use` hands back. `crud` is built this way.\n *\n * @param definition - A unique `name`, optional `routes` controls, and `setup`,\n * which must be synchronous.\n * @returns The plugin descriptor, frozen.\n * @throws When the name is empty or has surrounding whitespace.\n */\nexport function defineResourcePlugin<\n S extends Service<any, any> = Service<any, any>,\n R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,\n A extends object = object,\n>(\n definition: Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & {\n setup: (\n context: ResourcePluginContext<S, R>,\n ) => A & (A extends PromiseLike<unknown> ? never : unknown);\n },\n): ResourcePlugin<S, R, A> {\n validateName(definition.name);\n return Object.freeze({\n ...definition,\n routes: copyControls(definition.routes),\n [pluginKind]: \"resource\" as const,\n });\n}\n\nfunction validateName(name: string) {\n if (!name || name.trim() !== name)\n throw new Error(\n \"Plugin and route names must be nonempty and have no surrounding whitespace\",\n );\n}\nfunction validatePath(path: string) {\n if (\n !path.startsWith(\"/\") ||\n path.includes(\"?\") ||\n path.includes(\"#\") ||\n path.includes(\"//\") ||\n path.split(\"/\").some((part) => part === \".\" || part === \"..\")\n ) {\n throw new Error(`Invalid plugin route path '${path}'`);\n }\n}\nfunction copyControls<S extends PluginRouteScope>(\n controls: PluginRoutes<S> | undefined,\n): PluginRoutes<S> | undefined {\n if (controls === undefined || controls === false) return controls;\n const result: Record<string, false | { path?: string; scope?: S }> =\n Object.create(null);\n for (const [name, value] of Object.entries(controls)) {\n validateName(name);\n if (value === false) {\n result[name] = false;\n continue;\n }\n if (value.path !== undefined) validatePath(value.path);\n if (\n value.scope !== undefined &&\n ![\"app\", \"service\", \"resource\"].includes(value.scope)\n )\n throw new Error(`Invalid plugin route scope '${value.scope}'`);\n result[name] = Object.freeze({ ...value });\n }\n return Object.freeze(result);\n}\n\ninterface Binding {\n service: Service<any, any>;\n resource?: Resource<any, any, any>;\n /** Owning plugin descriptor name (e.g. `@brickkit/crud`). Kept separate from the public action name. */\n plugin: string;\n path: string;\n method: PluginRouteMethod;\n scope: PluginRouteScope;\n enabled: boolean;\n clientPath?: string[];\n}\ninterface RawBinding extends Binding {\n handler: (context: PluginEndpointContext<any>) => unknown | Promise<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\ninterface Installation {\n descriptor: object;\n status: \"installing\" | \"installed\";\n api?: unknown;\n}\ninterface PluginState {\n hosts: Map<object, Map<string, Installation>>;\n actions: Map<Action<any, any, any, any>, Binding>;\n endpoints: RawBinding[];\n}\nconst states = new WeakMap<object, PluginState>();\nconst actionBindings = new WeakMap<Action<any, any, any, any>, Binding>();\n/**\n * Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)\n * may load a second copy of core that owns a different WeakMap, while the\n * action objects themselves cross the boundary by reference. The binding\n * travels on the action under a process-global symbol so route lookups\n * (including disabled-route suppression) keep working there.\n */\nconst actionBindingKey = Symbol.for(\"brickkit.plugin.actionBinding\");\nfunction stateOf(service: Service<any, any>): PluginState {\n let state = states.get(service);\n if (!state) {\n state = { hosts: new Map(), actions: new Map(), endpoints: [] };\n states.set(service, state);\n }\n return state;\n}\nexport function isInstallingPlugin(service: Service<any, any>): boolean {\n return [...(states.get(service)?.hosts.values() ?? [])].some(\n (installations) =>\n [...installations.values()].some((item) => item.status === \"installing\"),\n );\n}\n\nfunction pathOf(binding: Binding, prefix: string) {\n return joinRoute(\n binding.scope === \"app\"\n ? ownerPath(prefix)\n : ownerPath(\n prefix,\n binding.service.name,\n binding.scope === \"resource\" ? binding.resource!.name : undefined,\n ),\n binding.path,\n );\n}\n/** v0.10 mounted resource scope at `${prefix}/${resource}`, with names as declared. */\nfunction legacyPathOf(binding: Binding, prefix: string) {\n const scope =\n binding.scope === \"app\"\n ? \"\"\n : `/${binding.scope === \"resource\" ? binding.resource!.name : binding.service.name}`;\n return joinRoute(`${prefix.replace(/\\/$/, \"\")}${scope}`, binding.path);\n}\n/**\n * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the\n * compiler, and the typed client.\n *\n * @param action - An action.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns `undefined` when no plugin bound the action (it uses its own route),\n * `false` when the plugin's route was switched off, otherwise the route's\n * `path`, the v0.10 `legacyPath`, `method`, the `clientPath` the typed client uses, and the owning\n * `plugin` and `resource`.\n */\nexport function getPluginActionRoute(\n action: Action<any, any, any, any>,\n prefix = \"/api\",\n) {\n const binding =\n (action as unknown as Record<symbol, Binding | undefined>)[\n actionBindingKey\n ] ?? actionBindings.get(action);\n if (!binding) return undefined;\n if (!binding.enabled) return false;\n return {\n path: pathOf(binding, prefix),\n legacyPath: legacyPathOf(binding, prefix),\n method: binding.method,\n clientPath: binding.clientPath,\n plugin: binding.plugin,\n resource: binding.resource?.name,\n };\n}\n/**\n * The raw HTTP endpoints plugins registered on a service, ready to mount on the\n * application. Each handler resolves the service's context before it runs.\n *\n * @param service - The service plugins were installed on.\n * @param prefix - The application's route prefix (default `/api`).\n * @returns The enabled endpoints: `path`, `method`, `handler`, and the\n * `summary`, `description`, and `tags` for OpenAPI.\n */\nexport function getPluginEndpoints(\n service: Service<any, any>,\n prefix = \"/api\",\n) {\n return stateOf(service)\n .endpoints.filter((binding) => binding.enabled)\n .map((binding) => ({\n path: pathOf(binding, prefix),\n legacyPath: legacyPathOf(binding, prefix),\n method: binding.method,\n service,\n plugin: binding.plugin,\n summary: binding.summary,\n description: binding.description,\n tags: binding.tags,\n handler: async (context: Omit<PluginEndpointContext, \"ctx\">) =>\n binding.handler({\n ...context,\n ctx: await service.resolveContext({ request: context.request }),\n }),\n }));\n}\n\n/** Descriptor identity is scoped to the service or resource installation host. */\nexport function installPlugin(\n service: Service<any, any>,\n resource: Resource<any, any, any> | undefined,\n descriptor: ServicePlugin<any, any> | ResourcePlugin<any, any, any>,\n) {\n if (service.isBuilt)\n throw new Error(\"Plugins must be installed before service build\");\n if (\n descriptor[pluginKind] !== (resource ? \"resource\" : \"service\") &&\n descriptor[pluginKind] !== \"plugin\"\n )\n throw new Error(\"Plugin does not support this installation host\");\n const state = stateOf(service);\n const host = resource ?? service;\n const existing = state.hosts.get(host)?.get(descriptor.name);\n if (existing) {\n if (existing.status === \"installing\")\n throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);\n if (existing.descriptor !== descriptor)\n throw new Error(\n `Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`,\n );\n return resource ?? existing.api;\n }\n const snapshots = {\n actions: new Map(service.actions),\n tools: new Map(service.tools),\n tables: new Map(service.tables),\n resources: new Map(service.resources),\n preparations: new Map(service.preparations),\n hosts: new Map(\n [...state.hosts].map(([key, installations]) => [\n key,\n new Map(installations),\n ]),\n ),\n bindings: new Map(state.actions),\n endpoints: [...state.endpoints],\n properties: new Map(\n [...service.resources.values()].map((item) => [\n item,\n Object.getOwnPropertyDescriptors(item),\n ]),\n ),\n };\n const installations =\n state.hosts.get(host) ?? new Map<string, Installation>();\n state.hosts.set(host, installations);\n installations.set(descriptor.name, { descriptor, status: \"installing\" });\n const names = new Set<string>();\n const ownedActions = new Set<Action<any, any, any, any>>();\n let active = true;\n const bindingFor = (config: {\n name: string;\n path: string;\n method: PluginRouteMethod;\n scope?: PluginRouteScope;\n }): Binding => {\n if (!active || service.isBuilt)\n throw new Error(\"Plugin routes can only be registered during setup\");\n validateName(config.name);\n validatePath(config.path);\n if (names.has(config.name))\n throw new Error(`Duplicate plugin route name '${config.name}'`);\n names.add(config.name);\n const control =\n descriptor.routes === false ? false : descriptor.routes?.[config.name];\n const scope =\n (control && control.scope) ||\n config.scope ||\n (resource ? \"resource\" : \"service\");\n if (scope === \"resource\" && !resource)\n throw new Error(\"Service plugin routes cannot use resource scope\");\n if (![\"app\", \"service\", \"resource\"].includes(scope))\n throw new Error(`Invalid plugin route scope '${scope}'`);\n if (![\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(config.method))\n throw new Error(`Invalid plugin route method '${config.method}'`);\n const path = (control && control.path) || config.path;\n validatePath(path);\n return {\n service,\n resource,\n plugin: descriptor.name,\n path,\n method: config.method,\n scope,\n enabled: control !== false,\n };\n };\n const routes: PluginRouteRegistrar<any> = {\n action(config: any) {\n const binding = bindingFor(config);\n for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) {\n if (\n !config.input?.properties ||\n !Object.hasOwn(config.input.properties, match[1]!)\n )\n throw new Error(\n `Plugin action path parameter '${match[1]}' must be declared in its input schema`,\n );\n }\n // Public contract name: resource/operation only (e.g. `page.list`).\n // The owning plugin stays in binding metadata (`plugin`) and on the\n // action (`plugin`/`resource`) so it never leaks into exported names,\n // OpenAPI, or client contracts.\n const name = `${resource ? `${resource.name}.` : \"\"}${config.name}`;\n if (service.actions.has(name))\n throw new Error(\n `Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`,\n );\n const { scope: _scope, ...actionConfig } = config;\n const action = defineAction({ ...actionConfig, name });\n (action as unknown as Record<string, unknown>).plugin = descriptor.name;\n if (resource)\n (action as unknown as Record<string, unknown>).resource = resource.name;\n service.action(action);\n ownedActions.add(action);\n state.actions.set(action, binding);\n actionBindings.set(action, binding);\n // Same object travels across bundler module copies; see actionBindingKey.\n (action as unknown as Record<symbol, Binding>)[actionBindingKey] =\n binding;\n return action;\n },\n endpoint(config) {\n const binding = bindingFor(config);\n state.endpoints.push({\n ...binding,\n handler: config.handler,\n summary: config.summary,\n description: config.description,\n tags: config.tags,\n });\n },\n };\n try {\n const api = resource\n ? (descriptor as ResourcePlugin<any, any, any>).setup({\n service,\n resource,\n routes,\n })\n : (descriptor as ServicePlugin<any, any>).setup({ service, routes });\n if (api && typeof api === \"object\" && \"then\" in api)\n throw new Error(\"Plugin setup must be synchronous\");\n if (\n descriptor.routes &&\n Object.keys(descriptor.routes).some((name) => !names.has(name))\n )\n throw new Error(\n `Plugin '${descriptor.name}' has an override for an unknown route`,\n );\n const walk = (value: unknown, path: string[], ancestors: Set<object>) => {\n if (typeof value === \"function\") {\n const binding = state.actions.get(value as Action<any, any, any, any>);\n if (binding && ownedActions.has(value as Action<any, any, any, any>)) {\n if (binding.clientPath)\n throw new Error(\"Plugin actions must have one returned API path\");\n binding.clientPath = resource\n ? [service.name, resource.name, ...path]\n : [service.name, ...path];\n }\n } else if (value && typeof value === \"object\" && !ancestors.has(value)) {\n const next = new Set(ancestors).add(value);\n for (const [key, child] of Object.entries(value))\n walk(child, [...path, key], next);\n }\n };\n walk(api, [], new Set());\n if (resource) {\n if (!api || typeof api !== \"object\" || Array.isArray(api))\n throw new Error(\"Resource plugins must return named API contributions\");\n for (const key of Object.keys(api)) {\n if (\n key in resource ||\n [\"__proto__\", \"prototype\", \"constructor\"].includes(key)\n )\n throw new Error(\n `Resource plugin contribution '${key}' collides with an existing property`,\n );\n }\n Object.assign(resource, api);\n }\n state.hosts.get(host)!.set(descriptor.name, {\n descriptor,\n status: \"installed\",\n api,\n });\n finish(descriptor, true);\n getGlobalRegistry().touch();\n return resource ?? api;\n } catch (error) {\n finish(descriptor, false);\n for (const action of state.actions.keys())\n if (!snapshots.bindings.has(action)) {\n actionBindings.delete(action);\n delete (action as unknown as Record<symbol, unknown>)[actionBindingKey];\n }\n restoreMap(service.actions, snapshots.actions);\n restoreMap(service.tools, snapshots.tools);\n restoreMap(service.tables, snapshots.tables);\n restoreMap(service.resources, snapshots.resources);\n restoreMap(service.preparations, snapshots.preparations);\n state.hosts = snapshots.hosts;\n state.actions = snapshots.bindings;\n state.endpoints = snapshots.endpoints;\n for (const [item, properties] of snapshots.properties) {\n for (const key of Reflect.ownKeys(item))\n if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);\n Object.defineProperties(item, properties);\n }\n getGlobalRegistry().touch();\n throw error;\n } finally {\n active = false;\n }\n}\nfunction finish(descriptor: object, installed: boolean) {\n (descriptor as { [pluginFinish]?: (installed: boolean) => void })[\n pluginFinish\n ]?.(installed);\n}\n/** Whether a plugin named `name` is installed on `host` (the service or a resource). */\nexport function hasPlugin(\n service: Service<any, any>,\n host: object,\n name: string,\n): boolean {\n return (\n states.get(service)?.hosts.get(host)?.get(name)?.status === \"installed\"\n );\n}\n/** Every descriptor installed on the service or its resources, in install order per host. */\nexport function installedPlugins(service: Service<any, any>): object[] {\n return [...(states.get(service)?.hosts.values() ?? [])].flatMap(\n (installations) =>\n [...installations.values()]\n .filter((item) => item.status === \"installed\")\n .map((item) => item.descriptor),\n );\n}\nfunction restoreMap<K, V>(target: Map<K, V>, snapshot: Map<K, V>) {\n target.clear();\n for (const [key, value] of snapshot) target.set(key, value);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\ndeclare const portType: unique symbol;\n\n/** A typed dependency slot, declared with `port<T>()` and filled by `brick({ deps })`. */\nexport interface Port<T> {\n readonly [portType]?: T;\n}\n\n/** The dependency slots of a service: `{ carrier: port<Carrier>() }`. */\nexport type Ports = Record<string, Port<unknown>>;\n\n/** The values a set of ports is filled with: `{ carrier: Carrier }`. */\nexport type DepsOf<P> = {\n [K in keyof P]: P[K] extends Port<infer T> ? T : never;\n};\n\n/**\n * Declare a dependency a service needs, without creating it. The app provides\n * the value with `brick({ deps })`, and the service's code reads it as\n * `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).\n *\n * @returns A slot typed as `T`. It holds nothing at runtime.\n * @example\n * import { defineService, port } from \"@brickkit/core\";\n *\n * export const orders = defineService(\"orders\", {\n * database,\n * deps: { carrier: port<Carrier>() },\n * });\n *\n * // app.ts\n * export default brick({ services: [orders], deps: { carrier: createCarrier() } });\n */\nexport function port<T>(): Port<T> {\n return Object.freeze({}) as Port<T>;\n}\n\n/** Where a socket a plugin declared keeps the plugin's deps; global so a second core copy finds it. */\nexport const PLUGIN_DEPS: unique symbol = Symbol.for(\"brickkit.plugin.deps\");\n\nconst running = new AsyncLocalStorage<Record<string, unknown>>();\n\n/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */\nexport function runWithDeps<T>(deps: Record<string, unknown>, fn: () => T): T {\n return running.run(deps, fn);\n}\n\n/**\n * The deps of the app that is running the current listener or workflow step.\n * Actions, tools and socket handlers read `ctx.deps` instead.\n *\n * A workflow step is a plain function the Workflow SDK calls by name, so it\n * cannot close over the app that started it. Brick runs every listener and every\n * step inside its app, and this returns that app's `brick({ deps })`.\n *\n * @param ports - Optional: the ports to type the result by (the same object a\n * service passes as its `deps` option). Otherwise pass the type: `useDeps<{ carrier: Carrier }>()`.\n * @returns The app's deps.\n * @throws When called outside a listener or workflow step of a Brick app.\n * @example\n * export const ordersDeps = { carrier: port<Carrier>() };\n *\n * async function bookCarrier(orderId: string) {\n * \"use step\";\n * return useDeps(ordersDeps).carrier.book(orderId);\n * }\n */\nexport function useDeps<const P extends Ports>(ports: P): DepsOf<P>;\nexport function useDeps<T = Record<string, unknown>>(): T;\nexport function useDeps(): Record<string, unknown> {\n const deps = running.getStore();\n if (!deps)\n throw new Error(\n \"useDeps() was called outside a Brick app: call it from a listener or a workflow step (actions read ctx.deps).\",\n );\n return deps;\n}\n\n/**\n * Check `brick({ deps })` against what the services declare, and give each\n * service the values of its own ports.\n *\n * @throws When a service declares a dep the app does not provide, or the app\n * provides one that no service declares.\n */\nexport function bindDeps(\n services: readonly {\n name: string;\n options: { deps?: Ports };\n setDeps?(deps: Record<string, unknown>): void;\n }[],\n provided: Record<string, unknown> = {},\n): void {\n const declared = new Set<string>();\n for (const service of services) {\n const own: Record<string, unknown> = {};\n for (const name of Object.keys(service.options.deps ?? {})) {\n if (!Object.hasOwn(provided, name) || provided[name] === undefined)\n throw new Error(\n `Brick: service \"${service.name}\" declares dep \"${name}\", but brick({ deps }) does not provide it`,\n );\n declared.add(name);\n own[name] = provided[name];\n }\n service.setDeps?.(Object.freeze(own));\n }\n for (const name of Object.keys(provided))\n if (!declared.has(name))\n throw new Error(\n `Brick: brick({ deps }) provides \"${name}\", but no service declares it (services: ${services.map((service) => service.name).join(\", \") || \"none\"})`,\n );\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport { getTableName, type Table } from \"drizzle-orm\";\nimport {\n integer as sqliteInteger,\n real as sqliteReal,\n sqliteTable,\n text as sqliteText,\n type SQLiteColumnBuilderBase,\n} from \"drizzle-orm/sqlite-core\";\nimport {\n boolean as pgBoolean,\n doublePrecision,\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp as pgTimestamp,\n} from \"drizzle-orm/pg-core\";\nimport { PLUGIN_DEPS, runWithDeps, type DepsOf, type Ports } from \"./deps\";\nimport type { EventCatalog, EventRef, EventRefs } from \"./events/catalog\";\nimport type { EventListener } from \"./events/types\";\nimport {\n hasPlugin,\n pluginFinish,\n type PluginRouteRegistrar,\n type ResourcePlugin,\n type ServicePlugin,\n} from \"./plugin\";\nimport { definitionSite } from \"./registry\";\nimport type { SecretRef } from \"./secrets\";\nimport { validateWithSchema } from \"./typebox\";\nimport type { ActionContext, BaseContext, Resource, Service } from \"./types\";\n\n/*\n * definePlugin: one plugin with a manifest Brick checks (name, supported Brick\n * versions, required plugins, typed options, secrets) and a place for each\n * capability: owned tables, catalog events, host CRUD hooks, routes, and an\n * app part with start/stop lifecycle, middleware and listeners. Installing on\n * a service or resource reuses `installPlugin`, so route registration,\n * collision checks and rollback are the same as for the older two kinds.\n */\n\n// ---------------------------------------------------------------- versions\n\nlet runningVersion: string | undefined;\n/** The version of this @brickkit/core, read from its package.json; `\"\"` when unknown. */\nexport function brickVersion(): string {\n if (runningVersion !== undefined) return runningVersion;\n // src/ and dist/ sit one level down, a shared chunk two.\n for (const relative of [\"../package.json\", \"../../package.json\"]) {\n try {\n const json = JSON.parse(\n readFileSync(fileURLToPath(new URL(relative, import.meta.url)), \"utf8\"),\n );\n if (json.name === \"@brickkit/core\")\n return (runningVersion = json.version);\n } catch {\n // Not there; try the next one.\n }\n }\n // shortcut: a bundle that inlined core has no package.json; the check then passes.\n return (runningVersion = \"\");\n}\n\ntype Triple = [number, number, number];\nfunction parseVersion(version: string): Triple {\n const [major = 0, minor = 0, patch = 0] = version\n .replace(/^v/, \"\")\n .split(/[-+]/)[0]!\n .split(\".\")\n .map(Number);\n return [major, minor, patch];\n}\nfunction compare(a: Triple, b: Triple): number {\n return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];\n}\n\n/**\n * Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,\n * `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.\n */\nexport function satisfiesRange(version: string, range: string): boolean {\n const current = parseVersion(version);\n return range.split(\"||\").some((set) =>\n set\n .trim()\n .split(/\\s+/)\n .filter(Boolean)\n .every((comparator) => {\n const match =\n /^(\\^|~|>=|<=|>|<|=)?v?([\\dx*]+(?:\\.[\\dx*]+){0,2})?/i.exec(\n comparator,\n );\n const operator = match?.[1] ?? \"\";\n const raw = match?.[2] ?? \"*\";\n const parts = raw.split(\".\");\n const wild = parts.findIndex((part) => /^[x*]$/i.test(part));\n const given = wild === -1 ? parts.length : wild;\n const low = parseVersion(parts.slice(0, given).join(\".\") || \"0\");\n if (given === 0) return true;\n const cmp = compare(current, low);\n if (operator === \">=\") return cmp >= 0;\n if (operator === \">\") return cmp > 0;\n if (operator === \"<\") return cmp < 0;\n if (operator === \"<=\") return cmp <= 0;\n let high: Triple;\n if (operator === \"^\")\n high =\n low[0] > 0 || given === 1\n ? [low[0] + 1, 0, 0]\n : low[1] > 0 || given === 2\n ? [0, low[1] + 1, 0]\n : [0, 0, low[2] + 1];\n else if (operator === \"~\" || given < 3)\n high = given === 1 ? [low[0] + 1, 0, 0] : [low[0], low[1] + 1, 0];\n else return cmp === 0;\n return cmp >= 0 && compare(current, high) < 0;\n }),\n );\n}\n\n// ------------------------------------------------------------------ tables\n\nconst OWNER = Symbol.for(\"brickkit.plugin.owner\");\n/** The plugin that owns a table, for tables a `definePlugin` contributed. */\nexport function pluginOwner(table: unknown): string | undefined {\n return table && typeof table === \"object\"\n ? (table as Record<symbol, string | undefined>)[OWNER]\n : undefined;\n}\n\nconst sqliteBuilders = {\n /** A table. Its name gets the plugin's prefix (`page_comments`). */\n table: <C extends Record<string, SQLiteColumnBuilderBase>>(\n name: string,\n columns: C,\n ) => sqliteTable(name, columns),\n text: (name: string) => sqliteText(name),\n integer: (name: string) => sqliteInteger(name, { mode: \"number\" }),\n real: (name: string) => sqliteReal(name),\n boolean: (name: string) => sqliteInteger(name, { mode: \"boolean\" }),\n /** A `Date`, stored as epoch milliseconds or `timestamptz`. */\n timestamp: (name: string) => sqliteInteger(name, { mode: \"timestamp_ms\" }),\n json: (name: string) => sqliteText(name, { mode: \"json\" }),\n};\n\n/**\n * Engine-neutral column builders for `tables`. Brick passes the SQLite or\n * Postgres ones to match the host database; the types follow SQLite's, and the\n * JavaScript values are the same on both (a `Date` for `timestamp`).\n */\nexport type PluginTableBuilders = typeof sqliteBuilders & {\n /** The host database's engine. */\n readonly engine: \"sqlite\" | \"postgres\";\n};\n\nfunction builders(\n engine: \"sqlite\" | \"postgres\",\n tableName: (name: string) => string,\n): PluginTableBuilders {\n if (engine === \"postgres\")\n return {\n engine,\n table: (name, columns) =>\n pgTable(tableName(name), columns as never) as never,\n text: (name) => pgText(name) as never,\n integer: (name) => pgInteger(name) as never,\n real: (name) => doublePrecision(name) as never,\n boolean: (name) => pgBoolean(name) as never,\n timestamp: (name) =>\n pgTimestamp(name, { mode: \"date\", withTimezone: true }) as never,\n json: (name) => jsonb(name) as never,\n };\n return {\n ...sqliteBuilders,\n engine,\n table: (name, columns) => sqliteTable(tableName(name), columns),\n };\n}\n\n// ------------------------------------------------------------------- hooks\n\n/** Where `hooks.*` stores a plugin's hooks; `@brickkit/crud` runs them. */\nconst HOST_HOOKS = Symbol.for(\"brickkit.plugin.hooks\");\n\ninterface HookBase<C> {\n ctx: C;\n /** The write's open transaction: write other tables through it. */\n tx: any;\n}\n/**\n * Subscribe to the host's CRUD writes (resources with `crud()`). `before*` and\n * `after*` run inside the write's transaction, after the host's own crud hooks;\n * a hook that throws rolls the write back. `afterCommit` runs after the commit.\n */\nexport interface PluginHooks<C = ActionContext> {\n beforeCreate(\n hook: (args: HookBase<C> & { data: Record<string, unknown> }) => unknown,\n ): void;\n afterCreate(\n hook: (args: HookBase<C> & { row: Record<string, unknown> }) => unknown,\n ): void;\n beforeUpdate(\n hook: (\n args: HookBase<C> & { id: unknown; data: Record<string, unknown> },\n ) => unknown,\n ): void;\n afterUpdate(\n hook: (\n args: HookBase<C> & { id: unknown; row: Record<string, unknown> },\n ) => unknown,\n ): void;\n beforeDelete(hook: (args: HookBase<C> & { id: unknown }) => unknown): void;\n afterDelete(hook: (args: HookBase<C> & { id: unknown }) => unknown): void;\n afterCommit(\n hook: (args: {\n operation: \"create\" | \"update\" | \"delete\";\n id: unknown;\n row?: Record<string, unknown>;\n ctx: C;\n }) => unknown,\n ): void;\n}\nconst HOOK_NAMES = [\n \"beforeCreate\",\n \"afterCreate\",\n \"beforeUpdate\",\n \"afterUpdate\",\n \"beforeDelete\",\n \"afterDelete\",\n \"afterCommit\",\n] as const;\n\n// ---------------------------------------------------------------- manifest\n\ntype Secrets = Record<string, SecretRef<any>>;\ntype OptionsOf<O> = O extends TSchema ? Static<O> : {};\n\n/**\n * The context of a plugin's actions, endpoints and hooks: the host's request\n * context, loosely typed, with `deps` set to the plugin's own declared deps.\n */\nexport type PluginContext<P extends Ports = {}> = BaseContext<any> &\n PluginServiceContext<P>;\n/** A plugin's view of its host's service context: loose, except `deps`, which is the plugin's. */\nexport type PluginServiceContext<P extends Ports = {}> = {\n [key: string]: any;\n /** The values passed for the plugin's `deps` when it was installed. */\n deps: DepsOf<P>;\n};\n\n/** What every setup callback receives. */\nexport interface PluginSetupContext<\n O,\n S,\n T,\n E extends EventCatalog,\n P extends Ports = {},\n> {\n /** The validated options, defaults filled in. */\n options: O;\n /** The declared secrets, to read when they are needed. */\n secrets: S;\n /** The tables this plugin owns, by the keys `tables` returned. */\n tables: T;\n /** The plugin's events, as `emitEvent` and `defineListener` take them. */\n events: EventRefs<E>;\n /** The values passed for `deps` when the plugin was installed. */\n deps: DepsOf<P>;\n /** The host service. Actions registered on it read the plugin's deps as `ctx.deps`. */\n service: Service<any, PluginServiceContext<P>>;\n routes: PluginRouteRegistrar<PluginContext<P>>;\n /** The host's CRUD writes: on a service, those of all its resources. */\n hooks: PluginHooks<PluginContext<P>>;\n}\n\n/** The lifecycle context of `on(\"start\")` and `on(\"stop\")`. */\nexport interface PluginLifecycleContext<O, S, P extends Ports = {}> {\n options: O;\n secrets: S;\n deps: DepsOf<P>;\n}\n\n/** What `app` receives: the app-wide part of a plugin. */\nexport interface PluginAppContext<O, S, P extends Ports = {}> {\n options: O;\n secrets: S;\n /** The values passed for `deps` when the plugin was installed. */\n deps: DepsOf<P>;\n /**\n * Run when the app starts (`app.start()`, which `listen`, `brick dev` and\n * `brick start` call) in install order, and when it stops in reverse order.\n */\n on(\n event: \"start\" | \"stop\",\n handler: (context: PluginLifecycleContext<O, S, P>) => void | Promise<void>,\n ): void;\n /**\n * Run before every request is routed. Return a `Response` (or any value) to\n * answer it here; return nothing to let it through.\n */\n middleware(\n handler: (context: {\n request: Request;\n set: { status?: number | string; headers: Record<string, string> };\n }) => unknown,\n ): void;\n /** Event listeners to add to the app's `events`; `useDeps()` in their `run` returns the plugin's deps. */\n listeners(...listeners: EventListener[]): void;\n}\n\nexport interface PluginManifest<\n O extends TSchema | undefined = undefined,\n S extends Secrets = {},\n T extends Record<string, Table> = {},\n E extends EventCatalog = {},\n RA extends object = {},\n SA = unknown,\n P extends Ports = {},\n> {\n /** The npm package name, scoped: `@acme/brick-comments`. */\n name: string;\n description?: string;\n /** The Brick versions it supports, as a semver range: `^0.11.0`. */\n brick?: string;\n /** Plugins that must be installed on the same host first, by name. */\n requires?: readonly string[];\n /** A TypeBox schema for the options; defaults fill what the user leaves out. */\n options?: O;\n /** Secrets it reads, from `defineSecret`. */\n secrets?: S;\n /**\n * What it needs from the app, declared with `port<T>()`. The user passes the\n * values when installing: `notify(options, { deps: { mailer } })`. Setup\n * parts read them as `deps`, the plugin's actions as `ctx.deps`.\n */\n deps?: P;\n /**\n * Tables it owns. They are created in the host service's database for its\n * engine, named `<host>_<table>` (or with the install's `prefix`), and join\n * schema sync and migrations through `database.tables`.\n */\n tables?: (builders: PluginTableBuilders) => T;\n /** Events it emits; they join the host catalog as `<plugin>.<event>`. */\n events?: E;\n /** Installed with `resource.use()`; returns what the resource gains. */\n resource?: (\n context: PluginSetupContext<OptionsOf<O>, S, T, E, P> & {\n resource: Resource<any, PluginContext<P>, any>;\n },\n ) => RA & (RA extends PromiseLike<unknown> ? never : unknown);\n /** Installed with `service.use()`; returns what `use` hands back. */\n service?: (\n context: PluginSetupContext<OptionsOf<O>, S, T, E, P>,\n ) => SA & (SA extends PromiseLike<unknown> ? never : unknown);\n /**\n * The app-wide part: lifecycle, middleware and listeners. Runs once per\n * plugin instance when `brick()` creates the app, whether the plugin was\n * installed with `brick({ plugins })`, `service.use()` or `resource.use()`.\n */\n app?: (context: PluginAppContext<OptionsOf<O>, S, P>) => void;\n /**\n * A dashboard extension module (`defineDashboard`), relative to the file\n * that calls `definePlugin`. `brick dev` merges it with the app's own.\n */\n dashboard?: string;\n}\n\n/** Where the plugin is installed, besides its options. */\nexport interface PluginInstallOptions {\n /** Table name prefix instead of `<host>_`, such as `\"blog_\"`; `\"\"` for none. */\n prefix?: string;\n}\n\n/** What the plugin's capabilities are, read from its manifest. */\nexport interface PluginInfo {\n readonly name: string;\n readonly description?: string;\n readonly brick?: string;\n readonly requires: readonly string[];\n readonly options?: TSchema;\n readonly secrets: readonly string[];\n /** The names of the deps it declares, passed when installing. */\n readonly deps: readonly string[];\n readonly capabilities: readonly (\n | \"tables\"\n | \"events\"\n | \"resource\"\n | \"service\"\n | \"app\"\n | \"dashboard\"\n )[];\n}\n\nconst INTERNALS = Symbol.for(\"brickkit.plugin.internals\");\ninterface Installation {\n scope: \"app\" | \"service\" | \"resource\";\n service?: string;\n resource?: string;\n}\ninterface Internals {\n manifest: PluginManifest<any, any, any, any, any, any, any>;\n options: Record<string, unknown>;\n deps: Readonly<Record<string, unknown>>;\n install: PluginInstallOptions;\n dashboard?: string;\n installs: Installation[];\n /** When it was first installed, to run `app` parts in install order. */\n order?: number;\n}\nlet installCount = 0;\n\n/** A plugin ready to install: `resource.use(p)`, `service.use(p)` or `brick({ plugins: [p] })`. */\nexport type PluginInstance<\n RA extends object = {},\n SA = unknown,\n> = ResourcePlugin<any, any, RA> &\n ServicePlugin<any, SA> & { readonly info: PluginInfo };\n\n/** `definePlugin`'s result: call it with options to get an instance. */\nexport type PluginFactory<\n O extends TSchema | undefined,\n RA extends object,\n SA,\n P extends Ports = {},\n> = ((\n // shortcut: every option is optional in the type (TypeBox types carry no\n // defaults); a required one without a default fails when installed.\n ...args: {} extends P\n ? [options?: Partial<OptionsOf<O>>, install?: PluginInstallOptions]\n : [\n options: Partial<OptionsOf<O>> | undefined,\n install: PluginInstallOptions & { deps: DepsOf<P> },\n ]\n) => PluginInstance<RA, SA>) & { readonly info: PluginInfo };\n\nconst toWords = (name: string) =>\n (name.split(\"/\").pop() ?? name)\n .replace(/^brick-/, \"\")\n .replace(/-plugin$/, \"\")\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\nconst snake = (value: string) =>\n value.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase();\n\n/**\n * Define a plugin: a manifest Brick checks, plus the capabilities the plugin\n * brings. Install its instances with `resource.use()`, `service.use()` or\n * `brick({ plugins })`; scope comes from where it is installed.\n *\n * @param manifest - `name`, `brick` (semver range), `requires`, `options`\n * (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`\n * parts, and a `dashboard` extension.\n * @returns A factory: `comments({ maxLength: 500 })` validates the options and\n * the Brick version and returns an instance to install.\n * @throws From the factory, when the running Brick is outside `brick` or an\n * option is invalid; when installed, when a required plugin is missing or the\n * host does not suit the plugin.\n * @example\n * export const audit = definePlugin({\n * name: \"@acme/brick-audit\",\n * brick: \"^0.11.0\",\n * requires: [\"@brickkit/crud\"],\n * options: t.Object({ table: t.String({ default: \"audit\" }) }),\n * tables: ({ table, text, timestamp }) => ({\n * log: table(\"log\", { id: text(\"id\").primaryKey(), at: timestamp(\"at\").notNull() }),\n * }),\n * resource: ({ tables, hooks }) => {\n * hooks.afterCreate(({ row, tx }) =>\n * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));\n * return {};\n * },\n * });\n *\n * page.use(audit());\n */\nexport function definePlugin<\n O extends TSchema | undefined = undefined,\n S extends Secrets = {},\n T extends Record<string, Table> = {},\n const E extends EventCatalog = {},\n RA extends object = {},\n SA = unknown,\n P extends Ports = {},\n>(\n manifest: PluginManifest<O, S, T, E, RA, SA, P>,\n): PluginFactory<O, RA, SA, P> {\n const { name } = manifest;\n if (!name || name.trim() !== name)\n throw new Error(\n \"Plugin names must be nonempty and have no surrounding whitespace\",\n );\n if (!manifest.resource && !manifest.service && !manifest.app)\n throw new Error(\n `Plugin \"${name}\" needs a resource, service or app part to install`,\n );\n for (const key of Object.keys(manifest.events ?? {}))\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key))\n throw new Error(\n `Event \"${key}\" of plugin \"${name}\" must be a plain name such as added`,\n );\n const site = definitionSite()?.replace(/:\\d+$/, \"\");\n const dashboard =\n manifest.dashboard === undefined\n ? undefined\n : manifest.dashboard.startsWith(\"file:\")\n ? fileURLToPath(manifest.dashboard)\n : isAbsolute(manifest.dashboard) || !site\n ? resolve(manifest.dashboard)\n : resolve(dirname(site), manifest.dashboard);\n const info: PluginInfo = Object.freeze({\n name,\n description: manifest.description,\n brick: manifest.brick,\n requires: Object.freeze([...(manifest.requires ?? [])]),\n options: manifest.options,\n secrets: Object.freeze(\n Object.values(manifest.secrets ?? {}).map((secret) => secret.name),\n ),\n deps: Object.freeze(Object.keys(manifest.deps ?? {})),\n capabilities: Object.freeze(\n (\n [\"tables\", \"events\", \"resource\", \"service\", \"app\", \"dashboard\"] as const\n ).filter((key) => manifest[key] !== undefined),\n ),\n });\n const words = toWords(name);\n // `comments` for events (`comments.added`), `comments` for tables.\n const eventSpace = words\n .map((word, index) =>\n index ? word[0]!.toUpperCase() + word.slice(1) : word,\n )\n .join(\"\");\n const tableSpace = snake(words.join(\"_\"));\n if (!eventSpace)\n throw new Error(`Plugin \"${name}\" needs letters or digits in its name`);\n\n const factory = (\n input: Partial<OptionsOf<O>> = {},\n install: PluginInstallOptions & { deps?: Record<string, unknown> } = {},\n ): PluginInstance<RA, SA> => {\n const version = brickVersion();\n if (manifest.brick && version && !satisfiesRange(version, manifest.brick))\n throw new Error(\n `${name} supports Brick ${manifest.brick}; this app runs ${version}`,\n );\n const options = checkOptions(name, manifest.options, input);\n const deps = checkDeps(name, eventSpace, manifest.deps, install.deps);\n const secrets = (manifest.secrets ?? {}) as S;\n const internals: Internals = {\n manifest,\n options,\n deps,\n install,\n dashboard,\n installs: [],\n };\n // A stack: a plugin may install another instance of itself during setup.\n const pending: (() => void)[] = [];\n\n const setup = (context: {\n service: Service<any, any>;\n resource?: Resource<any, any, any>;\n routes: PluginRouteRegistrar<any>;\n }) => {\n const { service, resource } = context;\n const host = resource ?? service;\n const where = resource\n ? `resource \"${resource.name}\"`\n : `service \"${service.name}\"`;\n const part = resource ? manifest.resource : manifest.service;\n if (!part)\n throw new Error(\n `${name} cannot be installed on a ${resource ? \"resource\" : \"service\"}; ${\n manifest.resource\n ? \"use resource.use()\"\n : manifest.service\n ? \"use service.use()\"\n : \"add it to brick({ plugins })\"\n }`,\n );\n for (const required of manifest.requires ?? [])\n if (!hasPlugin(service, host, required))\n throw new Error(\n `${name} requires ${required}, installed on ${where} before it`,\n );\n\n // Tables: built for the host's engine, registered with the service now\n // (rolled back with it), added to its database once installed.\n let tables = {} as T;\n if (manifest.tables) {\n const database = service.getDatabaseHandle?.();\n if (!database)\n throw new Error(\n `${name} owns tables, so service \"${service.name}\" needs a database`,\n );\n const prefix =\n install.prefix ?? `${snake(resource?.name ?? service.name)}_`;\n tables = manifest.tables(\n builders(database.engine, (table) =>\n install.prefix !== undefined || table === tableSpace\n ? `${prefix}${table}`\n : `${prefix}${tableSpace}_${table}`,\n ),\n );\n const taken = new Set(\n [...service.tables.values(), ...Object.values(database.tables)].map(\n (table) => getTableName(table),\n ),\n );\n for (const table of Object.values(tables)) {\n const tableName = getTableName(table);\n if (taken.has(tableName))\n throw new Error(\n `${name} table \"${tableName}\" clashes with a table service \"${service.name}\" already has; install it with another prefix`,\n );\n taken.add(tableName);\n Object.defineProperty(table, OWNER, { value: name });\n service.registerTable(table);\n }\n }\n\n // Events: `<plugin>.<event>` in the host catalog. The same plugin on\n // two resources of one service shares them.\n const catalog = service.events as Record<string, EventRef>;\n const events: Record<string, EventRef> = {};\n for (const [key, schema] of Object.entries(manifest.events ?? {})) {\n const existing = catalog[`${eventSpace}.${key}`];\n if (existing && existing.plugin !== name)\n throw new Error(\n `${name} event \"${eventSpace}.${key}\" is already in the catalog of service \"${service.name}\"`,\n );\n events[key] =\n existing ??\n Object.freeze({\n name: `${service.name}.${eventSpace}.${key}`,\n service: service.name,\n schema,\n plugin: name,\n });\n }\n\n const added: Record<string, ((args: any) => unknown)[]> = {};\n const hooks = Object.fromEntries(\n HOOK_NAMES.map((hook) => [\n hook,\n (fn: (args: any) => unknown) => {\n if (typeof fn !== \"function\")\n throw new Error(`${name}: hooks.${hook} needs a function`);\n (added[hook] ??= []).push((args) =>\n fn({ ...args, ctx: { ...args.ctx, deps } }),\n );\n },\n ]),\n ) as unknown as PluginHooks<any>;\n\n const routes: PluginRouteRegistrar<any> = {\n action: (config: any) => context.routes.action(config),\n endpoint: (config) =>\n context.routes.endpoint({\n ...config,\n handler: (args) =>\n config.handler({ ...args, ctx: { ...args.ctx, deps } }),\n }),\n };\n const before = new Set<unknown>([\n ...service.actions.values(),\n ...service.tools.values(),\n ...service.listSockets(),\n ]);\n const started = bindings;\n const api = part({\n options: options as never,\n secrets,\n tables,\n events: events as EventRefs<E>,\n deps: deps as DepsOf<P>,\n service: service as never,\n resource: resource as never,\n routes,\n hooks,\n });\n if (api && typeof (api as { then?: unknown }).then === \"function\")\n throw new Error(\"Plugin setup must be synchronous\");\n // Every action and socket the setup added (its own, its resources', crud's) runs with the plugin's deps.\n for (const action of [\n ...service.actions.values(),\n ...service.tools.values(),\n ])\n if (!before.has(action)) bindPluginDeps(name, action, deps, started);\n for (const socket of service.listSockets())\n if (!before.has(socket))\n (socket as unknown as Record<symbol, unknown>)[PLUGIN_DEPS] ??= deps;\n\n pending.push(() => {\n const database = service.getDatabaseHandle?.();\n for (const table of Object.values(tables))\n database?.addTable?.(getTableName(table), table);\n if (Object.keys(events).length)\n // `readonly` for users; the catalog grows only here.\n (service as { events: Record<string, EventRef> }).events =\n Object.freeze({\n ...catalog,\n ...Object.fromEntries(\n Object.entries(events).map(([key, ref]) => [\n `${eventSpace}.${key}`,\n ref,\n ]),\n ),\n });\n const store = ((host as unknown as Record<symbol, unknown>)[\n HOST_HOOKS\n ] ??= {}) as Record<string, ((args: any) => unknown)[]>;\n for (const [hook, fns] of Object.entries(added))\n (store[hook] ??= []).push(...fns);\n internals.installs.push({\n scope: resource ? \"resource\" : \"service\",\n service: service.name,\n resource: resource?.name,\n });\n internals.order ??= ++installCount;\n });\n return resource ? (api ?? {}) : api;\n };\n\n return Object.freeze({\n [Symbol.for(\"brickkit.plugin.kind\")]: \"plugin\",\n name,\n info,\n setup,\n [INTERNALS]: internals,\n [pluginFinish]: (installed: boolean) => {\n const commit = pending.pop();\n if (installed) commit?.();\n },\n }) as unknown as PluginInstance<RA, SA>;\n };\n return Object.assign(factory, { info });\n}\n\n/** Counts bindings, so a setup can tell a nested install's from an earlier one's. */\nlet bindings = 0;\n/**\n * Give an action's `execute` and `authorize` the plugin's deps as `ctx.deps`.\n * The config is changed in place: every way an action runs (HTTP, compiled\n * routes, `action.run`, RPC) reads `config.execute` from it. A nested\n * definePlugin binds its own actions first, so they keep its deps.\n *\n * @throws When the action is already bound to another install's deps: one\n * action object shared by two installs could only run with one of them.\n */\nfunction bindPluginDeps(\n plugin: string,\n action: unknown,\n deps: Readonly<Record<string, unknown>>,\n started: number,\n) {\n const config = (action as { config?: Record<string | symbol, any> }).config;\n if (!config) return;\n const bound = config[PLUGIN_DEPS] as\n | { deps: Readonly<Record<string, unknown>>; at: number }\n | undefined;\n if (bound) {\n if (bound.deps === deps || bound.at > started) return;\n throw new Error(\n `${plugin}: action \"${(action as { name?: string }).name}\" is already bound to the deps of another install; create the action inside the setup so each install gets its own`,\n );\n }\n config[PLUGIN_DEPS] = { deps, at: ++bindings };\n const { execute, authorize } = config;\n if (typeof execute === \"function\")\n config.execute = (args: { ctx?: object }) =>\n execute({ ...args, ctx: { ...args.ctx, deps } });\n if (typeof authorize === \"function\")\n config.authorize = (args: { ctx?: object }) =>\n authorize({ ...args, ctx: { ...args.ctx, deps } });\n}\n\n/** Check the deps passed at install against the ports the plugin declares. */\nfunction checkDeps(\n plugin: string,\n factory: string,\n ports: Ports | undefined,\n given: unknown = {},\n): Readonly<Record<string, unknown>> {\n if (given === null || typeof given !== \"object\" || Array.isArray(given))\n throw new Error(`${plugin}: deps must be an object`);\n const declared = Object.keys(ports ?? {});\n const provided = given as Record<string, unknown>;\n const extra = Object.keys(provided).filter((key) => !declared.includes(key));\n if (extra.length)\n throw new Error(\n `${plugin} does not declare ${extra.map((key) => `deps.${key}`).join(\", \")}; ${\n declared.length ? `it takes ${declared.join(\", \")}` : \"it takes no deps\"\n }`,\n );\n const missing = declared.filter((key) => provided[key] === undefined);\n if (missing.length)\n throw new Error(\n `${plugin} needs ${missing.map((key) => `deps.${key}`).join(\", \")}; pass it when installing: ${factory}(options, { deps: { ${missing.join(\", \")} } })`,\n );\n return Object.freeze(\n Object.fromEntries(declared.map((key) => [key, provided[key]])),\n );\n}\n\nfunction checkOptions(\n plugin: string,\n schema: TSchema | undefined,\n input: unknown,\n): Record<string, unknown> {\n if (input === null || typeof input !== \"object\" || Array.isArray(input))\n throw new Error(`${plugin}: options must be an object`);\n if (!schema) {\n if (Object.keys(input).length)\n throw new Error(`${plugin} takes no options`);\n return {};\n }\n const value = Value.Default(schema, structuredClone(input));\n const result = validateWithSchema(schema, value);\n if (!result.success) {\n const [first] = result.errors;\n const option = first!.path.replace(/^\\//, \"\").replaceAll(\"/\", \".\");\n throw new Error(\n `${plugin}: option ${option ? `\"${option}\"` : \"\"} ${first!.message}`.replace(\n /\\s+/g,\n \" \",\n ),\n );\n }\n return value as Record<string, unknown>;\n}\n\n// --------------------------------------------------------------- app part\n\n/** A plugin as `app.definition.plugins` lists it. */\nexport interface InstalledPlugin {\n readonly name: string;\n readonly brick?: string;\n readonly scope: \"app\" | \"service\" | \"resource\";\n readonly service?: string;\n readonly resource?: string;\n /** The plugin's dashboard extension, an absolute path. */\n readonly dashboard?: string;\n}\n\nexport function isPluginInstance(value: unknown): value is PluginInstance {\n return (\n typeof value === \"object\" &&\n value !== null &&\n INTERNALS in (value as object)\n );\n}\nfunction internalsOf(value: unknown): Internals | undefined {\n return isPluginInstance(value)\n ? ((value as unknown as Record<symbol, Internals>)[INTERNALS] ?? undefined)\n : undefined;\n}\n\n/**\n * What `brick()` does with plugins: install those given in `plugins` on the\n * app, run every plugin's `app` part in install order, and return the\n * lifecycle, middleware and listeners they contributed.\n */\nexport function setupAppPlugins(\n installedOnServices: readonly object[],\n appPlugins: readonly unknown[],\n) {\n const instances = new Set<PluginInstance>();\n for (const descriptor of installedOnServices)\n if (isPluginInstance(descriptor)) instances.add(descriptor);\n const ordered = [...instances].sort(\n (a, b) => (internalsOf(a)!.order ?? 0) - (internalsOf(b)!.order ?? 0),\n );\n const onApp = new Set<string>();\n for (const plugin of appPlugins) {\n const internals = internalsOf(plugin);\n if (!internals)\n throw new Error(\n \"brick({ plugins }) takes instances from definePlugin(), such as audit()\",\n );\n const { manifest } = internals;\n if (!manifest.app || manifest.tables || manifest.events)\n throw new Error(\n `${manifest.name} cannot be installed on the app; ${\n manifest.resource ? \"use resource.use()\" : \"use service.use()\"\n }`,\n );\n for (const required of manifest.requires ?? [])\n if (!onApp.has(required))\n throw new Error(\n `${manifest.name} requires ${required}, installed in brick({ plugins }) before it`,\n );\n if (onApp.has(manifest.name))\n throw new Error(`Plugin ${manifest.name} is installed on the app twice`);\n // Its `app` part already runs from the service or resource install; running it again would double every hook.\n const installed = ordered.find(\n (other) => internalsOf(other)!.manifest.name === manifest.name,\n );\n if (installed)\n throw new Error(\n `Plugin ${manifest.name} is already installed with ${internalsOf(\n installed,\n )!\n .installs.map((install) =>\n install.scope === \"resource\"\n ? `${install.service}.${install.resource}.use()`\n : `${install.service}.use()`,\n )\n .join(\n \", \",\n )}, which runs its app part too; remove it from brick({ plugins })`,\n );\n onApp.add(manifest.name);\n if (!internals.installs.some((item) => item.scope === \"app\"))\n internals.installs.push({ scope: \"app\" });\n ordered.push(plugin as PluginInstance);\n }\n\n const lifecycles: Lifecycle[] = [];\n const middleware: ((context: any) => unknown)[] = [];\n const listeners: EventListener[] = [];\n const listed: InstalledPlugin[] = [];\n for (const plugin of ordered) {\n const { manifest, options, deps, installs, dashboard } =\n internalsOf(plugin)!;\n for (const install of installs)\n listed.push(\n Object.freeze({\n name: manifest.name,\n ...(manifest.brick ? { brick: manifest.brick } : {}),\n ...install,\n ...(dashboard ? { dashboard } : {}),\n }),\n );\n if (!manifest.app) continue;\n const lifecycle = { options, secrets: manifest.secrets ?? {}, deps };\n // A plugin's start and stop pair up, so stop runs only after its start did.\n const own = { start: [] as Function[], stop: [] as Function[] };\n manifest.app({\n ...lifecycle,\n on(event, handler) {\n if (event !== \"start\" && event !== \"stop\")\n throw new Error(`${manifest.name}: on() takes \"start\" or \"stop\"`);\n own[event].push(handler);\n },\n middleware(handler) {\n middleware.push(handler);\n },\n listeners(...items) {\n // `useDeps()` in a plugin's listener returns the plugin's deps, not the app's.\n listeners.push(\n ...items.map((listener) => {\n // Workflow steps run in the app's workflow handler, where they'd see the app's deps.\n if (listener.workflow)\n throw new Error(\n `${manifest.name}: plugins can't add workflow listeners yet, because workflow steps would see the app's deps instead of the plugin's; use a run listener ('${listener.name}')`,\n );\n const run = listener.run;\n return run\n ? {\n ...listener,\n run: (delivery: Parameters<typeof run>[0]) =>\n runWithDeps(deps, () => run(delivery)),\n }\n : listener;\n }),\n );\n },\n });\n lifecycles.push({\n start: async () => {\n for (const handler of own.start) await handler(lifecycle);\n },\n stop: async () => {\n for (const handler of own.stop) await handler(lifecycle);\n },\n });\n }\n return { lifecycles, middleware, listeners, plugins: listed };\n}\n\ninterface Lifecycle {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\n/**\n * Start in install order. Stop what started, in reverse order; a start that\n * fails stops those before it and rethrows.\n */\nexport function pluginLifecycle(lifecycles: readonly Lifecycle[]) {\n let started: Promise<void> | undefined;\n const running: Lifecycle[] = [];\n const stopAll = async () => {\n const errors: unknown[] = [];\n for (const item of running.splice(0).reverse())\n try {\n await item.stop();\n } catch (error) {\n errors.push(error);\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length)\n throw new AggregateError(errors, \"Plugins failed to stop\");\n };\n return {\n start(): Promise<void> {\n return (started ??= (async () => {\n for (const item of lifecycles) {\n try {\n await item.start();\n } catch (error) {\n await stopAll().catch(() => undefined);\n started = undefined;\n throw error;\n }\n running.push(item);\n }\n })());\n },\n async stop(): Promise<void> {\n await started?.catch(() => undefined);\n started = undefined;\n await stopAll();\n },\n };\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"../types\";\n\nimport { toErrorResponse } from \"../error-response\";\nimport type { Logger } from \"../types\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n // Early return on the first key: an allocation-free emptiness check.\n for (const _ in value) return true; // NOSONAR\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\n// Generic pre-validation nesting cap for parsed HTTP input. Compiled input\n// validators recurse, so unbounded nesting (e.g. a 20k-deep filter object)\n// would throw RangeError (HTTP 500) instead of failing validation with a\n// 400. The walk is iterative and far above legitimate depths (a max-depth\n// CRUD filter is ~45 levels of JSON).\nconst MAX_INPUT_DEPTH = 128;\nexport function inputTooDeep(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const stack: { node: unknown; depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (depth > MAX_INPUT_DEPTH) return true;\n if (node && typeof node === \"object\") {\n const children = Array.isArray(node) ? node : Object.values(node);\n for (const child of children)\n if (child && typeof child === \"object\")\n stack.push({ node: child, depth: depth + 1 });\n }\n }\n return false;\n}\n\nfunction checkDepth(value: unknown, action: string) {\n if (!inputTooDeep(value)) return;\n throw new ValidationError(`Validation failed for action '${action}' input`, [\n { path: \"\", message: \"Input exceeds maximum nesting depth\" },\n ]);\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction mapError(\n err: unknown,\n set: any,\n options: { logger: Logger; requestId: string },\n) {\n const response = toErrorResponse(err, options);\n set.status = response.status;\n return response;\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n checkDepth,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n deny: (action: string, user: unknown): never => {\n throw new ActionExecutionError(\n user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${action}'`,\n user == null ? 401 : 403,\n );\n },\n});\n","import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n} from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { buildErrorHelpers } from \"./action\";\nimport { toErrorResponse } from \"./error-response\";\nimport { inputTooDeep } from \"./compiler/runtime\";\nimport { createLogger } from \"./logger\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n // Early return on the first key: an allocation-free emptiness check.\n for (const _ in obj) return true; // NOSONAR\n return false;\n}\n\n/**\n * Work out, once at startup, everything an action's route needs to answer a\n * request: where its input comes from (body, query, or path), the validators,\n * the authorization and execute functions, and its logger. Low level: `brick()`\n * does this for every route.\n *\n * @param service - The service the action belongs to.\n * @param action - The action.\n * @param routePath - The route's path.\n * @param method - The HTTP method (POST by default).\n * @returns The plan `executeCompiledRoute` runs.\n */\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n // Prefer a runtime-only output schema when the action provides one (CRUD\n // subset projections validate loosely at runtime while `config.output`\n // stays strict for contracts/OpenAPI).\n const runtimeOutputSchema =\n (action as { outputValidationSchema?: typeof outputSchema })\n .outputValidationSchema ?? outputSchema;\n const outputChecker = runtimeOutputSchema\n ? (getCompiledCheck(runtimeOutputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{\n key: string;\n isNumber: boolean;\n isBoolean: boolean;\n isArray?: boolean;\n }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{\n key: string;\n isNumber: boolean;\n isBoolean: boolean;\n isArray?: boolean;\n }> = [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n } else if (type === \"array\") {\n list.push({ key, isNumber: false, isBoolean: false, isArray: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = createLogger(tag);\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\n/**\n * Answer one request for a compiled route: read the input, run the action, and\n * return its output or the error response, with the `x-trace-id` and\n * `x-request-id` headers set. Low level: `brick()` mounts this for every route.\n *\n * @param plan - From `compileRoutePlan`.\n * @param elysiaCtx - The Elysia request context: `params`, `body`, `query`,\n * `headers`, `request`, and `set`.\n * @returns The action's output, or an error envelope with the status set on `set`.\n */\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isArray) {\n const values = request\n ? new URL(request.url).searchParams.getAll(c.key)\n : [];\n coercedQuery[c.key] = values.length\n ? values\n : Array.isArray(val)\n ? val\n : [val];\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n // Path segments are strings; numeric ids (`/:id`) need numbers.\n let coercedParams = params;\n if (params && plan.coercions) {\n for (const c of plan.coercions) {\n if (!c.isNumber || typeof params[c.key] !== \"string\") continue;\n const num = Number(params[c.key]);\n if (isNaN(num)) continue;\n if (coercedParams === params) coercedParams = { ...params };\n coercedParams[c.key] = num;\n }\n }\n const hasP = isNonEmpty(coercedParams);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = coercedParams;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, coercedParams, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = coercedParams;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, coercedParams, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n deps: plan.service.deps ?? EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (inputTooDeep(input)) {\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n [{ path: \"\", message: \"Input exceeds maximum nesting depth\" }],\n );\n }\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n ctx.user == null ? \"UNAUTHORIZED\" : \"FORBIDDEN\",\n `Access denied for action '${plan.actionName}'`,\n ctx.user == null ? 401 : 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err) {\n const response = toErrorResponse(err, { logger: ctx.logger, requestId });\n set.status = response.status;\n return response;\n }\n}\n\n/**\n * An Elysia handler for one action: `compileRoutePlan` and\n * `executeCompiledRoute` together. Use it to mount an action on your own\n * Elysia app; `brick()` does it for you.\n *\n * @param service - The service the action belongs to.\n * @param action - The action.\n * @param routePath - The route's path.\n * @param method - The HTTP method (POST by default).\n * @returns A function from the Elysia context to the response.\n */\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import type { RouteIR } from \"./ir\";\nimport type { HandlerFactory } from \"./runtime\";\nimport type { ActionContext } from \"../types\";\n\nfunction coerceQueryValue(\n value: unknown,\n type: RouteIR[\"coercions\"][number][\"type\"],\n request: Request | undefined,\n key: string,\n) {\n if (type === \"number\" && value !== undefined) {\n const number = Number(value);\n return Number.isNaN(number) ? value : number;\n }\n if (type === \"array\") {\n const values = request ? new URL(request.url).searchParams.getAll(key) : [];\n return values.length ? values : Array.isArray(value) ? value : [value];\n }\n if (type === \"boolean\") {\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n }\n return value;\n}\n\n/** Bind route metadata with ordinary closures; emitted factories remain build-only. */\nexport function createHandlerFactory(route: RouteIR): HandlerFactory {\n return (binding, runtime) => {\n const {\n execute,\n contextHook,\n authorize,\n inputChecker,\n outputChecker,\n errorBuilder,\n logger,\n cachedDb,\n service,\n } = binding;\n const readLike = route.inputPrecedence[0] === \"query\";\n const objectInput = binding.action.config.input?.type === \"object\";\n const readInput = route.input\n ? ({ params, body, query, request }: any) => {\n let coercedQuery = query;\n if (query && route.coercions.length) {\n coercedQuery = { ...query };\n for (const { key, type } of route.coercions) {\n if (query[key] !== undefined)\n coercedQuery[key] = coerceQueryValue(\n query[key],\n type,\n request,\n key,\n );\n }\n }\n // Path segments are strings; numeric ids (`/:id`) need numbers.\n let coercedParams = params;\n if (params && route.coercions.length) {\n for (const { key, type } of route.coercions) {\n if (type !== \"number\" || typeof params[key] !== \"string\")\n continue;\n const value = Number(params[key]);\n if (Number.isNaN(value)) continue;\n if (coercedParams === params) coercedParams = { ...params };\n coercedParams[key] = value;\n }\n }\n let input = readLike\n ? runtime.mergeInput(coercedQuery, coercedParams, body)\n : runtime.mergeInput(coercedParams, body, coercedQuery);\n if (objectInput) input ??= {};\n return input;\n }\n : () => undefined;\n const validateInput = (input: unknown) => {\n if (inputChecker) {\n runtime.checkDepth(input, route.action);\n runtime.validate(inputChecker, input, route.action, \"input\");\n }\n };\n const validateOutput = (result: unknown) => {\n if (route.output && outputChecker)\n runtime.validate(outputChecker, result, route.action, \"output\");\n return result;\n };\n const createContext = ({\n headers,\n request,\n set,\n }: any): ActionContext & { requestId: string } => {\n const seq = runtime.nextSequence();\n const traceId = headers?.[\"x-trace-id\"] || \"tr_\" + seq;\n const requestId = headers?.[\"x-request-id\"] || \"req_\" + seq;\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n return {\n request: request instanceof Request ? request : runtime.defaultRequest,\n traceId,\n requestId,\n db: cachedDb ?? service.getDb(),\n logger,\n services: runtime.emptyServices,\n deps: service.deps ?? runtime.emptyServices,\n metadata: { headers },\n _resolved: true,\n };\n };\n if (contextHook || authorize) {\n return async function brickAction(context) {\n const input = readInput(context);\n const ctx = createContext(context);\n try {\n if (contextHook) {\n const extra = await contextHook(ctx);\n if (extra) Object.assign(ctx, extra);\n }\n validateInput(input);\n if (authorize && !(await authorize({ ctx, input, user: ctx.user })))\n runtime.deny(route.action, ctx.user);\n return validateOutput(\n await execute({ input, ctx, error: errorBuilder }),\n );\n } catch (err) {\n return runtime.mapError(err, context.set, ctx);\n }\n };\n }\n return function brickAction(context) {\n const input = readInput(context);\n const ctx = createContext(context);\n try {\n validateInput(input);\n const result = execute({ input, ctx, error: errorBuilder });\n if (runtime.isThenable(result))\n return Promise.resolve(result)\n .then(validateOutput)\n .catch((err) => runtime.mapError(err, context.set, ctx));\n return validateOutput(result);\n } catch (err) {\n return runtime.mapError(err, context.set, ctx);\n }\n };\n };\n}\n","import type { BrickApp } from \"./endpoints\";\n\n/**\n * Whether a value is an application made by `brick()`. It checks for the\n * methods and `definition` a `BrickApp` has, so it also recognizes one built by\n * another copy of the package.\n *\n * @param app - Anything, such as the default export of an entry file.\n * @returns `true` for a `BrickApp`, narrowing its type.\n */\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\n/**\n * Check that a module's default export is an application ready to be served,\n * for tools that load an entry file.\n *\n * @param app - The default export of an entry file.\n * @returns The app.\n * @throws When it is not a `BrickApp`, or it already called `.listen()`: the\n * entry must only build the app, and leave listening to the server bootstrap.\n */\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n","import type { Service } from \"./types\";\nimport { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport { createHandlerFactory } from \"./compiler/handler\";\nimport {\n compilerRuntime,\n type CompiledHandler,\n type HandlerFactory,\n} from \"./compiler/runtime\";\nimport { requireBrickApp } from \"./app-entry\";\n\ntype ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;\nconst buildBindings = new Map<string, ApplicationBinder>();\n\nfunction applicationKey(\n services: readonly Service<any, any>[],\n prefix = \"/api\",\n) {\n return JSON.stringify([prefix, services.map((service) => service.name)]);\n}\n\n/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n ir: BrickIR,\n bind: ApplicationBinder,\n) {\n const key = JSON.stringify([ir.prefix, ir.services]);\n if (buildBindings.has(key))\n throw new Error(\"Brick compiler: overlapping compiled app imports\");\n buildBindings.set(key, bind);\n try {\n const app = requireBrickApp((await load()).default);\n if (applicationKey(app.definition.services, app.definition.prefix) !== key)\n throw new Error(\n \"Brick compiler: app services/prefix changed; rebuild the application\",\n );\n return app;\n } finally {\n buildBindings.delete(key);\n }\n}\n\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(\n compileRoutePlan(service, action, route.path, route.method),\n );\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const bind = buildBindings.get(\n applicationKey(options.services, options.prefix),\n );\n if (bind && options.mode !== \"generic\") return bind(options.services);\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] =\n options.mode === \"generic\"\n ? ir.routes.map(\n () => (plan) => (context) => executeCompiledRoute(plan, context),\n )\n : ir.routes.map(createHandlerFactory);\n if (options.mode !== \"generic\")\n for (const service of options.services) {\n service.prepareContributions();\n }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n for (const service of services) {\n service.prepareContributions();\n }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n","import type { Action, ActionAccessPolicy } from \"./types\";\n\nexport type { ActionAccessPolicy };\nexport interface ActionAccessInfo {\n hasAuthorize: boolean;\n hasScope: boolean;\n policy: ActionAccessPolicy;\n}\n\n/**\n * Cross-copy access metadata protocol. CRUD enforces its access policy\n * inside `execute`, so `config.authorize` is absent and introspection\n * can't see it. The plugin stamps each action under this process-global\n * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so\n * the binding survives a second copy of core (bundler SSR, Vitest),\n * same as the plugin action-binding key.\n */\nexport const ACTION_ACCESS_KEY = Symbol.for(\"brickkit.action.access\");\n\n/**\n * Record how an action is protected, for tools that cannot read it from the\n * configuration: plugins such as `crud` enforce access inside `execute`, so the\n * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard\n * read what is recorded here.\n *\n * @param action - The action to describe.\n * @param info - Whether it checks authorization and whether it scopes queries,\n * and the resulting policy.\n */\nexport function setActionAccess(action: object, info: ActionAccessInfo): void {\n (action as Record<symbol, ActionAccessInfo>)[ACTION_ACCESS_KEY] = {\n hasAuthorize: info.hasAuthorize,\n hasScope: info.hasScope,\n policy: info.policy,\n };\n}\n\n/**\n * How an action is protected: `\"public\"` when nothing checks the caller,\n * `\"authorized\"` when an `authorize` does, and `\"scoped\"` when the action also\n * limits what rows the caller can reach. It reads what a plugin recorded with\n * `setActionAccess`, else the action's own `authorize`, and keeps the policy\n * consistent with the flags.\n *\n * @param action - An action, or any object a plugin described.\n * @returns `hasAuthorize`, `hasScope`, and `policy`.\n */\nexport function getActionAccess(action: Action | object): ActionAccessInfo {\n const meta = (action as Record<symbol, unknown>)[ACTION_ACCESS_KEY] as\n | Partial<ActionAccessInfo>\n | undefined;\n const configAuthorize = Boolean(\n (action as Action)?.config &&\n typeof (action as Action).config === \"object\" &&\n \"authorize\" in (action as Action).config &&\n typeof (action as Action).config.authorize === \"function\",\n );\n if (!meta) {\n return {\n hasAuthorize: configAuthorize,\n hasScope: false,\n policy: configAuthorize ? \"authorized\" : \"public\",\n };\n }\n const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);\n const hasScope = Boolean(meta.hasScope);\n let policy: ActionAccessPolicy =\n meta.policy ??\n (hasAuthorize ? (hasScope ? \"scoped\" : \"authorized\") : \"public\");\n // Normalize conflicting metadata so the policy always agrees with the\n // effective flags (e.g. metadata stamped \"public\" on an action that also\n // declares config.authorize must not report policy \"public\").\n if (policy === \"public\" && hasAuthorize)\n policy = hasScope ? \"scoped\" : \"authorized\";\n else if (policy !== \"public\" && !hasAuthorize) policy = \"public\";\n else if (policy === \"scoped\" && !hasScope) policy = \"authorized\";\n return { hasAuthorize, hasScope, policy };\n}\n","import type { EventRef } from \"./events/catalog\";\nimport { getActionRoute } from \"./routes\";\nimport { getActionAccess } from \"./access\";\nimport type { ServiceRegistry } from \"./registry\";\nimport { getGlobalRegistry } from \"./registry\";\nimport type { Service, ActionErrorDefinition } from \"./types\";\n\nexport interface OpenApiGeneratorOptions {\n title?: string;\n version?: string;\n description?: string;\n prefix?: string;\n services?: Service<any, any>[];\n registry?: ServiceRegistry;\n}\n\nfunction isAnchor(\n node: unknown,\n): node is { $id: string } & Record<string, any> {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$id === \"string\"\n );\n}\n\nfunction isBareRef(node: unknown): node is { $ref: string } {\n return (\n typeof node === \"object\" &&\n node !== null &&\n typeof (node as Record<string, any>).$ref === \"string\" &&\n !(node as { $ref: string }).$ref.startsWith(\"#\")\n );\n}\n\nfunction toComponentKey(id: string): string {\n return id.replace(/[^A-Za-z0-9.\\-_]+/g, \"_\");\n}\n\n/**\n * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors\n * (`{ $id: \"T0\", ..., { $ref: \"T0\" } }`). OpenAPI interprets a bare `$ref`\n * as an external file reference, so downstream tooling tries to load a\n * file named `T0` and fails. Hoist every anchored subschema into\n * `#/components/schemas/` and rewrite the refs to local pointers.\n * First definition wins when one `$id` is declared twice.\n */\nexport function hoistAnchoredSchemas(spec: Record<string, any>): string[] {\n const anchored = new Map<string, any>();\n const conflicts: string[] = [];\n\n const collect = (node: any): any => {\n if (Array.isArray(node)) return node.map(collect);\n if (typeof node !== \"object\" || node === null) return node;\n if (isAnchor(node)) {\n const id = node.$id;\n const { $id: _dropped, ...rest } = node;\n const collected = collect(rest);\n if (anchored.has(id)) {\n if (JSON.stringify(anchored.get(id)) !== JSON.stringify(collected)) {\n conflicts.push(id);\n }\n } else {\n anchored.set(id, collected);\n }\n return { $ref: `#/components/schemas/${toComponentKey(id)}` };\n }\n for (const key of Object.keys(node)) {\n node[key] = collect(node[key]);\n }\n return node;\n };\n\n const rewrite = (node: any): void => {\n if (Array.isArray(node)) {\n for (const child of node) rewrite(child);\n return;\n }\n if (typeof node !== \"object\" || node === null) return;\n if (isBareRef(node)) {\n node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;\n }\n for (const key of Object.keys(node)) rewrite(node[key]);\n };\n\n collect(spec);\n\n const components = (spec.components ??= {}) as Record<string, any>;\n const schemas = (components.schemas ??= {}) as Record<string, any>;\n for (const [id, schema] of anchored) {\n schemas[toComponentKey(id)] = schema;\n }\n\n // Second pass covers refs inside the hoisted copies themselves\n // (e.g. the self-recursive JSON-value schema).\n rewrite(spec);\n\n return [...anchored.keys()];\n}\n\n/**\n * Build the OpenAPI 3.1 document for the services: one path per action route,\n * with request and response schemas from the actions' TypeBox schemas, their\n * declared errors, tags by service, and a bearer security scheme where any\n * action needs authorization. Declared events are listed under `x-brick-events`,\n * by wire name, with their service and payload schema.\n *\n * `brick()` calls this for `/openapi.json`; call it yourself to write the\n * document to a file or feed another tool.\n *\n * @param options - `title`, `version`, and `description` for the `info` block,\n * `prefix` (default `/api`), and the `services` or `registry` to describe\n * (the global registry by default).\n * @returns The document as a plain object.\n */\nexport function generateOpenApiSpec(\n options: OpenApiGeneratorOptions = {},\n): Record<string, any> {\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const description =\n options.description ??\n \"Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.\";\n const prefix = options.prefix ?? \"/api\";\n\n const services =\n options.services ??\n (options.registry ? options.registry.list() : getGlobalRegistry().list());\n\n const paths: Record<string, any> = {};\n const tags = new Map<string, string>();\n let hasAnyAuthorizedAction = false;\n\n for (const service of services) {\n tags.set(service.name, `Actions exposed by '${service.name}' service`);\n\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n const routePath = route.path;\n const method = route.method.toLowerCase();\n const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map(\n (match) => match[1]!,\n );\n const actionPath = routePath.replace(/:([^/]+)/g, \"{$1}\");\n if (!paths[actionPath]) paths[actionPath] = {};\n // Match the compiler's first-registration-wins policy for route collisions.\n if (paths[actionPath][method]) continue;\n\n const resource = (action as { resource?: string }).resource;\n // Resource routes group under `service · resource`.\n const group = resource ? `${service.name} · ${resource}` : service.name;\n if (resource)\n tags.set(\n group,\n `Routes of resource '${resource}' in service '${service.name}'`,\n );\n\n const hasAuth = getActionAccess(action).hasAuthorize;\n if (hasAuth) {\n hasAnyAuthorizedAction = true;\n }\n\n // Build responses map\n const responses: Record<string, any> = {};\n\n // 200 Success Response\n if (action.config.output) {\n responses[\"200\"] = {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: action.config.output,\n },\n },\n };\n } else {\n responses[\"200\"] = {\n description: \"Successful response\",\n };\n }\n\n const errorAlternatives = new Set<string>();\n const addError = (\n code: string,\n status: number,\n message: string,\n details?: unknown,\n ) => {\n const key = `${status}:${code}`;\n if (errorAlternatives.has(key)) return;\n errorAlternatives.add(key);\n const schema = {\n allOf: [\n { $ref: \"#/components/schemas/ErrorEnvelope\" },\n {\n type: \"object\",\n properties: {\n code: { const: code },\n status: { const: status },\n ...(details ? { details } : {}),\n },\n },\n ],\n };\n const existing = responses[String(status)];\n if (existing) {\n existing.description += \"; \" + message;\n existing.content[\"application/json\"].schema.oneOf.push(schema);\n } else {\n responses[String(status)] = {\n description: message,\n content: { \"application/json\": { schema: { oneOf: [schema] } } },\n };\n }\n };\n if (action.config.input)\n addError(\"VALIDATION_FAILED\", 400, \"Validation error\");\n if (hasAuth) {\n addError(\"UNAUTHORIZED\", 401, \"Authentication required\");\n addError(\"FORBIDDEN\", 403, \"Access denied\");\n }\n if (action.config.errors) {\n for (const [code, errorDef] of Object.entries(action.config.errors)) {\n const def = errorDef as ActionErrorDefinition;\n addError(code, def.status || 400, def.message || code, def.details);\n }\n }\n addError(\"INTERNAL_SERVER_ERROR\", 500, \"Internal server error\");\n if (action.config.output)\n addError(\"VALIDATION_FAILED\", 500, \"Output validation error\");\n\n const operation: Record<string, any> = {\n operationId: `${service.name}_${action.name}_${method}`,\n summary: `${service.name}.${action.name}`,\n description:\n action.config.description ??\n `Execute action '${action.name}' on service '${service.name}'`,\n tags: [...new Set([group, ...(action.config.tags ?? [])])],\n ...((action as { plugin?: string }).plugin\n ? { \"x-brick-plugin\": (action as { plugin?: string }).plugin }\n : {}),\n ...((action as { resource?: string }).resource\n ? { \"x-brick-resource\": (action as { resource?: string }).resource }\n : {}),\n responses,\n };\n\n const inputSchema = action.config.input;\n const properties = inputSchema?.properties ?? {};\n const parameters: any[] = [...new Set(pathParams)].map((key) => ({\n name: key,\n in: \"path\",\n required: true,\n schema: properties[key] ?? { type: \"string\" },\n }));\n const queryOnly = method === \"get\" || method === \"delete\";\n if (queryOnly) {\n for (const [key, schema] of Object.entries(properties)) {\n if (pathParams.includes(key)) continue;\n parameters.push({\n name: key,\n in: \"query\",\n required: inputSchema?.required?.includes(key) ?? false,\n schema,\n });\n }\n } else if (inputSchema) {\n const bodySchema =\n pathParams.length && inputSchema.properties\n ? {\n ...inputSchema,\n properties: Object.fromEntries(\n Object.entries(properties).filter(\n ([key]) => !pathParams.includes(key),\n ),\n ),\n required: (inputSchema.required ?? []).filter(\n (key: string) => !pathParams.includes(key),\n ),\n }\n : inputSchema;\n operation.requestBody = {\n required: true,\n content: { \"application/json\": { schema: bodySchema } },\n };\n }\n if (parameters.length) operation.parameters = parameters;\n if (hasAuth) operation.security = [{ bearerAuth: [] }];\n paths[actionPath][method] = operation;\n }\n }\n\n const spec: Record<string, any> = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n description,\n },\n paths,\n tags: Array.from(tags, ([name, description]) => ({ name, description })),\n };\n\n spec.components = {\n schemas: {\n ErrorEnvelope: {\n type: \"object\",\n required: [\"name\", \"code\", \"message\", \"status\", \"requestId\"],\n properties: {\n name: { type: \"string\" },\n code: { type: \"string\" },\n message: { type: \"string\" },\n status: { type: \"integer\" },\n requestId: { type: \"string\" },\n details: {},\n errors: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"path\", \"message\"],\n properties: {\n path: { type: \"string\" },\n message: { type: \"string\" },\n value: {},\n },\n },\n },\n },\n },\n },\n };\n if (hasAnyAuthorizedAction) {\n Object.assign(spec.components, {\n securitySchemes: {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description: \"Enter your Bearer authentication token\",\n },\n },\n });\n }\n\n const events = Object.fromEntries(\n services.flatMap((service) =>\n Object.values(\n (service as { events?: Record<string, EventRef> }).events ?? {},\n ).map((ref) => [\n ref.name,\n {\n service: service.name,\n payload: ref.schema,\n ...(ref.plugin ? { \"x-brick-plugin\": ref.plugin } : {}),\n },\n ]),\n ),\n );\n if (Object.keys(events).length) spec[\"x-brick-events\"] = events;\n\n // Operations reference live TypeBox schemas. Rewrite only the serialized\n // document so OpenAPI pointers cannot corrupt runtime validation schemas.\n const document: Record<string, any> = JSON.parse(JSON.stringify(spec));\n hoistAnchoredSchemas(document);\n\n return document;\n}\n","/**\n * Type-safe secrets & environment variables.\n *\n * Declare each secret once at module scope instead of scattering untyped\n * `process.env.FOO` reads:\n *\n * const port = defineSecret(\"PORT\").default(\"3333\").transform(Number).require();\n * const baseUrl = defineSecret(\"BASE_URL\").url().require();\n * const key = defineSecret(\"STRIPE_KEY\").validate((v) =>\n * v.startsWith(\"sk_\") || \"must start with sk_\"\n * ).require();\n *\n * Values resolve from the environment (Bun populates `process.env` from\n * `.env` locally; in prod the same env source applies — a future\n * `SecretSource` such as AWS can slot in without touching call sites).\n *\n * Resolution order per secret: test/session override → source (`process.env`\n * by default) → declared `default`. `resolveSecrets()` validates every\n * registered secret at boot and throws listing all missing required ones.\n */\n\nexport interface SecretSource {\n get(name: string): string | undefined;\n}\n\n/** Default source: `process.env` (Bun loads `.env` into it automatically). */\nexport const envSource: SecretSource = {\n get: (name: string) => process.env[name],\n};\n\nexport interface SecretOptions {\n /** Fallback when the source has no value. Secrets without a default are required. */\n default?: string;\n}\n\n/** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */\nexport type SecretValidator<T> = (value: T) => void | boolean | string;\n\nconst registry = new Map<string, SecretRef<any>>();\nconst overrides = new Map<string, string | undefined>();\n\nexport class SecretRef<T = string> {\n readonly name: string;\n readonly options: SecretOptions;\n private transformFn?: (raw: string) => T;\n private validators: SecretValidator<T>[] = [];\n\n constructor(name: string, options: SecretOptions = {}) {\n this.name = name;\n this.options = options;\n }\n\n /** True when a default was declared (i.e. the secret is optional). */\n get hasDefault(): boolean {\n return this.options.default !== undefined;\n }\n\n /** Fallback used when the source has no value. Makes the secret optional. */\n default(value: string): this {\n this.options.default = value;\n return this;\n }\n\n /**\n * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === \"true\"`).\n * Runs before validators; a throwing transform fails resolution.\n */\n transform<U>(fn: (raw: string) => U): SecretRef<U> {\n this.transformFn = fn as unknown as (raw: string) => T;\n return this as unknown as SecretRef<U>;\n }\n\n /** Run a custom check on the (transformed) value at every resolution. */\n validate(fn: SecretValidator<T>): this {\n this.validators.push(fn);\n return this;\n }\n\n /** Shorthand validator: value must parse as a URL. String refs only. */\n url(this: SecretRef<string>): SecretRef<string> {\n this.validators.push((v) => {\n try {\n new URL(v);\n } catch {\n return \"must be a valid URL\";\n }\n });\n return this;\n }\n\n private resolveRaw(source: SecretSource): string | undefined {\n if (overrides.has(this.name)) {\n const v = overrides.get(this.name);\n if (v !== undefined) return v;\n }\n return source.get(this.name) ?? this.options.default;\n }\n\n private coerce(raw: string): T {\n let value: T;\n if (this.transformFn) {\n try {\n value = this.transformFn(raw);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": transform failed (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n } else {\n value = raw as unknown as T;\n }\n for (const fn of this.validators) {\n let result: void | boolean | string;\n try {\n result = fn(value);\n } catch (err) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (result === false) {\n throw new Error(\n `Invalid value for secret \"${this.name}\": validation failed`,\n );\n }\n if (typeof result === \"string\") {\n throw new Error(`Invalid value for secret \"${this.name}\": ${result}`);\n }\n }\n return value;\n }\n\n /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */\n value(source: SecretSource = envSource): T | undefined {\n const raw = this.resolveRaw(source);\n if (raw === undefined) return undefined;\n return this.coerce(raw);\n }\n\n /** Resolved value, or throws naming the missing/invalid secret. */\n require(source: SecretSource = envSource): T {\n const raw = this.resolveRaw(source);\n if (raw === undefined) {\n throw new Error(\n `Missing required secret \"${this.name}\": set it in .env (local) or the environment (prod)`,\n );\n }\n return this.coerce(raw);\n }\n\n /** True when a value would resolve (override, source, or default). */\n isSet(source: SecretSource = envSource): boolean {\n return this.resolveRaw(source) !== undefined;\n }\n}\n\n/**\n * Declare a secret. Idempotent: re-declaring the same name returns the\n * original ref (first declaration wins) so module re-evaluation is safe.\n */\nexport function defineSecret(\n name: string,\n options: SecretOptions = {},\n): SecretRef<string> {\n const existing = registry.get(name);\n if (existing) return existing;\n const ref = new SecretRef<string>(name, options);\n registry.set(name, ref);\n return ref;\n}\n\n/**\n * Validate every registered secret at boot. Throws a single error listing\n * all missing required secrets. Returns the resolved values.\n */\nexport function resolveSecrets(\n opts: { source?: SecretSource } = {},\n): Record<string, unknown> {\n const source = opts.source ?? envSource;\n const missing: string[] = [];\n const resolved: Record<string, unknown> = {};\n for (const ref of registry.values()) {\n const v = ref.value(source);\n if (v === undefined) missing.push(ref.name);\n else resolved[ref.name] = v;\n }\n if (missing.length > 0) {\n throw new Error(\n `Missing required secrets: ${missing.join(\", \")}. Set them in .env (local) or the environment (prod)`,\n );\n }\n return resolved;\n}\n\n/** Metadata for introspection (values never exposed — future dashboard use). */\nexport function listSecrets(\n opts: { source?: SecretSource } = {},\n): Array<{ name: string; hasDefault: boolean; isSet: boolean }> {\n const source = opts.source ?? envSource;\n return [...registry.values()].map((ref) => ({\n hasDefault: ref.hasDefault,\n isSet: ref.isSet(source),\n name: ref.name,\n }));\n}\n\n/** Test/session override for one secret (`undefined` clears the override). */\nexport function overrideSecret(name: string, value: string | undefined): void {\n overrides.set(name, value);\n}\n\n/** Bulk overrides (test/session scoped). */\nexport function overrideSecrets(\n values: Record<string, string | undefined>,\n): void {\n for (const [name, value] of Object.entries(values)) {\n overrides.set(name, value);\n }\n}\n\n/** Clear registry and overrides. Test-only. */\nexport function resetSecrets(): void {\n registry.clear();\n overrides.clear();\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved. Logging only —\n * no CORS headers are set here.\n *\n * Hooks are registered with the \"global\" scope so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in beforeHandle\n * because request hooks are not propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({\n request,\n set,\n }: Pick<Context, \"request\" | \"set\">): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n logger(\n formatLog(request.method, path, set.status ?? 200, Date.now() - start),\n );\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.beforeHandle(\"global\", markStarted);\n plugin.afterHandle(\"global\", logSuccess);\n plugin.error(\"global\", logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\n\n/** An OpenAPI document as plain JSON. */\nexport type OpenApiDocument = Record<string, unknown>;\n\n/** An extra OpenAPI document for the API reference, such as Better Auth's. */\nexport interface ReferenceDocument {\n /** Name in the reference's list of documents. */\n title: string;\n /** The document, or a function returning it; called each time the app starts. */\n document:\n | OpenApiDocument\n | (() => OpenApiDocument | Promise<OpenApiDocument>);\n}\n\n/** A named OpenAPI document ready to render. */\nexport interface ApiDocument {\n title: string;\n document: OpenApiDocument;\n}\n\n/** Developer documentation for the `brick dev` dashboard. */\nexport interface DocumentationOptions {\n /**\n * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the\n * app entry, as it reads in the file that sets it.\n */\n dir: string;\n /**\n * Module whose exports are React components for MDX, added to the built-in\n * ones; a relative path starts where `dir` does. A default export or a\n * `components` export holds the name-to-component map. The dashboard bundles\n * it, so it may import anything the project has.\n */\n components?: string;\n}\n\nexport interface ReferenceOptions {\n /** Also serve a standalone Scalar page here. Without a path, no page is served. */\n path?: string;\n title?: string;\n specUrl?: string;\n /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */\n documents?: ReferenceDocument[];\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/** Mounts the Scalar reference route onto an existing app. */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","/** Who may open the dashboard that `brick start` serves for monitoring. */\nexport interface DashboardAuth {\n /**\n * Secrets that let a request in. A browser asks for one in its sign-in\n * prompt (any user name, the secret as the password), and monitors and\n * scripts send `Authorization: Bearer <secret>`. Give several to rotate one\n * while the other still works. Each is at least 16 characters long;\n * `openssl rand -base64 32` makes a good one.\n */\n token?: string | readonly string[];\n /**\n * Your own check, to sign people in with the auth the app already has: read\n * a session cookie, verify a Better Auth or Clerk session, look at a header\n * a proxy adds. It receives the request (method, URL, and headers; no body)\n * and returns `true` to let it in, `false` to refuse it with 401, or a\n * `Response` to send instead, such as a redirect to your login page. If it\n * throws or takes longer than five seconds, the request is refused with 503.\n *\n * A request is let in when it carries a valid `token`, or when this\n * returns `true`; give both to let monitors in by token and people in by\n * sign-in.\n */\n authorize?: (\n request: Request,\n ) => boolean | Response | Promise<boolean | Response>;\n}\n\n/**\n * The monitoring dashboard `brick start` serves beside the app, on a port of\n * its own: live requests, logs, errors, and the shape of the service, so it\n * stays reachable when the app's own routes are not. `brick dev` has its own\n * dashboard, set by command line options, and ignores this.\n *\n * Setting it turns on `telemetry`, since the dashboard shows what is traced.\n * While it is on, `ctx.logger` and `console` lines written during a request\n * go to the dashboard instead of the console.\n */\nexport interface DashboardOptions {\n /** Default 9400. */\n port?: number;\n /**\n * The address to listen on. Default `127.0.0.1`, reachable only from the same\n * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard\n * will not start on any other address without it.\n */\n host?: string;\n auth?: DashboardAuth;\n /**\n * Days of finished requests to keep on disk, in `.brick/` of the working\n * folder. Default 0: only what happened since the process started, which is\n * lost when it restarts. Needs a folder that outlives the container.\n */\n historyDays?: number;\n}\n\nconst MIN_TOKEN_LENGTH = 16;\n\n/**\n * Check what `brick()` was given, and freeze it. The secrets sit behind a getter\n * that is not enumerable, so logging or serializing the application definition\n * does not print them.\n */\nexport function normalizeDashboard(\n options: DashboardOptions | undefined,\n): DashboardOptions | undefined {\n if (options === undefined) return undefined;\n const { port, host, auth, historyDays } = options;\n if (\n port !== undefined &&\n (!Number.isInteger(port) || port < 1 || port > 65535)\n )\n throw new Error(\n `Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`,\n );\n if (host !== undefined && (typeof host !== \"string\" || host.trim() === \"\"))\n throw new Error(\n \"Brick: dashboard host must be an address, such as '0.0.0.0'.\",\n );\n if (\n historyDays !== undefined &&\n (!Number.isInteger(historyDays) || historyDays < 0)\n )\n throw new Error(\n `Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`,\n );\n const normalized: DashboardOptions = {\n ...(port !== undefined ? { port } : {}),\n ...(host !== undefined ? { host: host.trim() } : {}),\n ...(historyDays !== undefined ? { historyDays } : {}),\n };\n if (auth !== undefined) {\n const tokens =\n auth.token === undefined\n ? undefined\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n if (\n tokens?.some(\n (token) => typeof token !== \"string\" || token.length < MIN_TOKEN_LENGTH,\n )\n )\n throw new Error(\n `Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`,\n );\n if (auth.authorize !== undefined && typeof auth.authorize !== \"function\")\n throw new Error(\"Brick: dashboard authorize must be a function.\");\n if ((tokens === undefined || tokens.length === 0) && !auth.authorize)\n throw new Error(\n \"Brick: dashboard auth needs a token or an authorize function.\",\n );\n const secrets = Object.freeze({\n ...(tokens ? { token: Object.freeze(tokens) } : {}),\n ...(auth.authorize ? { authorize: auth.authorize } : {}),\n });\n // A getter, so inspecting the object (Bun prints hidden fields too) shows\n // `[Getter]` and not the secrets.\n Object.defineProperty(normalized, \"auth\", {\n enumerable: false,\n get: () => secrets,\n });\n }\n return Object.freeze(normalized);\n}\n","import type { RouteIR } from \"./compiler/ir\";\nimport type { Elysia } from \"elysia\";\nimport type { Service } from \"./types\";\nimport type { DatabaseHandle } from \"./db/define\";\nimport type { ApiDocument, DocumentationOptions } from \"./docs\";\nimport type { DashboardOptions } from \"./dashboard\";\nimport type { EventsDefinition, EventsHub } from \"./events/hub\";\nimport { toErrorResponse } from \"./error-response\";\nimport { createLogger } from \"./logger\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\nimport type { BrickSocketSchema } from \"./socket-types\";\nimport type { InstalledPlugin } from \"./define-plugin\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n /** The plugin that contributed it; OpenAPI labels it `x-brick-plugin`. */\n plugin?: string;\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb() ?? undefined;\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n const tag = `endpoint:${def.method} ${def.path}`;\n const logger = createLogger(`[${tag}]`);\n return async ({ params, body, query, headers, request, set }: any) => {\n const traceId = headers?.[\"x-trace-id\"] || `tr_${crypto.randomUUID()}`;\n const requestId = headers?.[\"x-request-id\"] || `req_${crypto.randomUUID()}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger,\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err) {\n const failure =\n !(\n err instanceof ActionExecutionError || err instanceof ValidationError\n ) &&\n err !== null &&\n typeof err === \"object\" &&\n \"status\" in err &&\n typeof err.status === \"number\" &&\n Number.isInteger(err.status) &&\n err.status >= 400 &&\n err.status < 500\n ? new ActionExecutionError(\n \"HTTP_ERROR\",\n \"message\" in err && typeof err.message === \"string\"\n ? err.message\n : \"Endpoint error\",\n err.status,\n undefined,\n { cause: err },\n )\n : err;\n const response = toErrorResponse(failure, {\n logger: ctx.logger,\n requestId,\n });\n set.status = response.status;\n return response;\n }\n };\n}\n\n/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(def.plugin ? { \"x-brick-plugin\": def.plugin } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions, prefix, and telemetry setting chosen at construction. */\n readonly definition: {\n readonly routes: readonly RouteIR[];\n readonly sockets: readonly (BrickSocketSchema & {\n service: string;\n path: string;\n })[];\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n readonly telemetry: boolean;\n readonly documentation?: DocumentationOptions;\n /** What `brick start` serves for monitoring; its `auth` is not enumerable. */\n readonly dashboard?: DashboardOptions;\n /** The listeners and settings of `events`, as plain data. */\n readonly events?: EventsDefinition;\n /** Every `definePlugin` installation, in install order. */\n readonly plugins?: readonly InstalledPlugin[];\n };\n /**\n * Run the plugins' `on(\"start\")` handlers in install order, once. `listen`\n * calls it; `brick dev` and `brick start` await it before serving. `stop()`\n * runs their `on(\"stop\")` handlers in reverse order.\n */\n start(): Promise<void>;\n /**\n * The events of this app, when `events` is set: start and stop delivery, drain\n * what is due, and see or retry what is parked. `brick dev` and `brick start`\n * start it for you.\n */\n readonly events?: EventsHub;\n /** Register a raw endpoint (outside the JSON action mesh). */\n endpoint(def: EndpointDefinition): void;\n /**\n * The OpenAPI documents behind the dashboard's APIs view: this app's own\n * unless `docs` is false, then those from `reference.documents`.\n */\n referenceDocuments(): Promise<ApiDocument[]>;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","import {\n bigserial,\n index as pgIndex,\n integer as pgInteger,\n jsonb,\n pgTable,\n text as pgText,\n timestamp,\n} from \"drizzle-orm/pg-core\";\nimport {\n index as sqliteIndex,\n integer as sqliteInteger,\n sqliteTable,\n text as sqliteText,\n} from \"drizzle-orm/sqlite-core\";\n\nconst OUTBOX = Symbol.for(\"brick.outbox\");\n\n/** What the outbox rows are in, by state. */\nexport type OutboxStatus = \"pending\" | \"claimed\" | \"delivered\" | \"dead\";\n\nfunction sqliteOutbox(name: string) {\n const timestampMs = (column: string) =>\n sqliteInteger(column, { mode: \"timestamp_ms\" });\n return sqliteTable(\n name,\n {\n seq: sqliteInteger(\"seq\").primaryKey({ autoIncrement: true }),\n id: sqliteText(\"id\").notNull().unique(),\n eventId: sqliteText(\"event_id\").notNull(),\n listener: sqliteText(\"listener\").notNull(),\n name: sqliteText(\"name\").notNull(),\n payload: sqliteText(\"payload\", { mode: \"json\" }).notNull(),\n traceId: sqliteText(\"trace_id\"),\n source: sqliteText(\"source\"),\n occurredAt: timestampMs(\"occurred_at\").notNull(),\n status: sqliteText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: sqliteInteger(\"attempts\").notNull().default(0),\n lastError: sqliteText(\"last_error\"),\n availableAt: timestampMs(\"available_at\").notNull(),\n claimedAt: timestampMs(\"claimed_at\"),\n deliveredAt: timestampMs(\"delivered_at\"),\n },\n (table) => [\n sqliteIndex(`${name}_due`).on(table.status, table.availableAt),\n sqliteIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\nfunction postgresOutbox(name: string) {\n const at = (column: string) => timestamp(column, { withTimezone: true });\n return pgTable(\n name,\n {\n seq: bigserial(\"seq\", { mode: \"number\" }).primaryKey(),\n id: pgText(\"id\").notNull().unique(),\n eventId: pgText(\"event_id\").notNull(),\n listener: pgText(\"listener\").notNull(),\n name: pgText(\"name\").notNull(),\n payload: jsonb(\"payload\").notNull(),\n traceId: pgText(\"trace_id\"),\n source: pgText(\"source\"),\n occurredAt: at(\"occurred_at\").notNull(),\n status: pgText(\"status\").$type<OutboxStatus>().notNull(),\n attempts: pgInteger(\"attempts\").notNull().default(0),\n lastError: pgText(\"last_error\"),\n availableAt: at(\"available_at\").notNull(),\n claimedAt: at(\"claimed_at\"),\n deliveredAt: at(\"delivered_at\"),\n },\n (table) => [\n pgIndex(`${name}_due`).on(table.status, table.availableAt),\n pgIndex(`${name}_event`).on(table.eventId),\n ],\n );\n}\n\n/** The outbox table of a SQLite database. */\nexport type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;\n/** The outbox table of a Postgres database. */\nexport type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;\n/** An outbox table, made by `outboxTable`. */\nexport type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;\n\n/**\n * The outbox table: where recorded events wait, one row per listener, until they\n * are delivered. A write and the events it causes are inserted in one transaction,\n * so an event is neither lost when the process dies after the write nor sent for a\n * write that was rolled back.\n *\n * Brick does not create tables for you. Put this in the schema of the database\n * whose writes emit events, and your migration tool (such as drizzle-kit) creates\n * it. A service whose database holds the table records events; one without it does\n * not.\n *\n * @param engine - The database engine, `\"sqlite\"` or `\"postgres\"`.\n * @param options - `name` to call the table something other than `brick_outbox`.\n * @returns A Drizzle table.\n * @example\n * import { defineDatabase, outboxTable } from \"@brickkit/core\";\n *\n * export const outbox = outboxTable(\"postgres\");\n * export const database = defineDatabase({\n * engine: \"postgres\",\n * tables: { users, outbox },\n * });\n */\nexport function outboxTable(\n engine: \"sqlite\",\n options?: { name?: string },\n): SQLiteOutboxTable;\nexport function outboxTable(\n engine: \"postgres\",\n options?: { name?: string },\n): PostgresOutboxTable;\nexport function outboxTable(\n engine: \"sqlite\" | \"postgres\",\n options: { name?: string } = {},\n): OutboxTable {\n const name = options.name ?? \"brick_outbox\";\n const table = engine === \"sqlite\" ? sqliteOutbox(name) : postgresOutbox(name);\n Object.defineProperty(table, OUTBOX, { value: { engine } });\n return table;\n}\n\n/**\n * Whether a value is an outbox table made by `outboxTable`.\n *\n * @param value - Anything.\n * @returns `true` for an outbox table, narrowing its type.\n */\nexport function isOutboxTable(value: unknown): value is OutboxTable {\n return typeof value === \"object\" && value !== null && OUTBOX in value;\n}\n\nexport function outboxEngine(table: OutboxTable): \"sqlite\" | \"postgres\" {\n return (\n table as unknown as Record<symbol, { engine: \"sqlite\" | \"postgres\" }>\n )[OUTBOX].engine;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst sqliteQueues = new WeakMap<object, Promise<unknown>>();\n\ninterface OpenTransaction {\n /** The handles a nested call can pass to join this transaction. */\n handles: Set<unknown>;\n commits: (() => unknown)[];\n open: boolean;\n savepoints: number;\n}\nconst active = new AsyncLocalStorage<OpenTransaction>();\n\nfunction joined(db: unknown): OpenTransaction | undefined {\n const open = active.getStore();\n return open?.open && open.handles.has(db) ? open : undefined;\n}\n\nexport function isSqliteDatabase(db: any): boolean {\n return (\n typeof db?.$client?.prepare === \"function\" &&\n typeof db?.$client?.run === \"function\"\n );\n}\n\nfunction rollbackQuietly(db: any, statement = \"ROLLBACK\"): void {\n try {\n db.$client.run(statement);\n } catch {\n return;\n }\n}\n\nasync function nested<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const commits = open.commits.length;\n try {\n if (!isSqliteDatabase(db))\n // Drizzle runs a nested transaction as a savepoint.\n return await db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n const name = `brick_${++open.savepoints}`;\n db.$client.run(`SAVEPOINT ${name}`);\n try {\n const result = await fn(db);\n db.$client.run(`RELEASE ${name}`);\n return result;\n } catch (error) {\n rollbackQuietly(db, `ROLLBACK TO ${name}`);\n rollbackQuietly(db, `RELEASE ${name}`);\n throw error;\n }\n } catch (error) {\n // Work that was rolled back must not run its commit callbacks.\n open.commits.length = commits;\n throw error;\n }\n}\n\n/**\n * Run `fn` in a database transaction: everything it writes through the `tx` it is\n * given is committed together when it returns, or undone if it throws.\n *\n * Postgres uses a real transaction on one connection. SQLite has one connection\n * and a synchronous driver, which Drizzle's own `transaction` cannot use with an\n * async callback (it would commit before the callback finished). So transactions\n * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.\n * A write made elsewhere in the process during that time, outside this helper,\n * would join the transaction; use Postgres where that matters.\n *\n * A call made inside `fn` with the `tx` it was given (on SQLite, the database\n * itself) joins the open transaction as a savepoint instead of waiting for it: a\n * nested failure undoes only the nested work, and the outer transaction decides\n * the commit. Nested calls must run one at a time.\n *\n * @param db - A Drizzle database, from `service.getDb()`.\n * @param fn - Receives the transaction handle to run queries on.\n * @returns What `fn` returned.\n * @throws What `fn` threw, after rolling back.\n */\nexport async function runInTransaction<T>(\n db: any,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n const outer = joined(db);\n if (outer) return nested(db, outer, fn);\n const open: OpenTransaction = {\n handles: new Set(),\n commits: [],\n open: true,\n savepoints: 0,\n };\n let result: T;\n try {\n result = await active.run(open, () => begin(db, open, fn));\n } finally {\n open.open = false;\n }\n for (const commit of open.commits) await commit();\n return result;\n}\n\nasync function begin<T>(\n db: any,\n open: OpenTransaction,\n fn: (tx: any) => Promise<T>,\n): Promise<T> {\n if (!isSqliteDatabase(db)) {\n return db.transaction((tx: any) => {\n open.handles.add(tx);\n return fn(tx);\n });\n }\n\n open.handles.add(db);\n const previous = sqliteQueues.get(db) ?? Promise.resolve();\n let release!: () => void;\n const turn = new Promise<void>((resolve) => {\n release = resolve;\n });\n sqliteQueues.set(\n db,\n previous.then(() => turn),\n );\n await previous;\n try {\n db.$client.run(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn(db);\n db.$client.run(\"COMMIT\");\n return result;\n } catch (error) {\n rollbackQuietly(db);\n throw error;\n }\n } finally {\n release();\n }\n}\n\n/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */\nexport function inTransaction(db: unknown): boolean {\n return joined(db) !== undefined;\n}\n\n/**\n * Run `fn` once the transaction that `db` belongs to has committed, or now when\n * `db` is not in one opened by `runInTransaction`. It never runs when that\n * transaction, or the savepoint it was queued in, rolls back. An error it throws\n * reaches the caller of the outermost `runInTransaction`, after the commit.\n *\n * @param db - The handle the work ran on: a `tx`, or a database.\n * @param fn - The side effect, such as clearing a cache.\n */\nexport async function onTransactionCommit(\n db: unknown,\n fn: () => unknown,\n): Promise<void> {\n const open = joined(db);\n if (open) open.commits.push(fn);\n else await fn();\n}\n","import { and, asc, eq, inArray, lt, lte, or, sql } from \"drizzle-orm\";\nimport { type OutboxStatus, type OutboxTable, outboxEngine } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type { Deliverable } from \"./hub\";\nimport { ActionExecutionError } from \"../types\";\nimport type { DispatchOptions, EventDelivery } from \"./types\";\n\nexport type ResolvedDispatchOptions = Required<DispatchOptions>;\n\nexport function resolveDispatchOptions(\n options: DispatchOptions = {},\n): ResolvedDispatchOptions {\n return {\n timer: options.timer ?? true,\n intervalMs: options.intervalMs ?? 1_000,\n batchSize: options.batchSize ?? 50,\n maxAttempts: options.maxAttempts ?? 8,\n claimTimeoutMs: options.claimTimeoutMs ?? 60_000,\n maxBackoffMs: options.maxBackoffMs ?? 300_000,\n retainDeliveredMs: options.retainDeliveredMs ?? 86_400_000,\n };\n}\n\n/** How many outbox rows are in each state. */\nexport type OutboxCounts = Record<OutboxStatus, number>;\n\ninterface OutboxRow {\n seq: number;\n id: string;\n eventId: string;\n listener: string;\n name: string;\n payload: unknown;\n traceId: string | null;\n source: string | null;\n occurredAt: Date;\n status: OutboxStatus;\n attempts: number;\n lastError: string | null;\n}\n\nconst PURGE_INTERVAL_MS = 60_000;\n\n/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as \"retry\". */\nfunction decideRetry(listener: Deliverable, error: unknown): \"retry\" | \"dead\" {\n if (!listener.retry) return \"retry\";\n try {\n return listener.retry(\n error instanceof ActionExecutionError && listener.errors?.[error.code]\n ? { code: error.code, message: error.message, details: error.details }\n : {\n code: \"UNKNOWN\",\n message: error instanceof Error ? error.message : String(error),\n cause: error,\n },\n );\n } catch {\n return \"retry\";\n }\n}\n\nexport function backoffMs(attempt: number, maxBackoffMs: number): number {\n return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);\n}\n\n/**\n * Delivers the events recorded in one outbox table to the app's listeners.\n *\n * It claims a batch of due rows, runs each listener, and marks the row delivered.\n * A listener that throws is retried later with a growing delay, and parked as\n * dead after its attempts run out. Several dispatchers can share a table: on\n * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not\n * finished within `claimTimeoutMs` (the process died) is taken by another.\n * Delivery is at least once, so a listener should tolerate running twice for the\n * same `deliveryId`.\n */\nexport class Dispatcher {\n private readonly engine: \"sqlite\" | \"postgres\";\n private readonly options: ResolvedDispatchOptions;\n private readonly inFlight = new Set<Promise<void>>();\n private timer?: ReturnType<typeof setInterval>;\n private tickQueue?: Promise<number>;\n private lastPurge = 0;\n\n constructor(\n private readonly db: any,\n private readonly table: OutboxTable,\n private readonly listeners: (name: string) => Deliverable | undefined,\n options: DispatchOptions = {},\n private readonly onError: (error: unknown) => void = (error) =>\n console.error(\"[Brick-TS events]\", error),\n ) {\n this.engine = outboxEngine(table);\n this.options = resolveDispatchOptions(options);\n }\n\n /** Whether the dispatcher is looking for work on a timer. */\n get running(): boolean {\n return this.timer !== undefined;\n }\n\n /** Start looking for due deliveries on a timer. Does nothing if it already is. */\n start(): void {\n if (this.timer || !this.options.timer) return;\n this.timer = setInterval(() => void this.tick(), this.options.intervalMs);\n this.timer.unref?.();\n void this.tick();\n }\n\n /**\n * Stop the timer and wait for the deliveries that are running to finish.\n */\n async stop(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n await this.tickQueue;\n await Promise.allSettled(this.inFlight);\n }\n\n /** Look for work soon, without waiting for the timer. Safe to call often. */\n notify(): void {\n if (!this.timer) return;\n setTimeout(() => void this.tick(), 0).unref?.();\n }\n\n /**\n * Claim what is due and run it, once. Used by the timer, and by tests and\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries it started.\n */\n tick(): Promise<number> {\n this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(\n () => this.claimAndRun(),\n () => this.claimAndRun(),\n );\n return this.tickQueue;\n }\n\n /**\n * Deliver everything that is due now and wait until those deliveries are done.\n * Deliveries that fail and are rescheduled are not waited for again.\n *\n * @returns How many deliveries it ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (;;) {\n const started = await this.tick();\n await Promise.allSettled(this.inFlight);\n if (started === 0) return total;\n total += started;\n }\n }\n\n /**\n * How many rows are in each state.\n */\n async counts(): Promise<OutboxCounts> {\n const t = this.table as any;\n const rows: { status: OutboxStatus; count: number }[] = await this.db\n .select({ status: t.status, count: sql<number>`count(*)` })\n .from(t)\n .groupBy(t.status);\n const counts: OutboxCounts = {\n pending: 0,\n claimed: 0,\n delivered: 0,\n dead: 0,\n };\n for (const row of rows) counts[row.status] = Number(row.count);\n return counts;\n }\n\n /**\n * Put parked deliveries back in line, with their attempts reset.\n *\n * @param deliveryId - One delivery to retry. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n const t = this.table as any;\n const rows: { id: string }[] = await this.db\n .update(t)\n .set({ status: \"pending\", attempts: 0, availableAt: new Date() })\n .where(\n deliveryId\n ? and(eq(t.status, \"dead\"), eq(t.id, deliveryId))\n : eq(t.status, \"dead\"),\n )\n .returning({ id: t.id });\n if (rows.length) this.notify();\n return rows.length;\n }\n\n private async claimAndRun(): Promise<number> {\n try {\n const room = this.options.batchSize - this.inFlight.size;\n if (room <= 0) return 0;\n const rows = await this.claim(room);\n for (const row of rows) {\n const run = this.deliver(row).finally(() => {\n this.inFlight.delete(run);\n });\n this.inFlight.add(run);\n }\n await this.purgeDelivered();\n return rows.length;\n } catch (error) {\n this.onError(error);\n return 0;\n }\n }\n\n private async claim(limit: number): Promise<OutboxRow[]> {\n const t = this.table as any;\n const now = new Date();\n const stale = new Date(now.getTime() - this.options.claimTimeoutMs);\n const due = or(\n and(eq(t.status, \"pending\"), lte(t.availableAt, now)),\n and(eq(t.status, \"claimed\"), lt(t.claimedAt, stale)),\n );\n const claimIn = async (tx: any): Promise<OutboxRow[]> => {\n let select = tx\n .select()\n .from(t)\n .where(due)\n .orderBy(asc(t.seq))\n .limit(limit);\n if (this.engine === \"postgres\")\n select = select.for(\"update\", { skipLocked: true });\n const picked: OutboxRow[] = await select;\n if (!picked.length) return [];\n await tx\n .update(t)\n .set({\n status: \"claimed\",\n claimedAt: now,\n attempts: sql`${t.attempts} + 1`,\n })\n .where(\n inArray(\n t.seq,\n picked.map((row) => row.seq),\n ),\n );\n return picked.map((row) => ({ ...row, attempts: row.attempts + 1 }));\n };\n return this.engine === \"postgres\"\n ? this.db.transaction(claimIn)\n : runInTransaction(this.db, claimIn);\n }\n\n private async deliver(row: OutboxRow): Promise<void> {\n const listener = this.listeners(row.listener);\n if (!listener) {\n await this.park(row, `No listener named '${row.listener}' is registered`);\n return;\n }\n const delivery: EventDelivery = {\n id: row.eventId,\n name: row.name,\n payload: row.payload,\n occurredAt: row.occurredAt.toISOString(),\n ...(row.traceId ? { traceId: row.traceId } : {}),\n ...(row.source ? { source: row.source } : {}),\n listener: row.listener,\n deliveryId: row.id,\n attempt: row.attempts,\n };\n try {\n await listener.run(delivery);\n } catch (error) {\n await this.fail(\n row,\n error,\n listener.maxAttempts ?? this.options.maxAttempts,\n decideRetry(listener, error),\n );\n return;\n }\n await this.markDelivered(row);\n }\n\n private async markDelivered(row: OutboxRow): Promise<void> {\n const t = this.table as any;\n try {\n if (this.options.retainDeliveredMs === 0)\n await this.db.delete(t).where(eq(t.seq, row.seq));\n else\n await this.db\n .update(t)\n .set({\n status: \"delivered\",\n deliveredAt: new Date(),\n lastError: null,\n })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.onError(error);\n }\n }\n\n private async fail(\n row: OutboxRow,\n error: unknown,\n maxAttempts: number,\n decision: \"retry\" | \"dead\" = \"retry\",\n ): Promise<void> {\n const message = error instanceof Error ? error.message : String(error);\n if (decision === \"dead\" || row.attempts >= maxAttempts) {\n await this.park(row, message);\n return;\n }\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({\n status: \"pending\",\n lastError: message,\n claimedAt: null,\n availableAt: new Date(\n Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs),\n ),\n })\n .where(eq(t.seq, row.seq));\n } catch (writeError) {\n this.onError(writeError);\n }\n }\n\n private async park(row: OutboxRow, message: string): Promise<void> {\n const t = this.table as any;\n try {\n await this.db\n .update(t)\n .set({ status: \"dead\", lastError: message, claimedAt: null })\n .where(eq(t.seq, row.seq));\n } catch (error) {\n this.onError(error);\n }\n }\n\n private async purgeDelivered(): Promise<void> {\n const keep = this.options.retainDeliveredMs;\n const now = Date.now();\n if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;\n this.lastPurge = now;\n const t = this.table as any;\n await this.db\n .delete(t)\n .where(\n and(eq(t.status, \"delivered\"), lt(t.deliveredAt, new Date(now - keep))),\n );\n }\n}\n","const ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nexport function newEventId(now: number = Date.now()): string {\n let time = \"\";\n let remaining = now;\n for (let index = 0; index < 10; index++) {\n time = ALPHABET[remaining % 32] + time;\n remaining = Math.floor(remaining / 32);\n }\n let random = \"\";\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n random += ALPHABET[byte % 32];\n }\n return `evt_${time}${random}`;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { runWithDeps } from \"../deps\";\nimport type {\n EventDelivery,\n EventListener,\n EventsWorld,\n WorkflowEvent,\n WorkflowsOptions,\n} from \"./types\";\n\n/** `getQueueTopicPrefix(\"workflow\")` from `@workflow/world`: the queue the runtime reads. */\nconst WORKFLOW_QUEUE_PREFIX = \"__wkf_workflow_\";\nconst BUNDLE_DIR = \".well-known/workflow/v1\";\nconst STOPPED = \"The events were stopped, so workflows can no longer run\";\n/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */\nexport const WEBHOOK_ROUTE = \"/.well-known/workflow/v1/webhook/*\";\n/** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */\nconst STEP_REGISTRY = Symbol.for(\"@workflow/core//registeredSteps\");\n\ninterface WorkflowSdk {\n start(\n workflow: unknown,\n args: unknown[],\n options: Record<string, unknown>,\n ): Promise<{ runId: string }>;\n setWorld(world: unknown): void;\n}\n\ninterface BundleManifest {\n steps?: Record<string, unknown>;\n workflows?: Record<string, Record<string, { workflowId?: string }>>;\n}\n\n/**\n * Where the workflow bundle is read from, and the project it is built from.\n *\n * @param options - The `events.workflows` option.\n * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the\n * builder finds the SDK from where it writes, and skips only this directory when it\n * looks for workflows.\n */\nexport function resolveWorkflowPaths(options: WorkflowsOptions = {}): {\n root: string;\n dir: string;\n} {\n const root = resolve(options.root ?? process.cwd());\n return { root, dir: join(root, BUNDLE_DIR) };\n}\n\n/**\n * Runs workflow listeners: wires the world into the Workflow SDK, serves the\n * built bundle from this process, and starts one run for each delivery.\n *\n * Nothing is loaded until it is needed, so an app without workflow listeners\n * never imports the SDK.\n */\nexport class WorkflowRuntime {\n readonly root: string;\n readonly dir: string;\n private ready: Promise<WorkflowSdk> | undefined;\n private connected: Promise<WorkflowSdk> | undefined;\n private closed = false;\n\n constructor(\n readonly world: EventsWorld,\n options: WorkflowsOptions | undefined,\n private readonly listeners: readonly EventListener[],\n private readonly deps: Record<string, unknown> = {},\n ) {\n ({ root: this.root, dir: this.dir } = resolveWorkflowPaths(options));\n }\n\n /** Begin loading the runtime now rather than at the first delivery. */\n warmUp(): void {\n this.ensure().catch((error) =>\n console.error(\n `[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n\n /**\n * Start the run for a delivery.\n *\n * The run is named after the delivery id, so a delivery that is tried again\n * finds the run it already started instead of starting another.\n *\n * @param listener - The workflow listener the delivery is for.\n * @param delivery - The delivery.\n * @returns The run id.\n */\n async startRun(\n listener: EventListener,\n delivery: EventDelivery,\n ): Promise<string> {\n const sdk = await this.ensure();\n const { attempt: _attempt, ...event } = delivery;\n const run = await sdk.start(\n listener.workflow,\n [event satisfies WorkflowEvent],\n {\n world: this.world,\n runKey: delivery.deliveryId,\n runKeyTime: Date.parse(delivery.occurredAt),\n },\n );\n return run.runId;\n }\n\n /**\n * Answer a request to a webhook a workflow created with `createWebhook`, by\n * resuming the workflow that waits on it. Needs the world but not the queue\n * consumer, so a process that only records events (`dispatch: false`) serves\n * webhooks too.\n *\n * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.\n * @returns The response the bundle's webhook handler gives.\n */\n async handleWebhook(request: Request): Promise<Response> {\n await this.connect();\n const file = join(this.dir, \"webhook.mjs\");\n if (!existsSync(file))\n throw new Error(\n `No webhook bundle at ${file}. brick dev and brick start build it; ` +\n \"in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\",\n );\n const handlers = await import(pathToFileURL(file).href);\n const handler = handlers[request.method];\n if (typeof handler !== \"function\")\n return new Response(null, { status: 405 });\n return handler(request);\n }\n\n /** Stop the world. The runtime cannot be started again afterwards. */\n async close(): Promise<void> {\n this.closed = true;\n await this.ready?.catch(() => {});\n await this.connected?.catch(() => {});\n await this.world.close?.();\n }\n\n private ensure(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.ready ??= this.initialize().catch((error) => {\n this.ready = undefined;\n throw error;\n });\n return this.ready;\n }\n\n /** Load the SDK and give it the world: all a webhook needs. */\n private connect(): Promise<WorkflowSdk> {\n if (this.closed) return Promise.reject(new Error(STOPPED));\n this.connected ??= this.loadSdk()\n .then((sdk) => {\n sdk.setWorld(this.world);\n return sdk;\n })\n .catch((error) => {\n this.connected = undefined;\n throw error;\n });\n return this.connected;\n }\n\n private async initialize(): Promise<WorkflowSdk> {\n if (typeof this.world.createRunId !== \"function\")\n throw new Error(\n \"This world cannot name a run after its key, so an event delivered twice would start two runs. \" +\n \"Use the world from @brickkit/redis-world or @brickkit/bullmq-world.\",\n );\n const sdk = await this.connect();\n const flow = join(this.dir, \"flow.mjs\");\n if (!existsSync(flow))\n throw new Error(\n `No workflow bundle at ${flow}. brick dev and brick start build it; ` +\n \"in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.\",\n );\n const manifest = this.readManifest();\n this.checkListeners(manifest);\n const bundle = await this.loadBundle(flow);\n if (typeof bundle.POST !== \"function\")\n throw new Error(`${flow} does not export a POST handler`);\n const post = bundle.POST;\n // Steps run inside this handler, so `useDeps()` in a step finds this app's deps.\n this.world.registerHandler?.(WORKFLOW_QUEUE_PREFIX, (request: Request) =>\n runWithDeps(this.deps, () => post(request)),\n );\n await this.world.start?.();\n return sdk;\n }\n\n private async loadSdk(): Promise<WorkflowSdk> {\n const from = createRequire(join(this.root, \"package.json\"));\n const load = async (specifier: string) => {\n let path: string;\n try {\n path = from.resolve(specifier);\n } catch {\n throw new Error(\n `The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`,\n );\n }\n return import(pathToFileURL(path).href);\n };\n const [api, runtime] = await Promise.all([\n load(\"workflow/api\"),\n load(\"workflow/runtime\"),\n ]);\n return { start: api.start, setWorld: runtime.setWorld };\n }\n\n /**\n * The bundle holds its own copy of every step and registers them all when it\n * loads, replacing the ones the app registered. A copy has its own module state:\n * a step would find no database connection, no config, none of what the app set\n * up. So the app's steps are put back, and the bundle's copies serve only the\n * steps the app never loaded.\n */\n private async loadBundle(\n flow: string,\n ): Promise<{ POST?: (request: Request) => Promise<Response> }> {\n const registry = () =>\n (globalThis as Record<symbol, unknown>)[STEP_REGISTRY] as\n | Map<string, unknown>\n | undefined;\n const app = new Map(registry());\n const bundle = await import(pathToFileURL(flow).href);\n const registered = registry();\n if (registered) for (const [id, step] of app) registered.set(id, step);\n return bundle;\n }\n\n private readManifest(): BundleManifest | undefined {\n const path = join(this.dir, \"manifest.json\");\n if (!existsSync(path)) return undefined;\n return JSON.parse(readFileSync(path, \"utf8\")) as BundleManifest;\n }\n\n /**\n * A listener's workflow must carry the id the transform gives it, and the bundle\n * must know that id: a function that was never transformed, or a bundle built\n * before the workflow existed, would fail on its first delivery with a less\n * helpful message.\n */\n private checkListeners(manifest: BundleManifest | undefined): void {\n const known = new Set<string>();\n for (const file of Object.values(manifest?.workflows ?? {}))\n for (const entry of Object.values(file))\n if (entry.workflowId) known.add(entry.workflowId);\n for (const listener of this.listeners) {\n const id = (listener.workflow as { workflowId?: unknown } | undefined)\n ?.workflowId;\n if (typeof id !== \"string\")\n throw new Error(\n `The workflow of listener '${listener.name}' was not transformed. ` +\n \"Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.\",\n );\n if (manifest && !known.has(id))\n throw new Error(\n `The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`,\n );\n }\n }\n}\n","import { Dispatcher, type OutboxCounts } from \"./dispatcher\";\nimport { newEventId } from \"./id\";\nimport type { OutboxTable } from \"./outbox\";\nimport { runInTransaction } from \"./transaction\";\nimport type {\n DispatchOptions,\n EventDelivery,\n EventListener,\n EventRecorder,\n EventsOptions,\n EventsWorld,\n ServiceEvents,\n} from \"./types\";\nimport { WorkflowRuntime } from \"./workflows\";\nimport { runWithDeps } from \"../deps\";\n\ninterface EventsHost {\n readonly name: string;\n getDb(): unknown;\n getOutbox?(): OutboxTable | undefined;\n setRecorder?(recorder: ServiceEvents | undefined): void;\n /** Throws for an event the service's catalog does not allow. */\n checkEvent?(name: string, payload: unknown): void;\n}\n\nexport function matchesEvent(pattern: string, name: string): boolean {\n if (pattern === \"*\") return true;\n if (pattern.endsWith(\"*\")) return name.startsWith(pattern.slice(0, -1));\n return pattern === name;\n}\n\n/** The recorder of each service database, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */\nexport const recorders = new WeakMap<object, ServiceEvents>();\n\n// Shared by name: the CLI that stops the hubs may hold another copy of this package.\nconst startedHubs = ((globalThis as Record<symbol, unknown>)[\n Symbol.for(\"brickkit.events.started\")\n] ??= new Set()) as Set<Pick<EventsHub, \"stop\">>;\n\n/**\n * Stop every events hub started in this process, by any copy of `@brickkit/core`,\n * and wait for their deliveries. A hub that fails to stop does not cut the wait\n * for the others: the first failure is thrown once every hub is done.\n */\nexport async function stopAllEvents(): Promise<void> {\n const results = await Promise.allSettled(\n [...startedHubs].map((hub) => hub.stop()),\n );\n const failed = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (failed) throw failed.reason;\n}\n\n/**\n * What an app's `events` option describes, as plain data. It goes in the app\n * definition, which is sent to the dev dashboard, so it holds no functions.\n */\nexport interface EventsDefinition {\n listeners: { name: string; on: string[]; kind: \"handler\" | \"workflow\" }[];\n dispatch: boolean;\n /** Names of the services whose writes record events. */\n recorders: string[];\n}\n\n/** What the dispatcher runs for a delivery. */\nexport interface Deliverable {\n readonly maxAttempts?: number;\n readonly errors?: EventListener[\"errors\"];\n readonly retry?: EventListener[\"retry\"];\n run(delivery: EventDelivery): void | Promise<void>;\n}\n\n/**\n * The events of one app: who listens, where events are recorded, and the\n * dispatchers that deliver them. `brick({ events })` makes one and puts it on\n * `app.events`.\n */\nexport class EventsHub {\n private readonly byName = new Map<string, EventListener>();\n private readonly dispatchers = new Map<OutboxTable, Dispatcher>();\n private readonly deliverables = new Map<string, Deliverable>();\n private readonly dispatchOptions: DispatchOptions | false;\n private readonly runtime: WorkflowRuntime | undefined;\n private readonly recorderNames: string[] = [];\n private started = false;\n private stopping: Promise<void> | undefined;\n\n /**\n * @param options - The `events` option.\n * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its\n * listeners and workflow steps.\n */\n constructor(\n options: EventsOptions,\n private readonly deps: Record<string, unknown> = {},\n ) {\n for (const listener of options.listeners ?? []) {\n if (typeof listener.name !== \"string\" || !listener.name)\n throw new Error(\"An event listener needs a name\");\n if (listener.name.includes(\":\"))\n throw new Error(\n `Event listener name '${listener.name}' must not contain ':'`,\n );\n if (!listener.on?.length)\n throw new Error(\n `Event listener '${listener.name}' listens for nothing`,\n );\n if (this.byName.has(listener.name))\n throw new Error(`Duplicate event listener '${listener.name}'`);\n if (!listener.run === !listener.workflow)\n throw new Error(\n `Event listener '${listener.name}' needs exactly one of run and workflow`,\n );\n this.byName.set(listener.name, listener);\n }\n const workflowListeners = [...this.byName.values()].filter(\n (listener) => listener.workflow,\n );\n if (workflowListeners.length) {\n if (!options.world)\n throw new Error(\n `Event listener '${workflowListeners[0]!.name}' runs a workflow, so events needs a world: ` +\n \"brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.\",\n );\n this.runtime = new WorkflowRuntime(\n options.world,\n options.workflows,\n workflowListeners,\n deps,\n );\n }\n this.dispatchOptions =\n options.dispatch === false\n ? false\n : options.dispatch === true || options.dispatch === undefined\n ? {}\n : options.dispatch;\n }\n\n /**\n * Give each service whose database holds an outbox table a recorder, and a\n * dispatcher for that table. Call it before the first request: a service has no\n * recorder until then.\n *\n * @param services - The app's services.\n * @returns The hub, for chaining.\n */\n attach(services: readonly EventsHost[]): this {\n let attached = 0;\n for (const service of services) {\n const table = service.getOutbox?.();\n if (!table) continue;\n attached++;\n this.recorderNames.push(service.name);\n const bound = this.bind(table, (name, payload) =>\n service.checkEvent?.(name, payload),\n );\n service.setRecorder?.(bound);\n const db = service.getDb();\n if (db && typeof db === \"object\") recorders.set(db, bound);\n }\n if (attached === 0 && this.byName.size > 0) {\n console.warn(\n \"[Brick-TS] events are configured, but no service database has an outbox table. \" +\n \"Add outboxTable() to a database's tables so its writes can record events.\",\n );\n }\n for (const service of services) {\n const table = service.getOutbox?.();\n if (table && !this.dispatchers.has(table)) {\n this.dispatchers.set(\n table,\n new Dispatcher(\n service.getDb(),\n table,\n (name) => this.deliverable(name),\n this.dispatchOptions || {},\n ),\n );\n }\n }\n return this;\n }\n\n /** The listeners that want an event. */\n matching(name: string): EventListener[] {\n const found: EventListener[] = [];\n for (const listener of this.byName.values())\n if (listener.on.some((pattern) => matchesEvent(pattern, name)))\n found.push(listener);\n return found;\n }\n\n /** The listeners and settings, as plain data. */\n describe(): EventsDefinition {\n return {\n listeners: [...this.byName.values()].map((listener) => ({\n name: listener.name,\n on: [...listener.on],\n kind: listener.workflow ? (\"workflow\" as const) : (\"handler\" as const),\n })),\n dispatch: this.dispatchOptions !== false,\n recorders: [...this.recorderNames],\n };\n }\n\n /**\n * Where the workflow bundle is read from, the project it is built from, and\n * the world the workflows run on. Only set when a listener runs a workflow.\n * The CLI builds the bundle there before events start, and shows the world's\n * runs in the dev dashboard.\n */\n get workflows():\n | { root: string; dir: string; world: EventsWorld }\n | undefined {\n return (\n this.runtime && {\n root: this.runtime.root,\n dir: this.runtime.dir,\n world: this.runtime.world,\n }\n );\n }\n\n /**\n * Resume the workflow that waits on a webhook. The server mounts this on the\n * route the Workflow SDK puts in webhook URLs.\n */\n webhook(request: Request): Promise<Response> {\n if (!this.runtime)\n throw new Error(\"No listener of this app runs a workflow\");\n return this.runtime.handleWebhook(request);\n }\n\n /**\n * Start delivering recorded events from this process, and start the world that\n * runs workflow listeners. Does nothing if this process only records events\n * (`dispatch: false`), already started, or a stop is still waiting.\n */\n start(): void {\n // A process being stopped exits when the stop is done, and would drop what\n // this start claims. A startup that finishes late, or a commit, lands here.\n if (this.dispatchOptions === false || this.started || this.stopping) return;\n this.started = true;\n startedHubs.add(this);\n this.runtime?.warmUp();\n for (const dispatcher of this.dispatchers.values()) dispatcher.start();\n }\n\n /**\n * Stop delivering, wait for the deliveries that are running, and close the\n * world. A world cannot be started again, so workflow listeners stop for good.\n * A stop that arrives while another runs waits for that one.\n */\n stop(): Promise<void> {\n return (this.stopping ??= this.shutDown().finally(() => {\n // Removed only when done, so a stop-all waits for a stop already running.\n this.stopping = undefined;\n startedHubs.delete(this);\n }));\n }\n\n private async shutDown(): Promise<void> {\n this.started = false;\n await Promise.all(\n [...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()),\n );\n await this.runtime?.close();\n }\n\n /**\n * Deliver everything that is due now and wait for it. For tests and for\n * workers that drive delivery themselves.\n *\n * @returns How many deliveries ran.\n */\n async drain(): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.drain();\n return total;\n }\n\n /** How many rows are in each state, across the app's outbox tables. */\n async counts(): Promise<OutboxCounts> {\n const total: OutboxCounts = {\n pending: 0,\n claimed: 0,\n delivered: 0,\n dead: 0,\n };\n for (const dispatcher of this.dispatchers.values()) {\n const counts = await dispatcher.counts();\n for (const status of Object.keys(total) as (keyof OutboxCounts)[])\n total[status] += counts[status];\n }\n return total;\n }\n\n /**\n * Put parked deliveries back in line.\n *\n * @param deliveryId - One delivery. Omit it to retry every dead one.\n * @returns How many deliveries were put back.\n */\n async retryDead(deliveryId?: string): Promise<number> {\n let total = 0;\n for (const dispatcher of this.dispatchers.values())\n total += await dispatcher.retryDead(deliveryId);\n return total;\n }\n\n private deliverable(name: string): Deliverable | undefined {\n const listener = this.byName.get(name);\n if (!listener) return undefined;\n let found = this.deliverables.get(name);\n if (!found) {\n const runtime = this.runtime;\n found = {\n ...(listener.errors ? { errors: listener.errors } : {}),\n ...(listener.retry ? { retry: listener.retry } : {}),\n ...(listener.workflow\n ? {\n ...(listener.maxAttempts !== undefined\n ? { maxAttempts: listener.maxAttempts }\n : {}),\n run: async (delivery) => {\n await runtime!.startRun(listener, delivery);\n },\n }\n : {\n ...(listener.maxAttempts !== undefined\n ? { maxAttempts: listener.maxAttempts }\n : {}),\n run: (delivery) =>\n runWithDeps(this.deps, () => listener.run!(delivery)),\n }),\n };\n this.deliverables.set(name, found);\n }\n return found;\n }\n\n private bind(\n table: OutboxTable,\n check: (name: string, payload: unknown) => void,\n ): ServiceEvents {\n const startAndNotify = () => {\n this.start();\n this.dispatchers.get(table)?.notify();\n };\n const insert = async (\n tx: any,\n context: { traceId?: string; source?: string },\n name: string,\n payload: unknown,\n ): Promise<boolean> => {\n check(name, payload);\n const listeners = this.matching(name);\n if (!listeners.length) return false;\n const eventId = newEventId();\n const occurredAt = new Date();\n await tx.insert(table as any).values(\n listeners.map((listener) => ({\n id: `${eventId}:${listener.name}`,\n eventId,\n listener: listener.name,\n name,\n payload,\n traceId: context.traceId ?? null,\n source: context.source ?? null,\n occurredAt,\n status: \"pending\",\n attempts: 0,\n availableAt: occurredAt,\n })),\n );\n return true;\n };\n return {\n wants: (name) => this.matching(name).length > 0,\n transaction: async (db, context, fn) => {\n let recorded = false;\n const result = await runInTransaction(db, async (tx) => {\n const record: EventRecorder = async (name, payload) => {\n if (await insert(tx, context, name, payload)) recorded = true;\n };\n return fn(tx, record);\n });\n if (recorded) startAndNotify();\n return result;\n },\n record: async (tx, context, name, payload) => {\n await insert(tx, context, name, payload);\n },\n };\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { Elysia } from \"elysia\";\nimport { websocket } from \"elysia/websocket\";\nimport { createLogger } from \"./logger\";\nimport { joinRoute, kebabCase, legacyPath, ownerPath } from \"./routes\";\nimport type { BaseContext } from \"./types\";\nimport { getCompiledCheck } from \"./typebox\";\nimport { inTransaction, onTransactionCommit } from \"./events/transaction\";\nimport {\n serializeSocketSchema,\n isSocketEnvelope,\n isSocketRoom,\n isSocketSeq,\n SOCKET_MAX_BYTES,\n SOCKET_BUFFER_BYTES,\n} from \"./socket-schema\";\nimport type {\n BrickSocketConfig,\n BrickSocketHandle,\n BrickSocketSchema,\n BrickSocketSender,\n SocketBroker,\n SocketBrokerMessage,\n SocketEmitArgs,\n SocketPayloads,\n SocketReplay,\n SocketSchemas,\n} from \"./socket-types\";\n\ninterface SocketSender {\n readonly isOpen: boolean;\n send(event: string, payload: unknown): void;\n close(): void;\n}\ninterface SocketSession {\n /** Server rooms, resolved from the handshake context. */\n rooms: readonly string[];\n open(socket: SocketSender): Promise<void>;\n message(event: string, data: unknown, socket: SocketSender): Promise<void>;\n join(room: string): Promise<boolean>;\n close(socket: SocketSender, code: number, reason: string): Promise<void>;\n}\nexport interface RegisteredSocket {\n schema: BrickSocketSchema;\n input: SocketSchemas;\n output: SocketSchemas;\n allowedOrigins?: readonly string[];\n allowMissingOrigin?: boolean;\n maxRooms: number;\n replay?: SocketReplay;\n /** Brokers of the apps this socket is mounted in. */\n brokers: Set<SocketBroker>;\n handle: BrickSocketHandle<any>;\n topicPrefix: string;\n topic(room: string): string;\n connect(request: Request): Promise<SocketSession>;\n}\n\nclass SocketDenied extends Error {}\n\nconst bytes = (value: string) => new TextEncoder().encode(value).byteLength;\n\n/** Validates and serializes one output message, rechecking what survives JSON. */\nfunction outputFrame(\n output: SocketSchemas,\n event: string,\n data: unknown,\n): string {\n const schema = Object.hasOwn(output, event) ? output[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new Error(\"Invalid socket output\");\n const frame = JSON.stringify({ event, data });\n if (bytes(frame) > SOCKET_MAX_BYTES)\n throw new Error(\"Socket output too large\");\n if (!getCompiledCheck(schema).Check(JSON.parse(frame).data))\n throw new Error(\"Socket output is not JSON-compatible\");\n return frame;\n}\n\n/** Delivers within this process. The default broker of every app. */\nexport function localBroker(): SocketBroker {\n const topics = new Map<string, Set<(message: SocketBrokerMessage) => void>>();\n // Replay history: one rising counter per process, prefixed with its start so a restart reads as a gap.\n const epoch = Date.now();\n let counter = 0;\n /** Rooms dropped from `kept` once idle, at counter values up to this. */\n let swept = 0;\n const kept = new Map<\n string,\n {\n entries: { n: number; at: number; message: SocketBrokerMessage }[];\n /** The highest n no longer kept. */\n trimmed: number;\n maxAgeMs: number;\n }\n >();\n const prune = (names: Iterable<string>) => {\n for (const topic of names) {\n const room = kept.get(topic);\n if (!room) continue;\n const oldest = Date.now() - room.maxAgeMs;\n while (room.entries[0] && room.entries[0].at < oldest)\n room.trimmed = room.entries.shift()!.n;\n if (!room.entries.length) {\n kept.delete(topic);\n swept = counter;\n }\n }\n };\n return {\n publish(message, replay) {\n if (message.type === \"emit\" && replay) {\n const n = ++counter;\n message = { ...message, seq: `${epoch}-${n}` };\n const room = kept.get(message.topic) ?? {\n entries: [],\n trimmed: 0,\n maxAgeMs: replay.maxAgeMs,\n };\n kept.set(message.topic, room);\n room.entries.push({ n, at: Date.now(), message });\n if (room.entries.length > replay.keep)\n room.trimmed = room.entries.shift()!.n;\n // shortcut: idle rooms are swept every 1000 emits, not on a timer; fine while emits keep coming.\n if (n % 1000 === 0) prune([...kept.keys()]);\n }\n for (const deliver of topics.get(message.topic) ?? []) deliver(message);\n },\n head: () => `${epoch}-${counter}`,\n history(topic, since) {\n const [from, n] = since.split(\"-\").map(Number) as [number, number];\n if (from !== epoch || n > counter) return undefined;\n prune([topic]);\n const room = kept.get(topic);\n if (!room) return n >= swept ? [] : undefined;\n if (n < room.trimmed) return undefined;\n return room.entries\n .filter((entry) => entry.n > n)\n .map((entry) => entry.message);\n },\n subscribe(topic, deliver) {\n const listeners = topics.get(topic) ?? new Set();\n listeners.add(deliver);\n topics.set(topic, listeners);\n return () => {\n listeners.delete(deliver);\n if (!listeners.size) topics.delete(topic);\n };\n },\n };\n}\n\nexport function defineServiceSocket<\n I extends SocketSchemas,\n O extends SocketSchemas,\n Ctx extends BaseContext,\n>(\n service: string,\n config: BrickSocketConfig<I, O, Ctx>,\n resolve: (request: Request) => Promise<Ctx>,\n): RegisteredSocket {\n if (\n !config.name ||\n config.name.split(\".\").some((part) => !/^[a-zA-Z_][\\w-]*$/.test(part))\n )\n throw new Error(\"Invalid socket name\");\n if (\n config.path !== undefined &&\n (!config.path.startsWith(\"/\") ||\n /[?#*]/.test(config.path) ||\n config.path.split(\"/\").some((segment) => segment.startsWith(\":\")))\n )\n throw new Error(\n \"Socket path must be a static route (relative to its service) without a query or fragment\",\n );\n const input = Object.freeze({ ...config.input });\n const output = Object.freeze({ ...config.output });\n const handlers = { ...config.handlers };\n if (\n Object.keys(input).length !== Object.keys(handlers).length ||\n Object.keys(input).some(\n (key) =>\n !Object.hasOwn(handlers, key) || typeof handlers[key] !== \"function\",\n )\n )\n throw new Error(\"Every socket input event needs exactly one handler\");\n if (\n [...Object.keys(input), ...Object.keys(output)].some((key) =>\n key.startsWith(\"$\"),\n )\n )\n throw new Error(\"Socket event names starting with $ are reserved\");\n const maxRooms = config.maxRooms ?? 100;\n if (!Number.isInteger(maxRooms) || maxRooms < 1)\n throw new Error(\"Socket maxRooms must be a positive integer\");\n const replay = config.replay && { ...config.replay };\n if (\n replay &&\n !(\n Number.isInteger(replay.keep) &&\n replay.keep > 0 &&\n replay.maxAgeMs > 0 &&\n Number.isFinite(replay.maxAgeMs)\n )\n )\n throw new Error(\n \"Socket replay needs a positive integer keep and a positive finite maxAgeMs\",\n );\n for (const schema of [...Object.values(input), ...Object.values(output)]) {\n serializeSocketSchema(schema);\n getCompiledCheck(schema);\n }\n const typed = (socket: SocketSender): BrickSocketSender<SocketPayloads<O>> =>\n socket;\n const context = async (request: Request) => {\n const ctx = await resolve(request);\n if (config.authorize && !(await config.authorize({ ctx })))\n throw new SocketDenied();\n return ctx;\n };\n const topicPrefix = `${service}.${config.name}:`;\n const topic = (room: string) => {\n if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);\n return topicPrefix + room;\n };\n const brokers = new Set<SocketBroker>();\n const publish = (messages: SocketBrokerMessage[], after: unknown) => {\n const send = () => {\n for (const broker of brokers)\n for (const message of messages) broker.publish(message, replay);\n };\n if (after === undefined) return send();\n if (!inTransaction(after))\n throw new Error(\n \"Socket emit { after: tx } needs a tx from runInTransaction(db, (tx) => ...); a plain db.transaction() is not tracked, so the emit could be sent for a write that rolls back\",\n );\n void onTransactionCommit(after, send);\n };\n return {\n schema: {\n name: config.name,\n path: config.path,\n description: config.description,\n input: Object.keys(input),\n output: Object.keys(output),\n hasAuthorize: !!config.authorize,\n },\n input,\n output,\n allowedOrigins: config.allowedOrigins\n ? [...config.allowedOrigins]\n : undefined,\n allowMissingOrigin: config.allowMissingOrigin,\n maxRooms,\n replay,\n brokers,\n topicPrefix,\n topic,\n handle: {\n name: config.name,\n emit(rooms, ...[event, payload, options]: SocketEmitArgs<any>) {\n const topics = [\n ...new Set(typeof rooms === \"string\" ? [rooms] : rooms),\n ].map(topic);\n const frame = outputFrame(output, event, payload);\n // Room and sequence are added to each replayed frame on delivery.\n if (replay && bytes(frame) > SOCKET_MAX_BYTES - 300)\n throw new Error(\"Socket output too large\");\n publish(\n topics.map((topic) => ({ type: \"emit\", topic, frame })),\n options?.after,\n );\n },\n kick(room, options = {}) {\n publish(\n [\n {\n type: \"kick\",\n topic: topic(room),\n ...(options.also !== undefined\n ? { also: topic(options.also) }\n : {}),\n ...(options.reason !== undefined\n ? { reason: String(options.reason) }\n : {}),\n },\n ],\n undefined,\n );\n },\n },\n async connect(request) {\n const initial = await context(request);\n const rooms = [\n ...new Set(config.rooms ? await config.rooms({ ctx: initial }) : []),\n ];\n rooms.forEach(topic);\n if (rooms.length > maxRooms) throw new Error(\"Too many socket rooms\");\n return {\n rooms,\n async open(socket) {\n await config.open?.({ ctx: initial, socket: typed(socket) });\n },\n async message(event, data, socket) {\n const schema = Object.hasOwn(input, event) ? input[event] : undefined;\n if (!schema || !getCompiledCheck(schema).Check(data))\n throw new SocketDenied();\n const ctx = await context(request);\n if (!socket.isOpen) return;\n // The schema and event were checked together before dispatch.\n const handler = handlers[event as keyof I];\n await handler({\n input: data as SocketPayloads<I>[keyof I],\n ctx,\n socket: typed(socket),\n });\n },\n async join(room) {\n const ctx = await context(request);\n return !!config.join && (await config.join({ ctx, room }));\n },\n async close(socket, code, reason) {\n await config.close?.({\n ctx: initial,\n socket: typed(socket),\n code,\n reason,\n });\n },\n };\n },\n };\n}\n\n/** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */\nexport function socketPath(\n prefix: string,\n service: string,\n socket: RegisteredSocket,\n): string {\n return joinRoute(\n ownerPath(prefix, service),\n socket.schema.path ?? `/${kebabCase(socket.schema.name)}`,\n );\n}\n\n/** The v0.10 route, served too by `brick({ legacyRoutes: true })`. */\nexport function legacySocketPath(\n prefix: string,\n service: string,\n socket: RegisteredSocket,\n): string | undefined {\n return legacyPath(prefix, service, socket.schema.name, socket.schema.path);\n}\n\n/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */\nfunction publicOrigin(request: Request): string {\n // Browsers cannot set X-Forwarded-* on a WebSocket handshake, so a cross-site page cannot forge a match.\n const forwarded = (name: string) =>\n request.headers.get(name)?.split(\",\")[0]?.trim() || undefined;\n const url = new URL(request.url);\n const proto = forwarded(\"x-forwarded-proto\");\n return `${proto ? `${proto}:` : url.protocol}//${forwarded(\"x-forwarded-host\") ?? url.host}`;\n}\n\nconst TOKEN_PROTOCOL = \"brick.token.\";\nconst protocols = (request: Request) =>\n (request.headers.get(\"sec-websocket-protocol\") ?? \"\")\n .split(\",\")\n .map((protocol) => protocol.trim())\n .filter(Boolean);\n\n/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */\nfunction tokenRequest(request: Request): {\n token: boolean;\n request: Request;\n} {\n const offered = protocols(request);\n const token = offered\n .find((protocol) => protocol.startsWith(TOKEN_PROTOCOL))\n ?.slice(TOKEN_PROTOCOL.length);\n if (!token) return { token: false, request };\n const headers = new Headers(request.headers);\n headers.set(\"authorization\", `Bearer ${token}`);\n const rest = offered.filter(\n (protocol) => !protocol.startsWith(TOKEN_PROTOCOL),\n );\n if (rest.length) headers.set(\"sec-websocket-protocol\", rest.join(\", \"));\n else headers.delete(\"sec-websocket-protocol\");\n return {\n token: true,\n request: new Request(request.url, { method: request.method, headers }),\n };\n}\n\n/** Mounts native adapters. Each connection owns its queue and service session. */\nexport function mountSockets(\n app: Elysia,\n sockets: { service: string; path: string; definition: RegisteredSocket }[],\n broker: SocketBroker,\n secret?: string,\n): void {\n if (secret === \"\") throw new Error(\"Brick: sockets.secret can't be empty\");\n // A sequence is signed for its room, so a client resumes only a room it was sent that sequence in.\n const key = secret ?? randomBytes(32);\n const signature = (topic: string, seq: string) =>\n createHmac(\"sha256\", key)\n .update(`${topic}\\n${seq}`)\n .digest(\"base64url\")\n .slice(0, 22);\n const sign = (topic: string, seq: string) =>\n `${seq}.${signature(topic, seq)}`;\n const verify = (topic: string, signed: string) => {\n const [seq, sig] = signed.split(\".\") as [string, string];\n return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq)))\n ? seq\n : undefined;\n };\n if (\n sockets.some(({ definition }) => definition.replay) &&\n !(broker.head && broker.history)\n )\n throw new Error(\"Brick: the socket broker does not support replay\");\n for (const { definition } of sockets) definition.brokers.add(broker);\n app.cleanup(async () => {\n for (const { definition } of sockets) definition.brokers.delete(broker);\n await broker.close?.();\n });\n if (!sockets.length) return;\n app.use(\n websocket({\n maxPayloadLength: SOCKET_MAX_BYTES,\n backpressureLimit: SOCKET_BUFFER_BYTES,\n closeOnBackpressureLimit: true,\n }),\n );\n // A socket also served on its v0.10 path shares one set of rooms, so a\n // broker message reaches each connection once.\n const paths = new Map<RegisteredSocket, string[]>();\n for (const { path, definition } of sockets)\n paths.set(definition, [...(paths.get(definition) ?? []), path]);\n for (const { service, definition } of sockets) {\n const routes = paths.get(definition);\n if (!routes) continue;\n paths.delete(definition);\n const logger = createLogger(\n `[Brick socket ${service}.${definition.schema.name}]`,\n );\n const sessions = new WeakMap<Request, SocketSession>();\n type Peer = {\n request: Request;\n send(data: string): number;\n close(code?: number, reason?: string): void;\n subscribe(topic: string): void;\n unsubscribe(topic: string): void;\n isSubscribed(topic: string): boolean;\n readonly readyState: number;\n };\n type Connection = {\n ws: Peer;\n session: SocketSession;\n sender: SocketSender;\n tail: Promise<void>;\n pending: number;\n bytes: number;\n closed: boolean;\n /** Every room topic the connection is in. */\n rooms: Set<string>;\n /** The topics the client joined, which it may leave. */\n requested: Set<string>;\n };\n const connections = new WeakMap<Request, Connection>();\n const roomOf = (topic: string) =>\n topic.slice(definition.topicPrefix.length);\n const holders = new Map<\n string,\n { connections: Set<Connection>; unsubscribe: () => void }\n >();\n const control = (ws: Peer, event: string, data: unknown) => {\n if (ws.readyState === 1) ws.send(JSON.stringify({ event, data }));\n };\n /** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */\n const enter = async (\n connection: Connection,\n topic: string,\n live = true,\n ) => {\n if (connection.rooms.has(topic)) return;\n connection.rooms.add(topic);\n if (live) connection.ws.subscribe(topic);\n let holder = holders.get(topic);\n if (!holder) {\n holder = {\n connections: new Set(),\n unsubscribe: () => {},\n };\n holders.set(topic, holder);\n holder.unsubscribe = broker.subscribe(topic, deliver);\n }\n holder.connections.add(connection);\n await broker.ready?.(topic).catch(() => {});\n };\n const exit = (connection: Connection, topic: string) => {\n if (!connection.rooms.delete(topic)) return;\n connection.requested.delete(topic);\n if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);\n const holder = holders.get(topic);\n if (!holder?.connections.delete(connection) || holder.connections.size)\n return;\n holders.delete(topic);\n holder.unsubscribe();\n };\n /** A replayable emit carries its room and sequence. */\n const frameOf = (message: SocketBrokerMessage & { type: \"emit\" }) =>\n message.seq === undefined\n ? message.frame\n : `${message.frame.slice(0, -1)},\"room\":${JSON.stringify(roomOf(message.topic))},\"seq\":${JSON.stringify(sign(message.topic, message.seq))}}`;\n const deliver = (message: SocketBrokerMessage) => {\n if (message.type === \"emit\") {\n app.server?.publish(message.topic, frameOf(message));\n return;\n }\n for (const connection of holders.get(message.topic)?.connections ?? []) {\n if (message.also && !connection.ws.isSubscribed(message.also)) continue;\n exit(connection, message.topic);\n control(connection.ws, \"$left\", {\n room: roomOf(message.topic),\n ...(message.reason !== undefined ? { reason: message.reason } : {}),\n });\n }\n };\n /** `$join` and `$leave`, acknowledged with the same event. */\n const room = async (\n connection: Connection,\n event: string,\n data: unknown,\n ) => {\n const fields = (data && typeof data === \"object\" ? data : {}) as Record<\n string,\n unknown\n >;\n const { room: name, since } = fields;\n if (!isSocketRoom(name) || (since !== undefined && !isSocketSeq(since)))\n throw new SocketDenied();\n const topic = definition.topic(name);\n if (event === \"$leave\") {\n if (connection.requested.has(topic)) exit(connection, topic);\n control(connection.ws, \"$leave\", { room: name });\n return;\n }\n const isOpen = () => !connection.closed && connection.ws.readyState === 1;\n const ok =\n connection.rooms.has(topic) ||\n (connection.rooms.size < definition.maxRooms &&\n (await connection.session.join(name)));\n if (!isOpen()) return;\n const replay = definition.replay;\n let seq: string | undefined;\n if (ok && !connection.rooms.has(topic)) {\n const entered = enter(connection, topic, !replay);\n connection.requested.add(topic);\n await entered;\n if (replay && connection.rooms.has(topic)) {\n // Held in this process before reading history, so later emits are either in it or arrive live.\n // A since not signed for this room gets no history, only $gap.\n const start =\n since === undefined\n ? await broker.head!(topic)\n : verify(topic, since);\n const missed =\n start === undefined\n ? undefined\n : await broker.history!(topic, start, replay);\n const restart = missed ? undefined : await broker.head!(topic);\n if (!isOpen()) return;\n if (connection.rooms.has(topic)) {\n connection.ws.subscribe(topic);\n if (since === undefined) seq = sign(topic, start!);\n for (const message of missed ?? [])\n if (message.type === \"emit\") connection.ws.send(frameOf(message));\n if (restart !== undefined)\n control(connection.ws, \"$gap\", {\n room: name,\n seq: sign(topic, restart),\n });\n }\n }\n }\n // A kick while joining wins.\n control(connection.ws, \"$join\", {\n room: name,\n ok: ok && connection.rooms.has(topic),\n ...(seq !== undefined ? { seq } : {}),\n });\n };\n const fail = (ws: Peer, error: unknown) => {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n if (ws.readyState !== 1) return;\n ws.close(\n error instanceof SocketDenied ? 1008 : 1011,\n error instanceof SocketDenied\n ? \"Message refused\"\n : \"Socket handler failed\",\n );\n };\n for (const path of routes)\n app.ws(path, {\n async beforeHandle({ request }) {\n if (sessions.has(request)) return;\n const { token, request: resolved } = tokenRequest(request);\n const origin = request.headers.get(\"origin\");\n if (\n origin\n ? !(\n definition.allowedOrigins ?? [publicOrigin(request)]\n ).includes(origin)\n : // Without cookies a missing Origin is no hijacking risk.\n !(definition.allowMissingOrigin ?? token)\n )\n return new Response(\"Socket origin refused\", { status: 403 });\n try {\n sessions.set(request, await definition.connect(resolved));\n } catch (error) {\n if (!(error instanceof SocketDenied))\n logger.error({ error, service, socket: definition.schema.name });\n return new Response(\"Socket connection refused\", {\n status: error instanceof SocketDenied ? 403 : 500,\n });\n }\n },\n upgrade: ({ request }: { request: Request }) =>\n protocols(request).includes(\"brick.v1\")\n ? { \"Sec-WebSocket-Protocol\": \"brick.v1\" }\n : undefined,\n async open(ws) {\n const session = sessions.get(ws.request);\n if (!session) {\n ws.close(1011, \"Missing socket session\");\n return;\n }\n const sender: SocketSender = {\n get isOpen() {\n return !state.closed && ws.readyState === 1;\n },\n close() {\n ws.close(1000, \"\");\n },\n send(event, data) {\n if (!sender.isOpen) throw new Error(\"Socket is closed\");\n const result = ws.send(\n outputFrame(definition.output, event, data),\n );\n if (result === 0) {\n ws.close(1013, \"Socket buffer full\");\n throw new Error(\"Socket buffer full\");\n }\n },\n };\n const state: Connection = {\n ws,\n session,\n sender,\n tail: Promise.resolve(),\n pending: 0,\n bytes: 0,\n closed: false,\n rooms: new Set(),\n requested: new Set(),\n };\n connections.set(ws.request, state);\n try {\n await Promise.all(\n session.rooms.map((room) => enter(state, definition.topic(room))),\n );\n await session.open(sender);\n } catch (error) {\n fail(ws, error);\n }\n },\n message(ws, value: unknown) {\n const state = connections.get(ws.request);\n if (!state || state.closed || ws.readyState !== 1) return;\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n ws.close(1003, \"Only JSON text is supported\");\n return;\n }\n if (typeof value === \"string\") {\n ws.close(1007, \"Expected JSON envelope\");\n return;\n }\n if (!isSocketEnvelope(value)) {\n ws.close(1008, \"Invalid socket envelope\");\n return;\n }\n const size = bytes(JSON.stringify(value));\n if (size > SOCKET_MAX_BYTES) {\n ws.close(1009, \"Message too large\");\n return;\n }\n if (state.pending >= 32 || state.bytes + size > SOCKET_BUFFER_BYTES) {\n ws.close(1013, \"Socket queue full\");\n return;\n }\n state.pending++;\n state.bytes += size;\n state.tail = state.tail\n .then(async () => {\n if (state.closed || ws.readyState !== 1) return;\n if (value.event === \"$join\" || value.event === \"$leave\")\n await room(state, value.event, value.data);\n else\n await state.session.message(\n value.event,\n value.data,\n state.sender,\n );\n })\n .catch((error: unknown) => fail(ws, error))\n .finally(() => {\n state.pending--;\n state.bytes -= size;\n });\n // Brick owns the queue. Returning the tail here makes native close wait on application work.\n },\n async close(ws, code = 1006, reason = \"\") {\n const state = connections.get(ws.request);\n sessions.delete(ws.request);\n if (!state || state.closed) return;\n state.closed = true;\n for (const topic of state.rooms) exit(state, topic);\n try {\n await state.session.close(state.sender, code, reason);\n } catch (error) {\n logger.error({\n error,\n service,\n socket: definition.schema.name,\n phase: \"cleanup\",\n });\n }\n connections.delete(ws.request);\n },\n });\n }\n}\n","import { Elysia } from \"elysia\";\nimport {\n compileBrickApplication,\n type CompiledApplication,\n type RouteIR,\n} from \"./compiler\";\nimport type { Service } from \"./types\";\nimport { getGlobalRegistry } from \"./registry\";\nimport {\n getPluginActionRoute,\n getPluginEndpoints,\n installedPlugins,\n} from \"./plugin\";\nimport {\n pluginLifecycle,\n setupAppPlugins,\n type PluginInstance,\n} from \"./define-plugin\";\nimport { getActionRoute } from \"./routes\";\nimport { generateOpenApiSpec } from \"./openapi\";\nimport { resolveSecrets, type SecretSource } from \"./secrets\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n registerReferenceRoute,\n type ApiDocument,\n type DocumentationOptions,\n type OpenApiDocument,\n type ReferenceOptions,\n} from \"./docs\";\nimport { normalizeDashboard, type DashboardOptions } from \"./dashboard\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\nimport { instrumentDatabase, traceHttpRequest, withSpan } from \"./telemetry\";\nimport { EventsHub } from \"./events/hub\";\nimport { bindDeps } from \"./deps\";\nimport { WEBHOOK_ROUTE } from \"./events/workflows\";\nimport type { EventsOptions } from \"./events/types\";\nimport {\n legacySocketPath,\n localBroker,\n mountSockets,\n socketPath,\n} from \"./socket\";\nimport type { SocketBroker } from \"./socket-types\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Generate specialized handlers once at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n /**\n * `true` serves a Scalar page at /reference. Options serve one only with a\n * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.\n */\n reference?: boolean | ReferenceOptions; // default false\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (outside the JSON action mesh), mounted at startup. */\n endpoints?: EndpointDefinition[];\n /**\n * Record request, action, and RPC spans with OpenTelemetry (default false).\n * Spans go to the globally registered tracer provider; without one they are\n * no-ops. `brick dev` shows them in its dashboard.\n */\n telemetry?: boolean;\n /**\n * Developer documentation for the `brick dev` dashboard (its Docs tab): a\n * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and\n * `meta.json` for ordering. A string is the folder. Relative paths start at\n * the folder of the app entry, as they read in the file that sets them (from\n * `src/app.ts`, `\"../docs\"` is `docs/` at the project root). Needs\n * `fumadocs-core` and `@mdx-js/mdx` installed.\n */\n documentation?: string | DocumentationOptions;\n /**\n * Monitoring dashboard for `brick start`, on a port of its own and behind\n * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.\n */\n dashboard?: DashboardOptions;\n /**\n * Record events in the same database transaction as the writes that cause them,\n * and deliver them to listeners after the commit. Generated CRUD writes emit\n * `<resource>.create`, `<resource>.update` and `<resource>.delete`. A service\n * records events once its database holds an `outboxTable()`. Reads emit nothing,\n * and an app without this option behaves exactly as before. See `EventsOptions`.\n */\n events?: EventsOptions;\n /**\n * Also serve the v0.10 paths (CRUD at `${prefix}/${resource}/...`, service\n * actions and sockets at `${prefix}/${service}/${name}` as declared, and\n * explicit paths that still start with the prefix) with the same handlers.\n * Their responses carry `Deprecation: true` and a `Link` to the new path, and\n * their spans `brick.legacy_route`. OpenAPI and the client describe only the\n * new paths. Removed in v0.12.\n */\n legacyRoutes?: boolean;\n /**\n * Socket fan-out. `broker` carries emits and kicks between processes\n * (default: this process only). See `redisBroker`. The app closes it on stop.\n * `secret` signs replay sequences; give every process the same one so a\n * client can resume on any of them (default: random per process).\n */\n sockets?: { broker?: SocketBroker; secret?: string };\n /**\n * The values of the services' declared `deps` (`port<T>()`), by name. Every\n * declared dep must be provided, and every provided one declared. Actions read\n * them as `ctx.deps`, listeners and workflow steps with `useDeps()`.\n */\n deps?: Record<string, unknown>;\n /**\n * App-wide plugins from `definePlugin`, in install order: their `app` part\n * adds start/stop lifecycle, middleware and listeners. Plugins installed with\n * `service.use()` or `resource.use()` take part too, before these.\n */\n plugins?: readonly PluginInstance<any, any>[];\n}\n\nexport {\n compileRoutePlan,\n executeCompiledRoute,\n createActionHandler,\n} from \"./action-handler\";\n\n/**\n * Create the HTTP application: an Elysia app that serves every service's\n * actions (and the tools that opt in with `http: true`) as routes, with\n * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,\n * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.\n *\n * Services come from the global registry unless `services` is given. The app\n * does not listen by itself: export it from your entry file, where `brick dev`,\n * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your\n * own server bootstrap.\n *\n * @param options - `prefix` for action routes (default `/api`), `services`,\n * `title`, `version`, and `description` for the OpenAPI document, `docs` and the\n * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,\n * `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.\n * @returns The app, with `definition` (its services, prefix, and routes),\n * `endpoint()` to add raw routes, and `listEndpoints()` to list them.\n * @throws When a required secret is missing, `documentation` or `dashboard`\n * is invalid, or `deps` misses a dep a service declares or has one none declares.\n * @example\n * import { brick } from \"@brickkit/core\";\n * import { pagesService } from \"./services/pages\";\n *\n * export default brick({\n * services: [pagesService],\n * title: \"Pages API\",\n * telemetry: true,\n * });\n */\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n const prefix = options.prefix ?? options.compilation?.ir.prefix ?? \"/api\";\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const compiled = options.compiler !== false;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? \"/openapi.json\";\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n const dashboard = normalizeDashboard(options.dashboard);\n // The dashboard shows what is traced, so having one means tracing.\n const telemetry = options.telemetry === true || dashboard !== undefined;\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n const plugins = setupAppPlugins(\n services.flatMap((service) => installedPlugins(service)),\n options.plugins ?? [],\n );\n for (const handler of plugins.middleware) app.request(handler);\n\n // Diagnostics & health\n app.get(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false) {\n const pluginOpts = requestLogging === true ? {} : requestLogging;\n if (pluginOpts.enabled !== false) {\n app.use(requestLoggingPlugin(pluginOpts));\n }\n }\n\n // Scalar API reference page (opt-in): `reference: true`, or options with a path.\n const reference = options.reference ?? false;\n const referenceOptions: ReferenceOptions =\n typeof reference === \"object\" ? reference : {};\n const referencePath =\n reference === true ? \"/reference\" : referenceOptions.path;\n if (referencePath !== undefined) {\n const settings = {\n path: referencePath,\n title: referenceOptions.title ?? title,\n specUrl: referenceOptions.specUrl ?? openApiPath,\n };\n if (compiled)\n app.get(\n settings.path,\n htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)),\n );\n else registerReferenceRoute(app, settings);\n }\n\n const byName = new Map<string, unknown>();\n for (const service of services) {\n if ((byName.get(service.name) ?? service) !== service)\n throw new Error(`Brick: duplicate service \"${service.name}\" in brick()`);\n byName.set(service.name, service);\n }\n bindDeps(services, options.deps);\n const eventsOptions = plugins.listeners.length\n ? {\n ...options.events,\n listeners: [...(options.events?.listeners ?? []), ...plugins.listeners],\n }\n : options.events;\n const events = eventsOptions\n ? new EventsHub(eventsOptions, options.deps).attach(services)\n : undefined;\n if (events?.workflows)\n app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));\n if (telemetry) {\n for (const service of services) instrumentDatabase(service.getDb());\n }\n\n // Precompute plans and freeze immutable plans across all services\n for (const service of services) {\n if (typeof (service as any).build === \"function\") {\n (service as any).build();\n }\n }\n\n // Raw endpoints declared via options or app.endpoint() (declaration order).\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n const paths = { ...spec.paths };\n for (const [path, operations] of Object.entries(\n endpointPaths(endpointDefs),\n ))\n paths[path] = { ...paths[path], ...operations };\n return { ...spec, paths };\n };\n\n // OpenAPI 3.1 & Interactive Documentation Endpoints\n if (enableDocs) {\n app.get(\n openApiPath,\n compiled\n ? cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n )\n : buildSpec,\n );\n\n if (compiled) {\n app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n } else {\n app.get(docsPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(openApiPath, title);\n });\n\n app.get(swaggerPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return swaggerDocsHTML(openApiPath, title);\n });\n }\n }\n\n // Dedicated Route Registry\n const registeredRoutes = new Map<string, boolean>();\n const routeKey = (method: string, path: string) =>\n `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n registeredRoutes.set(routeKey(\"GET\", \"/_health\"), false);\n registeredRoutes.set(routeKey(\"GET\", \"/_brick/services\"), false);\n if (enableDocs) {\n for (const path of [openApiPath, docsPath, swaggerPath])\n registeredRoutes.set(routeKey(\"GET\", path), false);\n }\n if (referencePath !== undefined)\n registeredRoutes.set(routeKey(\"GET\", referencePath), false);\n\n const sockets = services.flatMap((service) =>\n service.listSockets().map((definition) => ({\n service: service.name,\n path: socketPath(prefix, service.name, definition),\n definition,\n })),\n );\n const socketRoutes = new Set<string>();\n for (const socket of sockets) {\n const key = routeKey(\"GET\", socket.path);\n if (registeredRoutes.has(key) || socketRoutes.has(key))\n throw new Error(`Brick: duplicate socket route '${socket.path}'`);\n socketRoutes.add(key);\n }\n // v0.10 socket routes, where they are free; the upgrade carries no headers.\n const legacySockets = options.legacyRoutes\n ? services.flatMap((service) =>\n service.listSockets().flatMap((definition) => {\n const path = legacySocketPath(prefix, service.name, definition);\n if (path === undefined) return [];\n const key = routeKey(\"GET\", path);\n if (registeredRoutes.has(key) || socketRoutes.has(key)) return [];\n socketRoutes.add(key);\n return [{ service: service.name, path, definition }];\n }),\n )\n : [];\n\n // v0.10 paths, mounted after every current route so they never take one.\n const legacyRoutes: {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n successor: string;\n handler: (context: any) => unknown;\n }[] = [];\n const addLegacy = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string | undefined,\n successor: string,\n handler: (context: any) => unknown,\n ) => {\n if (options.legacyRoutes && path !== undefined && path !== successor)\n legacyRoutes.push({ method, path, successor, handler });\n };\n\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any,\n plugin = false,\n ) => {\n const key = routeKey(method, path);\n if (socketRoutes.has(key))\n throw new Error(\n `Brick: route '${method} ${path}' conflicts with a socket`,\n );\n if (registeredRoutes.has(key)) {\n if (plugin || registeredRoutes.get(key))\n throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);\n return false;\n }\n switch (method) {\n case \"GET\":\n app.get(path, handler);\n break;\n case \"POST\":\n app.post(path, handler);\n break;\n case \"PUT\":\n app.put(path, handler);\n break;\n case \"PATCH\":\n app.patch(path, handler);\n break;\n case \"DELETE\":\n app.delete(path, handler);\n break;\n }\n registeredRoutes.set(key, plugin);\n return true;\n };\n\n // Raw endpoints (outside the JSON action mesh).\n const mountEndpoint = (\n def: EndpointDefinition,\n plugin = false,\n legacyPath?: string,\n ) => {\n const handler = createEndpointHandler(def, services);\n addLegacy(def.method, legacyPath, def.path, handler);\n mountRoute(\n def.method,\n def.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, def.method, def.path, () =>\n handler(context),\n )\n : handler,\n plugin,\n );\n endpointDefs.push(def);\n endpointRevision++;\n };\n\n for (const service of services) {\n for (const def of getPluginEndpoints(service, prefix))\n mountEndpoint(def, true, def.legacyPath);\n }\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n brickApp.referenceDocuments = async () => {\n const documents: ApiDocument[] = enableDocs\n ? [{ title, document: buildSpec() as unknown as OpenApiDocument }]\n : [];\n for (const extra of referenceOptions.documents ?? []) {\n try {\n const document =\n typeof extra.document === \"function\"\n ? await extra.document()\n : extra.document;\n documents.push({ title: extra.title, document });\n } catch (error) {\n console.warn(\n `[Brick-TS] Skipping the \"${extra.title}\" API document: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return documents;\n };\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n const mountedRoutes: RouteIR[] = [];\n for (const route of compilation.routes) {\n const service = services.find(\n (candidate) => candidate.name === route.ir.service,\n )!;\n const action = service\n .listActions()\n .find((candidate) => candidate.name === route.ir.action)!;\n const invoke = (context: any) => {\n const result = telemetry\n ? withSpan(\n `action ${route.ir.service}.${route.ir.action}`,\n {\n \"brick.service\": route.ir.service,\n \"brick.action\": route.ir.action,\n },\n () => route.handler(context),\n )\n : route.handler(context);\n return result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ? Promise.resolve(result).then(jsonActionResult)\n : jsonActionResult(result);\n };\n const mounted = mountRoute(\n route.ir.method,\n route.ir.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(context, route.ir.method, route.ir.path, () =>\n invoke(context),\n )\n : invoke,\n getPluginActionRoute(action, prefix) !== undefined,\n );\n if (mounted) {\n mountedRoutes.push(route.ir);\n const current = getActionRoute(action, prefix);\n if (current)\n addLegacy(route.ir.method, current.legacyPath, route.ir.path, invoke);\n }\n }\n\n for (const legacy of legacyRoutes) {\n const key = routeKey(legacy.method, legacy.path);\n // A current route or socket owns the path: the old one is not served.\n if (registeredRoutes.has(key) || socketRoutes.has(key)) continue;\n const handle = (context: any) => {\n context.set.headers[\"deprecation\"] = \"true\";\n context.set.headers[\"link\"] = `<${legacy.successor.replace(\n /:([^/]+)/g,\n (match, name: string) =>\n context.params?.[name] === undefined\n ? match\n : encodeURIComponent(context.params[name]),\n )}>; rel=\"successor-version\"`;\n return legacy.handler(context);\n };\n mountRoute(\n legacy.method,\n legacy.path,\n telemetry\n ? (context: any) =>\n traceHttpRequest(\n context,\n legacy.method,\n legacy.path,\n () => handle(context),\n { \"brick.legacy_route\": true },\n )\n : handle,\n );\n }\n\n mountSockets(\n app,\n [...sockets, ...legacySockets],\n options.sockets?.broker ?? localBroker(),\n options.sockets?.secret,\n );\n const definition = Object.freeze({\n services: Object.freeze([...services]),\n prefix,\n routes: Object.freeze(mountedRoutes),\n sockets: Object.freeze(\n sockets.map(({ service, path, definition }) => ({\n ...definition.schema,\n service,\n path,\n })),\n ),\n telemetry,\n documentation: normalizeDocumentation(options.documentation),\n dashboard,\n ...(events ? { events: events.describe() } : {}),\n plugins: Object.freeze(plugins.plugins),\n });\n Object.defineProperty(brickApp, \"definition\", { value: definition });\n Object.defineProperty(brickApp, \"events\", { value: events });\n // Plugin lifecycle: start before serving, stop after the server stops.\n const lifecycle = pluginLifecycle(plugins.lifecycles);\n const listen = app.listen.bind(app);\n const stop = app.stop.bind(app);\n Object.defineProperty(brickApp, \"start\", { value: lifecycle.start });\n brickApp.listen = ((...args: Parameters<typeof listen>) => {\n lifecycle\n .start()\n .catch((error) =>\n console.error(\"[Brick-TS] A plugin failed to start:\", error),\n );\n return listen(...args);\n }) as typeof brickApp.listen;\n brickApp.stop = (async (closeActiveConnections?: boolean) => {\n try {\n await stop(closeActiveConnections);\n } finally {\n await lifecycle.stop();\n }\n }) as typeof brickApp.stop;\n getGlobalRegistry().setApplicationRoutes(definition);\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n app.get(\n \"/_brick/services\",\n compiled\n ? cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(definition),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n )\n : () => getGlobalRegistry().exportArchitecture(definition),\n );\n\n return brickApp;\n}\n\nfunction normalizeDocumentation(\n documentation: string | DocumentationOptions | undefined,\n): DocumentationOptions | undefined {\n if (documentation === undefined) return undefined;\n const options =\n typeof documentation === \"string\" ? { dir: documentation } : documentation;\n if (typeof options.dir !== \"string\" || options.dir === \"\")\n throw new Error(\"Brick: documentation needs a folder, such as './docs'.\");\n return Object.freeze({\n dir: options.dir,\n ...(options.components ? { components: options.components } : {}),\n });\n}\n\nfunction jsonActionResult(value: unknown): unknown {\n return value === null\n ? new Response(\"null\", { headers: { \"content-type\": \"application/json\" } })\n : value;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n","import type { RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input\n ? \"params, body, query, headers, request, set\"\n : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\")\n input.push(\n `if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`,\n );\n else if (coercion.type === \"array\")\n input.push(\n `if (v${index} !== undefined) { const values${index} = request ? new URL(request.url).searchParams.getAll(${key}) : []; coercedQuery[${key}] = values${index}.length ? values${index} : Array.isArray(v${index}) ? v${index} : [v${index}]; }`,\n );\n else\n input.push(\n `if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`,\n );\n }\n input.push(\"}\");\n }\n input.push(\"let coercedParams = params;\");\n const numeric = route.coercions.filter(({ type }) => type === \"number\");\n if (numeric.length) {\n // Path segments are strings; numeric ids (`/:id`) need numbers.\n input.push(\"if (params) {\", \"coercedParams = { ...params };\");\n for (const [index, coercion] of numeric.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(\n `const p${index} = params[${key}]; if (typeof p${index} === \"string\") { const pn${index} = Number(p${index}); if (!Number.isNaN(pn${index})) coercedParams[${key}] = pn${index}; }`,\n );\n }\n input.push(\"}\");\n }\n input.push(\n `input = mergeInput(${route.inputPrecedence.map((source) => (source === \"query\" ? \"coercedQuery\" : source === \"params\" ? \"coercedParams\" : source)).join(\", \")});`,\n );\n if ((route.inputSchema as { type?: string } | undefined)?.type === \"object\")\n input.push(\"input ??= {};\");\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context\n ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\"\n : \"\";\n const validation = route.input\n ? `checkDepth(input, ${name}); validate(inputChecker, input, ${name}, \"input\");`\n : \"\";\n const authorization = route.authorize\n ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name}, ctx.user);`\n : \"\";\n const output = route.output\n ? `validate(outputChecker, result, ${name}, \"output\");`\n : \"\";\n const execute = asyncStages\n ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;`\n : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set, ctx));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, checkDepth, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, deps: service.deps ?? emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set, ctx); }\n};\n}`;\n}\n","import type { TSchema } from \"@sinclair/typebox\";\nimport { defineAction } from \"./action\";\nimport type {\n Tool,\n ToolConfigWithAuthorize,\n ToolConfigWithoutAuthorize,\n ActionErrorDefinition,\n ActionContext,\n} from \"./types\";\n\n/**\n * Define a tool: an action that AI agents can call through MCP. It takes the\n * same configuration as `defineAction` (validation, `authorize`, errors), plus\n * `title`, `annotations` (the MCP hints about what the tool does), and `http`\n * to also serve it over HTTP and in OpenAPI (off by default).\n *\n * @param config - An action configuration and tool options. `input` must be an\n * object schema, since MCP passes arguments by name.\n * @returns The tool, which is also an action. Register it with `service.tool(tool)`.\n * @throws When `input` is not an object schema.\n * @example\n * import { defineTool, t } from \"@brickkit/core\";\n *\n * export const echoTool = defineTool({\n * name: \"echo\",\n * title: \"Echo a message\",\n * description: \"Returns the message it is given.\",\n * input: t.Object({ message: t.String() }),\n * output: t.String(),\n * execute: ({ input }) => `Echo: ${input.message}`,\n * });\n */\nexport function defineTool<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ToolConfigWithAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n>(\n config: ToolConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >,\n): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;\n\nexport function defineTool(config: any): any {\n if (config.input && config.input.type !== \"object\") {\n throw new Error(`Tool '${config.name}' input must be an object schema`);\n }\n const tool = defineAction(config);\n Object.defineProperty(tool, \"kind\", { value: \"tool\" });\n return tool;\n}\n\n/**\n * Whether a value was made with `defineTool`, as opposed to `defineAction`.\n *\n * @param value - Anything.\n * @returns `true` for a tool, narrowing its type.\n */\nexport function isTool(value: unknown): value is Tool<any, any, any, any> {\n return typeof value === \"function\" && (value as Tool).kind === \"tool\";\n}\n","import type { Database } from \"bun:sqlite\";\nimport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nimport { createRequire } from \"node:module\";\n\nconst requireSQLite = createRequire(import.meta.url);\n\nexport type { BunSQLiteDatabase } from \"drizzle-orm/bun-sqlite\";\n\nexport {\n sqliteTable,\n text,\n integer,\n real,\n blob,\n index,\n uniqueIndex,\n primaryKey,\n foreignKey,\n} from \"drizzle-orm/sqlite-core\";\n\nexport interface SQLiteDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Database file path or ':memory:' (default: ':memory:') */\n path?: string;\n /** Alias for path */\n filename?: string;\n /** Whether to enable WAL journal mode for file-based DBs (default: true) */\n wal?: boolean;\n /** Whether to enforce foreign key constraints (default: true) */\n foreignKeys?: boolean;\n /** Optional existing bun:sqlite Database instance */\n client?: Database;\n /** Optional Drizzle schema object for typed relational queries */\n schema?: TSchema;\n}\n\nexport type BrickSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = BunSQLiteDatabase<TSchema> & {\n $client: Database;\n};\n\n/**\n * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine\n * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).\n *\n * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on\n * other runtimes (e.g. Node) stays safe until this function is actually\n * called.\n */\nexport function createSQLiteDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: SQLiteDatabaseConfig<TSchema> = {}): BunSQLiteDatabase<TSchema> {\n let Database: new (path: string) => Database;\n let drizzle: (\n client: Database,\n config?: { schema?: TSchema },\n ) => BunSQLiteDatabase<TSchema>;\n try {\n ({ Database } = requireSQLite(\"bun:sqlite\"));\n // Keep the adapter lazy for Node imports, but visible to Bun's bundler.\n ({ drizzle } = require(\"drizzle-orm/bun-sqlite\"));\n } catch (err: any) {\n throw new Error(\n `[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`,\n );\n }\n const filePath = config.filename ?? config.path ?? \":memory:\";\n const client = config.client ?? new Database(filePath);\n\n if (config.foreignKeys !== false) {\n client.run(\"PRAGMA foreign_keys = ON;\");\n }\n\n if (config.wal !== false && filePath !== \":memory:\") {\n client.run(\"PRAGMA journal_mode = WAL;\");\n }\n\n const db = (\n config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client)\n ) as BunSQLiteDatabase<TSchema>;\n\n if (!(db as any).$client) {\n (db as any).$client = client;\n }\n\n return db;\n}\n","import postgres, { type Sql } from \"postgres\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\n\nexport interface PostgresDatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */\n client?: Sql;\n /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */\n url?: string;\n /** Connection string alias */\n connectionString?: string;\n host?: string;\n port?: number;\n user?: string;\n password?: string;\n database?: string;\n ssl?: boolean | \"require\" | \"allow\" | \"prefer\" | \"verify-full\";\n max?: number;\n /**\n * Disable prepared statements (required for transaction-mode poolers such\n * as Supabase's Supavisor on :6543, which cannot hold named prepared\n * statements across transactions).\n */\n prepare?: boolean;\n /** Optional Drizzle schema for relational queries */\n schema?: TSchema;\n /** Custom schema name for Encore-style isolated schemas */\n schemaName?: string;\n}\n\nexport type PostgresDatabase<\n _TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = any;\n\nexport interface DatabaseAdapter<TDb = any, TConfig = any> {\n createDatabase(config?: TConfig): TDb;\n}\n\n/**\n * Creates a PostgreSQL Drizzle instance using postgres-js.\n * Static imports (both are hard dependencies in package.json) so bundlers\n * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in\n * `sqlite.ts` since it only exists under Bun.\n */\nexport function createPostgresDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(config: PostgresDatabaseConfig<TSchema> = {}): PostgresDatabase<TSchema> {\n const connectionUrl =\n config.url ??\n config.connectionString ??\n (typeof process !== \"undefined\" ? process.env?.DATABASE_URL : undefined);\n\n const client =\n config.client ??\n (connectionUrl\n ? postgres(connectionUrl, {\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n })\n : postgres({\n host: config.host ?? \"localhost\",\n port: config.port ?? 5432,\n user: config.user,\n password: config.password,\n database: config.database,\n max: config.max,\n prepare: config.prepare,\n ssl: config.ssl,\n }));\n\n return drizzle(client, {\n schema: config.schema,\n ...(config.schemaName ? { schemaFilter: [config.schemaName] } : {}),\n });\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { type Table, getTableName } from \"drizzle-orm\";\nimport type { PostgresJsDatabase } from \"drizzle-orm/postgres-js\";\nimport type { Sql } from \"postgres\";\nimport { SecretRef } from \"../secrets\";\nimport {\n createSQLiteDatabase,\n type SQLiteDatabaseConfig,\n type BunSQLiteDatabase,\n type BrickSQLiteDatabase,\n} from \"./sqlite\";\nimport {\n createPostgresDatabase,\n type PostgresDatabaseConfig,\n} from \"./postgres\";\n\nexport type EnvInput<T> = T | SecretRef<T>;\ntype EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>> };\n\ninterface DefinitionOptions<TSchema extends Record<string, unknown>> {\n name?: string;\n /** Drizzle tables retained for schema tooling. Never applied at runtime. */\n tables?: (TSchema & Record<string, Table>) | readonly Table[];\n schema?: TSchema;\n}\n\nexport type SQLiteDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine?: \"sqlite\";\n client?: SQLiteDatabaseConfig<TSchema>[\"client\"];\n url?: never;\n connectionString?: never;\n };\n\nexport type PostgresDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = DefinitionOptions<TSchema> &\n EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, \"schema\" | \"client\">> & {\n engine: \"postgres\";\n path?: never;\n filename?: never;\n wal?: never;\n foreignKeys?: never;\n client?: PostgresDatabaseConfig<TSchema>[\"client\"];\n };\n\nexport type DatabaseDefinition<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;\n\nexport interface DatabaseHandle<\n TDb,\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> {\n readonly kind: \"brick-database\";\n readonly name?: string;\n readonly engine: \"sqlite\" | \"postgres\";\n readonly tables: Readonly<Record<string, Table>>;\n readonly schema: TSchema;\n /**\n * Add a table after definition, as `definePlugin` does for the tables a\n * plugin owns. Before `getDb()` it also joins the relational schema.\n */\n addTable?(key: string, table: Table): void;\n getDb(): TDb;\n close?(): void | Promise<void>;\n}\n\n/**\n * Whether a value is a database handle made by `defineDatabase`.\n *\n * @param value - Anything.\n * @returns `true` for a handle, narrowing its type.\n */\nexport function isDatabaseHandle(\n value: unknown,\n): value is DatabaseHandle<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n value.kind === \"brick-database\"\n );\n}\n\n/**\n * Declare a service's database: its engine, its Drizzle tables, and how to\n * reach it. Nothing connects until the handle is used (`getDb()`), so defining\n * one has no side effects.\n *\n * SQLite is the default and needs no options. Pass `engine: \"postgres\"` with a\n * `url` for Postgres. Options that belong to the other engine (such as `url` for\n * SQLite, or `path` for Postgres) are refused.\n *\n * @param options - `engine` (`\"sqlite\"` or `\"postgres\"`), `tables`, an optional\n * `name`, and the engine's connection settings.\n * @returns A handle to give to `defineService({ database })`. `getDb()` returns\n * the Drizzle database.\n * @throws When the engine is unsupported, or an option does not suit the engine.\n * @example\n * import { defineDatabase } from \"@brickkit/core\";\n * import { sqliteTable, text } from \"drizzle-orm/sqlite-core\";\n *\n * const pages = sqliteTable(\"pages\", {\n * id: text(\"id\").primaryKey(),\n * title: text(\"title\").notNull(),\n * });\n *\n * export const database = defineDatabase({ tables: { pages } });\n */\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options?: SQLiteDefinition<TSchema>,\n): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>;\nexport function defineDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n options: PostgresDefinition<TSchema>,\n): DatabaseHandle<PostgresJsDatabase<TSchema> & { $client: Sql }, TSchema>;\nexport function defineDatabase(\n options: DatabaseDefinition = {},\n): DatabaseHandle<unknown> {\n const engine = options.engine ?? \"sqlite\";\n if (engine !== \"sqlite\" && engine !== \"postgres\") {\n throw new Error(`Unsupported database engine: ${engine}`);\n }\n const forbidden =\n engine === \"sqlite\"\n ? [\n \"url\",\n \"connectionString\",\n \"host\",\n \"port\",\n \"user\",\n \"password\",\n \"database\",\n \"ssl\",\n \"max\",\n \"schemaName\",\n ]\n : [\"path\", \"filename\", \"wal\", \"foreignKeys\"];\n for (const key of forbidden) {\n if (key in options)\n throw new Error(`Database option \"${key}\" is not valid for ${engine}`);\n }\n const declared = options.tables ?? {};\n const tables: Record<string, Table> = Array.isArray(declared)\n ? Object.fromEntries(declared.map((table) => [getTableName(table), table]))\n : { ...declared };\n const schema = options.schema ?? tables;\n let frozen = Object.freeze({ ...tables });\n let db: unknown;\n let closeClient: (() => void | Promise<void>) | undefined;\n let closed = false;\n let closing: void | Promise<void>;\n\n return {\n kind: \"brick-database\",\n name: options.name,\n engine,\n get tables() {\n return frozen;\n },\n schema,\n addTable(key, table) {\n const name = getTableName(table);\n if (\n Object.hasOwn(tables, key) ||\n Object.values(tables).some((item) => getTableName(item) === name)\n )\n throw new Error(\n `Database already has a table \"${key}\" or one named \"${name}\"`,\n );\n // Also joins `schema` when that is `tables` itself (no `schema` given).\n tables[key] = table;\n frozen = Object.freeze({ ...tables });\n },\n close() {\n if (closed) return closing;\n closed = true;\n closing = closeClient?.();\n return closing;\n },\n getDb() {\n if (closed) throw new Error(\"Brick database handle is closed\");\n if (db !== undefined) return db;\n const config: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if ([\"tables\", \"schema\", \"name\", \"engine\"].includes(key)) continue;\n // An injected Postgres client already owns all connection settings.\n if (\n engine === \"postgres\" &&\n options.client &&\n key !== \"client\" &&\n key !== \"schemaName\"\n )\n continue;\n config[key] = value instanceof SecretRef ? value.require() : value;\n }\n if (engine === \"sqlite\") {\n const path = (config.filename ?? config.path ?? \":memory:\") as string;\n if (!config.client && path !== \":memory:\")\n mkdirSync(dirname(path), { recursive: true });\n const instance = createSQLiteDatabase({ ...config, schema });\n db = instance;\n if (!options.client)\n closeClient = () => (instance as BrickSQLiteDatabase).$client.close();\n } else {\n const instance: PostgresJsDatabase & { $client: Sql } =\n createPostgresDatabase({ ...config, schema });\n db = instance;\n if (!options.client) closeClient = () => instance.$client.end();\n }\n return db;\n },\n };\n}\n","import type { Service } from \"../types\";\nimport type { DatabaseHandle } from \"./define\";\nimport {\n createSQLiteDatabase,\n type SQLiteDatabaseConfig,\n type BunSQLiteDatabase,\n} from \"./sqlite\";\nimport {\n createPostgresDatabase,\n type PostgresDatabaseConfig,\n type PostgresDatabase,\n} from \"./postgres\";\nimport { getTableColumns, getTableName, sql } from \"drizzle-orm\";\n\nexport * from \"./sqlite\";\nexport * from \"./postgres\";\nexport * from \"./define\";\n\n// Re-export core Drizzle SQL expressions & operators for convenience\nexport {\n sql,\n eq,\n ne,\n gt,\n gte,\n lt,\n lte,\n and,\n or,\n not,\n desc,\n asc,\n inArray,\n notInArray,\n isNull,\n isNotNull,\n like,\n ilike,\n relations,\n getTableColumns,\n getTableName,\n Table,\n is,\n} from \"drizzle-orm\";\n\nexport interface DatabaseConfig<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>\n extends\n Omit<SQLiteDatabaseConfig<TSchema>, \"client\">,\n Omit<PostgresDatabaseConfig<TSchema>, \"client\"> {\n client?:\n | SQLiteDatabaseConfig<TSchema>[\"client\"]\n | PostgresDatabaseConfig<TSchema>[\"client\"];\n /** Database engine. Default: 'sqlite' */\n engine?: \"sqlite\" | \"postgres\" | \"clickhouse\";\n /** Optional service name associated with this database */\n name?: string;\n}\n\nexport type BrickDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n> = BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;\n\n/**\n * Creates a database instance based on the provided configuration.\n * Zero-config: calling `createDatabase()` returns an ultra-fast Bun-native SQLite\n * database in `:memory:` mode wrapped with Drizzle ORM.\n */\nexport function createDatabase<\n TSchema extends Record<string, unknown> = Record<string, unknown>,\n>(\n config: DatabaseConfig<TSchema> = {},\n): BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema> {\n const engine = config.engine ?? \"sqlite\";\n\n if (engine === \"sqlite\") {\n return createSQLiteDatabase<TSchema>(\n config as SQLiteDatabaseConfig<TSchema>,\n );\n }\n\n if (engine === \"postgres\") {\n return createPostgresDatabase<TSchema>(\n config as PostgresDatabaseConfig<TSchema>,\n );\n }\n\n throw new Error(`[Brick-TS DB] Unsupported database engine: '${engine}'`);\n}\n\n/** Attach a defined database. Schema changes remain the caller's responsibility. */\nexport function attachDatabase<TDb>(\n service: Service<TDb, any>,\n database: DatabaseHandle<TDb>,\n): TDb {\n service.setDb(database);\n return database.getDb();\n}\n\n/**\n * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition\n * directly from a Drizzle table schema.\n */\nexport function generateSQLiteTableDdl(table: any): string {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colDefs: string[] = [];\n\n for (const [, col] of Object.entries(columns) as [string, any][]) {\n let def = `\"${col.name}\" ${col.getSQLType().toUpperCase()}`;\n if (col.primary) def += \" PRIMARY KEY\";\n if (col.notNull) def += \" NOT NULL\";\n if (col.isUnique) def += \" UNIQUE\";\n if (col.hasDefault) {\n if (typeof col.default === \"string\") {\n def += ` DEFAULT '${col.default.replace(/'/g, \"''\")}'`;\n } else if (typeof col.default === \"boolean\") {\n def += ` DEFAULT ${col.default ? 1 : 0}`;\n } else if (typeof col.default === \"number\") {\n def += ` DEFAULT ${col.default}`;\n } else if (col.default !== undefined) {\n def += ` DEFAULT ${col.default}`;\n }\n }\n colDefs.push(def);\n }\n\n return `CREATE TABLE IF NOT EXISTS \"${tableName}\" (\\n ${colDefs.join(\",\\n \")}\\n);`;\n}\n\n/**\n * Generates idempotent secondary index DDL for a Drizzle table.\n * Covers owner scoping, sort columns, and exact-match filters.\n * UNIQUE columns already carry an implicit index — skipped here.\n * FTS/trigram indexes are handled separately by the search layer.\n */\nexport function generateSQLiteIndexDdl(\n table: any,\n opts: { ownerField?: string; sortFields?: string[] } = {},\n): string[] {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const stmts: string[] = [];\n const seen = new Set<string>();\n const push = (name: string, cols: string[]) => {\n const clean = cols.filter(Boolean);\n if (clean.length === 0) return;\n const key = `${name}(${clean.join(\",\")})`;\n if (seen.has(key)) return;\n seen.add(key);\n const colList = clean.map((c) => `\"${c}\"`).join(\", \");\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"${name}\" ON \"${tableName}\" (${colList});`,\n );\n };\n\n const colNameOf = (field: string): string | undefined => {\n if ((columns as any)[field]) return (columns as any)[field].name ?? field;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === field) return col.name;\n }\n return undefined;\n };\n\n // Owner scope index: WHERE user_id = ? (+ sort composite below).\n let ownerCol: string | undefined;\n if (opts.ownerField) {\n const oc = colNameOf(opts.ownerField);\n if (oc) {\n ownerCol = oc;\n push(`idx_${tableName}_${oc}`, [oc]);\n }\n }\n\n // Sort column indexes (updated_at / created_at drive default ORDER BY).\n const sorts = opts.sortFields ?? [\"updated_at\", \"created_at\"];\n const sortCols: string[] = [];\n for (const f of sorts) {\n const c = colNameOf(f);\n if (c) {\n sortCols.push(c);\n push(`idx_${tableName}_${c}`, [c]);\n }\n }\n\n // Composite owner+sort — the hot path for scoped sorted lists.\n if (ownerCol && sortCols.length > 0) {\n push(`idx_${tableName}_${ownerCol}_${sortCols[0]}`, [\n ownerCol,\n sortCols[0],\n ]);\n }\n\n return stmts;\n}\n\n/**\n * Ensures secondary indexes exist for a resource table.\n * SQLite: B-tree indexes for owner scope + sort + composite hot path.\n * Postgres: same B-trees plus pg_trgm GIN indexes for substring search.\n * Best-effort: failures warn and continue (e.g. read-only replicas).\n */\nexport function ensureResourceIndexes(\n db: any,\n table: any,\n opts: {\n ownerField?: string;\n sortFields?: string[];\n searchFields?: string[];\n } = {},\n): void {\n if (!db) return;\n const isPostgres =\n typeof (db as any).execute === \"function\" && !(db as any).$client?.run;\n const stmts = generateSQLiteIndexDdl(table, opts);\n // Postgres trigram support for LIKE %term% (requires superuser for extension;\n // failure is silently ignored — LIKE still works, just slower).\n if (isPostgres && opts.searchFields && opts.searchFields.length > 0) {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n for (const f of opts.searchFields) {\n const c = colNameOf(f);\n if (c) {\n stmts.push(\n `CREATE INDEX IF NOT EXISTS \"idx_${tableName}_${c}_trgm\" ON \"${tableName}\" USING gin (\"${c}\" gin_trgm_ops);`,\n );\n }\n }\n }\n if (stmts.length === 0) return;\n const run = (stmt: string) => {\n try {\n if ((db as any).$client?.run) {\n (db as any).$client.run(stmt);\n } else if (typeof (db as any).execute === \"function\") {\n void (db as any).execute(sql.raw(stmt)).catch(() => {});\n } else if ((db as any).run) {\n (db as any).run(stmt);\n }\n } catch {\n // best-effort\n }\n };\n if (isPostgres) {\n run(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);\n }\n for (const s of stmts) run(s);\n}\n\n/**\n * SQLite FTS5 search layer for resource list (?search=).\n * B-tree indexes cannot serve LIKE '%term%' (leading wildcard forces a full\n * scan). FTS5 gives indexed substring/prefix search on title/slug-scale text.\n * Postgres uses ilike + pg_trgm GIN indexes instead (see ensureResourceIndexes).\n */\n\nfunction ftsTableName(table: any): string {\n return `${getTableName(table)}_fts`;\n}\n\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.\n * Idempotent; safe to call on every resource registration.\n * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.\n */\nexport function ensureSQLiteFts(\n db: any,\n table: any,\n searchCols: string[],\n): void {\n if (!db || searchCols.length === 0) return;\n // SQLite only: Postgres has execute() but no $client.run.\n const client = (db as any).$client;\n const runRaw = (db as any).run;\n if (!client?.run && !runRaw) return;\n const run = (stmt: string) => {\n if (client?.run) client.run(stmt);\n else runRaw(stmt);\n };\n try {\n const tableName = getTableName(table);\n const columns = getTableColumns(table);\n const colNameOf = (f: string): string | undefined => {\n if ((columns as any)[f]) return (columns as any)[f].name ?? f;\n for (const col of Object.values(columns) as any[]) {\n if (col.name === f) return col.name;\n }\n return undefined;\n };\n // Resolve to DB column names, drop unknowns.\n const dbCols = searchCols.map(colNameOf).filter((c): c is string => !!c);\n if (dbCols.length === 0) return;\n const idCol =\n colNameOf(\"id\") ??\n (Object.values(columns) as any[]).find((c) => c.primary)?.name ??\n \"id\";\n const fts = ftsTableName(table);\n const ftsCols = [\n `\"id\" UNINDEXED`,\n ...dbCols.map((c) => quoteIdent(c)),\n ].join(\", \");\n run(\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${quoteIdent(fts)} USING fts5(${ftsCols}, tokenize='porter');`,\n );\n const colList = dbCols.map(quoteIdent).join(\", \");\n const newVals = dbCols.map((c) => `new.${quoteIdent(c)}`).join(\", \");\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ai`)} AFTER INSERT ON ${quoteIdent(tableName)} BEGIN INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; END;`,\n );\n run(\n `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_au`)} AFTER UPDATE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE \"id\" = old.${quoteIdent(idCol)}; INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`,\n );\n // Backfill rows predating the FTS table (dedupe via NOT IN).\n run(\n `INSERT INTO ${quoteIdent(fts)}(\"id\", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT \"id\" FROM ${quoteIdent(fts)});`,\n );\n } catch {\n // best-effort: LIKE fallback in the list path covers FTS absence.\n }\n}\n\n/**\n * Builds an FTS5 MATCH condition for a resource search term.\n * Returns null when the term has no usable tokens or FTS errors.\n * Caller falls back to LIKE in that case.\n */\nexport function buildFtsMatchQuery(search: string): string | null {\n const terms = search\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean)\n .slice(0, 10);\n if (terms.length === 0) return null;\n const escaped = terms\n .map((term) => {\n const clean = term.replace(/\"/g, \"\").trim();\n if (!clean) return null;\n return `\"${clean.replace(/\"/g, '\"\"')}\"*`;\n })\n .filter((x): x is string => !!x);\n if (escaped.length === 0) return null;\n return escaped.join(\" AND \");\n}\n\n/**\n * Explicit SQLite development/test schema preparation helper.\n * Never called by services, resources, auth, or server startup.\n * Not a migration runner; PostgreSQL schema management is caller-owned.\n */\nexport function syncSchema(\n tablesOrService: Map<string, any> | any[] | Record<string, any> | Service,\n dbInstance?: any,\n): Promise<void> | void {\n let db = dbInstance;\n let tables: any[] = [];\n\n if (\n tablesOrService &&\n typeof (tablesOrService as any).listActions === \"function\" &&\n (tablesOrService as any).tables\n ) {\n const service = tablesOrService as Service;\n tables = Array.from(service.tables.values());\n if (!db) {\n db = service.getDb();\n }\n } else if (tablesOrService instanceof Map) {\n tables = Array.from(tablesOrService.values());\n } else if (Array.isArray(tablesOrService)) {\n tables = tablesOrService;\n } else if (tablesOrService && typeof tablesOrService === \"object\") {\n tables = Object.values(tablesOrService);\n }\n\n if (!db || tables.length === 0) return;\n\n // Bun SQLite\n if ((db as any).$client?.run || (db as any).run) {\n for (const table of tables) {\n try {\n const ddl = generateSQLiteTableDdl(table);\n if ((db as any).$client?.run) {\n (db as any).$client.run(ddl);\n } else if ((db as any).run) {\n (db as any).run(sql.raw(ddl));\n }\n } catch (err: any) {\n console.warn(`[Brick-TS DB] Failed to create table:`, err.message);\n }\n }\n return;\n }\n\n // Postgres async mode\n return (async () => {\n for (const table of tables) {\n try {\n const _tableName = getTableName(table);\n // Postgres sync or migration runner if configured\n } catch (err: any) {\n console.warn(`[Brick-TS DB] Postgres syncSchema error:`, err.message);\n }\n }\n })();\n}\n","import { and, eq, getTableColumns, inArray, type Column } from \"drizzle-orm\";\nimport type { TObject, TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport { installPlugin } from \"./plugin\";\nimport { buildErrorHelpers, defineAction } from \"./action\";\nimport { kebabCase, type ResourceActionInfo } from \"./routes\";\nimport { Type } from \"./typebox\";\nimport { runInTransaction } from \"./events/transaction\";\nimport type { EventRef } from \"./events/catalog\";\nimport type { ServiceEvents } from \"./events/types\";\nimport {\n ActionExecutionError,\n type ActionContext,\n type ActionErrorDefinition,\n type CommandConfig,\n type CommandDecision,\n type Resource,\n type ResourceActionAccess,\n type ResourceActionConfig,\n type ResourceChild,\n type ResourceConfig,\n type ResourceTypeOptions,\n type ResourceIdentity,\n type Service,\n} from \"./types\";\n\n/** Resource actions can't take a CRUD route segment. */\nconst CRUD_SEGMENTS = new Set([\n \"query\",\n \"count\",\n \"exists\",\n \"find-one\",\n \"bulk-create\",\n \"bulk-update\",\n \"bulk-delete\",\n]);\n\n/**\n * Load the row a record action (or command) works on, through its `access`.\n *\n * @returns The row, or `undefined` when it is missing or hidden.\n * @throws When `access` is missing.\n */\nexport async function loadRecord(\n resource: Resource<any, any, any>,\n args: {\n id: unknown;\n ctx: any;\n db?: any;\n access?: ResourceActionAccess;\n },\n): Promise<Record<string, unknown> | undefined> {\n if (!args.access)\n throw new Error(\n `Resource '${resource.name}' has no access rule for loading records: set \\`access\\` on the record action`,\n );\n const db = args.db ?? args.ctx?.db;\n // An id its column can't hold names no row.\n const id = idValue(resource.id, args.id);\n if (id === undefined) return undefined;\n if (!db) throw new Error(\"Record actions require a configured database\");\n const scope =\n args.access === \"public\"\n ? undefined\n : await args.access.scope({ ctx: args.ctx });\n const [row] = await db\n .select()\n .from(resource.table)\n .where(and(scope, eq(resource.id, id)))\n .limit(1);\n return row;\n}\n\n/** Startup check: a record action needs its own `access`. */\nexport function checkRecordAccess(\n resource: Resource<any, any, any>,\n info: ResourceActionInfo,\n): void {\n const name = `${resource.name}.${info.name}`;\n if (info.access === undefined)\n throw new Error(\n `Record action '${name}' needs \\`access\\` (\"public\" or { scope })`,\n );\n}\n\n/** The id from the path as its column stores it: a Date or BigInt for those columns, undefined when it can't be one. */\nfunction idValue(column: Column, id: unknown): unknown {\n if (typeof id !== \"string\") return id;\n if (column.dataType === \"date\") {\n const date = new Date(id);\n return Number.isNaN(date.getTime()) ? undefined : date;\n }\n if (column.dataType === \"bigint\")\n return /^-?\\d+$/.test(id) ? BigInt(id) : undefined;\n return id;\n}\n\nfunction idSchema(column: Column): TSchema {\n return column.dataType === \"number\" ? Type.Number() : Type.String();\n}\n\nfunction defineResourceAction(\n service: Service<any, any>,\n resource: Resource<any, any, any>,\n config: ResourceActionConfig<any, any, any, any, any, boolean>,\n /** A command's body: it loads the row itself, in its transaction. */\n command?: (args: { input: any; ctx: any; error: any }) => Promise<unknown>,\n) {\n const { record = false, access, execute, ...rest } = config;\n if (!config.name || /[./]/.test(config.name))\n throw new Error(`Invalid resource action name '${config.name}'`);\n const name = `${resource.name}.${config.name}`;\n const segment = kebabCase(config.name);\n if (CRUD_SEGMENTS.has(segment))\n throw new Error(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\": \"${segment}\" is a CRUD route`,\n );\n if ((service.getAction(name) as { plugin?: string } | undefined)?.plugin)\n throw new Error(\n `Brick: duplicate name \"${name}\" in service \"${service.name}\"`,\n );\n if (!record && access !== undefined)\n throw new Error(`Only record actions take \\`access\\` ('${name}')`);\n if (record && config.path !== undefined && !/\\/:id(\\/|$)/.test(config.path))\n throw new Error(`Record action '${name}' needs ':id' in its path`);\n let input = config.input as TSchema | undefined;\n if (record) {\n const own = input as TObject | undefined;\n if (own && own.type !== \"object\")\n throw new Error(`Record action '${name}' input must be an object`);\n input = Type.Object(\n { ...own?.properties, id: idSchema(resource.id) },\n own?.additionalProperties === undefined\n ? {}\n : { additionalProperties: own.additionalProperties },\n );\n }\n const action = defineAction({\n ...rest,\n name,\n input,\n execute: async ({ input, ctx, error }: any) => {\n if (command) return command({ input, ctx, error });\n const row = record\n ? await loadRecord(resource, { id: input.id, ctx, access })\n : undefined;\n if (record && row === undefined)\n error.NOT_FOUND(`${resource.name} '${String(input.id)}' not found`);\n return execute({ input, ctx, error, row } as any);\n },\n } as any);\n const info: ResourceActionInfo = {\n resource: resource.name,\n name: config.name,\n record,\n ...(access === undefined ? {} : { access }),\n };\n Object.assign(action, { resource: resource.name, resourceAction: info });\n service.action(action);\n return action;\n}\n\nfunction primaryColumn(table: unknown): [string, Column] | undefined {\n const primary = Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).filter(([, column]) => column.primary);\n return primary.length === 1 ? primary[0] : undefined;\n}\n\nfunction fieldOf(table: unknown, column: Column): string | undefined {\n return Object.entries(\n getTableColumns(table as Parameters<typeof getTableColumns>[0]),\n ).find(([, own]) => own === column)?.[0];\n}\n\ninterface ChildInfo {\n table: any;\n parent: Column;\n parentField: string;\n id: Column;\n idField: string;\n}\n\nfunction childInfo(\n resource: Resource<any, any, any>,\n name: string,\n where: string,\n): ChildInfo {\n const child = (\n resource.config as { children?: Record<string, ResourceChild> }\n ).children?.[name];\n if (!child || !Object.hasOwn(resource.config.children ?? {}, name))\n throw new Error(\n `${where}: resource '${resource.name}' has no child table '${name}'`,\n );\n const parentField = fieldOf(child.table, child.parent);\n const id = child.id ?? primaryColumn(child.table)?.[1];\n const idField = id && fieldOf(child.table, id);\n if (!parentField || !id || !idField)\n throw new Error(\n `Resource '${resource.name}' child '${name}' needs a parent column and an id column of its table`,\n );\n return { table: child.table, parent: child.parent, parentField, id, idField };\n}\n\n/** The `error` helpers of `decide`: they return the rejection, not throw it. */\nfunction commandErrors(errors?: Record<string, ActionErrorDefinition>) {\n const throwing = buildErrorHelpers(errors) as Record<\n string,\n (message?: string, details?: unknown) => never\n >;\n return Object.fromEntries(\n Object.entries(throwing).map(([code, helper]) => [\n code,\n (message?: string, details?: unknown) => {\n try {\n helper(message, details);\n } catch (rejection) {\n return rejection;\n }\n },\n ]),\n );\n}\n\nfunction defineCommand(\n service: Service<any, any>,\n resource: Resource<any, any, any>,\n name: string,\n config: CommandConfig<any, any, any, any, any, any, any, readonly string[]>,\n) {\n const where = `Command '${resource.name}.${name}'`;\n if (typeof config.decide !== \"function\")\n throw new Error(`${where} needs a decide function`);\n const loaded = (config.load?.children ?? []).map((child) => ({\n name: child,\n ...childInfo(resource, child, where),\n }));\n const error = commandErrors(config.errors);\n const decide = (row: any, input: any) =>\n config.decide(row, input, { error } as any);\n const events = service.events as Record<string, EventRef>;\n\n const run = async ({ input, ctx }: { input: any; ctx: any }) => {\n const db = ctx.db;\n if (!db) throw new Error(`${where} requires a configured database`);\n const recorder = (service as { recorder?: ServiceEvents }).recorder;\n const body = async (\n tx: any,\n record?: (name: string, payload: unknown) => Promise<void>,\n ) => {\n const row = await loadRecord(resource, {\n id: input.id,\n ctx,\n db: tx,\n access: config.access,\n });\n if (row === undefined)\n throw new ActionExecutionError(\n \"NOT_FOUND\",\n `${resource.name} '${String(input.id)}' not found`,\n 404,\n );\n const id = row[resource.idField];\n for (const child of loaded)\n row[child.name] = await tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n\n const decision = decide(row, input);\n if (decision instanceof ActionExecutionError) throw decision;\n const { set, children, emit } = (decision ?? {}) as CommandDecision<\n any,\n Record<string, unknown>\n >;\n // Every event is checked before anything is written.\n const emits = Object.entries(emit ?? {})\n .filter(([, payload]) => payload !== undefined)\n .map(([key, payload]) => {\n const ref = Object.hasOwn(events, key) ? events[key] : undefined;\n if (!ref)\n throw new Error(\n `${where} emits '${key}', which is not in the event catalog of service '${service.name}'`,\n );\n (\n service as { checkEvent?(n: string, p: unknown): void }\n ).checkEvent?.(ref.name, payload);\n return [ref.name, payload] as const;\n });\n if (emits.length && !record)\n throw new Error(\n `${where} emits events, but service '${service.name}' records none: give its database an outbox table and the app \\`events\\``,\n );\n\n if (set && Object.keys(set).length)\n await tx.update(resource.table).set(set).where(eq(resource.id, id));\n for (const [childName, changes] of Object.entries(children ?? {})) {\n if (!changes) continue;\n const child = childInfo(resource, childName, where);\n const own = eq(child.parent, id);\n if (changes.insert?.length)\n await tx.insert(child.table).values(\n changes.insert.map((item) => ({\n ...item,\n [child.parentField]: id,\n })),\n );\n for (const item of changes.update ?? []) {\n const { [child.idField]: childId, ...values } = item as Record<\n string,\n unknown\n >;\n if (childId === undefined)\n throw new Error(\n `${where}: an update of child '${childName}' needs its '${child.idField}'`,\n );\n if (Object.keys(values).length)\n await tx\n .update(child.table)\n .set(values)\n .where(and(eq(child.id, childId), own));\n }\n if (changes.delete?.length)\n await tx\n .delete(child.table)\n .where(and(inArray(child.id, changes.delete), own));\n }\n for (const [eventName, payload] of emits)\n await record!(eventName, payload);\n\n if (!config.output) return { id };\n const [updated] = await tx\n .select()\n .from(resource.table)\n .where(eq(resource.id, id))\n .limit(1);\n for (const child of loaded)\n updated[child.name] = await tx\n .select()\n .from(child.table)\n .where(eq(child.parent, id));\n return Value.Clean(config.output, updated);\n };\n return recorder\n ? recorder.transaction(\n db,\n { traceId: ctx.traceId, source: `${service.name}.${resource.name}` },\n body,\n )\n : runInTransaction(db, (tx) => body(tx));\n };\n\n const action = defineResourceAction(\n service,\n resource,\n {\n name,\n record: true,\n description: config.description,\n tags: config.tags,\n input: config.input,\n output: config.output ?? Type.Object({ id: idSchema(resource.id) }),\n errors: config.errors,\n ...(config.access === undefined ? {} : { access: config.access }),\n ...(config.authorize ? { authorize: config.authorize } : {}),\n execute: () => undefined,\n } as ResourceActionConfig<any, any, any, any, any, boolean>,\n run,\n );\n Object.assign(action, { decide, command: true });\n return action;\n}\n\n/** Declares a plugin host without registering actions or changing the schema. */\nexport function defineResource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n const O extends ResourceTypeOptions = ResourceTypeOptions,\n>(\n service: Service<any, any>,\n config: ResourceConfig<TTable, TCtx> & O,\n): Resource<TTable, TCtx, ResourceIdentity<TTable, O>> {\n const columns = getTableColumns(\n config.table as Parameters<typeof getTableColumns>[0],\n );\n const primary = Object.entries(columns).filter(\n ([, column]) => column.primary,\n );\n const id: Column | undefined =\n config.id ?? (primary.length === 1 ? primary[0]?.[1] : undefined);\n const entry = Object.entries(columns).find(([, column]) => column === id);\n if (!entry || !id)\n throw new Error(\n `Resource '${config.name}' requires an id column belonging to its table`,\n );\n if (\n !config.name ||\n config.name.includes(\"/\") ||\n [\"__proto__\", \"constructor\", \"prototype\"].includes(config.name)\n )\n throw new Error(`Invalid resource name '${config.name}'`);\n service.registerTable(config.table);\n const resource = {\n name: config.name,\n serviceName: service.name,\n table: config.table,\n id,\n idField: entry[0],\n config: Object.freeze({ ...config, id }),\n use(plugin: import(\"./plugin\").ResourcePlugin<any, any, any>) {\n return installPlugin(\n service,\n resource as unknown as Resource<\n TTable,\n TCtx,\n ResourceIdentity<TTable, O>\n >,\n plugin,\n );\n },\n action(\n actionConfig: ResourceActionConfig<any, any, any, any, any, boolean>,\n ) {\n return defineResourceAction(\n service,\n resource as unknown as Resource<any, any, any>,\n actionConfig,\n );\n },\n command(name: string, commandConfig: CommandConfig<any, any, any, any>) {\n return defineCommand(\n service,\n resource as unknown as Resource<any, any, any>,\n name,\n commandConfig as CommandConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n readonly string[]\n >,\n );\n },\n };\n return resource as unknown as Resource<\n TTable,\n TCtx,\n ResourceIdentity<TTable, O>\n >;\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport { validateWithSchema } from \"../typebox\";\n\n/** A service's declared events: payload schema by event name. */\nexport type EventCatalog = Record<string, TSchema>;\n\n/**\n * One declared event, as `service.events.<name>`. Pass it to `defineListener({ on })`\n * for a typed payload, or to `emitEvent` for a checked one.\n */\nexport interface EventRef<TPayload = unknown> {\n /** The event name on the wire: `<service>.<event>`, such as `orders.shipped`. */\n readonly name: string;\n readonly service: string;\n readonly schema: TSchema;\n /** The plugin that declared it, for events a `definePlugin` adds. */\n readonly plugin?: string;\n /** Type-level only: the payload this event carries. */\n readonly __payload?: TPayload;\n}\n\n/** `service.events`: one `EventRef` per catalog entry. */\nexport type EventRefs<C extends EventCatalog> = {\n readonly [K in keyof C & string]: EventRef<Static<C[K]>>;\n};\n\n/** What a service with a catalog checks before recording an event. */\nexport interface EventChecker {\n readonly name: string;\n readonly events: Readonly<Record<string, EventRef>>;\n /** Whether the service has a catalog at all. */\n readonly hasCatalog: boolean;\n listResources(): readonly { name: string }[];\n}\n\nexport function isEventRef(value: unknown): value is EventRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as EventRef).name === \"string\" &&\n typeof (value as EventRef).service === \"string\" &&\n typeof (value as EventRef).schema === \"object\"\n );\n}\n\n/** Build `service.events` from its catalog. */\nexport function eventRefs(\n service: string,\n catalog: EventCatalog | undefined,\n): Record<string, EventRef> {\n const refs: Record<string, EventRef> = Object.create(null);\n for (const [key, schema] of Object.entries(catalog ?? {})) {\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key))\n throw new Error(\n `Event \"${key}\" in service \"${service}\" must be a plain name such as shipped or itemAdded`,\n );\n if (!schema || typeof schema !== \"object\")\n throw new Error(\n `Event \"${service}.${key}\" needs a payload schema, such as t.Object({ ... })`,\n );\n refs[key] = Object.freeze({ name: `${service}.${key}`, service, schema });\n }\n return Object.freeze(refs);\n}\n\nconst CRUD_EVENT = /^(create|update|delete)$/;\n\n/**\n * Check an event against the catalog of the service recording it. Without a\n * catalog any name goes. With one, the name must be `<service>.<event>` from it\n * (the payload is checked against its schema) or a CRUD event of one of the\n * service's resources (`<resource>.create|update|delete`).\n *\n * @throws When the name is not declared or the payload does not match.\n */\nexport function checkEvent(\n service: EventChecker,\n name: string,\n payload: unknown,\n): void {\n const prefix = `${service.name}.`;\n const ref = name.startsWith(prefix)\n ? service.events[name.slice(prefix.length)]\n : undefined;\n if (ref) {\n const result = validateWithSchema(ref.schema, payload);\n if (!result.success)\n throw new Error(\n `Event \"${name}\" payload does not match its schema: ${result.errors\n .map((error) => `${error.path || \"/\"} ${error.message}`)\n .join(\"; \")}`,\n );\n return;\n }\n if (!service.hasCatalog) return;\n const dot = name.indexOf(\".\");\n if (\n dot > 0 &&\n CRUD_EVENT.test(name.slice(dot + 1)) &&\n service.listResources().some((r) => r.name === name.slice(0, dot))\n )\n return;\n throw new Error(\n `Event \"${name}\" is not in the event catalog of service \"${service.name}\" (declared: ${\n Object.values(service.events)\n .map((ref) => ref.name)\n .join(\", \") || \"none\"\n })`,\n );\n}\n","import type { BaseContext } from \"./types\";\n\ntype ContextEnvelope = Pick<\n BaseContext,\n \"caller\" | \"traceId\" | \"requestId\" | \"tenantId\"\n> & { user?: unknown };\n\nexport function pickContextEnvelope(\n context?: Partial<BaseContext> & { user?: unknown },\n): Partial<ContextEnvelope> {\n if (!context) return {};\n const envelope: Partial<ContextEnvelope> = {};\n if (context.caller !== undefined) envelope.caller = context.caller;\n if (context.user !== undefined) envelope.user = context.user;\n if (context.traceId !== undefined) envelope.traceId = context.traceId;\n if (context.requestId !== undefined) envelope.requestId = context.requestId;\n if (context.tenantId !== undefined) envelope.tenantId = context.tenantId;\n return envelope;\n}\n","import {\n installPlugin,\n isInstallingPlugin,\n type ServicePlugin,\n} from \"./plugin\";\nimport type { TSchema } from \"@sinclair/typebox\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type {\n Service,\n ServiceOptions,\n Action,\n Tool,\n ToolConfigWithAuthorize,\n ToolConfigWithoutAuthorize,\n ActionConfigWithAuthorize,\n ActionConfigWithoutAuthorize,\n ActionErrorDefinition,\n ServiceSchema,\n BaseContext,\n Logger,\n Resource,\n ResourceConfig,\n ResourceTypeOptions,\n ResourceIdentity,\n PreparationContribution,\n} from \"./types\";\nimport { defineTool, isTool } from \"./tool\";\nimport { defineAction } from \"./action\";\nimport { claimName, definitionSite, getGlobalRegistry } from \"./registry\";\nimport { getTableName, isDatabaseHandle, type DatabaseHandle } from \"./db\";\nimport { checkRecordAccess, defineResource } from \"./resource\";\nimport type { ResourceActionInfo } from \"./routes\";\nimport { isOutboxTable, type OutboxTable } from \"./events/outbox\";\nimport type { ServiceEvents } from \"./events/types\";\nimport {\n checkEvent,\n eventRefs,\n type EventCatalog,\n type EventRef,\n} from \"./events/catalog\";\nimport { getActionAccess } from \"./access\";\nimport { pluginOwner } from \"./define-plugin\";\nimport { pickContextEnvelope } from \"./context\";\nimport { PLUGIN_DEPS, type DepsOf, type Ports } from \"./deps\";\nimport type { NamedService } from \"./rpc\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\nimport { defineServiceSocket, type RegisteredSocket } from \"./socket\";\nimport type {\n BrickSocketConfig,\n BrickSocketHandle,\n SocketPayloads,\n SocketSchemas,\n} from \"./socket-types\";\n\nconst defaultLogger: Logger = createLogger(DEFAULT_LOG_PREFIXES);\n\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nconst EMPTY_SERVICES = Object.freeze({});\nconst EMPTY_METADATA = Object.freeze({});\nconst EMPTY_DEPS = Object.freeze({});\nlet _ctxSeq = 0;\n\n// Symbol to tie context resolution to a specific service instance and invocation\nconst RESOLVED_SYMBOL = Symbol(\"resolved\");\n/** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */\nconst OWN_DEPS = Symbol(\"ownDeps\");\n\nexport class ServiceImpl<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> implements Service<TDb, TServiceContext> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n readonly actions = new Map<string, Action<any, any, any, any>>();\n readonly tools = new Map<string, Tool<any, any, any, any>>();\n readonly tables = new Map<string, any>();\n private readonly sockets = new Map<string, RegisteredSocket>();\n readonly resources = new Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >();\n readonly preparations = new Map<string, PreparationContribution>();\n /** Where each `kind:name` was defined, to reject duplicates from another file. */\n private readonly sites = new Map<string, string | undefined>();\n private database?: DatabaseHandle<TDb>;\n private _isBuilt = false;\n /** The declared events: `service.events.<name>`. */\n readonly events: Readonly<Record<string, EventRef>>;\n\n constructor(\n name: string,\n options: ServiceOptions<TServiceContext, TDb> = {},\n ) {\n this.name = name;\n this.options = options;\n this.events = eventRefs(name, options.events);\n for (const key of Object.keys(this.events)) this.claim(\"event\", key);\n if (options.database !== undefined && !isDatabaseHandle(options.database)) {\n throw new Error(\"Service database must be created with defineDatabase()\");\n }\n this.database = options.database;\n }\n\n use<A>(plugin: ServicePlugin<this, A>): A {\n return installPlugin(this, undefined, plugin) as A;\n }\n\n get db(): TDb | undefined {\n return this.getDb();\n }\n\n get isBuilt(): boolean {\n return this._isBuilt;\n }\n\n /**\n * Closes declarations after plugins have registered their actions and preparations.\n */\n build(): this {\n if (isInstallingPlugin(this))\n throw new Error(\"Cannot build a service during plugin setup\");\n if (this._isBuilt) return this;\n for (const action of this.actions.values()) {\n const info = (action as { resourceAction?: ResourceActionInfo })\n .resourceAction;\n const resource = info?.record && this.resources.get(info.resource);\n if (resource) checkRecordAccess(resource, info);\n }\n this._isBuilt = true;\n return this;\n }\n\n private claim(kind: string, name: string): void {\n claimName(\n this.sites,\n `${kind} \"${name}\" in service \"${this.name}\"`,\n `${kind}:${name}`,\n definitionSite(),\n );\n }\n\n contributePreparation(contribution: PreparationContribution): void {\n if (this._isBuilt)\n throw new Error(\"Preparations must be registered before service build\");\n if (this.preparations.has(contribution.name))\n throw new Error(`Duplicate preparation '${contribution.name}'`);\n this.preparations.set(contribution.name, contribution);\n getGlobalRegistry().touch();\n }\n\n listPreparations(): PreparationContribution[] {\n return [...this.preparations.values()];\n }\n prepareContributions(): void {\n for (const contribution of this.preparations.values())\n contribution.prepare();\n }\n\n registerTable(table: any): this {\n try {\n const tableName = getTableName(table);\n this.tables.set(tableName, table);\n } catch {\n const fallbackName =\n (table as any)._?.name ?? `table_${this.tables.size + 1}`;\n this.tables.set(fallbackName, table);\n }\n\n return this;\n }\n\n // The public signature preserves config literals; runtime registration stores\n // resources with different tables in the same map.\n resource = <\n TTable = any,\n const TOptions extends ResourceTypeOptions = ResourceTypeOptions,\n >(\n config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> &\n TOptions &\n Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>,\n ): Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n > => {\n if (this._isBuilt)\n throw new Error(\"Resources must be registered before service build\");\n this.claim(\"resource\", config.name);\n const resourceInstance = defineResource(this, config);\n this.resources.set(resourceInstance.name, resourceInstance);\n getGlobalRegistry().touch();\n return resourceInstance as Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n >;\n };\n\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined {\n return this.resources.get(name);\n }\n\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[] {\n return Array.from(this.resources.values());\n }\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n action(actionOrConfig: any): any {\n let actionInstance: Action<any, any, any, any>;\n const isActionFunction =\n typeof actionOrConfig === \"function\" && \"config\" in actionOrConfig;\n\n if (isActionFunction) {\n actionInstance = actionOrConfig;\n } else {\n actionInstance = defineAction(actionOrConfig);\n }\n\n if (\n isInstallingPlugin(this) &&\n this.actions.has(actionInstance.name) &&\n this.actions.get(actionInstance.name) !== actionInstance\n )\n throw new Error(`Duplicate plugin action: ${actionInstance.name}`);\n if (this.actions.get(actionInstance.name) !== actionInstance)\n this.claim(\"action\", actionInstance.name);\n if (isTool(actionInstance)) actionInstance.config.http = true;\n actionInstance.serviceName = this.name;\n (actionInstance as any).service = this;\n this.actions.set(actionInstance.name, actionInstance);\n getGlobalRegistry().touch();\n\n if (isActionFunction) {\n return this;\n }\n return actionInstance;\n }\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n tool(toolOrConfig: any): any {\n const existing = isTool(toolOrConfig);\n const tool = existing ? toolOrConfig : defineTool(toolOrConfig);\n this.claim(\"tool\", tool.name);\n tool.serviceName = this.name;\n (tool as any).service = this;\n this.tools.set(tool.name, tool);\n if (tool.config.http) this.action(tool);\n getGlobalRegistry().touch();\n return existing ? this : tool;\n }\n\n getTool(name: string): Tool<any, any, any, any> | undefined {\n return this.tools.get(name);\n }\n\n socket<const I extends SocketSchemas, const O extends SocketSchemas>(\n config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext>,\n ): BrickSocketHandle<SocketPayloads<O>> {\n if (this._isBuilt)\n throw new Error(\"Sockets must be declared before service build\");\n this.claim(\"socket\", config.name);\n const socket: RegisteredSocket = defineServiceSocket(\n this.name,\n config,\n async (request) => {\n const ctx = await resolveServiceContext(this, { request });\n // A socket a plugin declared runs with the plugin's deps.\n const deps = (socket as unknown as Record<symbol, unknown>)[\n PLUGIN_DEPS\n ];\n return deps ? { ...ctx, deps } : ctx;\n },\n );\n this.sockets.set(config.name, socket);\n getGlobalRegistry().touch();\n return socket.handle;\n }\n\n listSockets(): RegisteredSocket[] {\n return [...this.sockets.values()];\n }\n\n listTools(): Tool<any, any, any, any>[] {\n return Array.from(this.tools.values());\n }\n\n getAction(name: string): Action<any, any, any, any> | undefined {\n return this.actions.get(name);\n }\n\n listActions(): Action<any, any, any, any>[] {\n return Array.from(new Set(this.actions.values()));\n }\n\n getDb(): TDb | undefined {\n return this.database?.getDb();\n }\n\n /** The handle from `defineDatabase`, without connecting. */\n getDatabaseHandle(): DatabaseHandle<TDb> | undefined {\n return this.database;\n }\n\n /** What a write needs to record events. Set by `brick({ events })`. */\n recorder?: ServiceEvents;\n\n getOutbox(): OutboxTable | undefined {\n return Object.values(this.database?.tables ?? {}).find(isOutboxTable);\n }\n\n setRecorder(recorder: ServiceEvents | undefined): void {\n this.recorder = recorder;\n }\n\n /** Whether the service declares an event catalog. */\n get hasCatalog(): boolean {\n return this.options.events !== undefined;\n }\n\n /** @throws When the event is not in the catalog or its payload does not match. */\n checkEvent(name: string, payload: unknown): void {\n checkEvent(this, name, payload);\n }\n\n /** The values of this service's `deps`. Set by `brick({ deps })`. */\n deps?: Readonly<Record<string, unknown>>;\n\n setDeps(deps: Readonly<Record<string, unknown>>): void {\n this.deps = deps;\n }\n\n setDb(database: DatabaseHandle<TDb>): void {\n if (!isDatabaseHandle(database))\n throw new Error(\"Use defineDatabase() to set a service database\");\n this.database = database;\n getGlobalRegistry().touch();\n }\n\n /**\n * Resolves the complete service execution context once per incoming request.\n * Merges framework BaseContext with the service's custom context hook.\n * Always rebuilds context for this service to prevent caller context from overriding.\n */\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n ): Promise<BaseContext<TDb> & TServiceContext> {\n return resolveServiceContext(this, callCtx);\n }\n\n introspect(): ServiceSchema {\n const databaseConfig = this.database\n ? {\n name: this.database.name,\n engine: this.database.engine,\n tables: Object.keys(this.database.tables),\n ...pluginTables(this.database.tables),\n }\n : undefined;\n // The schema is data. A function among the options (context, an auth policy,\n // lifecycle hooks) cannot cross to the dev dashboard: structured clone\n // refuses the whole architecture. JSON keeps the data and drops the rest.\n const { database: _database, events: _events, ...config } = this.options;\n const options: ServiceSchema[\"options\"] = JSON.parse(\n JSON.stringify(config),\n );\n return {\n name: this.name,\n options,\n hasDatabase: Boolean(this.database),\n sockets: this.listSockets().map((socket) => socket.schema),\n databaseConfig,\n actions: this.listActions().map((act) => {\n const access = getActionAccess(act);\n return {\n name: act.name,\n serviceName: this.name,\n ...((act as { plugin?: string }).plugin\n ? { plugin: (act as { plugin?: string }).plugin }\n : {}),\n ...((act as { resource?: string }).resource\n ? { resource: (act as { resource?: string }).resource }\n : {}),\n description: act.config.description,\n inputSchema: act.config.input,\n outputSchema: act.config.output,\n hasAuthorize: access.hasAuthorize,\n hasScope: access.hasScope,\n accessPolicy: access.policy,\n errors: act.config.errors,\n emits: act.config.emits,\n tags: act.config.tags,\n };\n }),\n tools: this.listTools().map((tool) => ({ name: tool.name })),\n ...(this.hasCatalog || Object.keys(this.events).length\n ? {\n events: Object.values(this.events).map((ref) => ({\n name: ref.name,\n schema: JSON.parse(JSON.stringify(ref.schema)),\n ...(ref.plugin ? { plugin: ref.plugin } : {}),\n })),\n }\n : {}),\n resources: this.listResources().map((res) => ({\n name: res.name,\n })),\n };\n }\n}\n\n/** `plugins`: which plugin owns each table it contributed, by table key. */\nfunction pluginTables(tables: Record<string, unknown>) {\n const owners = Object.entries(tables).flatMap(([key, table]) => {\n const plugin = pluginOwner(table);\n return plugin ? [[key, plugin] as const] : [];\n });\n return owners.length ? { plugins: Object.fromEntries(owners) } : {};\n}\n\nasync function resolveServiceContext<\n TDb,\n TServiceContext extends Record<string, any>,\n>(\n service: ServiceImpl<TDb, TServiceContext>,\n callCtx?: Partial<BaseContext<TDb>> & { user?: unknown },\n): Promise<BaseContext<TDb> & TServiceContext> {\n // Only a context this service resolved itself is accepted as it is.\n if ((callCtx as any)?.[RESOLVED_SYMBOL] === service) {\n // A plugin action's copy carries the plugin's deps; this service's own actions get their own back.\n const own = (callCtx as any)[OWN_DEPS];\n return (\n (callCtx as { deps?: unknown }).deps === own\n ? callCtx\n : { ...callCtx, deps: own }\n ) as BaseContext<TDb> & TServiceContext;\n }\n const seq = ++_ctxSeq;\n const req = callCtx?.request ?? DEFAULT_REQUEST;\n // Always use this service's own database, never the caller's\n const db = service.getDb() as TDb;\n const logger = callCtx?.logger ?? defaultLogger;\n const traceId = callCtx?.traceId ?? `tr_${seq.toString(36)}`;\n const requestId = callCtx?.requestId ?? `req_${seq.toString(36)}`;\n const services = callCtx?.services ?? EMPTY_SERVICES;\n const metadata = callCtx?.metadata ?? EMPTY_METADATA;\n // The app's deps for this service; a direct call with no app (a unit test) may pass its own,\n // but never those of a context another service (or a plugin) resolved.\n const deps =\n service.deps ??\n ((callCtx as any)?.[RESOLVED_SYMBOL]\n ? undefined\n : (callCtx as { deps?: unknown } | undefined)?.deps) ??\n EMPTY_DEPS;\n\n const fullBaseCtx: BaseContext<TDb> = {\n request: req,\n db,\n logger,\n traceId,\n requestId,\n services,\n metadata,\n // Only the envelope fields a caller may set, never the framework's own.\n ...pickContextEnvelope(callCtx),\n };\n\n const resolvedExtra = service.options.context\n ? await service.options.context(fullBaseCtx)\n : {};\n const finalCtx: any = {\n ...fullBaseCtx,\n ...resolvedExtra,\n deps,\n [RESOLVED_SYMBOL]: service,\n [OWN_DEPS]: deps,\n };\n return finalCtx;\n}\n\n/**\n * Declare a service: a named group of actions, tools, and resources with its own\n * database and request context. It is registered globally, so `brick()`, the\n * OpenAPI generator, and `useService` find it by name.\n *\n * Add actions with `service.action(...)`, tools with `service.tool(...)`,\n * resources with `service.resource(...)`, and plugins with `service.use(...)`.\n *\n * @param name - Unique name. It is the service's segment of every action route\n * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it\n * again from the same file (a dev reload) replaces it; from another file throws.\n * @param options - `database` (a handle from `defineDatabase`), `deps` (typed\n * slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),\n * `context` (adds fields such as the signed-in user to every action's `ctx`),\n * `events` (the event catalog: a payload schema per event name, recorded as\n * `<service>.<name>` and offered as `service.events.<name>`), and `auth`,\n * `rateLimit`, `cache`, `resilience`, `telemetry`, and `lifecycle`.\n * @returns The service.\n * @example\n * import { defineDatabase, defineService, t } from \"@brickkit/core\";\n *\n * const database = defineDatabase({ tables: { pages } });\n *\n * export const pagesService = defineService(\"pages\", {\n * database,\n * // Added to `ctx` in every action of this service.\n * context: async ({ request }) => ({ user: await readUser(request) }),\n * });\n *\n * pagesService.action({\n * name: \"list\",\n * input: t.Object({ limit: t.Optional(t.Number()) }),\n * output: t.Array(t.Object({ id: t.String(), title: t.String() })),\n * execute: ({ input, ctx }) =>\n * ctx.db.select().from(pages).limit(input.limit ?? 20),\n * });\n */\nexport function defineService<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n const TEvents extends EventCatalog = {},\n const TName extends string = string,\n TPorts extends Ports = {},\n>(\n name: TName,\n options?: ServiceOptions<TServiceContext, TDb> & {\n events?: TEvents;\n deps?: TPorts;\n },\n): Service<\n TDb,\n {} extends TPorts\n ? TServiceContext\n : TServiceContext & { deps: DepsOf<TPorts> },\n TEvents\n> &\n NamedService<TName> {\n const service = new ServiceImpl<TDb, TServiceContext>(name, options);\n getGlobalRegistry().register(service as any);\n return service as any;\n}\n","import { compareSocketSeq } from \"./socket-schema\";\nimport type { SocketBroker, SocketBrokerMessage } from \"./socket-types\";\n\n// From the global, as @types/bun doesn't export RedisClient from \"bun\" for the .d.ts build.\ntype RedisClient = InstanceType<typeof Bun.RedisClient>;\n\nexport interface RedisBrokerOptions {\n /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */\n url?: string;\n /** Emits held while Redis is unreachable; older ones are dropped. Default 1000. */\n queue?: number;\n}\n\n/** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */\nexport function reconnectDelay(failures: number): number {\n const ceiling = Math.min(30_000, 500 * 2 ** failures);\n return ceiling / 2 + Math.random() * (ceiling / 2);\n}\n\n/** One Redis connection that reconnects by itself and reports each fresh connection. */\nexport function connection(\n url: string | undefined,\n connected: (redis: RedisClient) => void,\n) {\n let redis: RedisClient | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let failures = 0;\n const waiters: (() => void)[] = [];\n const lost = (client: RedisClient) => {\n if (redis !== client) return;\n redis = undefined;\n if (closed || timer) return;\n timer = setTimeout(() => {\n timer = undefined;\n start();\n }, reconnectDelay(failures++));\n };\n const start = () => {\n if (closed || redis || timer) return;\n // Bun's own reconnect keeps no subscriptions we can see; a fresh client resubscribes explicitly.\n const client = new Bun.RedisClient(url, {\n autoReconnect: false,\n enableOfflineQueue: false,\n });\n redis = client;\n client.onclose = () => lost(client);\n client.connect().then(\n () => {\n if (redis !== client) return;\n failures = 0;\n connected(client);\n for (const wake of waiters.splice(0)) wake();\n },\n () => lost(client),\n );\n };\n return {\n /** The connected client, starting a connection when there is none. */\n get(): RedisClient | undefined {\n start();\n return redis?.connected ? redis : undefined;\n },\n /** Resolves after the next connection is made and announced, or after `ms`. */\n opened(ms: number): Promise<void> {\n if (redis?.connected) return Promise.resolve();\n start();\n return new Promise((resolve) => {\n waiters.push(resolve);\n setTimeout(resolve, ms);\n });\n },\n close() {\n closed = true;\n clearTimeout(timer);\n for (const wake of waiters.splice(0)) wake();\n const client = redis;\n redis = undefined;\n client?.close();\n },\n };\n}\n\n/**\n * Fans socket emits and kicks out across processes through Redis pub/sub, one\n * channel per room topic. An emit is a PUBLISH only: every process, the emitting\n * one included, delivers it once to its own connections. Uses Bun's built-in\n * Redis client and two connections, one to publish and one to subscribe.\n */\nexport function redisBroker(options: RedisBrokerOptions = {}): SocketBroker {\n const limit = options.queue ?? 1000;\n if (!Number.isInteger(limit) || limit < 0)\n throw new Error(\"redisBroker queue must be a nonnegative integer\");\n const channel = (topic: string) => `brick:socket:${topic}`;\n const listeners = new Map<\n string,\n Set<(message: SocketBrokerMessage) => void>\n >();\n const pending = new Map<string, Promise<unknown>>();\n const stream = (topic: string) => `brick:socket:stream:${topic}`;\n const queue: ((redis: RedisClient) => void)[] = [];\n const send = (work: (redis: RedisClient) => void) => {\n const redis = publisher.get();\n if (redis) return work(redis);\n queue.push(work);\n if (queue.length > limit) queue.shift();\n };\n const receive = (payload: string, name: string) => {\n let message: SocketBrokerMessage;\n try {\n message = JSON.parse(payload);\n } catch {\n return;\n }\n for (const deliver of listeners.get(name) ?? []) deliver(message);\n };\n const subscribe = (redis: RedisClient, name: string) => {\n const done = redis.subscribe(name, receive).catch(() => {});\n pending.set(name, done);\n void done.then(() => {\n if (pending.get(name) === done) pending.delete(name);\n });\n };\n const publisher = connection(options.url, (redis) => {\n for (const work of queue.splice(0)) work(redis);\n });\n const subscriber = connection(options.url, (redis) => {\n for (const name of listeners.keys()) subscribe(redis, name);\n });\n return {\n publish(message, replay) {\n const name = channel(message.topic);\n if (message.type !== \"emit\" || !replay)\n return send(\n (redis) =>\n void redis.publish(name, JSON.stringify(message)).catch(() => {}),\n );\n const key = stream(message.topic);\n send((redis) => {\n // Replies come back in order, so each PUBLISH follows its XADD in emit order.\n void redis\n .send(\"XADD\", [\n key,\n \"MAXLEN\",\n \"~\",\n String(replay.keep),\n \"*\",\n \"m\",\n message.frame,\n ])\n .then((seq: string) => {\n void redis\n .send(\"PEXPIRE\", [key, String(replay.maxAgeMs)])\n .catch(() => {});\n return redis.publish(name, JSON.stringify({ ...message, seq }));\n })\n .catch(() => {});\n });\n },\n async head() {\n try {\n await publisher.opened(1000);\n const [seconds, micros] = (await publisher.get()!.send(\"TIME\", [])) as [\n string,\n string,\n ];\n return `${Number(seconds) * 1000 + Math.floor(Number(micros) / 1000) - 1}-0`;\n } catch {\n return `${Date.now() - 1}-0`;\n }\n },\n async history(topic, since, replay) {\n let raw: [string, string[]][];\n try {\n await publisher.opened(1000);\n raw = await publisher.get()!.send(\"XRANGE\", [stream(topic), \"-\", \"+\"]);\n } catch {\n return undefined;\n }\n const ms = (seq: string) => Number(seq.split(\"-\")[0]);\n const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);\n // Nothing kept at or before `since`: entries after it may have been trimmed or expired.\n if (\n after.length === raw.length &&\n (raw.length >= replay.keep ||\n (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)\n )\n return undefined;\n return after.map(([seq, fields]) => ({\n type: \"emit\" as const,\n topic,\n frame: fields[fields.indexOf(\"m\") + 1]!,\n seq,\n }));\n },\n subscribe(topic, deliver) {\n const name = channel(topic);\n let local = listeners.get(name);\n if (!local) {\n local = new Set();\n listeners.set(name, local);\n const redis = subscriber.get();\n if (redis) subscribe(redis, name);\n }\n local.add(deliver);\n return () => {\n local.delete(deliver);\n if (local.size || listeners.get(name) !== local) return;\n listeners.delete(name);\n pending.delete(name);\n void subscriber\n .get()\n ?.unsubscribe(name)\n .catch(() => {});\n };\n },\n async ready(topic) {\n const name = channel(topic);\n // Wait briefly for Redis, so a join is acknowledged once its emits can arrive.\n if (!pending.has(name)) await subscriber.opened(1000);\n await pending.get(name);\n },\n close() {\n publisher.close();\n subscriber.close();\n },\n };\n}\n","import type { Action, ActionContext, ProxyOptions, Service } from \"./types\";\nimport type {\n BrickClientAction,\n BrickClientSocket,\n BrickServices,\n InferActionInput,\n InferActionOutput,\n} from \"./client\";\nimport { getGlobalRegistry } from \"./registry\";\nimport { getPluginActionRoute } from \"./plugin\";\nimport { pickContextEnvelope } from \"./context\";\nimport { withCallSpan } from \"./telemetry\";\n\n/** An in-process caller for one action: its input, then an optional call context. */\nexport type ServiceActionCaller<A> =\n undefined extends InferActionInput<A>\n ? (\n input?: InferActionInput<A>,\n ctx?: Partial<ActionContext>,\n ) => Promise<InferActionOutput<A>>\n : (\n input: InferActionInput<A>,\n ctx?: Partial<ActionContext>,\n ) => Promise<InferActionOutput<A>>;\n\n/**\n * What `useService` returns: the service's actions as methods, with each\n * resource's actions under the resource's name. Sockets are left out.\n */\nexport type ServiceClient<T> = {\n [\n K in keyof T as T[K] extends BrickClientSocket<any, any> ? never : K\n ]: T[K] extends\n | BrickClientAction<any, any, any>\n | Action<any, any, any, any>\n | ((...args: any[]) => any)\n ? ServiceActionCaller<T[K]>\n : ServiceClient<T[K]>;\n};\n\ndeclare const serviceNameType: unique symbol;\n\n/** Type only: the literal name of a service, which `useService` finds its contract by. */\nexport interface NamedService<N extends string> {\n readonly [serviceNameType]?: N;\n}\n\n/** What `useService` returns while the contract does not describe the service yet. */\nexport type UntypedServiceClient = { [name: string]: any };\n\n/**\n * Call another service's actions in-process, typed from that service. Each\n * action is a method, and each resource's actions sit under the resource's\n * name: `billing.charge(input)`, `billing.invoice.list()`.\n *\n * The types come from the app's generated contract (`_brick/contract.ts`, which\n * `brick dev` and `brick gen client` keep current), so renaming an action or\n * changing its input is a compile error at every caller. Until the contract\n * describes the service, the client is untyped.\n *\n * A call runs through the target's own validation and authorization, with the\n * target's database, context and deps (never the caller's), and shows as an\n * `rpc` span in the trace.\n *\n * @param service - The service to call, as `defineService` returned it.\n * @param options - `from` (the calling service's name, which becomes `ctx.caller`\n * in the target and cannot be spoofed) and `context` (defaults for every call).\n * Each call also takes an optional call context after its input.\n * @returns The client.\n * @throws On a call, when the service is not registered or has no such action.\n * @example\n * import { useService } from \"@brickkit/core\";\n * import { billingService } from \"../billing/billing.service\";\n *\n * const billing = useService(billingService, { from: \"orders\" });\n * await billing.charge({ orderId, amountCents });\n * await billing.invoice.list({ limit: 10 });\n */\nexport function useService<const N extends string = string>(\n service: { readonly name: string } & NamedService<N>,\n options: ProxyOptions = {},\n): N extends keyof BrickServices\n ? ServiceClient<BrickServices[N]>\n : UntypedServiceClient {\n return serviceRef(service.name, options, []);\n}\n\nfunction serviceRef(\n serviceName: string,\n options: ProxyOptions,\n path: readonly string[],\n): any {\n return new Proxy(function () {}, {\n get(_, key) {\n // Only string keys name actions; `then` stays unset so the client is not a promise.\n if (typeof key !== \"string\" || key === \"then\") return undefined;\n return serviceRef(serviceName, options, [...path, key]);\n },\n apply(_, __, [payload, callCtx]) {\n const name = path.join(\".\");\n const clientPath = [serviceName, ...path].join(\".\");\n return callAction(\n serviceName,\n name,\n (service) =>\n service.getAction(name) ??\n // Plugin actions (CRUD) are found by the path the typed client uses.\n service\n .listActions()\n .find(\n (action) =>\n (getPluginActionRoute(action) || undefined)?.clientPath?.join(\n \".\",\n ) === clientPath,\n ),\n payload,\n callCtx,\n options,\n );\n },\n });\n}\n\nasync function callAction(\n serviceName: string,\n actionName: string,\n find: (service: Service<any, any>) => Action<any, any, any, any> | undefined,\n payload: unknown,\n callCtx: Partial<ActionContext> | undefined,\n options: ProxyOptions,\n) {\n const service = getGlobalRegistry().get(serviceName);\n if (!service) {\n throw new Error(\n `[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`,\n );\n }\n const action = find(service);\n if (!action) {\n throw new Error(\n `[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`,\n );\n }\n const envelopeCtx = createRpcEnvelope(options.from, options.context, callCtx);\n return withCallSpan(\n `rpc ${serviceName}.${actionName}`,\n { \"brick.service\": serviceName, \"brick.action\": actionName },\n () => action.execute({ input: payload, ctx: envelopeCtx }),\n );\n}\n\n/** Build the trusted envelope for a proxy call.\n *\n * When `from` is provided, it identifies the service that created the proxy\n * and always sets `caller` — any `caller` supplied via `options.context` or\n * the per-call context is ignored so it cannot be spoofed. When `from` is\n * omitted, an explicitly supplied `caller` still passes through for backward\n * compatibility; otherwise `caller` stays unset (never the target service).\n */\nexport function createRpcEnvelope(\n from: string | undefined,\n defaultContext?: Partial<ActionContext>,\n callContext?: Partial<ActionContext>,\n): Partial<ActionContext> {\n const envelope = {\n ...pickContextEnvelope(defaultContext),\n ...pickContextEnvelope(callContext),\n } as Partial<ActionContext> & { caller?: string };\n // `caller` identifies the service that created this proxy, never the target.\n // A configured `from` wins over any supplied value; without `from` we keep\n // an explicitly supplied caller (legacy) and otherwise leave it unset.\n if (from !== undefined) {\n envelope.caller = from;\n }\n return envelope;\n}\n","import { isEventRef, type EventRef } from \"./catalog\";\nimport { buildErrorHelpers } from \"../action\";\nimport type { ActionErrorDefinition, ErrorBuilder } from \"../types\";\nimport type {\n EventDelivery,\n EventListener,\n EventWorkflow,\n ListenerFailure,\n RetryDecision,\n} from \"./types\";\n\ntype EventOn = EventRef<any> | readonly EventRef<any>[];\ntype PayloadOf<O> =\n O extends EventRef<infer P>\n ? P\n : O extends readonly EventRef<infer P>[]\n ? P\n : never;\n\ntype ListenerConfig<\n TPayload,\n TOn = string | readonly string[],\n TErrors extends Record<string, ActionErrorDefinition> = {},\n> = {\n name: string;\n on: TOn;\n maxAttempts?: number;\n /** Errors `run` may raise with `error.CODE()`. Spread `defineError(...)` results or `errorsOf(action)` here. */\n errors?: TErrors;\n /** Decides what a failure does next. Without it every failure retries until `maxAttempts`. */\n retry?: (error: ListenerFailure<TErrors>) => RetryDecision;\n} & (\n | {\n run: (\n delivery: EventDelivery<TPayload>,\n helpers: { error: ErrorBuilder<TErrors> },\n ) => void | Promise<void>;\n workflow?: never;\n }\n | { workflow: EventWorkflow<TPayload>; run?: never }\n);\n\n/**\n * Define a listener: code that runs for each event it listens for, after the write\n * that caused the event has been committed. Pass it to `brick({ events: {\n * listeners } })`.\n *\n * It either runs a handler (`run`) in the process that delivers events, or starts\n * a durable workflow (`workflow`) on the app's `events.world`. Delivery is at\n * least once. A handler that throws is retried later with a growing delay, then\n * parked as dead, so it can run again for the same event: use\n * `delivery.deliveryId` to make its work idempotent. A workflow needs no such\n * care: a delivery starts one run however often it is tried, and the workflow\n * retries its own steps.\n *\n * A listener can declare `errors`, as an action does, and raise them in `run` with\n * `error.CODE()`. `retry(error)` then picks `\"retry\"` or `\"dead\"` from the typed\n * `error.code`; anything not declared arrives as `{ code: \"UNKNOWN\", cause }`.\n *\n * @param config - `name` (unique; it is part of each delivery's id), `on` (a\n * declared event such as `orders.events.shipped`, which types the payload, or an\n * event name; or a list of either; a trailing `*` matches a prefix, as in\n * `user.*`), `run` or `workflow`, and optionally `maxAttempts`.\n * @returns The listener.\n * @throws When the name is empty or contains `:`, `on` is empty, or the listener\n * has both or neither of `run` and `workflow`.\n * @example\n * import { brick, defineListener } from \"@brickkit/core\";\n *\n * const welcome = defineListener({\n * name: \"welcome-email\",\n * on: \"user.create\",\n * run: async ({ payload, deliveryId }) => {\n * await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });\n * },\n * });\n *\n * export default brick({ services, events: { listeners: [welcome] } });\n * @example\n * // src/workflows/onboard.ts\n * export async function onboard(event: WorkflowEvent<CrudEventPayload>) {\n * \"use workflow\";\n * await sendWelcome(event.payload.row.email);\n * }\n *\n * defineListener({ name: \"onboard\", on: \"user.create\", workflow: onboard });\n * @example\n * // payload is { id: string; trackingId: string }, from the orders catalog.\n * defineListener({\n * name: \"notify-shipped\",\n * on: orders.events.shipped,\n * run: ({ payload }) => notify(payload.id, payload.trackingId),\n * });\n */\nexport function defineListener<\n const TOn extends EventOn,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<PayloadOf<TOn>, TOn, TErrors>,\n): EventListener<PayloadOf<TOn>>;\nexport function defineListener<\n TPayload = any,\n const TErrors extends Record<string, ActionErrorDefinition> = {},\n>(\n config: ListenerConfig<\n TPayload,\n string | EventRef<any> | readonly (string | EventRef<any>)[],\n TErrors\n >,\n): EventListener<TPayload>;\nexport function defineListener(\n config: ListenerConfig<any, unknown, any>,\n): EventListener {\n if (typeof config.name !== \"string\" || !config.name)\n throw new Error(\"An event listener needs a name\");\n if (config.name.includes(\":\"))\n throw new Error(\n `Event listener name '${config.name}' must not contain ':'`,\n );\n const on = (Array.isArray(config.on) ? config.on : [config.on]).map(\n (item: unknown) => (isEventRef(item) ? item.name : item),\n ) as string[];\n if (\n !on.length ||\n on.some((pattern) => !pattern || typeof pattern !== \"string\")\n )\n throw new Error(`Event listener '${config.name}' listens for nothing`);\n if (\n config.maxAttempts !== undefined &&\n (!Number.isInteger(config.maxAttempts) || config.maxAttempts < 1)\n )\n throw new Error(\n `Event listener '${config.name}': maxAttempts must be a positive integer`,\n );\n const { name, run, workflow } = config as {\n name: string;\n run?: unknown;\n workflow?: unknown;\n };\n if (run !== undefined && workflow !== undefined)\n throw new Error(\n `Event listener '${name}' has both run and workflow; give it one`,\n );\n if (run === undefined && workflow === undefined)\n throw new Error(\n `Event listener '${name}' needs a run handler or a workflow`,\n );\n if (run !== undefined && typeof run !== \"function\")\n throw new Error(`Event listener '${name}': run must be a function`);\n if (workflow !== undefined && typeof workflow !== \"function\")\n throw new Error(\n `Event listener '${name}': workflow must be a function marked \"use workflow\"`,\n );\n const helpers = buildErrorHelpers(config.errors);\n return Object.freeze({\n name: config.name,\n on: Object.freeze(on),\n ...(config.run !== undefined\n ? {\n run: ((delivery: EventDelivery) =>\n config.run!(delivery, { error: helpers })) as EventListener[\"run\"],\n }\n : {}),\n ...(config.errors ? { errors: config.errors } : {}),\n ...(config.retry ? { retry: config.retry } : {}),\n ...(config.workflow !== undefined ? { workflow: config.workflow } : {}),\n ...(config.maxAttempts !== undefined\n ? { maxAttempts: config.maxAttempts }\n : {}),\n });\n}\n","import { checkEvent, type EventRef } from \"./catalog\";\nimport { recorders } from \"./hub\";\n\n/**\n * Record an event of your own from an action, a tool or a hook. Listeners get it\n * as they get a generated CRUD event, with the payload you give.\n *\n * By default the event is committed in a transaction of its own. Pass the `tx`\n * of a transaction you have open to commit it with your writes instead: then it\n * is delivered at the dispatcher's next poll, because Brick does not see your\n * commit. Nothing is recorded when no listener wants the event.\n *\n * @param ctx - The action context: its `db` finds the service's outbox, and its\n * `traceId` follows the event to its listeners.\n * @param event - A declared event, such as `orders.events.shipped`, whose payload\n * is typed and checked against its schema; or an event name such as\n * `orders.refunded`. A service with an event catalog only records names from it\n * (and the CRUD events of its resources).\n * @param payload - JSON data for the listeners.\n * @param options - `tx`: an open transaction on the service's database. `source`:\n * what emitted it, shown to listeners.\n * @throws When the context's database has no outbox table, or the app has no\n * `events`; when the event is not in the service's catalog, or its payload does\n * not match the declared schema.\n * @example\n * refund: service.action({\n * name: \"refund\",\n * execute: async ({ ctx, input }) => {\n * await ctx.db.update(orders).set({ status: \"refunded\" }).where(eq(orders.id, input.id));\n * await emitEvent(ctx, orders.events.refunded, { id: input.id });\n * },\n * });\n */\nexport async function emitEvent<TPayload>(\n ctx: { db?: unknown; traceId?: string },\n event: EventRef<TPayload>,\n payload: NoInfer<TPayload>,\n options?: { tx?: unknown; source?: string },\n): Promise<void>;\nexport async function emitEvent(\n ctx: { db?: unknown; traceId?: string },\n name: string,\n payload: unknown,\n options?: { tx?: unknown; source?: string },\n): Promise<void>;\nexport async function emitEvent(\n ctx: { db?: unknown; traceId?: string },\n event: string | EventRef,\n payload: unknown,\n options: { tx?: unknown; source?: string } = {},\n): Promise<void> {\n const name = typeof event === \"string\" ? event : event.name;\n if (typeof event !== \"string\")\n checkEvent(\n {\n name: event.service,\n events: { [name.slice(event.service.length + 1)]: event },\n hasCatalog: true,\n listResources: () => [],\n },\n name,\n payload,\n );\n const events =\n ctx.db && typeof ctx.db === \"object\" ? recorders.get(ctx.db) : undefined;\n if (!events)\n throw new Error(\n `Cannot emit '${name}': ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database, not a transaction)`,\n );\n const context = { traceId: ctx.traceId, source: options.source };\n if (options.tx !== undefined)\n return events.record(options.tx, context, name, payload);\n await events.transaction(ctx.db, context, async (_tx, record) => {\n await record(name, payload);\n });\n}\n","import type { ActionContext, Service, Tool, ToolAnnotations } from \"./types\";\n\nexport interface McpToolDefinition {\n name: string;\n title?: string;\n description: string;\n inputSchema: unknown;\n annotations: ToolAnnotations;\n}\n\nexport interface McpRegistryOptions {\n services?: readonly Pick<Service<any, any>, \"listTools\">[];\n tools?: readonly Tool<any, any, any, any>[];\n}\n\nexport interface McpRegistry {\n listTools(): McpToolDefinition[];\n callTool(\n name: string,\n args?: Record<string, unknown>,\n ctx?: Partial<ActionContext>,\n ): Promise<unknown>;\n}\n\nexport class UnknownToolError extends Error {\n constructor(name: string) {\n super(`unknown tool: ${name}`);\n this.name = \"UnknownToolError\";\n }\n}\n\n/** Collect only explicitly defined tools, without exposing ordinary actions. */\nexport function createMcpRegistry(options: McpRegistryOptions): McpRegistry {\n function toolsByName() {\n const tools = new Map<string, Tool<any, any, any, any>>();\n for (const tool of [\n ...(options.tools ?? []),\n ...(options.services ?? []).flatMap((service) => service.listTools()),\n ]) {\n const existing = tools.get(tool.name);\n if (existing && existing !== tool)\n throw new Error(`Duplicate MCP tool: ${tool.name}`);\n tools.set(tool.name, tool);\n }\n return tools;\n }\n toolsByName();\n return {\n listTools: () =>\n Array.from(toolsByName().values(), (tool) => ({\n name: tool.name,\n ...((tool.config.title ?? tool.config.annotations?.title)\n ? { title: tool.config.title ?? tool.config.annotations?.title }\n : {}),\n description: tool.config.description ?? \"\",\n inputSchema: tool.config.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n annotations: tool.config.annotations ?? {},\n })),\n async callTool(name, args = {}, ctx) {\n const tool = toolsByName().get(name);\n if (!tool) throw new UnknownToolError(name);\n return tool({ input: args, ctx });\n },\n };\n}\n\nexport interface McpHandlerOptions {\n registry: McpRegistry;\n serverInfo: { name: string; version: string; title?: string };\n /** Versions supported by this transport, newest first. */\n protocolVersions?: readonly string[];\n}\n\nfunction result(id: unknown, value: unknown) {\n return Response.json({ jsonrpc: \"2.0\", id, result: value });\n}\nfunction rpcError(id: unknown, code: number, message: string) {\n return Response.json({ jsonrpc: \"2.0\", id, error: { code, message } });\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */\nexport function createMcpHandler(options: McpHandlerOptions) {\n const versions = options.protocolVersions ?? [\"2025-06-18\"];\n if (!versions.length)\n throw new Error(\"At least one MCP protocol version is required\");\n return async (\n request: Request,\n ctx?: Partial<ActionContext>,\n ): Promise<Response> => {\n if (request.method !== \"POST\")\n return new Response(null, { status: 405, headers: { Allow: \"POST\" } });\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return rpcError(null, -32700, \"parse error\");\n }\n if (\n !isRecord(body) ||\n body.jsonrpc !== \"2.0\" ||\n typeof body.method !== \"string\" ||\n (body.id !== undefined &&\n body.id !== null &&\n typeof body.id !== \"string\" &&\n typeof body.id !== \"number\") ||\n (body.params !== undefined && !isRecord(body.params))\n ) {\n return rpcError(null, -32600, \"invalid request\");\n }\n if (body.id === undefined) return new Response(null, { status: 202 });\n const { id, method } = body;\n const params = body.params as Record<string, unknown> | undefined;\n switch (method) {\n case \"initialize\": {\n const requested = params?.protocolVersion;\n return result(id, {\n capabilities: { tools: {} },\n protocolVersion:\n typeof requested === \"string\" && versions.includes(requested)\n ? requested\n : versions[0],\n serverInfo: options.serverInfo,\n });\n }\n case \"ping\":\n return result(id, {});\n case \"tools/list\":\n try {\n return result(id, { tools: options.registry.listTools() });\n } catch {\n return rpcError(id, -32603, \"internal error\");\n }\n case \"tools/call\": {\n if (\n typeof params?.name !== \"string\" ||\n (params.arguments !== undefined && !isRecord(params.arguments))\n ) {\n return rpcError(id, -32602, \"invalid tool parameters\");\n }\n try {\n const value = await options.registry.callTool(\n params.name,\n params.arguments as Record<string, unknown> | undefined,\n { ...ctx, request },\n );\n return result(id, {\n content: [\n {\n type: \"text\",\n text:\n typeof value === \"string\"\n ? value\n : (JSON.stringify(value, null, 2) ?? \"null\"),\n },\n ],\n });\n } catch (error) {\n if (error instanceof UnknownToolError)\n return rpcError(id, -32602, error.message);\n return result(id, {\n content: [\n {\n type: \"text\",\n text: error instanceof Error ? error.message : String(error),\n },\n ],\n isError: true,\n });\n }\n }\n default:\n return rpcError(id, -32601, `method not found: ${method}`);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAgB,UACd,QACA,SACA,UACQ;CACR,IAAI,OAAO,OAAO,QAAQ,OAAO,EAAE;CACn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