@brickkit/core 0.7.3 → 0.8.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/README.md +34 -80
- package/dist/chunks/client.d.ts +120 -2
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js +264 -0
- package/dist/chunks/client.js.map +1 -0
- package/dist/client.js +1 -206
- package/dist/index.d.ts +902 -2
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3283 -4
- package/dist/index.js.map +1 -1
- package/dist/tanstack-query.d.ts +1 -1
- package/dist/tanstack-query.d.ts.map +1 -1
- package/dist/tanstack-query.js +1 -1
- package/dist/tanstack-query.js.map +1 -1
- package/package.json +10 -9
- package/dist/chunks/effect.d.ts +0 -583
- package/dist/chunks/effect.d.ts.map +0 -1
- package/dist/chunks/effect.js +0 -2965
- package/dist/chunks/effect.js.map +0 -1
- package/dist/chunks/types.js +0 -46
- package/dist/chunks/types.js.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/effect.d.ts +0 -3
- package/dist/effect.js +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/compiler/emit.ts"],"sourcesContent":["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\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"],"mappings":";;;;;AAGA,SAAgB,mBAAmB,OAAwB;CACzD,MAAM,OAAO,KAAK,UAAU,MAAM,MAAM;CACxC,MAAM,SAAS,MAAM,QACjB,+CACA;CACJ,MAAM,QAAkB,CAAC,YAAY;CACrC,IAAI,MAAM,OAAO;EACf,MAAM,KAAK,2BAA2B;EACtC,IAAI,MAAM,UAAU,QAAQ;GAC1B,MAAM,KAAK,gBAAgB,8BAA8B;GACzD,KAAK,MAAM,CAAC,OAAO,aAAa,MAAM,UAAU,QAAQ,GAAG;IACzD,MAAM,MAAM,KAAK,UAAU,SAAS,GAAG;IACvC,MAAM,KAAK,UAAU,MAAM,WAAW,IAAI,GAAG;IAC7C,IAAI,SAAS,SAAS,UACpB,MAAM,KACJ,QAAQ,MAAM,2BAA2B,MAAM,aAAa,MAAM,wBAAwB,MAAM,kBAAkB,IAAI,OAAO,MAAM,IACrI;SAEA,MAAM,KACJ,QAAQ,MAAM,kBAAkB,MAAM,yBAAyB,IAAI,sBAAsB,MAAM,mBAAmB,MAAM,yBAAyB,IAAI,WACvJ;GACJ;GACA,MAAM,KAAK,GAAG;EAChB;EACA,MAAM,KACJ,sBAAsB,MAAM,gBAAgB,KAAK,WAAY,WAAW,UAAU,iBAAiB,MAAO,CAAC,CAAC,KAAK,IAAI,EAAE,GACzH;EACA,IAAK,MAAM,aAA+C,SAAS,UACjE,MAAM,KAAK,eAAe;CAC9B;CACA,MAAM,cAAc,MAAM,WAAW,MAAM;CAC3C,MAAM,UAAU,MAAM,UAClB,gFACA;CACJ,MAAM,aAAa,MAAM,QACrB,qBAAqB,KAAK,mCAAmC,KAAK,eAClE;CACJ,MAAM,gBAAgB,MAAM,YACxB,8DAA8D,KAAK,gBACnE;CACJ,MAAM,SAAS,MAAM,SACjB,mCAAmC,KAAK,gBACxC;CACJ,MAAM,UAAU,cACZ,uEAAuE,OAAO,oBAC9E;;IAEF,MAAM,SAAS,kCAAkC,KAAK,gBAAgB,GAAG;;;EAG3E,OAAO;;CAEP,OAAO;;;SAGA,cAAc,WAAW,GAAG,yBAAyB,OAAO;;;;;EAKnE,MAAM,KAAK,IAAI,EAAE;;;;EAIjB,QAAQ;EACR,WAAW;EACX,cAAc;EACd,QAAQ;;;;AAIV"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["defaultLogger","DEFAULT_REQUEST","RESOLVED_SYMBOL","EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty","EMPTY_SERVICES","DEFAULT_REQUEST","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/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/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\";\n\nexport interface ArchitectureApplication {\n services: readonly Service[];\n routes: readonly RouteIR[];\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 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 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 { toErrorResponse } from \"./error-response\";\nimport { createLogger } from \"./logger\";\nimport { ActionExecutionError, ValidationError } from \"./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 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 };\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 { 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\";\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\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 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 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 (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 const definition = Object.freeze({\n services: Object.freeze([...services]),\n prefix,\n routes: Object.freeze(mountedRoutes),\n telemetry,\n documentation: normalizeDocumentation(options.documentation),\n dashboard,\n });\n Object.defineProperty(brickApp, \"definition\", { value: definition });\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 { getActionAccess } from \"./access\";\nimport { pickContextEnvelope } from \"./context\";\nimport { createLogger, DEFAULT_LOG_PREFIXES } from \"./logger\";\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 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 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 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 const { database: _database, ...options } = this.options;\n return {\n name: this.name,\n options,\n hasDatabase: Boolean(this.database),\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> & TServiceContext>,\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 { 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,GACx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