@brickkit/core 0.7.4 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,2455 @@
1
- import { $ as foreignKey, $t as ServiceRegistry, A as getTableName, At as getActionAccess, B as lte, Bt as compilerRuntime, C as desc, Ct as overrideSecrets, D as generateSQLiteIndexDdl, Dt as generateOpenApiSpec, E as eq, Et as secret, F as is, Ft as isBrickApp, G as relations, Gt as buildErrorHelpers, H as not, Ht as defineServicePlugin, I as isNotNull, It as requireBrickApp, J as defineDatabase, Jt as getCompiledCheck, K as sql, Kt as defineAction, L as isNull, Lt as compileRoutePlan, M as gte, Mt as bindCompiledApplication, N as ilike, Nt as compileBrickApplication, O as generateSQLiteTableDdl, Ot as hoistAnchoredSchemas, P as inArray, Pt as loadCompiledBrickApp, Q as createSQLiteDatabase, R as like, Rt as createActionHandler, S as createDatabase, St as overrideSecret, T as ensureSQLiteFts, Tt as resolveSecrets, U as notInArray, Ut as getPluginActionRoute, V as ne, Vt as defineResourcePlugin, W as or, Wt as getPluginEndpoints, X as createPostgresDatabase, Xt as validateWithSchema, Y as isDatabaseHandle, Yt as t, Z as blob, Zt as toErrorResponse, _ as Table, _t as swaggerDocsHTML, at as text, b as attachDatabase, bt as envSource, c as createMcpHandler, ct as isTool, d as defineEffectResourcePlugin, dt as endpointPaths, en as getGlobalRegistry, et as index, f as defineEffectServicePlugin, ft as resolveEndpointDb, g as defineResource, gt as scalarDocsHTML, h as defineService, ht as registerReferenceRoute, it as sqliteTable, j as gt, jt as setActionAccess, k as getTableColumns, kt as ACTION_ACCESS_KEY, l as createMcpRegistry, lt as brick, m as ServiceImpl, mt as referencePlugin, n as defineEffectAction, nt as primaryKey, o as createServiceProxy, ot as uniqueIndex, p as defineEffectService, pt as toOpenApiPath, q as syncSchema, qt as Type, r as defineEffectTool, rt as real, s as UnknownToolError, st as defineTool, tn as resetGlobalRegistry, tt as integer, u as effectBrick, ut as createEndpointHandler, v as and, vt as requestLoggingPlugin, w as ensureResourceIndexes, wt as resetSecrets, x as buildFtsMatchQuery, xt as listSecrets, y as asc, yt as SecretRef, z as lt, zt as executeCompiledRoute } from "./chunks/effect.js";
2
- import { n as ValidationError, t as ActionExecutionError } from "./chunks/types.js";
3
- import { BrickServerError, BrickTransportError, createBrickClient, isBrickServerError, isBrickTransportError } from "./client.js";
1
+ import { a as isBrickTransportError, i as isBrickServerError, n as BrickTransportError, o as ActionExecutionError, r as createBrickClient, s as ValidationError, t as BrickServerError } from "./chunks/client.js";
2
+ import { createRequire } from "node:module";
3
+ import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
4
+ import { Type, Type as t } from "@sinclair/typebox";
5
+ import { TypeCompiler } from "@sinclair/typebox/compiler";
6
+ import { formatWithOptions } from "node:util";
7
+ import { Elysia } from "elysia";
8
+ import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
9
+ import postgres from "postgres";
10
+ import { drizzle } from "drizzle-orm/postgres-js";
11
+ import { Table, and, asc, desc, eq, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql, sql as sql$1 } from "drizzle-orm";
12
+ import { mkdirSync } from "node:fs";
13
+ import { dirname } from "node:path";
14
+ //#region \0rolldown/runtime.js
15
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
16
+ //#endregion
17
+ //#region src/compiler/ir.ts
18
+ function freezeIR(value) {
19
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
20
+ for (const child of Object.values(value)) freezeIR(child);
21
+ Object.freeze(value);
22
+ }
23
+ return value;
24
+ }
25
+ function schemaSnapshot(schema) {
26
+ return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
27
+ }
28
+ function analyzeApplication(services, prefix = "/api") {
29
+ for (const service of services) service.build();
30
+ return analyzeDeclaredApplication(services, prefix);
31
+ }
32
+ /** Inspect current declarations without closing service/plugin setup. */
33
+ function analyzeDeclaredApplication(services, prefix = "/api") {
34
+ if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
35
+ const names = /* @__PURE__ */ new Set();
36
+ for (const service of services) {
37
+ if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
38
+ names.add(service.name);
39
+ }
40
+ const routes = [];
41
+ const bindings = [];
42
+ const registered = /* @__PURE__ */ new Map();
43
+ const diagnostics = [];
44
+ const add = (service, action, method, path, kind) => {
45
+ if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
46
+ const plugin = getPluginActionRoute(action, prefix) !== void 0;
47
+ const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
48
+ const previous = registered.get(key);
49
+ if (previous) {
50
+ if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
51
+ diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
52
+ return;
53
+ }
54
+ if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
55
+ registered.set(key, {
56
+ name: `${service.name}.${action.name}`,
57
+ plugin
58
+ });
59
+ const readLike = method === "GET" || action.name.startsWith("get") || action.name.endsWith(".get") || action.name.startsWith("list") || action.name.endsWith(".list") || action.name.startsWith("find") || action.name.startsWith("read");
60
+ const coercions = [];
61
+ for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
62
+ key,
63
+ type: "number"
64
+ });
65
+ else if (prop.type === "boolean") coercions.push({
66
+ key,
67
+ type: "boolean"
68
+ });
69
+ else if (prop.type === "array") coercions.push({
70
+ key,
71
+ type: "array"
72
+ });
73
+ routes.push({
74
+ method,
75
+ path,
76
+ service: service.name,
77
+ action: action.name,
78
+ kind,
79
+ input: Boolean(action.config.input),
80
+ output: Boolean(action.config.output),
81
+ context: typeof service.options.context === "function",
82
+ authorize: typeof action.config.authorize === "function",
83
+ inputPrecedence: readLike ? [
84
+ "query",
85
+ "params",
86
+ "body"
87
+ ] : [
88
+ "params",
89
+ "body",
90
+ "query"
91
+ ],
92
+ coercions,
93
+ inputSchema: schemaSnapshot(action.config.input),
94
+ outputSchema: schemaSnapshot(action.config.output)
95
+ });
96
+ bindings.push({
97
+ service,
98
+ action
99
+ });
100
+ };
101
+ for (const service of services) for (const action of service.listActions()) {
102
+ const pluginRoute = getPluginActionRoute(action, prefix);
103
+ if (pluginRoute === false) continue;
104
+ const path = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
105
+ add(service, action, pluginRoute?.method ?? action.config.method ?? "POST", path, "action");
106
+ }
107
+ const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
108
+ service: service.name,
109
+ name: contribution.name,
110
+ metadata: schemaSnapshot(contribution.describe?.())
111
+ })));
112
+ return {
113
+ ir: freezeIR({
114
+ version: 1,
115
+ target: "bun-elysia",
116
+ prefix,
117
+ services: [...names],
118
+ routes,
119
+ preparations,
120
+ diagnostics
121
+ }),
122
+ bindings
123
+ };
124
+ }
125
+ //#endregion
126
+ //#region src/registry.ts
127
+ var ServiceRegistry = class {
128
+ _revision = 0;
129
+ /** Definition revision for invalidating serialized architecture snapshots. */
130
+ get revision() {
131
+ return this._revision;
132
+ }
133
+ touch() {
134
+ this._revision++;
135
+ }
136
+ services = /* @__PURE__ */ new Map();
137
+ routes = /* @__PURE__ */ new Map();
138
+ /** Remember the actual registered routes for subsequent registry exports. */
139
+ setApplicationRoutes(application) {
140
+ for (const service of application.services) this.routes.set(service, application.routes.filter((route) => route.service === service.name));
141
+ this.touch();
142
+ }
143
+ register(service) {
144
+ if (this.services.has(service.name)) console.warn(`[Brick-TS] Service '${service.name}' is already registered. Overwriting.`);
145
+ const previous = this.services.get(service.name);
146
+ if (previous) this.routes.delete(previous);
147
+ this.services.set(service.name, service);
148
+ this.touch();
149
+ }
150
+ get(name) {
151
+ return this.services.get(name);
152
+ }
153
+ has(name) {
154
+ return this.services.has(name);
155
+ }
156
+ list() {
157
+ return Array.from(this.services.values());
158
+ }
159
+ clear() {
160
+ this.services.clear();
161
+ this.routes.clear();
162
+ this.touch();
163
+ }
164
+ exportArchitecture(application) {
165
+ return {
166
+ version: "1.0.0",
167
+ services: (application?.services ?? this.list()).map((service) => {
168
+ const routes = application ? application.routes.filter((route) => route.service === service.name) : this.routes.get(service) ?? analyzeDeclaredApplication([service]).ir.routes;
169
+ const byAction = new Map(routes.map((route) => [route.action, route]));
170
+ const schema = service.introspect();
171
+ return {
172
+ ...schema,
173
+ actions: schema.actions.map((action) => {
174
+ const route = byAction.get(action.name);
175
+ return route ? {
176
+ ...action,
177
+ method: route.method,
178
+ path: route.path
179
+ } : action;
180
+ })
181
+ };
182
+ })
183
+ };
184
+ }
185
+ };
186
+ let globalRegistry = new ServiceRegistry();
187
+ /**
188
+ * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
189
+ * generator, `createServiceProxy`, and the dashboard find services by name.
190
+ *
191
+ * @returns The current global registry.
192
+ */
193
+ function getGlobalRegistry() {
194
+ return globalRegistry;
195
+ }
196
+ /**
197
+ * Start over with an empty global registry. For tests, which define the same
198
+ * services again in each case; an application never needs it.
199
+ */
200
+ function resetGlobalRegistry() {
201
+ globalRegistry = new ServiceRegistry();
202
+ }
203
+ //#endregion
204
+ //#region src/telemetry.ts
205
+ const INSTRUMENTATION_SCOPE = "@brickkit/core";
206
+ const MAX_TEXT_LENGTH = 500;
207
+ const MAX_STATEMENT_LENGTH = 2e3;
208
+ const DATABASE_INSTRUMENTED = Symbol.for("brickkit.telemetry.database");
209
+ const SQLITE_STATEMENT_METHODS = [
210
+ "all",
211
+ "get",
212
+ "run",
213
+ "values"
214
+ ];
215
+ /** Run `fn` as a child of the active span, ending the span when its result settles. */
216
+ function withSpan(name, attributes, fn, kind = SpanKind.INTERNAL) {
217
+ return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(name, {
218
+ kind,
219
+ attributes
220
+ }, (span) => settle(fn, (outcome) => {
221
+ if (outcome.failed) recordThrown(span, outcome.error);
222
+ span.end();
223
+ }));
224
+ }
225
+ /**
226
+ * Add a child span for an in-process call, but only inside a request that is
227
+ * already traced. Calls made outside instrumented requests run unchanged.
228
+ */
229
+ function withCallSpan(name, attributes, fn) {
230
+ return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();
231
+ }
232
+ /**
233
+ * Wrap a raw route handler so each of its requests gets a server span. Use it
234
+ * for routes registered directly on the app, outside actions and endpoints,
235
+ * such as auth or webhook routes. Spans are recorded whenever a tracer provider
236
+ * is registered; `brick({ telemetry })` does not apply to these routes.
237
+ *
238
+ * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia
239
+ * decides what to parse from the handler's destructuring, and forwarding the
240
+ * whole context would parse the body and leave `request.json()` with nothing.
241
+ */
242
+ function traceRoute(route, handler) {
243
+ return ({ request, headers, set, params, query }) => traceHttpRequest({
244
+ request,
245
+ headers,
246
+ set
247
+ }, request.method, route, () => handler({
248
+ request,
249
+ headers,
250
+ set,
251
+ params,
252
+ query
253
+ }));
254
+ }
255
+ /**
256
+ * Wrap one HTTP request in a server span. The span continues the caller's
257
+ * trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the
258
+ * request id Brick returns is the span's trace id, so clients can find the
259
+ * request in the dashboard.
260
+ */
261
+ function traceHttpRequest(request, method, route, fn) {
262
+ const attributes = {
263
+ "http.request.method": method,
264
+ "http.route": route
265
+ };
266
+ if (request.request) attributes["url.path"] = new URL(request.request.url).pathname;
267
+ const headers = request.headers ?? {};
268
+ const parent = propagation.extract(context.active(), headers);
269
+ return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(`${method} ${route}`, {
270
+ kind: SpanKind.SERVER,
271
+ attributes
272
+ }, parent, (span) => {
273
+ if (!headers["x-trace-id"]) headers["x-trace-id"] = span.spanContext().traceId;
274
+ const outgoing = {};
275
+ propagation.inject(context.active(), outgoing);
276
+ if (request.set?.headers) Object.assign(request.set.headers, outgoing);
277
+ return settle(fn, (outcome) => {
278
+ const status = outcome.failed ? 500 : outcome.value instanceof Response ? outcome.value.status : responseStatus(request.set?.status);
279
+ if (outcome.failed) recordThrown(span, outcome.error);
280
+ span.setAttribute("http.response.status_code", status);
281
+ const traceId = headers["x-trace-id"];
282
+ if (traceId) span.setAttribute("brick.trace_id", traceId);
283
+ if (status >= 500) span.setStatus({
284
+ code: SpanStatusCode.ERROR,
285
+ message: `HTTP ${status}`
286
+ });
287
+ span.end();
288
+ });
289
+ });
290
+ }
291
+ /**
292
+ * Attach a handled failure to the active span. Brick returns these as
293
+ * responses rather than throwing, so only server faults (5xx) mark the span
294
+ * as errored; client errors keep their code as an attribute.
295
+ */
296
+ function recordFailure(error, failure) {
297
+ const span = trace.getActiveSpan();
298
+ if (!span) return;
299
+ span.setAttributes({
300
+ "brick.error.code": failure.code,
301
+ "brick.error.status": failure.status,
302
+ "brick.error.message": truncate(failure.message)
303
+ });
304
+ if (failure.status >= 500) recordThrown(span, error);
305
+ }
306
+ /**
307
+ * Record SQL statements as client spans for the database behind a service.
308
+ * Drizzle's logger has no timing, so the hook sits on the driver: each
309
+ * statement is timed where the driver runs it. Statements outside traced
310
+ * requests are not recorded. Calling this again on the same client is a no-op.
311
+ */
312
+ function instrumentDatabase(db) {
313
+ const client = db?.$client;
314
+ if (typeof client !== "object" && typeof client !== "function" || client === null) return;
315
+ const driver = client;
316
+ if (driver[DATABASE_INSTRUMENTED]) return;
317
+ if (typeof driver.prepare === "function") instrumentBunSqlite(driver);
318
+ else if (typeof driver.unsafe === "function") instrumentPostgres(driver);
319
+ else return;
320
+ driver[DATABASE_INSTRUMENTED] = true;
321
+ }
322
+ function instrumentBunSqlite(client) {
323
+ const prepare = client.prepare.bind(client);
324
+ client.prepare = (sql) => {
325
+ const statement = prepare(sql);
326
+ for (const method of SQLITE_STATEMENT_METHODS) {
327
+ const original = statement[method];
328
+ if (typeof original !== "function") continue;
329
+ statement[method] = (...args) => recordStatement(sql, "sqlite", () => original.apply(statement, args));
330
+ }
331
+ return statement;
332
+ };
333
+ }
334
+ /**
335
+ * postgres.js returns a query that runs when awaited, and `values()` returns
336
+ * that same object, so overriding `then` on it times the whole round trip.
337
+ */
338
+ function instrumentPostgres(client) {
339
+ const unsafe = client.unsafe.bind(client);
340
+ client.unsafe = (sql, ...rest) => {
341
+ const query = unsafe(sql, ...rest);
342
+ if (!trace.getActiveSpan() || typeof query?.then !== "function") return query;
343
+ const span = startStatementSpan(sql, "postgresql");
344
+ let finished = false;
345
+ const finish = (outcome) => {
346
+ if (finished) return;
347
+ finished = true;
348
+ if (outcome.failed) recordThrown(span, outcome.error);
349
+ span.end();
350
+ };
351
+ const then = query.then.bind(query);
352
+ query.then = (onFulfilled, onRejected) => then((value) => {
353
+ finish({
354
+ failed: false,
355
+ value
356
+ });
357
+ return onFulfilled ? onFulfilled(value) : value;
358
+ }, (error) => {
359
+ finish({
360
+ failed: true,
361
+ error
362
+ });
363
+ if (onRejected) return onRejected(error);
364
+ throw error;
365
+ });
366
+ return query;
367
+ };
368
+ }
369
+ function recordStatement(sql, system, fn) {
370
+ if (!trace.getActiveSpan()) return fn();
371
+ return withSpan(statementName(sql), statementAttributes(sql, system), fn, SpanKind.CLIENT);
372
+ }
373
+ function startStatementSpan(sql, system) {
374
+ return trace.getTracer(INSTRUMENTATION_SCOPE).startSpan(statementName(sql), {
375
+ kind: SpanKind.CLIENT,
376
+ attributes: statementAttributes(sql, system)
377
+ }, context.active());
378
+ }
379
+ function statementName(sql) {
380
+ return `SQL ${operationOf(sql)}`;
381
+ }
382
+ function statementAttributes(sql, system) {
383
+ return {
384
+ "db.system": system,
385
+ "db.operation": operationOf(sql),
386
+ "db.statement": truncate(sql, MAX_STATEMENT_LENGTH)
387
+ };
388
+ }
389
+ function operationOf(sql) {
390
+ return sql.trim().split(/\s+/, 1)[0]?.toUpperCase() || "SQL";
391
+ }
392
+ function settle(fn, done) {
393
+ let result;
394
+ try {
395
+ result = fn();
396
+ } catch (error) {
397
+ done({
398
+ failed: true,
399
+ error
400
+ });
401
+ throw error;
402
+ }
403
+ if (isPromiseLike(result)) return result.then((value) => {
404
+ done({
405
+ failed: false,
406
+ value
407
+ });
408
+ return value;
409
+ }, (error) => {
410
+ done({
411
+ failed: true,
412
+ error
413
+ });
414
+ throw error;
415
+ });
416
+ done({
417
+ failed: false,
418
+ value: result
419
+ });
420
+ return result;
421
+ }
422
+ function recordThrown(span, error) {
423
+ span.recordException(error instanceof Error ? error : String(error));
424
+ span.setStatus({
425
+ code: SpanStatusCode.ERROR,
426
+ message: truncate(messageOf(error))
427
+ });
428
+ }
429
+ function responseStatus(value) {
430
+ const status = typeof value === "number" ? value : Number(value ?? 200);
431
+ return Number.isInteger(status) ? status : 200;
432
+ }
433
+ function isPromiseLike(value) {
434
+ return typeof value === "object" && value !== null && typeof value.then === "function";
435
+ }
436
+ function messageOf(error) {
437
+ return error instanceof Error ? error.message : String(error);
438
+ }
439
+ function truncate(text, limit = MAX_TEXT_LENGTH) {
440
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
441
+ }
442
+ //#endregion
443
+ //#region src/error-response.ts
444
+ /** Preserve declared failures, log and wrap unexpected throws without exposing internals. */
445
+ function normalizeActionError(err, { logger, requestId }) {
446
+ if (err instanceof ActionExecutionError || err instanceof ValidationError) return err;
447
+ logger.error("Unexpected action error", { requestId }, err);
448
+ const failure = new ActionExecutionError("INTERNAL_SERVER_ERROR", "Internal Server Error", 500, void 0, { cause: err });
449
+ failure.name = "InternalServerError";
450
+ return failure;
451
+ }
452
+ /**
453
+ * Turn what an action threw into the JSON body of its HTTP response, and record
454
+ * the failure on the active trace. Declared failures and validation errors keep
455
+ * their code, status, and details; anything else is logged and answered as a
456
+ * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.
457
+ *
458
+ * @param err - Whatever was thrown.
459
+ * @param context - A `logger` with `error()`, and the `requestId` to put in the body.
460
+ * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and
461
+ * `details` or `errors` when there are any.
462
+ */
463
+ function toErrorResponse(err, context) {
464
+ const envelope = buildErrorEnvelope(err, context);
465
+ recordFailure(err, envelope);
466
+ return envelope;
467
+ }
468
+ function buildErrorEnvelope(err, context) {
469
+ const failure = normalizeActionError(err, context);
470
+ if (failure.status >= 500 && (err instanceof ActionExecutionError || err instanceof ValidationError)) context.logger.error("Server action error", { requestId: context.requestId }, err);
471
+ if (failure instanceof ValidationError && failure.status >= 500) return {
472
+ name: failure.name,
473
+ code: failure.code,
474
+ message: failure.message,
475
+ status: failure.status,
476
+ requestId: context.requestId
477
+ };
478
+ return {
479
+ ...failure.toJSON(),
480
+ requestId: context.requestId
481
+ };
482
+ }
483
+ //#endregion
484
+ //#region src/typebox.ts
485
+ const compilerCache = /* @__PURE__ */ new WeakMap();
486
+ /**
487
+ * The compiled validator for a TypeBox schema. Compiling is slow and checking
488
+ * is fast, so each schema is compiled once and kept for as long as the schema
489
+ * object lives.
490
+ *
491
+ * @param schema - A TypeBox schema.
492
+ * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.
493
+ */
494
+ function getCompiledCheck(schema) {
495
+ let compiled = compilerCache.get(schema);
496
+ if (!compiled) {
497
+ compiled = TypeCompiler.Compile(schema);
498
+ compilerCache.set(schema, compiled);
499
+ }
500
+ return compiled;
501
+ }
502
+ /**
503
+ * Check a value against a schema, the way actions check their input and output.
504
+ *
505
+ * @param schema - A TypeBox schema, or `undefined` to accept anything.
506
+ * @param value - The value to check.
507
+ * @returns `{ success: true, data }`, or `{ success: false, errors }` with a
508
+ * `path`, `message`, `type`, and the offending `value` for each problem.
509
+ */
510
+ function validateWithSchema(schema, value) {
511
+ if (!schema) return {
512
+ success: true,
513
+ data: value
514
+ };
515
+ const check = getCompiledCheck(schema);
516
+ if (check.Check(value)) return {
517
+ success: true,
518
+ data: value
519
+ };
520
+ const errors = [];
521
+ for (const error of check.Errors(value)) errors.push({
522
+ path: error.path,
523
+ message: error.message,
524
+ value: error.value,
525
+ type: error.type
526
+ });
527
+ return {
528
+ success: false,
529
+ errors
530
+ };
531
+ }
532
+ //#endregion
533
+ //#region src/logger.ts
534
+ /**
535
+ * Set by the CLI when a dashboard is collecting logs, in `brick dev` or in
536
+ * `brick start` with the `dashboard` option. A shared symbol, not an option or
537
+ * an export: the CLI and the app may each hold their own copy of this package,
538
+ * and nothing but a dashboard turns it on.
539
+ */
540
+ const CAPTURE = Symbol.for("brickkit.logs.capture");
541
+ /** The span event a log line becomes; the dashboard reads these. */
542
+ const LOG_EVENT = "log";
543
+ const MAX_MESSAGE_LENGTH = 4e3;
544
+ /**
545
+ * Logs one span keeps. OpenTelemetry keeps 128 events per span by default,
546
+ * exceptions among them, so a chatty action must not use them all up and
547
+ * lose the stack trace of the error that ends it.
548
+ */
549
+ const MAX_LOGS_PER_SPAN = 100;
550
+ const logged = /* @__PURE__ */ new WeakMap();
551
+ /**
552
+ * Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and
553
+ * titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their
554
+ * console output, which in a web page shows as stray characters.
555
+ */
556
+ const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\))/g;
557
+ /** `text` without terminal formatting. */
558
+ function stripAnsi(text) {
559
+ return text.includes("\x1B") ? text.replace(ANSI, "") : text;
560
+ }
561
+ /**
562
+ * What `console.log` would print, without terminal colors, with objects cut off
563
+ * at a sensible size.
564
+ */
565
+ function render(args) {
566
+ const text = stripAnsi(formatWithOptions({
567
+ depth: 3,
568
+ breakLength: 120,
569
+ maxArrayLength: 50,
570
+ maxStringLength: 1e3
571
+ }, ...args));
572
+ return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;
573
+ }
574
+ function record(span, level, args) {
575
+ const count = (logged.get(span) ?? 0) + 1;
576
+ logged.set(span, count);
577
+ if (count > MAX_LOGS_PER_SPAN) {
578
+ span.setAttribute("brick.logs.dropped", count - MAX_LOGS_PER_SPAN);
579
+ return;
580
+ }
581
+ span.addEvent(LOG_EVENT, {
582
+ "log.level": level,
583
+ "log.message": render(args)
584
+ });
585
+ }
586
+ /**
587
+ * Record a line on the running span, if a recording one is running. Returns
588
+ * whether it did, so the caller prints only when it did not.
589
+ */
590
+ function recordActive(level, args) {
591
+ const span = trace.getActiveSpan();
592
+ if (!span?.isRecording()) return false;
593
+ record(span, level, args);
594
+ return true;
595
+ }
596
+ globalThis[Symbol.for("brickkit.logs.record")] = recordActive;
597
+ /**
598
+ * A logger for actions, tools, and endpoints. While a dashboard is on, a line
599
+ * logged while a request is being traced becomes an event on the span that is
600
+ * running, which the dashboard shows with that request (and in its Logs tab);
601
+ * it is not printed. Everywhere else, and for lines logged outside a request,
602
+ * it prints to the console, prefixed by `prefix`: one for all levels, or one
603
+ * per level.
604
+ *
605
+ * Capturing costs one context lookup and a span event per line, and nothing
606
+ * is serialized for the dashboard until the span ends, so it is cheaper than
607
+ * a console write. Lines are cut at 4,000 characters and a span keeps 100.
608
+ */
609
+ function createLogger(prefix) {
610
+ const level = (name, print) => (...args) => {
611
+ if (globalThis[CAPTURE] === true && recordActive(name, args)) return;
612
+ print(typeof prefix === "string" ? prefix : prefix[name], ...args);
613
+ };
614
+ return {
615
+ info: level("info", (...args) => console.log(...args)),
616
+ warn: level("warn", (...args) => console.warn(...args)),
617
+ error: level("error", (...args) => console.error(...args)),
618
+ debug: level("debug", (...args) => console.debug(...args))
619
+ };
620
+ }
621
+ /** The prefixes of loggers a caller did not supply. */
622
+ const DEFAULT_LOG_PREFIXES = {
623
+ info: "[INFO]",
624
+ warn: "[WARN]",
625
+ error: "[ERROR]",
626
+ debug: "[DEBUG]"
627
+ };
628
+ //#endregion
629
+ //#region src/action.ts
630
+ const defaultLogger$1 = createLogger(DEFAULT_LOG_PREFIXES);
631
+ const DEFAULT_REQUEST$3 = new Request("http://localhost");
632
+ let _defaultCtxSeq = 0;
633
+ const RESOLVED_SYMBOL$1 = Symbol("resolved");
634
+ const standardErrorDefaults = {
635
+ BAD_REQUEST: {
636
+ status: 400,
637
+ message: "Bad Request"
638
+ },
639
+ UNAUTHORIZED: {
640
+ status: 401,
641
+ message: "Unauthorized"
642
+ },
643
+ FORBIDDEN: {
644
+ status: 403,
645
+ message: "Forbidden"
646
+ },
647
+ NOT_FOUND: {
648
+ status: 404,
649
+ message: "Not Found"
650
+ },
651
+ CONFLICT: {
652
+ status: 409,
653
+ message: "Conflict"
654
+ },
655
+ INTERNAL_SERVER_ERROR: {
656
+ status: 500,
657
+ message: "Internal Server Error"
658
+ }
659
+ };
660
+ function createDefaultContext(partial) {
661
+ if (partial?.[RESOLVED_SYMBOL$1]) return partial;
662
+ const seq = (++_defaultCtxSeq).toString(36);
663
+ return {
664
+ request: partial?.request ?? DEFAULT_REQUEST$3,
665
+ traceId: partial?.traceId || `tr_${seq}`,
666
+ requestId: partial?.requestId || `req_${seq}`,
667
+ db: partial?.db,
668
+ user: partial?.user,
669
+ logger: partial?.logger || defaultLogger$1,
670
+ services: partial?.services || {},
671
+ metadata: partial?.metadata || {},
672
+ ...partial,
673
+ [RESOLVED_SYMBOL$1]: true
674
+ };
675
+ }
676
+ /**
677
+ * The `error` helpers an action receives: one function per error code that
678
+ * throws an `ActionExecutionError` with that code and status. The standard HTTP
679
+ * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
680
+ * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
681
+ * them or replace one.
682
+ *
683
+ * @param errorsDef - The action's `errors`: for each code, its `message` and
684
+ * `status` (default 400).
685
+ * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
686
+ * and always throw.
687
+ */
688
+ function buildErrorHelpers(errorsDef) {
689
+ const helpers = {};
690
+ for (const [code, def] of Object.entries(standardErrorDefaults)) helpers[code] = (overrideMessage, details, options) => {
691
+ const message = overrideMessage || def.message;
692
+ const status = def.status;
693
+ throw new ActionExecutionError(code, message, status, details, options);
694
+ };
695
+ if (errorsDef) for (const [code, def] of Object.entries(errorsDef)) helpers[code] = (overrideMessage, details, options) => {
696
+ const message = overrideMessage || def.message;
697
+ const status = def.status || 400;
698
+ throw new ActionExecutionError(code, message, status, details, options);
699
+ };
700
+ return helpers;
701
+ }
702
+ function defineAction(config) {
703
+ const errorHelpers = buildErrorHelpers(config.errors);
704
+ const actionFn = (async (params) => {
705
+ return actionFn.execute(params);
706
+ });
707
+ Object.defineProperty(actionFn, "name", {
708
+ value: config.name,
709
+ configurable: true
710
+ });
711
+ actionFn.config = config;
712
+ actionFn.errorHelpers = errorHelpers;
713
+ actionFn.validateInput = (input) => {
714
+ return validateWithSchema(config.input, input);
715
+ };
716
+ actionFn.validateOutput = (output) => {
717
+ return validateWithSchema(actionFn.outputValidationSchema ?? config.output, output);
718
+ };
719
+ actionFn.run = async (input, ctx) => {
720
+ return actionFn.execute({
721
+ input,
722
+ ctx
723
+ });
724
+ };
725
+ actionFn.execute = async (params) => {
726
+ const boundService = actionFn.service;
727
+ const fullCtx = boundService?.resolveContext ? await boundService.resolveContext(params?.ctx) : createDefaultContext(params?.ctx);
728
+ try {
729
+ if (!fullCtx.db) {
730
+ const service = boundService ?? (actionFn.serviceName ? getGlobalRegistry().get(actionFn.serviceName) : void 0);
731
+ if (service?.getDb()) fullCtx.db = service.getDb();
732
+ }
733
+ if (config.input) {
734
+ const inputValidation = actionFn.validateInput(params?.input);
735
+ if (!inputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' input`, inputValidation.errors);
736
+ }
737
+ if (config.authorize) {
738
+ if (!await config.authorize({
739
+ user: fullCtx.user,
740
+ input: params?.input,
741
+ ctx: fullCtx
742
+ })) throw new ActionExecutionError(fullCtx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${config.name}'`, fullCtx.user == null ? 401 : 403);
743
+ }
744
+ const result = await config.execute({
745
+ input: params?.input,
746
+ ctx: fullCtx,
747
+ error: errorHelpers
748
+ });
749
+ if (actionFn.outputValidationSchema ?? config.output) {
750
+ const outputValidation = actionFn.validateOutput(result);
751
+ if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
752
+ }
753
+ return result;
754
+ } catch (err) {
755
+ throw normalizeActionError(err, fullCtx);
756
+ }
757
+ };
758
+ return actionFn;
759
+ }
760
+ //#endregion
761
+ //#region src/plugin.ts
762
+ const pluginKind = Symbol.for("brickkit.plugin.kind");
763
+ /**
764
+ * Define a plugin that installs onto a service with `service.use(plugin)`. Its
765
+ * `setup` receives the service and a `routes` registrar for adding actions and
766
+ * raw HTTP endpoints, and returns the typed API that `service.use` hands back.
767
+ *
768
+ * @param definition - A unique `name`, optional `routes` controls that let the
769
+ * user move or switch off the plugin's routes, and `setup`, which must be
770
+ * synchronous.
771
+ * @returns The plugin descriptor, frozen.
772
+ * @throws When the name is empty or has surrounding whitespace.
773
+ * @example
774
+ * import { defineServicePlugin, t } from "@brickkit/core";
775
+ *
776
+ * export const greeting = (salutation = "Hello") =>
777
+ * defineServicePlugin({
778
+ * name: "example/greeting",
779
+ * setup({ routes }) {
780
+ * const hello = routes.action({
781
+ * name: "hello",
782
+ * input: t.Object({ name: t.String() }),
783
+ * output: t.String(),
784
+ * execute: ({ input }) => `${salutation}, ${input.name}!`,
785
+ * });
786
+ * return { hello };
787
+ * },
788
+ * });
789
+ *
790
+ * const api = greeterService.use(greeting("Welcome"));
791
+ * await api.hello({ input: { name: "Ada" } });
792
+ */
793
+ function defineServicePlugin(definition) {
794
+ validateName(definition.name);
795
+ return Object.freeze({
796
+ ...definition,
797
+ routes: copyControls(definition.routes),
798
+ [pluginKind]: "service"
799
+ });
800
+ }
801
+ /**
802
+ * Define a plugin that installs onto a resource (a table and its entity) with
803
+ * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
804
+ * `routes` registrar, whose routes are scoped under the resource's name, and
805
+ * returns the typed API that `resource.use` hands back. `crud` is built this way.
806
+ *
807
+ * @param definition - A unique `name`, optional `routes` controls, and `setup`,
808
+ * which must be synchronous.
809
+ * @returns The plugin descriptor, frozen.
810
+ * @throws When the name is empty or has surrounding whitespace.
811
+ */
812
+ function defineResourcePlugin(definition) {
813
+ validateName(definition.name);
814
+ return Object.freeze({
815
+ ...definition,
816
+ routes: copyControls(definition.routes),
817
+ [pluginKind]: "resource"
818
+ });
819
+ }
820
+ function validateName(name) {
821
+ if (!name || name.trim() !== name) throw new Error("Plugin and route names must be nonempty and have no surrounding whitespace");
822
+ }
823
+ function validatePath(path) {
824
+ if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("//") || path.split("/").some((part) => part === "." || part === "..")) throw new Error(`Invalid plugin route path '${path}'`);
825
+ }
826
+ function copyControls(controls) {
827
+ if (controls === void 0 || controls === false) return controls;
828
+ const result = Object.create(null);
829
+ for (const [name, value] of Object.entries(controls)) {
830
+ validateName(name);
831
+ if (value === false) {
832
+ result[name] = false;
833
+ continue;
834
+ }
835
+ if (value.path !== void 0) validatePath(value.path);
836
+ if (value.scope !== void 0 && ![
837
+ "app",
838
+ "service",
839
+ "resource"
840
+ ].includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
841
+ result[name] = Object.freeze({ ...value });
842
+ }
843
+ return Object.freeze(result);
844
+ }
845
+ const states = /* @__PURE__ */ new WeakMap();
846
+ const actionBindings = /* @__PURE__ */ new WeakMap();
847
+ /**
848
+ * Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)
849
+ * may load a second copy of core that owns a different WeakMap, while the
850
+ * action objects themselves cross the boundary by reference. The binding
851
+ * travels on the action under a process-global symbol so route lookups
852
+ * (including disabled-route suppression) keep working there.
853
+ */
854
+ const actionBindingKey = Symbol.for("brickkit.plugin.actionBinding");
855
+ function stateOf(service) {
856
+ let state = states.get(service);
857
+ if (!state) {
858
+ state = {
859
+ hosts: /* @__PURE__ */ new Map(),
860
+ actions: /* @__PURE__ */ new Map(),
861
+ endpoints: []
862
+ };
863
+ states.set(service, state);
864
+ }
865
+ return state;
866
+ }
867
+ function isInstallingPlugin(service) {
868
+ return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
869
+ }
870
+ function pathOf(binding, prefix) {
871
+ const scope = binding.scope === "app" ? "" : `/${binding.scope === "resource" ? binding.resource.name : binding.service.name}`;
872
+ return `${prefix.replace(/\/$/, "")}${scope}${binding.path === "/" ? "" : binding.path}` || "/";
873
+ }
874
+ /**
875
+ * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
876
+ * compiler, and the typed client.
877
+ *
878
+ * @param action - An action.
879
+ * @param prefix - The application's route prefix (default `/api`).
880
+ * @returns `undefined` when no plugin bound the action (it uses its own route),
881
+ * `false` when the plugin's route was switched off, otherwise the route's
882
+ * `path` and `method`, the `clientPath` the typed client uses, and the owning
883
+ * `plugin` and `resource`.
884
+ */
885
+ function getPluginActionRoute(action, prefix = "/api") {
886
+ const binding = action[actionBindingKey] ?? actionBindings.get(action);
887
+ if (!binding) return void 0;
888
+ if (!binding.enabled) return false;
889
+ return {
890
+ path: pathOf(binding, prefix),
891
+ method: binding.method,
892
+ clientPath: binding.clientPath,
893
+ plugin: binding.plugin,
894
+ resource: binding.resource?.name
895
+ };
896
+ }
897
+ /**
898
+ * The raw HTTP endpoints plugins registered on a service, ready to mount on the
899
+ * application. Each handler resolves the service's context before it runs.
900
+ *
901
+ * @param service - The service plugins were installed on.
902
+ * @param prefix - The application's route prefix (default `/api`).
903
+ * @returns The enabled endpoints: `path`, `method`, `handler`, and the
904
+ * `summary`, `description`, and `tags` for OpenAPI.
905
+ */
906
+ function getPluginEndpoints(service, prefix = "/api") {
907
+ return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
908
+ path: pathOf(binding, prefix),
909
+ method: binding.method,
910
+ service,
911
+ summary: binding.summary,
912
+ description: binding.description,
913
+ tags: binding.tags,
914
+ handler: async (context) => binding.handler({
915
+ ...context,
916
+ ctx: await service.resolveContext({ request: context.request })
917
+ })
918
+ }));
919
+ }
920
+ /** Descriptor identity is scoped to the service or resource installation host. */
921
+ function installPlugin(service, resource, descriptor) {
922
+ if (service.isBuilt) throw new Error("Plugins must be installed before service build");
923
+ if (descriptor[pluginKind] !== (resource ? "resource" : "service")) throw new Error("Plugin does not support this installation host");
924
+ const state = stateOf(service);
925
+ const host = resource ?? service;
926
+ const existing = state.hosts.get(host)?.get(descriptor.name);
927
+ if (existing) {
928
+ if (existing.status === "installing") throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);
929
+ if (existing.descriptor !== descriptor) throw new Error(`Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`);
930
+ return resource ?? existing.api;
931
+ }
932
+ const snapshots = {
933
+ actions: new Map(service.actions),
934
+ tools: new Map(service.tools),
935
+ tables: new Map(service.tables),
936
+ resources: new Map(service.resources),
937
+ preparations: new Map(service.preparations),
938
+ hosts: new Map([...state.hosts].map(([key, installations]) => [key, new Map(installations)])),
939
+ bindings: new Map(state.actions),
940
+ endpoints: [...state.endpoints],
941
+ properties: new Map([...service.resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]))
942
+ };
943
+ const installations = state.hosts.get(host) ?? /* @__PURE__ */ new Map();
944
+ state.hosts.set(host, installations);
945
+ installations.set(descriptor.name, {
946
+ descriptor,
947
+ status: "installing"
948
+ });
949
+ const names = /* @__PURE__ */ new Set();
950
+ const ownedActions = /* @__PURE__ */ new Set();
951
+ let active = true;
952
+ const bindingFor = (config) => {
953
+ if (!active || service.isBuilt) throw new Error("Plugin routes can only be registered during setup");
954
+ validateName(config.name);
955
+ validatePath(config.path);
956
+ if (names.has(config.name)) throw new Error(`Duplicate plugin route name '${config.name}'`);
957
+ names.add(config.name);
958
+ const control = descriptor.routes === false ? false : descriptor.routes?.[config.name];
959
+ const scope = control && control.scope || config.scope || (resource ? "resource" : "service");
960
+ if (scope === "resource" && !resource) throw new Error("Service plugin routes cannot use resource scope");
961
+ if (![
962
+ "app",
963
+ "service",
964
+ "resource"
965
+ ].includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
966
+ if (![
967
+ "GET",
968
+ "POST",
969
+ "PUT",
970
+ "PATCH",
971
+ "DELETE"
972
+ ].includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
973
+ const path = control && control.path || config.path;
974
+ validatePath(path);
975
+ return {
976
+ service,
977
+ resource,
978
+ plugin: descriptor.name,
979
+ path,
980
+ method: config.method,
981
+ scope,
982
+ enabled: control !== false
983
+ };
984
+ };
985
+ const routes = {
986
+ action(config) {
987
+ const binding = bindingFor(config);
988
+ for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, match[1])) throw new Error(`Plugin action path parameter '${match[1]}' must be declared in its input schema`);
989
+ const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
990
+ if (service.actions.has(name)) throw new Error(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
991
+ const { scope: _scope, ...actionConfig } = config;
992
+ const action = defineAction({
993
+ ...actionConfig,
994
+ name
995
+ });
996
+ action.plugin = descriptor.name;
997
+ if (resource) action.resource = resource.name;
998
+ service.action(action);
999
+ ownedActions.add(action);
1000
+ state.actions.set(action, binding);
1001
+ actionBindings.set(action, binding);
1002
+ action[actionBindingKey] = binding;
1003
+ return action;
1004
+ },
1005
+ endpoint(config) {
1006
+ const binding = bindingFor(config);
1007
+ state.endpoints.push({
1008
+ ...binding,
1009
+ handler: config.handler,
1010
+ summary: config.summary,
1011
+ description: config.description,
1012
+ tags: config.tags
1013
+ });
1014
+ }
1015
+ };
1016
+ try {
1017
+ const api = resource ? descriptor.setup({
1018
+ service,
1019
+ resource,
1020
+ routes
1021
+ }) : descriptor.setup({
1022
+ service,
1023
+ routes
1024
+ });
1025
+ if (api && typeof api === "object" && "then" in api) throw new Error("Plugin setup must be synchronous");
1026
+ if (descriptor.routes && Object.keys(descriptor.routes).some((name) => !names.has(name))) throw new Error(`Plugin '${descriptor.name}' has an override for an unknown route`);
1027
+ const walk = (value, path, ancestors) => {
1028
+ if (typeof value === "function") {
1029
+ const binding = state.actions.get(value);
1030
+ if (binding && ownedActions.has(value)) {
1031
+ if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
1032
+ binding.clientPath = [resource?.name ?? service.name, ...path];
1033
+ }
1034
+ } else if (value && typeof value === "object" && !ancestors.has(value)) {
1035
+ const next = new Set(ancestors).add(value);
1036
+ for (const [key, child] of Object.entries(value)) walk(child, [...path, key], next);
1037
+ }
1038
+ };
1039
+ walk(api, [], /* @__PURE__ */ new Set());
1040
+ if (resource) {
1041
+ if (!api || typeof api !== "object" || Array.isArray(api)) throw new Error("Resource plugins must return named API contributions");
1042
+ for (const key of Object.keys(api)) if (key in resource || [
1043
+ "__proto__",
1044
+ "prototype",
1045
+ "constructor"
1046
+ ].includes(key)) throw new Error(`Resource plugin contribution '${key}' collides with an existing property`);
1047
+ Object.assign(resource, api);
1048
+ }
1049
+ state.hosts.get(host).set(descriptor.name, {
1050
+ descriptor,
1051
+ status: "installed",
1052
+ api
1053
+ });
1054
+ getGlobalRegistry().touch();
1055
+ return resource ?? api;
1056
+ } catch (error) {
1057
+ for (const action of state.actions.keys()) if (!snapshots.bindings.has(action)) {
1058
+ actionBindings.delete(action);
1059
+ delete action[actionBindingKey];
1060
+ }
1061
+ restoreMap(service.actions, snapshots.actions);
1062
+ restoreMap(service.tools, snapshots.tools);
1063
+ restoreMap(service.tables, snapshots.tables);
1064
+ restoreMap(service.resources, snapshots.resources);
1065
+ restoreMap(service.preparations, snapshots.preparations);
1066
+ state.hosts = snapshots.hosts;
1067
+ state.actions = snapshots.bindings;
1068
+ state.endpoints = snapshots.endpoints;
1069
+ for (const [item, properties] of snapshots.properties) {
1070
+ for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);
1071
+ Object.defineProperties(item, properties);
1072
+ }
1073
+ getGlobalRegistry().touch();
1074
+ throw error;
1075
+ } finally {
1076
+ active = false;
1077
+ }
1078
+ }
1079
+ function restoreMap(target, snapshot) {
1080
+ target.clear();
1081
+ for (const [key, value] of snapshot) target.set(key, value);
1082
+ }
1083
+ //#endregion
1084
+ //#region src/compiler/runtime.ts
1085
+ const EMPTY_SERVICES$2 = Object.freeze({});
1086
+ const DEFAULT_REQUEST$2 = new Request("http://localhost");
1087
+ let sequence = 0;
1088
+ function isNonEmpty$1(value) {
1089
+ if (value == null) return false;
1090
+ for (const _ in value) return true;
1091
+ return false;
1092
+ }
1093
+ /** Retains Brick's existing source precedence and treatment of empty bodies. */
1094
+ function mergeInput(first, second, third) {
1095
+ const a = isNonEmpty$1(first), b = isNonEmpty$1(second), c = isNonEmpty$1(third);
1096
+ if (a && !b && !c) return first;
1097
+ if (b && !a && !c) return second;
1098
+ if (c && !a && !b) return third;
1099
+ if (a || b || c) return Object.assign({}, first, second, third);
1100
+ }
1101
+ const MAX_INPUT_DEPTH = 128;
1102
+ function inputTooDeep(value) {
1103
+ if (!value || typeof value !== "object") return false;
1104
+ const stack = [{
1105
+ node: value,
1106
+ depth: 0
1107
+ }];
1108
+ while (stack.length > 0) {
1109
+ const { node, depth } = stack.pop();
1110
+ if (depth > MAX_INPUT_DEPTH) return true;
1111
+ if (node && typeof node === "object") {
1112
+ const children = Array.isArray(node) ? node : Object.values(node);
1113
+ for (const child of children) if (child && typeof child === "object") stack.push({
1114
+ node: child,
1115
+ depth: depth + 1
1116
+ });
1117
+ }
1118
+ }
1119
+ return false;
1120
+ }
1121
+ function checkDepth(value, action) {
1122
+ if (!inputTooDeep(value)) return;
1123
+ throw new ValidationError(`Validation failed for action '${action}' input`, [{
1124
+ path: "",
1125
+ message: "Input exceeds maximum nesting depth"
1126
+ }]);
1127
+ }
1128
+ function validate(check, value, action, stage) {
1129
+ if (check.Check(value)) return;
1130
+ const errors = Array.from(check.Errors(value)).map((err) => ({
1131
+ path: err.path,
1132
+ message: err.message,
1133
+ value: err.value
1134
+ }));
1135
+ throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
1136
+ }
1137
+ function mapError(err, set, options) {
1138
+ const response = toErrorResponse(err, options);
1139
+ set.status = response.status;
1140
+ return response;
1141
+ }
1142
+ const compilerRuntime = Object.freeze({
1143
+ emptyServices: EMPTY_SERVICES$2,
1144
+ defaultRequest: DEFAULT_REQUEST$2,
1145
+ nextSequence: () => (++sequence).toString(36),
1146
+ mergeInput,
1147
+ checkDepth,
1148
+ validate,
1149
+ mapError,
1150
+ isThenable: (value) => value != null && typeof value.then === "function",
1151
+ deny: (action, user) => {
1152
+ throw new ActionExecutionError(user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${action}'`, user == null ? 401 : 403);
1153
+ }
1154
+ });
1155
+ //#endregion
1156
+ //#region src/action-handler.ts
1157
+ let _srvSeq = 0;
1158
+ const EMPTY_SERVICES$1 = Object.freeze({});
1159
+ const DEFAULT_REQUEST$1 = new Request("http://localhost");
1160
+ function isNonEmpty(obj) {
1161
+ if (obj == null) return false;
1162
+ for (const _ in obj) return true;
1163
+ return false;
1164
+ }
1165
+ /**
1166
+ * Work out, once at startup, everything an action's route needs to answer a
1167
+ * request: where its input comes from (body, query, or path), the validators,
1168
+ * the authorization and execute functions, and its logger. Low level: `brick()`
1169
+ * does this for every route.
1170
+ *
1171
+ * @param service - The service the action belongs to.
1172
+ * @param action - The action.
1173
+ * @param routePath - The route's path.
1174
+ * @param method - The HTTP method (POST by default).
1175
+ * @returns The plan `executeCompiledRoute` runs.
1176
+ */
1177
+ function compileRoutePlan(service, action, routePath, method) {
1178
+ const actionName = action.name;
1179
+ const serviceName = service.name;
1180
+ const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
1181
+ const inputSchema = action.config?.input;
1182
+ const outputSchema = action.config?.output;
1183
+ const hasInput = Boolean(inputSchema);
1184
+ const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
1185
+ const runtimeOutputSchema = action.outputValidationSchema ?? outputSchema;
1186
+ const outputChecker = runtimeOutputSchema ? getCompiledCheck(runtimeOutputSchema) : void 0;
1187
+ let coercions;
1188
+ if (inputSchema && typeof inputSchema.properties === "object") {
1189
+ const list = [];
1190
+ for (const [key, prop] of Object.entries(inputSchema.properties)) {
1191
+ const type = prop?.type;
1192
+ if (type === "number" || type === "integer") list.push({
1193
+ key,
1194
+ isNumber: true,
1195
+ isBoolean: false
1196
+ });
1197
+ else if (type === "boolean") list.push({
1198
+ key,
1199
+ isNumber: false,
1200
+ isBoolean: true
1201
+ });
1202
+ else if (type === "array") list.push({
1203
+ key,
1204
+ isNumber: false,
1205
+ isBoolean: false,
1206
+ isArray: true
1207
+ });
1208
+ }
1209
+ if (list.length > 0) coercions = list;
1210
+ }
1211
+ const contextHook = service.options?.context;
1212
+ const hasContextHook = typeof contextHook === "function";
1213
+ const authorize = action.config?.authorize;
1214
+ const hasAuthorize = typeof authorize === "function";
1215
+ const execute = action.config?.execute;
1216
+ const logger = createLogger(`[${serviceName}:${actionName}]`);
1217
+ const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
1218
+ const cachedDb = service.getDb();
1219
+ return {
1220
+ service,
1221
+ action,
1222
+ actionName,
1223
+ serviceName,
1224
+ routePath,
1225
+ method,
1226
+ isGetLike,
1227
+ hasInput,
1228
+ hasContextHook,
1229
+ contextHook,
1230
+ hasAuthorize,
1231
+ authorize,
1232
+ execute,
1233
+ inputChecker,
1234
+ outputChecker,
1235
+ coercions,
1236
+ logger,
1237
+ errorBuilder,
1238
+ cachedDb
1239
+ };
1240
+ }
1241
+ /**
1242
+ * Answer one request for a compiled route: read the input, run the action, and
1243
+ * return its output or the error response, with the `x-trace-id` and
1244
+ * `x-request-id` headers set. Low level: `brick()` mounts this for every route.
1245
+ *
1246
+ * @param plan - From `compileRoutePlan`.
1247
+ * @param elysiaCtx - The Elysia request context: `params`, `body`, `query`,
1248
+ * `headers`, `request`, and `set`.
1249
+ * @returns The action's output, or an error envelope with the status set on `set`.
1250
+ */
1251
+ async function executeCompiledRoute(plan, elysiaCtx) {
1252
+ const { params, body, query, headers, request, set } = elysiaCtx;
1253
+ const seq = (++_srvSeq).toString(36);
1254
+ const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
1255
+ const requestId = headers && headers["x-request-id"] || `req_${seq}`;
1256
+ if (set?.headers) {
1257
+ set.headers["x-trace-id"] = traceId;
1258
+ set.headers["x-request-id"] = requestId;
1259
+ }
1260
+ let input;
1261
+ if (plan.hasInput) {
1262
+ let coercedQuery = query;
1263
+ if (query && plan.coercions && plan.coercions.length > 0) {
1264
+ coercedQuery = { ...query };
1265
+ for (let i = 0; i < plan.coercions.length; i++) {
1266
+ const c = plan.coercions[i];
1267
+ const val = query[c.key];
1268
+ if (val !== void 0) {
1269
+ if (c.isNumber) {
1270
+ const num = Number(val);
1271
+ if (!isNaN(num)) coercedQuery[c.key] = num;
1272
+ } else if (c.isArray) {
1273
+ const values = request ? new URL(request.url).searchParams.getAll(c.key) : [];
1274
+ coercedQuery[c.key] = values.length ? values : Array.isArray(val) ? val : [val];
1275
+ } else if (c.isBoolean) {
1276
+ if (val === "true" || val === "1") coercedQuery[c.key] = true;
1277
+ else if (val === "false" || val === "0") coercedQuery[c.key] = false;
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+ const hasP = isNonEmpty(params);
1283
+ const hasB = isNonEmpty(body);
1284
+ const hasQ = isNonEmpty(coercedQuery);
1285
+ if (plan.isGetLike) {
1286
+ if (hasQ && !hasP && !hasB) input = coercedQuery;
1287
+ else if (hasP && !hasQ && !hasB) input = params;
1288
+ else if (hasB && !hasP && !hasQ) input = body;
1289
+ else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, params, body);
1290
+ } else if (hasB && !hasP && !hasQ) input = body;
1291
+ else if (hasP && !hasB && !hasQ) input = params;
1292
+ else if (hasQ && !hasP && !hasB) input = coercedQuery;
1293
+ else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
1294
+ }
1295
+ const ctx = {
1296
+ request: request instanceof Request ? request : DEFAULT_REQUEST$1,
1297
+ traceId,
1298
+ requestId,
1299
+ db: plan.cachedDb ?? plan.service.getDb(),
1300
+ logger: plan.logger,
1301
+ services: EMPTY_SERVICES$1,
1302
+ metadata: { headers },
1303
+ _resolved: true
1304
+ };
1305
+ try {
1306
+ if (plan.hasContextHook) {
1307
+ const extra = plan.contextHook(ctx);
1308
+ const resolved = extra instanceof Promise ? await extra : extra;
1309
+ if (resolved) Object.assign(ctx, resolved);
1310
+ }
1311
+ if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
1312
+ if (plan.hasInput && plan.inputChecker) {
1313
+ if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
1314
+ path: "",
1315
+ message: "Input exceeds maximum nesting depth"
1316
+ }]);
1317
+ if (!plan.inputChecker.Check(input)) {
1318
+ const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
1319
+ path: err.path,
1320
+ message: err.message,
1321
+ value: err.value
1322
+ }));
1323
+ throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
1324
+ }
1325
+ }
1326
+ if (plan.hasAuthorize) {
1327
+ const authRes = plan.authorize({
1328
+ ctx,
1329
+ input,
1330
+ user: ctx.user
1331
+ });
1332
+ if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError(ctx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${plan.actionName}'`, ctx.user == null ? 401 : 403);
1333
+ }
1334
+ const execRes = plan.execute({
1335
+ input,
1336
+ ctx,
1337
+ error: plan.errorBuilder
1338
+ });
1339
+ const result = execRes instanceof Promise ? await execRes : execRes;
1340
+ if (plan.outputChecker) {
1341
+ if (!plan.outputChecker.Check(result)) {
1342
+ const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
1343
+ path: err.path,
1344
+ message: err.message,
1345
+ value: err.value
1346
+ }));
1347
+ throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
1348
+ }
1349
+ }
1350
+ return result;
1351
+ } catch (err) {
1352
+ const response = toErrorResponse(err, {
1353
+ logger: ctx.logger,
1354
+ requestId
1355
+ });
1356
+ set.status = response.status;
1357
+ return response;
1358
+ }
1359
+ }
1360
+ /**
1361
+ * An Elysia handler for one action: `compileRoutePlan` and
1362
+ * `executeCompiledRoute` together. Use it to mount an action on your own
1363
+ * Elysia app; `brick()` does it for you.
1364
+ *
1365
+ * @param service - The service the action belongs to.
1366
+ * @param action - The action.
1367
+ * @param routePath - The route's path.
1368
+ * @param method - The HTTP method (POST by default).
1369
+ * @returns A function from the Elysia context to the response.
1370
+ */
1371
+ function createActionHandler(service, action, routePath, method) {
1372
+ const plan = compileRoutePlan(service, action, routePath, method);
1373
+ return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
1374
+ }
1375
+ //#endregion
1376
+ //#region src/compiler/handler.ts
1377
+ function coerceQueryValue(value, type, request, key) {
1378
+ if (type === "number" && value !== void 0) {
1379
+ const number = Number(value);
1380
+ return Number.isNaN(number) ? value : number;
1381
+ }
1382
+ if (type === "array") {
1383
+ const values = request ? new URL(request.url).searchParams.getAll(key) : [];
1384
+ return values.length ? values : Array.isArray(value) ? value : [value];
1385
+ }
1386
+ if (type === "boolean") {
1387
+ if (value === "true" || value === "1") return true;
1388
+ if (value === "false" || value === "0") return false;
1389
+ }
1390
+ return value;
1391
+ }
1392
+ /** Bind route metadata with ordinary closures; emitted factories remain build-only. */
1393
+ function createHandlerFactory(route) {
1394
+ return (binding, runtime) => {
1395
+ const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
1396
+ const readLike = route.inputPrecedence[0] === "query";
1397
+ const objectInput = binding.action.config.input?.type === "object";
1398
+ const readInput = route.input ? ({ params, body, query, request }) => {
1399
+ let coercedQuery = query;
1400
+ if (query && route.coercions.length) {
1401
+ coercedQuery = { ...query };
1402
+ for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
1403
+ }
1404
+ let input = readLike ? runtime.mergeInput(coercedQuery, params, body) : runtime.mergeInput(params, body, coercedQuery);
1405
+ if (objectInput) input ??= {};
1406
+ return input;
1407
+ } : () => void 0;
1408
+ const validateInput = (input) => {
1409
+ if (inputChecker) {
1410
+ runtime.checkDepth(input, route.action);
1411
+ runtime.validate(inputChecker, input, route.action, "input");
1412
+ }
1413
+ };
1414
+ const validateOutput = (result) => {
1415
+ if (route.output && outputChecker) runtime.validate(outputChecker, result, route.action, "output");
1416
+ return result;
1417
+ };
1418
+ const createContext = ({ headers, request, set }) => {
1419
+ const seq = runtime.nextSequence();
1420
+ const traceId = headers?.["x-trace-id"] || "tr_" + seq;
1421
+ const requestId = headers?.["x-request-id"] || "req_" + seq;
1422
+ if (set?.headers) {
1423
+ set.headers["x-trace-id"] = traceId;
1424
+ set.headers["x-request-id"] = requestId;
1425
+ }
1426
+ return {
1427
+ request: request instanceof Request ? request : runtime.defaultRequest,
1428
+ traceId,
1429
+ requestId,
1430
+ db: cachedDb ?? service.getDb(),
1431
+ logger,
1432
+ services: runtime.emptyServices,
1433
+ metadata: { headers },
1434
+ _resolved: true
1435
+ };
1436
+ };
1437
+ if (contextHook || authorize) return async function brickAction(context) {
1438
+ const input = readInput(context);
1439
+ const ctx = createContext(context);
1440
+ try {
1441
+ if (contextHook) {
1442
+ const extra = await contextHook(ctx);
1443
+ if (extra) Object.assign(ctx, extra);
1444
+ }
1445
+ validateInput(input);
1446
+ if (authorize && !await authorize({
1447
+ ctx,
1448
+ input,
1449
+ user: ctx.user
1450
+ })) runtime.deny(route.action, ctx.user);
1451
+ return validateOutput(await execute({
1452
+ input,
1453
+ ctx,
1454
+ error: errorBuilder
1455
+ }));
1456
+ } catch (err) {
1457
+ return runtime.mapError(err, context.set, ctx);
1458
+ }
1459
+ };
1460
+ return function brickAction(context) {
1461
+ const input = readInput(context);
1462
+ const ctx = createContext(context);
1463
+ try {
1464
+ validateInput(input);
1465
+ const result = execute({
1466
+ input,
1467
+ ctx,
1468
+ error: errorBuilder
1469
+ });
1470
+ if (runtime.isThenable(result)) return Promise.resolve(result).then(validateOutput).catch((err) => runtime.mapError(err, context.set, ctx));
1471
+ return validateOutput(result);
1472
+ } catch (err) {
1473
+ return runtime.mapError(err, context.set, ctx);
1474
+ }
1475
+ };
1476
+ };
1477
+ }
1478
+ //#endregion
1479
+ //#region src/app-entry.ts
1480
+ /**
1481
+ * Whether a value is an application made by `brick()`. It checks for the
1482
+ * methods and `definition` a `BrickApp` has, so it also recognizes one built by
1483
+ * another copy of the package.
1484
+ *
1485
+ * @param app - Anything, such as the default export of an entry file.
1486
+ * @returns `true` for a `BrickApp`, narrowing its type.
1487
+ */
1488
+ function isBrickApp(app) {
1489
+ if (!app || typeof app !== "object") return false;
1490
+ return "endpoint" in app && typeof app.endpoint === "function" && "fetch" in app && typeof app.fetch === "function" && "listen" in app && typeof app.listen === "function" && "definition" in app && !!app.definition && typeof app.definition === "object" && "services" in app.definition && Array.isArray(app.definition.services) && "prefix" in app.definition && typeof app.definition.prefix === "string";
1491
+ }
1492
+ /**
1493
+ * Check that a module's default export is an application ready to be served,
1494
+ * for tools that load an entry file.
1495
+ *
1496
+ * @param app - The default export of an entry file.
1497
+ * @returns The app.
1498
+ * @throws When it is not a `BrickApp`, or it already called `.listen()`: the
1499
+ * entry must only build the app, and leave listening to the server bootstrap.
1500
+ */
1501
+ function requireBrickApp(app) {
1502
+ if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
1503
+ if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
1504
+ return app;
1505
+ }
1506
+ //#endregion
1507
+ //#region src/compiler.ts
1508
+ const buildBindings = /* @__PURE__ */ new Map();
1509
+ function applicationKey(services, prefix = "/api") {
1510
+ return JSON.stringify([prefix, services.map((service) => service.name)]);
1511
+ }
1512
+ /** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
1513
+ async function loadCompiledBrickApp(load, ir, bind) {
1514
+ const key = JSON.stringify([ir.prefix, ir.services]);
1515
+ if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
1516
+ buildBindings.set(key, bind);
1517
+ try {
1518
+ const app = requireBrickApp((await load()).default);
1519
+ if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
1520
+ return app;
1521
+ } finally {
1522
+ buildBindings.delete(key);
1523
+ }
1524
+ }
1525
+ function bindAnalyzed(ir, bindings, factories) {
1526
+ if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
1527
+ const routes = ir.routes.map((route, index) => {
1528
+ const { service, action } = bindings[index];
1529
+ const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
1530
+ const handler = factories[index](plan, compilerRuntime);
1531
+ return Object.freeze({
1532
+ ir: route,
1533
+ handler
1534
+ });
1535
+ });
1536
+ return Object.freeze({
1537
+ ir: freezeIR(ir),
1538
+ routes: Object.freeze(routes)
1539
+ });
1540
+ }
1541
+ /** Startup compiler: analyzes once, then binds live callbacks. */
1542
+ function compileBrickApplication(options) {
1543
+ const bind = buildBindings.get(applicationKey(options.services, options.prefix));
1544
+ if (bind && options.mode !== "generic") return bind(options.services);
1545
+ const { ir, bindings } = analyzeApplication(options.services, options.prefix);
1546
+ const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(createHandlerFactory);
1547
+ if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
1548
+ return bindAnalyzed(ir, bindings, factories);
1549
+ }
1550
+ /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
1551
+ function bindCompiledApplication(ir, services, factories) {
1552
+ if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
1553
+ const analyzed = analyzeApplication(services, ir.prefix);
1554
+ if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
1555
+ for (const service of services) service.prepareContributions();
1556
+ return bindAnalyzed(ir, analyzed.bindings, factories);
1557
+ }
1558
+ //#endregion
1559
+ //#region src/access.ts
1560
+ /**
1561
+ * Cross-copy access metadata protocol. CRUD enforces its access policy
1562
+ * inside `execute`, so `config.authorize` is absent and introspection
1563
+ * can't see it. The plugin stamps each action under this process-global
1564
+ * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
1565
+ * the binding survives a second copy of core (bundler SSR, Vitest),
1566
+ * same as the plugin action-binding key.
1567
+ */
1568
+ const ACTION_ACCESS_KEY = Symbol.for("brickkit.action.access");
1569
+ /**
1570
+ * Record how an action is protected, for tools that cannot read it from the
1571
+ * configuration: plugins such as `crud` enforce access inside `execute`, so the
1572
+ * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
1573
+ * read what is recorded here.
1574
+ *
1575
+ * @param action - The action to describe.
1576
+ * @param info - Whether it checks authorization and whether it scopes queries,
1577
+ * and the resulting policy.
1578
+ */
1579
+ function setActionAccess(action, info) {
1580
+ action[ACTION_ACCESS_KEY] = {
1581
+ hasAuthorize: info.hasAuthorize,
1582
+ hasScope: info.hasScope,
1583
+ policy: info.policy
1584
+ };
1585
+ }
1586
+ /**
1587
+ * How an action is protected: `"public"` when nothing checks the caller,
1588
+ * `"authorized"` when an `authorize` does, and `"scoped"` when the action also
1589
+ * limits what rows the caller can reach. It reads what a plugin recorded with
1590
+ * `setActionAccess`, else the action's own `authorize`, and keeps the policy
1591
+ * consistent with the flags.
1592
+ *
1593
+ * @param action - An action, or any object a plugin described.
1594
+ * @returns `hasAuthorize`, `hasScope`, and `policy`.
1595
+ */
1596
+ function getActionAccess(action) {
1597
+ const meta = action[ACTION_ACCESS_KEY];
1598
+ const configAuthorize = Boolean(action?.config && typeof action.config === "object" && "authorize" in action.config && typeof action.config.authorize === "function");
1599
+ if (!meta) return {
1600
+ hasAuthorize: configAuthorize,
1601
+ hasScope: false,
1602
+ policy: configAuthorize ? "authorized" : "public"
1603
+ };
1604
+ const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
1605
+ const hasScope = Boolean(meta.hasScope);
1606
+ let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
1607
+ if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
1608
+ else if (policy !== "public" && !hasAuthorize) policy = "public";
1609
+ else if (policy === "scoped" && !hasScope) policy = "authorized";
1610
+ return {
1611
+ hasAuthorize,
1612
+ hasScope,
1613
+ policy
1614
+ };
1615
+ }
1616
+ //#endregion
1617
+ //#region src/openapi.ts
1618
+ function isAnchor(node) {
1619
+ return typeof node === "object" && node !== null && typeof node.$id === "string";
1620
+ }
1621
+ function isBareRef(node) {
1622
+ return typeof node === "object" && node !== null && typeof node.$ref === "string" && !node.$ref.startsWith("#");
1623
+ }
1624
+ function toComponentKey(id) {
1625
+ return id.replace(/[^A-Za-z0-9.\-_]+/g, "_");
1626
+ }
1627
+ /**
1628
+ * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors
1629
+ * (`{ $id: "T0", ..., { $ref: "T0" } }`). OpenAPI interprets a bare `$ref`
1630
+ * as an external file reference, so downstream tooling tries to load a
1631
+ * file named `T0` and fails. Hoist every anchored subschema into
1632
+ * `#/components/schemas/` and rewrite the refs to local pointers.
1633
+ * First definition wins when one `$id` is declared twice.
1634
+ */
1635
+ function hoistAnchoredSchemas(spec) {
1636
+ const anchored = /* @__PURE__ */ new Map();
1637
+ const conflicts = [];
1638
+ const collect = (node) => {
1639
+ if (Array.isArray(node)) return node.map(collect);
1640
+ if (typeof node !== "object" || node === null) return node;
1641
+ if (isAnchor(node)) {
1642
+ const id = node.$id;
1643
+ const { $id: _dropped, ...rest } = node;
1644
+ const collected = collect(rest);
1645
+ if (anchored.has(id)) {
1646
+ if (JSON.stringify(anchored.get(id)) !== JSON.stringify(collected)) conflicts.push(id);
1647
+ } else anchored.set(id, collected);
1648
+ return { $ref: `#/components/schemas/${toComponentKey(id)}` };
1649
+ }
1650
+ for (const key of Object.keys(node)) node[key] = collect(node[key]);
1651
+ return node;
1652
+ };
1653
+ const rewrite = (node) => {
1654
+ if (Array.isArray(node)) {
1655
+ for (const child of node) rewrite(child);
1656
+ return;
1657
+ }
1658
+ if (typeof node !== "object" || node === null) return;
1659
+ if (isBareRef(node)) node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;
1660
+ for (const key of Object.keys(node)) rewrite(node[key]);
1661
+ };
1662
+ collect(spec);
1663
+ const components = spec.components ??= {};
1664
+ const schemas = components.schemas ??= {};
1665
+ for (const [id, schema] of anchored) schemas[toComponentKey(id)] = schema;
1666
+ rewrite(spec);
1667
+ return [...anchored.keys()];
1668
+ }
1669
+ /**
1670
+ * Build the OpenAPI 3.1 document for the services: one path per action route,
1671
+ * with request and response schemas from the actions' TypeBox schemas, their
1672
+ * declared errors, tags by service, and a bearer security scheme where any
1673
+ * action needs authorization.
1674
+ *
1675
+ * `brick()` calls this for `/openapi.json`; call it yourself to write the
1676
+ * document to a file or feed another tool.
1677
+ *
1678
+ * @param options - `title`, `version`, and `description` for the `info` block,
1679
+ * `prefix` (default `/api`), and the `services` or `registry` to describe
1680
+ * (the global registry by default).
1681
+ * @returns The document as a plain object.
1682
+ */
1683
+ function generateOpenApiSpec(options = {}) {
1684
+ const title = options.title ?? "Brick-TS API Mesh";
1685
+ const version = options.version ?? "1.0.0";
1686
+ const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
1687
+ const prefix = options.prefix ?? "/api";
1688
+ const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
1689
+ const paths = {};
1690
+ const tagsSet = /* @__PURE__ */ new Set();
1691
+ let hasAnyAuthorizedAction = false;
1692
+ for (const service of services) {
1693
+ tagsSet.add(service.name);
1694
+ for (const action of service.listActions()) {
1695
+ const pluginRoute = getPluginActionRoute(action, prefix);
1696
+ if (pluginRoute === false) continue;
1697
+ const routePath = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
1698
+ const method = (pluginRoute?.method ?? action.config.method ?? "POST").toLowerCase();
1699
+ const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
1700
+ const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
1701
+ if (!paths[actionPath]) paths[actionPath] = {};
1702
+ if (paths[actionPath][method]) continue;
1703
+ const hasAuth = getActionAccess(action).hasAuthorize;
1704
+ if (hasAuth) hasAnyAuthorizedAction = true;
1705
+ const responses = {};
1706
+ if (action.config.output) responses["200"] = {
1707
+ description: "Successful response",
1708
+ content: { "application/json": { schema: action.config.output } }
1709
+ };
1710
+ else responses["200"] = { description: "Successful response" };
1711
+ const errorAlternatives = /* @__PURE__ */ new Set();
1712
+ const addError = (code, status, message) => {
1713
+ const key = `${status}:${code}`;
1714
+ if (errorAlternatives.has(key)) return;
1715
+ errorAlternatives.add(key);
1716
+ const schema = { allOf: [{ $ref: "#/components/schemas/ErrorEnvelope" }, {
1717
+ type: "object",
1718
+ properties: {
1719
+ code: { const: code },
1720
+ status: { const: status }
1721
+ }
1722
+ }] };
1723
+ const existing = responses[String(status)];
1724
+ if (existing) {
1725
+ existing.description += "; " + message;
1726
+ existing.content["application/json"].schema.oneOf.push(schema);
1727
+ } else responses[String(status)] = {
1728
+ description: message,
1729
+ content: { "application/json": { schema: { oneOf: [schema] } } }
1730
+ };
1731
+ };
1732
+ if (action.config.input) addError("VALIDATION_FAILED", 400, "Validation error");
1733
+ if (hasAuth) {
1734
+ addError("UNAUTHORIZED", 401, "Authentication required");
1735
+ addError("FORBIDDEN", 403, "Access denied");
1736
+ }
1737
+ if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
1738
+ const def = errorDef;
1739
+ addError(code, def.status || 400, def.message || code);
1740
+ }
1741
+ addError("INTERNAL_SERVER_ERROR", 500, "Internal server error");
1742
+ if (action.config.output) addError("VALIDATION_FAILED", 500, "Output validation error");
1743
+ const operation = {
1744
+ operationId: `${service.name}_${action.name}_${method}`,
1745
+ summary: `${service.name}.${action.name}`,
1746
+ description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
1747
+ tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
1748
+ ...action.plugin ? { "x-brick-plugin": action.plugin } : {},
1749
+ ...action.resource ? { "x-brick-resource": action.resource } : {},
1750
+ responses
1751
+ };
1752
+ const inputSchema = action.config.input;
1753
+ const properties = inputSchema?.properties ?? {};
1754
+ const parameters = [...new Set(pathParams)].map((key) => ({
1755
+ name: key,
1756
+ in: "path",
1757
+ required: true,
1758
+ schema: properties[key] ?? { type: "string" }
1759
+ }));
1760
+ if (method === "get" || method === "delete") for (const [key, schema] of Object.entries(properties)) {
1761
+ if (pathParams.includes(key)) continue;
1762
+ parameters.push({
1763
+ name: key,
1764
+ in: "query",
1765
+ required: inputSchema?.required?.includes(key) ?? false,
1766
+ schema
1767
+ });
1768
+ }
1769
+ else if (inputSchema) operation.requestBody = {
1770
+ required: true,
1771
+ content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
1772
+ ...inputSchema,
1773
+ properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
1774
+ required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
1775
+ } : inputSchema } }
1776
+ };
1777
+ if (parameters.length) operation.parameters = parameters;
1778
+ if (hasAuth) operation.security = [{ bearerAuth: [] }];
1779
+ paths[actionPath][method] = operation;
1780
+ }
1781
+ }
1782
+ const spec = {
1783
+ openapi: "3.1.0",
1784
+ info: {
1785
+ title,
1786
+ version,
1787
+ description
1788
+ },
1789
+ paths,
1790
+ tags: Array.from(tagsSet).map((name) => ({
1791
+ name,
1792
+ description: `Actions exposed by '${name}' service`
1793
+ }))
1794
+ };
1795
+ spec.components = { schemas: { ErrorEnvelope: {
1796
+ type: "object",
1797
+ required: [
1798
+ "name",
1799
+ "code",
1800
+ "message",
1801
+ "status",
1802
+ "requestId"
1803
+ ],
1804
+ properties: {
1805
+ name: { type: "string" },
1806
+ code: { type: "string" },
1807
+ message: { type: "string" },
1808
+ status: { type: "integer" },
1809
+ requestId: { type: "string" },
1810
+ details: {},
1811
+ errors: {
1812
+ type: "array",
1813
+ items: {
1814
+ type: "object",
1815
+ required: ["path", "message"],
1816
+ properties: {
1817
+ path: { type: "string" },
1818
+ message: { type: "string" },
1819
+ value: {}
1820
+ }
1821
+ }
1822
+ }
1823
+ }
1824
+ } } };
1825
+ if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
1826
+ type: "http",
1827
+ scheme: "bearer",
1828
+ bearerFormat: "JWT",
1829
+ description: "Enter your Bearer authentication token"
1830
+ } } });
1831
+ const document = JSON.parse(JSON.stringify(spec));
1832
+ hoistAnchoredSchemas(document);
1833
+ return document;
1834
+ }
1835
+ //#endregion
1836
+ //#region src/secrets.ts
1837
+ /** Default source: `process.env` (Bun loads `.env` into it automatically). */
1838
+ const envSource = { get: (name) => process.env[name] };
1839
+ const registry = /* @__PURE__ */ new Map();
1840
+ const overrides = /* @__PURE__ */ new Map();
1841
+ var SecretRef = class {
1842
+ name;
1843
+ options;
1844
+ transformFn;
1845
+ validators = [];
1846
+ constructor(name, options = {}) {
1847
+ this.name = name;
1848
+ this.options = options;
1849
+ }
1850
+ /** True when a default was declared (i.e. the secret is optional). */
1851
+ get hasDefault() {
1852
+ return this.options.default !== void 0;
1853
+ }
1854
+ /** Fallback used when the source has no value. Makes the secret optional. */
1855
+ default(value) {
1856
+ this.options.default = value;
1857
+ return this;
1858
+ }
1859
+ /**
1860
+ * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
1861
+ * Runs before validators; a throwing transform fails resolution.
1862
+ */
1863
+ transform(fn) {
1864
+ this.transformFn = fn;
1865
+ return this;
1866
+ }
1867
+ /** Run a custom check on the (transformed) value at every resolution. */
1868
+ validate(fn) {
1869
+ this.validators.push(fn);
1870
+ return this;
1871
+ }
1872
+ /** Shorthand validator: value must parse as a URL. String refs only. */
1873
+ url() {
1874
+ this.validators.push((v) => {
1875
+ try {
1876
+ new URL(v);
1877
+ } catch {
1878
+ return "must be a valid URL";
1879
+ }
1880
+ });
1881
+ return this;
1882
+ }
1883
+ resolveRaw(source) {
1884
+ if (overrides.has(this.name)) {
1885
+ const v = overrides.get(this.name);
1886
+ if (v !== void 0) return v;
1887
+ }
1888
+ return source.get(this.name) ?? this.options.default;
1889
+ }
1890
+ coerce(raw) {
1891
+ let value;
1892
+ if (this.transformFn) try {
1893
+ value = this.transformFn(raw);
1894
+ } catch (err) {
1895
+ throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
1896
+ }
1897
+ else value = raw;
1898
+ for (const fn of this.validators) {
1899
+ let result;
1900
+ try {
1901
+ result = fn(value);
1902
+ } catch (err) {
1903
+ throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
1904
+ }
1905
+ if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
1906
+ if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
1907
+ }
1908
+ return value;
1909
+ }
1910
+ /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
1911
+ value(source = envSource) {
1912
+ const raw = this.resolveRaw(source);
1913
+ if (raw === void 0) return void 0;
1914
+ return this.coerce(raw);
1915
+ }
1916
+ /** Resolved value, or throws naming the missing/invalid secret. */
1917
+ require(source = envSource) {
1918
+ const raw = this.resolveRaw(source);
1919
+ if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
1920
+ return this.coerce(raw);
1921
+ }
1922
+ /** True when a value would resolve (override, source, or default). */
1923
+ isSet(source = envSource) {
1924
+ return this.resolveRaw(source) !== void 0;
1925
+ }
1926
+ };
1927
+ /**
1928
+ * Declare a secret. Idempotent: re-declaring the same name returns the
1929
+ * original ref (first declaration wins) so module re-evaluation is safe.
1930
+ */
1931
+ function secret(name, options = {}) {
1932
+ const existing = registry.get(name);
1933
+ if (existing) return existing;
1934
+ const ref = new SecretRef(name, options);
1935
+ registry.set(name, ref);
1936
+ return ref;
1937
+ }
1938
+ /**
1939
+ * Validate every registered secret at boot. Throws a single error listing
1940
+ * all missing required secrets. Returns the resolved values.
1941
+ */
1942
+ function resolveSecrets(opts = {}) {
1943
+ const source = opts.source ?? envSource;
1944
+ const missing = [];
1945
+ const resolved = {};
1946
+ for (const ref of registry.values()) {
1947
+ const v = ref.value(source);
1948
+ if (v === void 0) missing.push(ref.name);
1949
+ else resolved[ref.name] = v;
1950
+ }
1951
+ if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
1952
+ return resolved;
1953
+ }
1954
+ /** Metadata for introspection (values never exposed — future dashboard use). */
1955
+ function listSecrets(opts = {}) {
1956
+ const source = opts.source ?? envSource;
1957
+ return [...registry.values()].map((ref) => ({
1958
+ hasDefault: ref.hasDefault,
1959
+ isSet: ref.isSet(source),
1960
+ name: ref.name
1961
+ }));
1962
+ }
1963
+ /** Test/session override for one secret (`undefined` clears the override). */
1964
+ function overrideSecret(name, value) {
1965
+ overrides.set(name, value);
1966
+ }
1967
+ /** Bulk overrides (test/session scoped). */
1968
+ function overrideSecrets(values) {
1969
+ for (const [name, value] of Object.entries(values)) overrides.set(name, value);
1970
+ }
1971
+ /** Clear registry and overrides. Test-only. */
1972
+ function resetSecrets() {
1973
+ registry.clear();
1974
+ overrides.clear();
1975
+ }
1976
+ //#endregion
1977
+ //#region src/request-logger.ts
1978
+ function formatLog(method, path, status, elapsedMs) {
1979
+ return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;
1980
+ }
1981
+ /**
1982
+ * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError
1983
+ * while `set.status` may still hold the 200 default when onError runs).
1984
+ */
1985
+ function thrownStatus(error) {
1986
+ if (typeof error === "object" && error !== null && "status" in error) {
1987
+ const status = error.status;
1988
+ if (typeof status === "number") return status;
1989
+ }
1990
+ }
1991
+ /**
1992
+ * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
1993
+ * Timing is tracked per-Request via a WeakMap. The onError hook only logs and
1994
+ * returns undefined so existing error mapping is preserved. Logging only —
1995
+ * no CORS headers are set here.
1996
+ *
1997
+ * Hooks are registered with the "global" scope so they propagate to the
1998
+ * parent app when mounted via `app.use(...)` — Elysia scopes plain instance
1999
+ * hooks to the plugin's own routes. Timing is captured in beforeHandle
2000
+ * because request hooks are not propagated from a
2001
+ * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
2002
+ */
2003
+ function requestLoggingPlugin(opts = {}) {
2004
+ const plugin = new Elysia();
2005
+ if (!(opts.enabled ?? true)) return plugin;
2006
+ const logger = opts.logger ?? console.log;
2007
+ const startedAt = /* @__PURE__ */ new WeakMap();
2008
+ const markStarted = ({ request }) => {
2009
+ startedAt.set(request, Date.now());
2010
+ };
2011
+ const logSuccess = ({ request, set }) => {
2012
+ const start = startedAt.get(request) ?? Date.now();
2013
+ const path = new URL(request.url).pathname;
2014
+ logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
2015
+ };
2016
+ const logError = ({ request, set, error }) => {
2017
+ if (request) {
2018
+ const start = startedAt.get(request) ?? Date.now();
2019
+ const path = new URL(request.url).pathname;
2020
+ const status = thrownStatus(error) ?? set.status ?? 500;
2021
+ logger(formatLog(request.method, path, status, Date.now() - start));
2022
+ }
2023
+ };
2024
+ plugin.beforeHandle("global", markStarted);
2025
+ plugin.afterHandle("global", logSuccess);
2026
+ plugin.error("global", logError);
2027
+ return plugin;
2028
+ }
2029
+ //#endregion
2030
+ //#region src/docs.ts
2031
+ /** Renders the Scalar API reference page for the given OpenAPI URL. */
2032
+ function scalarDocsHTML(specUrl, title) {
2033
+ return `<!doctype html>
2034
+ <html>
2035
+ <head>
2036
+ <title>${title} — API Reference</title>
2037
+ <meta charset="utf-8" />
2038
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
2039
+ <link rel="icon" type="image/svg+xml" href="https://scalar.com/favicon.svg" />
2040
+ <style>
2041
+ body { margin: 0; padding: 0; height: 100vh; }
2042
+ </style>
2043
+ </head>
2044
+ <body>
2045
+ <script
2046
+ id="api-reference"
2047
+ data-url="${specUrl}"
2048
+ data-configuration='{"theme": "purple", "layout": "modern"}'
2049
+ src="https://cdn.jsdelivr.net/npm/@scalar/api-reference">
2050
+ <\/script>
2051
+ </body>
2052
+ </html>`;
2053
+ }
2054
+ /** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
2055
+ function referencePlugin(opts = {}) {
2056
+ const path = opts.path ?? "/reference";
2057
+ const title = opts.title ?? "Brick-TS API Mesh";
2058
+ const specUrl = opts.specUrl ?? "/openapi.json";
2059
+ const plugin = new Elysia();
2060
+ plugin.get(path, ({ set }) => {
2061
+ set.headers["content-type"] = "text/html; charset=utf-8";
2062
+ return scalarDocsHTML(specUrl, title);
2063
+ });
2064
+ return plugin;
2065
+ }
2066
+ /** Mounts the Scalar reference route onto an existing app. */
2067
+ function registerReferenceRoute(app, opts = {}) {
2068
+ return app.use(referencePlugin(opts));
2069
+ }
2070
+ /** Renders the Swagger UI page. */
2071
+ function swaggerDocsHTML(specUrl, title) {
2072
+ return `<!DOCTYPE html>
2073
+ <html lang="en">
2074
+ <head>
2075
+ <meta charset="UTF-8">
2076
+ <title>${title} — Swagger UI</title>
2077
+ <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
2078
+ <style>
2079
+ html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }
2080
+ *, *:before, *:after { box-sizing: inherit; }
2081
+ body { margin:0; background: #fafafa; }
2082
+ </style>
2083
+ </head>
2084
+ <body>
2085
+ <div id="swagger-ui"></div>
2086
+ <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" charset="UTF-8"><\/script>
2087
+ <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" charset="UTF-8"><\/script>
2088
+ <script>
2089
+ window.onload = function() {
2090
+ SwaggerUIBundle({
2091
+ url: "${specUrl}",
2092
+ dom_id: '#swagger-ui',
2093
+ deepLinking: true,
2094
+ presets: [
2095
+ SwaggerUIBundle.presets.apis,
2096
+ SwaggerUIStandalonePreset
2097
+ ],
2098
+ plugins: [
2099
+ SwaggerUIBundle.plugins.DownloadUrl
2100
+ ],
2101
+ layout: "StandaloneLayout"
2102
+ });
2103
+ };
2104
+ <\/script>
2105
+ </body>
2106
+ </html>`;
2107
+ }
2108
+ //#endregion
2109
+ //#region src/dashboard.ts
2110
+ const MIN_TOKEN_LENGTH = 16;
2111
+ /**
2112
+ * Check what `brick()` was given, and freeze it. The secrets sit behind a getter
2113
+ * that is not enumerable, so logging or serializing the application definition
2114
+ * does not print them.
2115
+ */
2116
+ function normalizeDashboard(options) {
2117
+ if (options === void 0) return void 0;
2118
+ const { port, host, auth, historyDays } = options;
2119
+ if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new Error(`Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`);
2120
+ if (host !== void 0 && (typeof host !== "string" || host.trim() === "")) throw new Error("Brick: dashboard host must be an address, such as '0.0.0.0'.");
2121
+ if (historyDays !== void 0 && (!Number.isInteger(historyDays) || historyDays < 0)) throw new Error(`Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`);
2122
+ const normalized = {
2123
+ ...port !== void 0 ? { port } : {},
2124
+ ...host !== void 0 ? { host: host.trim() } : {},
2125
+ ...historyDays !== void 0 ? { historyDays } : {}
2126
+ };
2127
+ if (auth !== void 0) {
2128
+ const tokens = auth.token === void 0 ? void 0 : typeof auth.token === "string" ? [auth.token] : [...auth.token];
2129
+ if (tokens?.some((token) => typeof token !== "string" || token.length < MIN_TOKEN_LENGTH)) throw new Error(`Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`);
2130
+ if (auth.authorize !== void 0 && typeof auth.authorize !== "function") throw new Error("Brick: dashboard authorize must be a function.");
2131
+ if ((tokens === void 0 || tokens.length === 0) && !auth.authorize) throw new Error("Brick: dashboard auth needs a token or an authorize function.");
2132
+ const secrets = Object.freeze({
2133
+ ...tokens ? { token: Object.freeze(tokens) } : {},
2134
+ ...auth.authorize ? { authorize: auth.authorize } : {}
2135
+ });
2136
+ Object.defineProperty(normalized, "auth", {
2137
+ enumerable: false,
2138
+ get: () => secrets
2139
+ });
2140
+ }
2141
+ return Object.freeze(normalized);
2142
+ }
2143
+ //#endregion
2144
+ //#region src/endpoints.ts
2145
+ /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
2146
+ function resolveEndpointDb(service, services) {
2147
+ if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb() ?? void 0;
2148
+ for (const svc of services) {
2149
+ const db = svc.getDb();
2150
+ if (db) return db;
2151
+ }
2152
+ }
2153
+ /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
2154
+ function createEndpointHandler(def, services) {
2155
+ const logger = createLogger(`[${`endpoint:${def.method} ${def.path}`}]`);
2156
+ return async ({ params, body, query, headers, request, set }) => {
2157
+ const traceId = headers?.["x-trace-id"] || `tr_${crypto.randomUUID()}`;
2158
+ const requestId = headers?.["x-request-id"] || `req_${crypto.randomUUID()}`;
2159
+ if (set?.headers) {
2160
+ set.headers["x-trace-id"] = traceId;
2161
+ set.headers["x-request-id"] = requestId;
2162
+ }
2163
+ const ctx = {
2164
+ body,
2165
+ db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
2166
+ headers: headers ?? {},
2167
+ logger,
2168
+ params: params ?? {},
2169
+ query: query ?? {},
2170
+ request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
2171
+ headers: new Headers(headers ?? {}),
2172
+ method: def.method
2173
+ }),
2174
+ requestId,
2175
+ set,
2176
+ traceId
2177
+ };
2178
+ try {
2179
+ return await def.handler(ctx);
2180
+ } catch (err) {
2181
+ const response = toErrorResponse(!(err instanceof ActionExecutionError || err instanceof ValidationError) && err !== null && typeof err === "object" && "status" in err && typeof err.status === "number" && Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? new ActionExecutionError("HTTP_ERROR", "message" in err && typeof err.message === "string" ? err.message : "Endpoint error", err.status, void 0, { cause: err }) : err, {
2182
+ logger: ctx.logger,
2183
+ requestId
2184
+ });
2185
+ set.status = response.status;
2186
+ return response;
2187
+ }
2188
+ };
2189
+ }
2190
+ /** `/p/:slug` → `/p/{slug}` for OpenAPI. */
2191
+ function toOpenApiPath(elysiaPath) {
2192
+ return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
2193
+ }
2194
+ /** Parameter names (`:slug`) extracted for the OpenAPI path item. */
2195
+ function pathParamNames(elysiaPath) {
2196
+ return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
2197
+ }
2198
+ /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
2199
+ function endpointPaths(defs) {
2200
+ const paths = {};
2201
+ for (const def of defs) {
2202
+ const openApiPath = toOpenApiPath(def.path);
2203
+ if (!paths[openApiPath]) paths[openApiPath] = {};
2204
+ const params = pathParamNames(def.path).map((name) => ({
2205
+ in: "path",
2206
+ name,
2207
+ required: true,
2208
+ schema: { type: "string" }
2209
+ }));
2210
+ paths[openApiPath][def.method.toLowerCase()] = {
2211
+ ...def.summary ? { summary: def.summary } : {},
2212
+ ...def.description ? { description: def.description } : {},
2213
+ ...def.tags ? { tags: def.tags } : {},
2214
+ ...params.length > 0 ? { parameters: params } : {},
2215
+ responses: { 200: { description: "Successful response" } }
2216
+ };
2217
+ }
2218
+ return paths;
2219
+ }
2220
+ //#endregion
2221
+ //#region src/server.ts
2222
+ /**
2223
+ * Create the HTTP application: an Elysia app that serves every service's
2224
+ * actions (and the tools that opt in with `http: true`) as routes, with
2225
+ * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,
2226
+ * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.
2227
+ *
2228
+ * Services come from the global registry unless `services` is given. The app
2229
+ * does not listen by itself: export it from your entry file, where `brick dev`,
2230
+ * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your
2231
+ * own server bootstrap.
2232
+ *
2233
+ * @param options - `prefix` for action routes (default `/api`), `services`,
2234
+ * `title`, `version`, and `description` for the OpenAPI document, `docs` and the
2235
+ * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
2236
+ * `telemetry`, `documentation`, and `dashboard`. See `CreateServerOptions`.
2237
+ * @returns The app, with `definition` (its services, prefix, and routes),
2238
+ * `endpoint()` to add raw routes, and `listEndpoints()` to list them.
2239
+ * @throws When a required secret is missing, or `documentation` or `dashboard`
2240
+ * is invalid.
2241
+ * @example
2242
+ * import { brick } from "@brickkit/core";
2243
+ * import { pagesService } from "./services/pages";
2244
+ *
2245
+ * export default brick({
2246
+ * services: [pagesService],
2247
+ * title: "Pages API",
2248
+ * telemetry: true,
2249
+ * });
2250
+ */
2251
+ function brick(options = {}) {
2252
+ const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
2253
+ const title = options.title ?? "Brick-TS API Mesh";
2254
+ const version = options.version ?? "1.0.0";
2255
+ const compiled = options.compiler !== false;
2256
+ const enableDocs = options.docs ?? true;
2257
+ const openApiPath = options.openApiPath ?? "/openapi.json";
2258
+ const docsPath = options.docsPath ?? "/docs";
2259
+ const swaggerPath = options.swaggerPath ?? "/swagger";
2260
+ const dashboard = normalizeDashboard(options.dashboard);
2261
+ const telemetry = options.telemetry === true || dashboard !== void 0;
2262
+ const app = new Elysia();
2263
+ if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
2264
+ app.get("/_health", () => ({
2265
+ status: "ok",
2266
+ uptime: process.uptime(),
2267
+ timestamp: Date.now()
2268
+ }));
2269
+ const requestLogging = options.requestLogging ?? true;
2270
+ if (requestLogging !== false) {
2271
+ const pluginOpts = requestLogging === true ? {} : requestLogging;
2272
+ if (pluginOpts.enabled !== false) app.use(requestLoggingPlugin(pluginOpts));
2273
+ }
2274
+ const reference = options.reference ?? false;
2275
+ const referenceOptions = typeof reference === "object" ? reference : {};
2276
+ const referencePath = reference === true ? "/reference" : referenceOptions.path;
2277
+ if (referencePath !== void 0) {
2278
+ const settings = {
2279
+ path: referencePath,
2280
+ title: referenceOptions.title ?? title,
2281
+ specUrl: referenceOptions.specUrl ?? openApiPath
2282
+ };
2283
+ if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
2284
+ else registerReferenceRoute(app, settings);
2285
+ }
2286
+ const services = options.services ?? getGlobalRegistry().list();
2287
+ if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
2288
+ for (const service of services) if (typeof service.build === "function") service.build();
2289
+ const endpointDefs = [];
2290
+ let endpointRevision = 0;
2291
+ const buildSpec = () => {
2292
+ const spec = generateOpenApiSpec({
2293
+ title,
2294
+ version,
2295
+ description: options.description,
2296
+ prefix,
2297
+ services
2298
+ });
2299
+ const paths = { ...spec.paths };
2300
+ for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
2301
+ ...paths[path],
2302
+ ...operations
2303
+ };
2304
+ return {
2305
+ ...spec,
2306
+ paths
2307
+ };
2308
+ };
2309
+ if (enableDocs) {
2310
+ app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
2311
+ if (compiled) {
2312
+ app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
2313
+ app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
2314
+ } else {
2315
+ app.get(docsPath, ({ set }) => {
2316
+ set.headers["content-type"] = "text/html; charset=utf-8";
2317
+ return scalarDocsHTML(openApiPath, title);
2318
+ });
2319
+ app.get(swaggerPath, ({ set }) => {
2320
+ set.headers["content-type"] = "text/html; charset=utf-8";
2321
+ return swaggerDocsHTML(openApiPath, title);
2322
+ });
2323
+ }
2324
+ }
2325
+ const registeredRoutes = /* @__PURE__ */ new Map();
2326
+ const routeKey = (method, path) => `${method} ${path.replace(/:[^/]+/g, ":param")}`;
2327
+ registeredRoutes.set(routeKey("GET", "/_health"), false);
2328
+ registeredRoutes.set(routeKey("GET", "/_brick/services"), false);
2329
+ if (enableDocs) for (const path of [
2330
+ openApiPath,
2331
+ docsPath,
2332
+ swaggerPath
2333
+ ]) registeredRoutes.set(routeKey("GET", path), false);
2334
+ if (referencePath !== void 0) registeredRoutes.set(routeKey("GET", referencePath), false);
2335
+ const mountRoute = (method, path, handler, plugin = false) => {
2336
+ const key = routeKey(method, path);
2337
+ if (registeredRoutes.has(key)) {
2338
+ if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
2339
+ return false;
2340
+ }
2341
+ switch (method) {
2342
+ case "GET":
2343
+ app.get(path, handler);
2344
+ break;
2345
+ case "POST":
2346
+ app.post(path, handler);
2347
+ break;
2348
+ case "PUT":
2349
+ app.put(path, handler);
2350
+ break;
2351
+ case "PATCH":
2352
+ app.patch(path, handler);
2353
+ break;
2354
+ case "DELETE": app.delete(path, handler);
2355
+ }
2356
+ registeredRoutes.set(key, plugin);
2357
+ return true;
2358
+ };
2359
+ const mountEndpoint = (def, plugin = false) => {
2360
+ const handler = createEndpointHandler(def, services);
2361
+ mountRoute(def.method, def.path, telemetry ? (context) => traceHttpRequest(context, def.method, def.path, () => handler(context)) : handler, plugin);
2362
+ endpointDefs.push(def);
2363
+ endpointRevision++;
2364
+ };
2365
+ for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
2366
+ for (const def of options.endpoints ?? []) mountEndpoint(def);
2367
+ const brickApp = app;
2368
+ brickApp.endpoint = (def) => {
2369
+ mountEndpoint(def);
2370
+ };
2371
+ brickApp.listEndpoints = () => [...endpointDefs];
2372
+ brickApp.referenceDocuments = async () => {
2373
+ const documents = enableDocs ? [{
2374
+ title,
2375
+ document: buildSpec()
2376
+ }] : [];
2377
+ for (const extra of referenceOptions.documents ?? []) try {
2378
+ const document = typeof extra.document === "function" ? await extra.document() : extra.document;
2379
+ documents.push({
2380
+ title: extra.title,
2381
+ document
2382
+ });
2383
+ } catch (error) {
2384
+ console.warn(`[Brick-TS] Skipping the "${extra.title}" API document: ${error instanceof Error ? error.message : String(error)}`);
2385
+ }
2386
+ return documents;
2387
+ };
2388
+ const compilation = options.compilation ?? compileBrickApplication({
2389
+ services,
2390
+ prefix,
2391
+ mode: options.compiler === false ? "generic" : "specialized"
2392
+ });
2393
+ if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
2394
+ const mountedRoutes = [];
2395
+ for (const route of compilation.routes) {
2396
+ const action = services.find((candidate) => candidate.name === route.ir.service).listActions().find((candidate) => candidate.name === route.ir.action);
2397
+ const invoke = (context) => {
2398
+ const result = telemetry ? withSpan(`action ${route.ir.service}.${route.ir.action}`, {
2399
+ "brick.service": route.ir.service,
2400
+ "brick.action": route.ir.action
2401
+ }, () => route.handler(context)) : route.handler(context);
2402
+ return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
2403
+ };
2404
+ if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, getPluginActionRoute(action, prefix) !== void 0)) mountedRoutes.push(route.ir);
2405
+ }
2406
+ const definition = Object.freeze({
2407
+ services: Object.freeze([...services]),
2408
+ prefix,
2409
+ routes: Object.freeze(mountedRoutes),
2410
+ telemetry,
2411
+ documentation: normalizeDocumentation(options.documentation),
2412
+ dashboard
2413
+ });
2414
+ Object.defineProperty(brickApp, "definition", { value: definition });
2415
+ getGlobalRegistry().setApplicationRoutes(definition);
2416
+ app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
2417
+ const registry = getGlobalRegistry();
2418
+ return [registry, registry.revision];
2419
+ }) : () => getGlobalRegistry().exportArchitecture(definition));
2420
+ return brickApp;
2421
+ }
2422
+ function normalizeDocumentation(documentation) {
2423
+ if (documentation === void 0) return void 0;
2424
+ const options = typeof documentation === "string" ? { dir: documentation } : documentation;
2425
+ if (typeof options.dir !== "string" || options.dir === "") throw new Error("Brick: documentation needs a folder, such as './docs'.");
2426
+ return Object.freeze({
2427
+ dir: options.dir,
2428
+ ...options.components ? { components: options.components } : {}
2429
+ });
2430
+ }
2431
+ function jsonActionResult(value) {
2432
+ return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
2433
+ }
2434
+ function htmlResponse(html) {
2435
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
2436
+ }
2437
+ /** Reuse serialized JSON, without sharing a mutable response body between requests. */
2438
+ function cachedJsonRoute(build, revision) {
2439
+ let [owner, version] = revision();
2440
+ let json = JSON.stringify(build());
2441
+ return ({ set }) => {
2442
+ const [currentOwner, currentVersion] = revision();
2443
+ if (currentOwner !== owner || currentVersion !== version) {
2444
+ json = JSON.stringify(build());
2445
+ owner = currentOwner;
2446
+ version = currentVersion;
2447
+ }
2448
+ set.headers["content-type"] = "application/json;charset=utf-8";
2449
+ return json;
2450
+ };
2451
+ }
2452
+ //#endregion
4
2453
  //#region src/compiler/emit.ts
5
2454
  /** Emits framework code only. User callbacks remain closures bound separately. */
6
2455
  function emitHandlerFactory(route) {
@@ -15,6 +2464,7 @@ function emitHandlerFactory(route) {
15
2464
  const key = JSON.stringify(coercion.key);
16
2465
  input.push(`const v${index} = query[${key}];`);
17
2466
  if (coercion.type === "number") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);
2467
+ else if (coercion.type === "array") input.push(`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}]; }`);
18
2468
  else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
19
2469
  }
20
2470
  input.push("}");
@@ -55,6 +2505,836 @@ ${execute}
55
2505
  }`;
56
2506
  }
57
2507
  //#endregion
58
- export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineEffectAction, defineEffectResourcePlugin, defineEffectService, defineEffectServicePlugin, defineEffectTool, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, effectBrick, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hoistAnchoredSchemas, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
2508
+ //#region src/tool.ts
2509
+ function defineTool(config) {
2510
+ if (config.input && config.input.type !== "object") throw new Error(`Tool '${config.name}' input must be an object schema`);
2511
+ const tool = defineAction(config);
2512
+ Object.defineProperty(tool, "kind", { value: "tool" });
2513
+ return tool;
2514
+ }
2515
+ /**
2516
+ * Whether a value was made with `defineTool`, as opposed to `defineAction`.
2517
+ *
2518
+ * @param value - Anything.
2519
+ * @returns `true` for a tool, narrowing its type.
2520
+ */
2521
+ function isTool(value) {
2522
+ return typeof value === "function" && value.kind === "tool";
2523
+ }
2524
+ //#endregion
2525
+ //#region src/db/sqlite.ts
2526
+ const requireSQLite = createRequire(import.meta.url);
2527
+ /**
2528
+ * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
2529
+ * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
2530
+ *
2531
+ * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
2532
+ * other runtimes (e.g. Node) stays safe until this function is actually
2533
+ * called.
2534
+ */
2535
+ function createSQLiteDatabase(config = {}) {
2536
+ let Database;
2537
+ let drizzle;
2538
+ try {
2539
+ ({Database} = requireSQLite("bun:sqlite"));
2540
+ ({drizzle} = __require("drizzle-orm/bun-sqlite"));
2541
+ } catch (err) {
2542
+ throw new Error(`[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`);
2543
+ }
2544
+ const filePath = config.filename ?? config.path ?? ":memory:";
2545
+ const client = config.client ?? new Database(filePath);
2546
+ if (config.foreignKeys !== false) client.run("PRAGMA foreign_keys = ON;");
2547
+ if (config.wal !== false && filePath !== ":memory:") client.run("PRAGMA journal_mode = WAL;");
2548
+ const db = config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client);
2549
+ if (!db.$client) db.$client = client;
2550
+ return db;
2551
+ }
2552
+ //#endregion
2553
+ //#region src/db/postgres.ts
2554
+ /**
2555
+ * Creates a PostgreSQL Drizzle instance using postgres-js.
2556
+ * Static imports (both are hard dependencies in package.json) so bundlers
2557
+ * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
2558
+ * `sqlite.ts` since it only exists under Bun.
2559
+ */
2560
+ function createPostgresDatabase(config = {}) {
2561
+ const connectionUrl = config.url ?? config.connectionString ?? (typeof process !== "undefined" ? process.env?.DATABASE_URL : void 0);
2562
+ const client = config.client ?? (connectionUrl ? postgres(connectionUrl, {
2563
+ max: config.max,
2564
+ prepare: config.prepare,
2565
+ ssl: config.ssl
2566
+ }) : postgres({
2567
+ host: config.host ?? "localhost",
2568
+ port: config.port ?? 5432,
2569
+ user: config.user,
2570
+ password: config.password,
2571
+ database: config.database,
2572
+ max: config.max,
2573
+ prepare: config.prepare,
2574
+ ssl: config.ssl
2575
+ }));
2576
+ return drizzle(client, {
2577
+ schema: config.schema,
2578
+ ...config.schemaName ? { schemaFilter: [config.schemaName] } : {}
2579
+ });
2580
+ }
2581
+ //#endregion
2582
+ //#region src/db/define.ts
2583
+ /**
2584
+ * Whether a value is a database handle made by `defineDatabase`.
2585
+ *
2586
+ * @param value - Anything.
2587
+ * @returns `true` for a handle, narrowing its type.
2588
+ */
2589
+ function isDatabaseHandle(value) {
2590
+ return typeof value === "object" && value !== null && "kind" in value && value.kind === "brick-database";
2591
+ }
2592
+ function defineDatabase(options = {}) {
2593
+ const engine = options.engine ?? "sqlite";
2594
+ if (engine !== "sqlite" && engine !== "postgres") throw new Error(`Unsupported database engine: ${engine}`);
2595
+ const forbidden = engine === "sqlite" ? [
2596
+ "url",
2597
+ "connectionString",
2598
+ "host",
2599
+ "port",
2600
+ "user",
2601
+ "password",
2602
+ "database",
2603
+ "ssl",
2604
+ "max",
2605
+ "schemaName"
2606
+ ] : [
2607
+ "path",
2608
+ "filename",
2609
+ "wal",
2610
+ "foreignKeys"
2611
+ ];
2612
+ for (const key of forbidden) if (key in options) throw new Error(`Database option "${key}" is not valid for ${engine}`);
2613
+ const declared = options.tables ?? {};
2614
+ const tables = Array.isArray(declared) ? Object.fromEntries(declared.map((table) => [getTableName$1(table), table])) : { ...declared };
2615
+ const schema = options.schema ?? tables;
2616
+ let db;
2617
+ let closeClient;
2618
+ let closed = false;
2619
+ let closing;
2620
+ return {
2621
+ kind: "brick-database",
2622
+ name: options.name,
2623
+ engine,
2624
+ tables: Object.freeze(tables),
2625
+ schema,
2626
+ close() {
2627
+ if (closed) return closing;
2628
+ closed = true;
2629
+ closing = closeClient?.();
2630
+ return closing;
2631
+ },
2632
+ getDb() {
2633
+ if (closed) throw new Error("Brick database handle is closed");
2634
+ if (db !== void 0) return db;
2635
+ const config = {};
2636
+ for (const [key, value] of Object.entries(options)) {
2637
+ if ([
2638
+ "tables",
2639
+ "schema",
2640
+ "name",
2641
+ "engine"
2642
+ ].includes(key)) continue;
2643
+ if (engine === "postgres" && options.client && key !== "client" && key !== "schemaName") continue;
2644
+ config[key] = value instanceof SecretRef ? value.require() : value;
2645
+ }
2646
+ if (engine === "sqlite") {
2647
+ const path = config.filename ?? config.path ?? ":memory:";
2648
+ if (!config.client && path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
2649
+ const instance = createSQLiteDatabase({
2650
+ ...config,
2651
+ schema
2652
+ });
2653
+ db = instance;
2654
+ if (!options.client) closeClient = () => instance.$client.close();
2655
+ } else {
2656
+ const instance = createPostgresDatabase({
2657
+ ...config,
2658
+ schema
2659
+ });
2660
+ db = instance;
2661
+ if (!options.client) closeClient = () => instance.$client.end();
2662
+ }
2663
+ return db;
2664
+ }
2665
+ };
2666
+ }
2667
+ //#endregion
2668
+ //#region src/db/index.ts
2669
+ /**
2670
+ * Creates a database instance based on the provided configuration.
2671
+ * Zero-config: calling `createDatabase()` returns an ultra-fast Bun-native SQLite
2672
+ * database in `:memory:` mode wrapped with Drizzle ORM.
2673
+ */
2674
+ function createDatabase(config = {}) {
2675
+ const engine = config.engine ?? "sqlite";
2676
+ if (engine === "sqlite") return createSQLiteDatabase(config);
2677
+ if (engine === "postgres") return createPostgresDatabase(config);
2678
+ throw new Error(`[Brick-TS DB] Unsupported database engine: '${engine}'`);
2679
+ }
2680
+ /** Attach a defined database. Schema changes remain the caller's responsibility. */
2681
+ function attachDatabase(service, database) {
2682
+ service.setDb(database);
2683
+ return database.getDb();
2684
+ }
2685
+ /**
2686
+ * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition
2687
+ * directly from a Drizzle table schema.
2688
+ */
2689
+ function generateSQLiteTableDdl(table) {
2690
+ const tableName = getTableName$1(table);
2691
+ const columns = getTableColumns$1(table);
2692
+ const colDefs = [];
2693
+ for (const [, col] of Object.entries(columns)) {
2694
+ let def = `"${col.name}" ${col.getSQLType().toUpperCase()}`;
2695
+ if (col.primary) def += " PRIMARY KEY";
2696
+ if (col.notNull) def += " NOT NULL";
2697
+ if (col.isUnique) def += " UNIQUE";
2698
+ if (col.hasDefault) {
2699
+ if (typeof col.default === "string") def += ` DEFAULT '${col.default.replace(/'/g, "''")}'`;
2700
+ else if (typeof col.default === "boolean") def += ` DEFAULT ${col.default ? 1 : 0}`;
2701
+ else if (typeof col.default === "number") def += ` DEFAULT ${col.default}`;
2702
+ else if (col.default !== void 0) def += ` DEFAULT ${col.default}`;
2703
+ }
2704
+ colDefs.push(def);
2705
+ }
2706
+ return `CREATE TABLE IF NOT EXISTS "${tableName}" (\n ${colDefs.join(",\n ")}\n);`;
2707
+ }
2708
+ /**
2709
+ * Generates idempotent secondary index DDL for a Drizzle table.
2710
+ * Covers owner scoping, sort columns, and exact-match filters.
2711
+ * UNIQUE columns already carry an implicit index — skipped here.
2712
+ * FTS/trigram indexes are handled separately by the search layer.
2713
+ */
2714
+ function generateSQLiteIndexDdl(table, opts = {}) {
2715
+ const tableName = getTableName$1(table);
2716
+ const columns = getTableColumns$1(table);
2717
+ const stmts = [];
2718
+ const seen = /* @__PURE__ */ new Set();
2719
+ const push = (name, cols) => {
2720
+ const clean = cols.filter(Boolean);
2721
+ if (clean.length === 0) return;
2722
+ const key = `${name}(${clean.join(",")})`;
2723
+ if (seen.has(key)) return;
2724
+ seen.add(key);
2725
+ const colList = clean.map((c) => `"${c}"`).join(", ");
2726
+ stmts.push(`CREATE INDEX IF NOT EXISTS "${name}" ON "${tableName}" (${colList});`);
2727
+ };
2728
+ const colNameOf = (field) => {
2729
+ if (columns[field]) return columns[field].name ?? field;
2730
+ for (const col of Object.values(columns)) if (col.name === field) return col.name;
2731
+ };
2732
+ let ownerCol;
2733
+ if (opts.ownerField) {
2734
+ const oc = colNameOf(opts.ownerField);
2735
+ if (oc) {
2736
+ ownerCol = oc;
2737
+ push(`idx_${tableName}_${oc}`, [oc]);
2738
+ }
2739
+ }
2740
+ const sorts = opts.sortFields ?? ["updated_at", "created_at"];
2741
+ const sortCols = [];
2742
+ for (const f of sorts) {
2743
+ const c = colNameOf(f);
2744
+ if (c) {
2745
+ sortCols.push(c);
2746
+ push(`idx_${tableName}_${c}`, [c]);
2747
+ }
2748
+ }
2749
+ if (ownerCol && sortCols.length > 0) push(`idx_${tableName}_${ownerCol}_${sortCols[0]}`, [ownerCol, sortCols[0]]);
2750
+ return stmts;
2751
+ }
2752
+ /**
2753
+ * Ensures secondary indexes exist for a resource table.
2754
+ * SQLite: B-tree indexes for owner scope + sort + composite hot path.
2755
+ * Postgres: same B-trees plus pg_trgm GIN indexes for substring search.
2756
+ * Best-effort: failures warn and continue (e.g. read-only replicas).
2757
+ */
2758
+ function ensureResourceIndexes(db, table, opts = {}) {
2759
+ if (!db) return;
2760
+ const isPostgres = typeof db.execute === "function" && !db.$client?.run;
2761
+ const stmts = generateSQLiteIndexDdl(table, opts);
2762
+ if (isPostgres && opts.searchFields && opts.searchFields.length > 0) {
2763
+ const tableName = getTableName$1(table);
2764
+ const columns = getTableColumns$1(table);
2765
+ const colNameOf = (f) => {
2766
+ if (columns[f]) return columns[f].name ?? f;
2767
+ for (const col of Object.values(columns)) if (col.name === f) return col.name;
2768
+ };
2769
+ for (const f of opts.searchFields) {
2770
+ const c = colNameOf(f);
2771
+ if (c) stmts.push(`CREATE INDEX IF NOT EXISTS "idx_${tableName}_${c}_trgm" ON "${tableName}" USING gin ("${c}" gin_trgm_ops);`);
2772
+ }
2773
+ }
2774
+ if (stmts.length === 0) return;
2775
+ const run = (stmt) => {
2776
+ try {
2777
+ if (db.$client?.run) db.$client.run(stmt);
2778
+ else if (typeof db.execute === "function") db.execute(sql$1.raw(stmt)).catch(() => {});
2779
+ else if (db.run) db.run(stmt);
2780
+ } catch {}
2781
+ };
2782
+ if (isPostgres) run(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);
2783
+ for (const s of stmts) run(s);
2784
+ }
2785
+ /**
2786
+ * SQLite FTS5 search layer for resource list (?search=).
2787
+ * B-tree indexes cannot serve LIKE '%term%' (leading wildcard forces a full
2788
+ * scan). FTS5 gives indexed substring/prefix search on title/slug-scale text.
2789
+ * Postgres uses ilike + pg_trgm GIN indexes instead (see ensureResourceIndexes).
2790
+ */
2791
+ function ftsTableName(table) {
2792
+ return `${getTableName$1(table)}_fts`;
2793
+ }
2794
+ function quoteIdent(name) {
2795
+ return `"${name.replace(/"/g, "\"\"")}"`;
2796
+ }
2797
+ /**
2798
+ * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.
2799
+ * Idempotent; safe to call on every resource registration.
2800
+ * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.
2801
+ */
2802
+ function ensureSQLiteFts(db, table, searchCols) {
2803
+ if (!db || searchCols.length === 0) return;
2804
+ const client = db.$client;
2805
+ const runRaw = db.run;
2806
+ if (!client?.run && !runRaw) return;
2807
+ const run = (stmt) => {
2808
+ if (client?.run) client.run(stmt);
2809
+ else runRaw(stmt);
2810
+ };
2811
+ try {
2812
+ const tableName = getTableName$1(table);
2813
+ const columns = getTableColumns$1(table);
2814
+ const colNameOf = (f) => {
2815
+ if (columns[f]) return columns[f].name ?? f;
2816
+ for (const col of Object.values(columns)) if (col.name === f) return col.name;
2817
+ };
2818
+ const dbCols = searchCols.map(colNameOf).filter((c) => !!c);
2819
+ if (dbCols.length === 0) return;
2820
+ const idCol = colNameOf("id") ?? Object.values(columns).find((c) => c.primary)?.name ?? "id";
2821
+ const fts = ftsTableName(table);
2822
+ const ftsCols = [`"id" UNINDEXED`, ...dbCols.map((c) => quoteIdent(c))].join(", ");
2823
+ run(`CREATE VIRTUAL TABLE IF NOT EXISTS ${quoteIdent(fts)} USING fts5(${ftsCols}, tokenize='porter');`);
2824
+ const colList = dbCols.map(quoteIdent).join(", ");
2825
+ const newVals = dbCols.map((c) => `new.${quoteIdent(c)}`).join(", ");
2826
+ run(`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;`);
2827
+ run(`CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE "id" = old.${quoteIdent(idCol)}; END;`);
2828
+ run(`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;`);
2829
+ run(`INSERT INTO ${quoteIdent(fts)}("id", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT "id" FROM ${quoteIdent(fts)});`);
2830
+ } catch {}
2831
+ }
2832
+ /**
2833
+ * Builds an FTS5 MATCH condition for a resource search term.
2834
+ * Returns null when the term has no usable tokens or FTS errors.
2835
+ * Caller falls back to LIKE in that case.
2836
+ */
2837
+ function buildFtsMatchQuery(search) {
2838
+ const terms = search.split(/\s+/).map((s) => s.trim()).filter(Boolean).slice(0, 10);
2839
+ if (terms.length === 0) return null;
2840
+ const escaped = terms.map((term) => {
2841
+ const clean = term.replace(/"/g, "").trim();
2842
+ if (!clean) return null;
2843
+ return `"${clean.replace(/"/g, "\"\"")}"*`;
2844
+ }).filter((x) => !!x);
2845
+ if (escaped.length === 0) return null;
2846
+ return escaped.join(" AND ");
2847
+ }
2848
+ /**
2849
+ * Explicit SQLite development/test schema preparation helper.
2850
+ * Never called by services, resources, auth, or server startup.
2851
+ * Not a migration runner; PostgreSQL schema management is caller-owned.
2852
+ */
2853
+ function syncSchema(tablesOrService, dbInstance) {
2854
+ let db = dbInstance;
2855
+ let tables = [];
2856
+ if (tablesOrService && typeof tablesOrService.listActions === "function" && tablesOrService.tables) {
2857
+ const service = tablesOrService;
2858
+ tables = Array.from(service.tables.values());
2859
+ if (!db) db = service.getDb();
2860
+ } else if (tablesOrService instanceof Map) tables = Array.from(tablesOrService.values());
2861
+ else if (Array.isArray(tablesOrService)) tables = tablesOrService;
2862
+ else if (tablesOrService && typeof tablesOrService === "object") tables = Object.values(tablesOrService);
2863
+ if (!db || tables.length === 0) return;
2864
+ if (db.$client?.run || db.run) {
2865
+ for (const table of tables) try {
2866
+ const ddl = generateSQLiteTableDdl(table);
2867
+ if (db.$client?.run) db.$client.run(ddl);
2868
+ else if (db.run) db.run(sql$1.raw(ddl));
2869
+ } catch (err) {
2870
+ console.warn(`[Brick-TS DB] Failed to create table:`, err.message);
2871
+ }
2872
+ return;
2873
+ }
2874
+ return (async () => {
2875
+ for (const table of tables) try {
2876
+ getTableName$1(table);
2877
+ } catch (err) {
2878
+ console.warn(`[Brick-TS DB] Postgres syncSchema error:`, err.message);
2879
+ }
2880
+ })();
2881
+ }
2882
+ //#endregion
2883
+ //#region src/resource.ts
2884
+ /** Declares a plugin host without registering actions or changing the schema. */
2885
+ function defineResource(service, config) {
2886
+ const columns = getTableColumns$1(config.table);
2887
+ const primary = Object.entries(columns).filter(([, column]) => column.primary);
2888
+ const id = config.id ?? (primary.length === 1 ? primary[0]?.[1] : void 0);
2889
+ const entry = Object.entries(columns).find(([, column]) => column === id);
2890
+ if (!entry || !id) throw new Error(`Resource '${config.name}' requires an id column belonging to its table`);
2891
+ if (!config.name || config.name.includes("/") || [
2892
+ "__proto__",
2893
+ "constructor",
2894
+ "prototype"
2895
+ ].includes(config.name)) throw new Error(`Invalid resource name '${config.name}'`);
2896
+ service.registerTable(config.table);
2897
+ const resource = {
2898
+ name: config.name,
2899
+ serviceName: service.name,
2900
+ table: config.table,
2901
+ id,
2902
+ idField: entry[0],
2903
+ config: Object.freeze({
2904
+ ...config,
2905
+ id
2906
+ }),
2907
+ use(plugin) {
2908
+ return installPlugin(service, resource, plugin);
2909
+ }
2910
+ };
2911
+ return resource;
2912
+ }
2913
+ //#endregion
2914
+ //#region src/context.ts
2915
+ function pickContextEnvelope(context) {
2916
+ if (!context) return {};
2917
+ const envelope = {};
2918
+ if (context.caller !== void 0) envelope.caller = context.caller;
2919
+ if (context.user !== void 0) envelope.user = context.user;
2920
+ if (context.traceId !== void 0) envelope.traceId = context.traceId;
2921
+ if (context.requestId !== void 0) envelope.requestId = context.requestId;
2922
+ if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
2923
+ return envelope;
2924
+ }
2925
+ //#endregion
2926
+ //#region src/service.ts
2927
+ const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
2928
+ const DEFAULT_REQUEST = new Request("http://localhost");
2929
+ const EMPTY_SERVICES = Object.freeze({});
2930
+ const EMPTY_METADATA = Object.freeze({});
2931
+ let _ctxSeq = 0;
2932
+ const RESOLVED_SYMBOL = Symbol("resolved");
2933
+ var ServiceImpl = class {
2934
+ name;
2935
+ options;
2936
+ actions = /* @__PURE__ */ new Map();
2937
+ tools = /* @__PURE__ */ new Map();
2938
+ tables = /* @__PURE__ */ new Map();
2939
+ resources = /* @__PURE__ */ new Map();
2940
+ preparations = /* @__PURE__ */ new Map();
2941
+ database;
2942
+ _isBuilt = false;
2943
+ constructor(name, options = {}) {
2944
+ this.name = name;
2945
+ this.options = options;
2946
+ if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
2947
+ this.database = options.database;
2948
+ }
2949
+ use(plugin) {
2950
+ return installPlugin(this, void 0, plugin);
2951
+ }
2952
+ get db() {
2953
+ return this.getDb();
2954
+ }
2955
+ get isBuilt() {
2956
+ return this._isBuilt;
2957
+ }
2958
+ /**
2959
+ * Closes declarations after plugins have registered their actions and preparations.
2960
+ */
2961
+ build() {
2962
+ if (isInstallingPlugin(this)) throw new Error("Cannot build a service during plugin setup");
2963
+ if (this._isBuilt) return this;
2964
+ this._isBuilt = true;
2965
+ return this;
2966
+ }
2967
+ contributePreparation(contribution) {
2968
+ if (this._isBuilt) throw new Error("Preparations must be registered before service build");
2969
+ if (this.preparations.has(contribution.name)) throw new Error(`Duplicate preparation '${contribution.name}'`);
2970
+ this.preparations.set(contribution.name, contribution);
2971
+ getGlobalRegistry().touch();
2972
+ }
2973
+ listPreparations() {
2974
+ return [...this.preparations.values()];
2975
+ }
2976
+ prepareContributions() {
2977
+ for (const contribution of this.preparations.values()) contribution.prepare();
2978
+ }
2979
+ registerTable(table) {
2980
+ try {
2981
+ const tableName = getTableName(table);
2982
+ this.tables.set(tableName, table);
2983
+ } catch {
2984
+ const fallbackName = table._?.name ?? `table_${this.tables.size + 1}`;
2985
+ this.tables.set(fallbackName, table);
2986
+ }
2987
+ return this;
2988
+ }
2989
+ resource = (config) => {
2990
+ if (this._isBuilt) throw new Error("Resources must be registered before service build");
2991
+ if (this.resources.has(config.name)) throw new Error(`Duplicate plugin resource: ${config.name}`);
2992
+ const resourceInstance = defineResource(this, config);
2993
+ this.resources.set(resourceInstance.name, resourceInstance);
2994
+ getGlobalRegistry().touch();
2995
+ return resourceInstance;
2996
+ };
2997
+ getResource(name) {
2998
+ return this.resources.get(name);
2999
+ }
3000
+ listResources() {
3001
+ return Array.from(this.resources.values());
3002
+ }
3003
+ action(actionOrConfig) {
3004
+ let actionInstance;
3005
+ const isActionFunction = typeof actionOrConfig === "function" && "config" in actionOrConfig;
3006
+ if (isActionFunction) actionInstance = actionOrConfig;
3007
+ else actionInstance = defineAction(actionOrConfig);
3008
+ if (isInstallingPlugin(this) && this.actions.has(actionInstance.name) && this.actions.get(actionInstance.name) !== actionInstance) throw new Error(`Duplicate plugin action: ${actionInstance.name}`);
3009
+ if (isTool(actionInstance)) actionInstance.config.http = true;
3010
+ actionInstance.serviceName = this.name;
3011
+ actionInstance.service = this;
3012
+ this.actions.set(actionInstance.name, actionInstance);
3013
+ getGlobalRegistry().touch();
3014
+ if (isActionFunction) return this;
3015
+ return actionInstance;
3016
+ }
3017
+ tool(toolOrConfig) {
3018
+ const existing = isTool(toolOrConfig);
3019
+ const tool = existing ? toolOrConfig : defineTool(toolOrConfig);
3020
+ if (this.tools.has(tool.name)) throw new Error(`Duplicate tool: ${tool.name}`);
3021
+ tool.serviceName = this.name;
3022
+ tool.service = this;
3023
+ this.tools.set(tool.name, tool);
3024
+ if (tool.config.http) this.action(tool);
3025
+ getGlobalRegistry().touch();
3026
+ return existing ? this : tool;
3027
+ }
3028
+ getTool(name) {
3029
+ return this.tools.get(name);
3030
+ }
3031
+ listTools() {
3032
+ return Array.from(this.tools.values());
3033
+ }
3034
+ getAction(name) {
3035
+ return this.actions.get(name);
3036
+ }
3037
+ listActions() {
3038
+ return Array.from(new Set(this.actions.values()));
3039
+ }
3040
+ getDb() {
3041
+ return this.database?.getDb();
3042
+ }
3043
+ setDb(database) {
3044
+ if (!isDatabaseHandle(database)) throw new Error("Use defineDatabase() to set a service database");
3045
+ this.database = database;
3046
+ getGlobalRegistry().touch();
3047
+ }
3048
+ /**
3049
+ * Resolves the complete service execution context once per incoming request.
3050
+ * Merges framework BaseContext with the service's custom context hook.
3051
+ * Always rebuilds context for this service to prevent caller context from overriding.
3052
+ */
3053
+ resolveContext(callCtx) {
3054
+ return resolveServiceContext(this, callCtx);
3055
+ }
3056
+ introspect() {
3057
+ const databaseConfig = this.database ? {
3058
+ name: this.database.name,
3059
+ engine: this.database.engine,
3060
+ tables: Object.keys(this.database.tables)
3061
+ } : void 0;
3062
+ const { database: _database, ...config } = this.options;
3063
+ const options = JSON.parse(JSON.stringify(config));
3064
+ return {
3065
+ name: this.name,
3066
+ options,
3067
+ hasDatabase: Boolean(this.database),
3068
+ databaseConfig,
3069
+ actions: this.listActions().map((act) => {
3070
+ const access = getActionAccess(act);
3071
+ return {
3072
+ name: act.name,
3073
+ serviceName: this.name,
3074
+ ...act.plugin ? { plugin: act.plugin } : {},
3075
+ ...act.resource ? { resource: act.resource } : {},
3076
+ description: act.config.description,
3077
+ inputSchema: act.config.input,
3078
+ outputSchema: act.config.output,
3079
+ hasAuthorize: access.hasAuthorize,
3080
+ hasScope: access.hasScope,
3081
+ accessPolicy: access.policy,
3082
+ errors: act.config.errors,
3083
+ emits: act.config.emits,
3084
+ tags: act.config.tags
3085
+ };
3086
+ }),
3087
+ tools: this.listTools().map((tool) => ({ name: tool.name })),
3088
+ resources: this.listResources().map((res) => ({ name: res.name }))
3089
+ };
3090
+ }
3091
+ };
3092
+ async function resolveServiceContext(service, callCtx) {
3093
+ if (callCtx?.[RESOLVED_SYMBOL] === service) return callCtx;
3094
+ const seq = ++_ctxSeq;
3095
+ const fullBaseCtx = {
3096
+ request: callCtx?.request ?? DEFAULT_REQUEST,
3097
+ db: service.getDb(),
3098
+ logger: callCtx?.logger ?? defaultLogger,
3099
+ traceId: callCtx?.traceId ?? `tr_${seq.toString(36)}`,
3100
+ requestId: callCtx?.requestId ?? `req_${seq.toString(36)}`,
3101
+ services: callCtx?.services ?? EMPTY_SERVICES,
3102
+ metadata: callCtx?.metadata ?? EMPTY_METADATA,
3103
+ ...pickContextEnvelope(callCtx)
3104
+ };
3105
+ const resolvedExtra = service.options.context ? await service.options.context(fullBaseCtx) : {};
3106
+ return {
3107
+ ...fullBaseCtx,
3108
+ ...resolvedExtra,
3109
+ [RESOLVED_SYMBOL]: service
3110
+ };
3111
+ }
3112
+ /**
3113
+ * Declare a service: a named group of actions, tools, and resources with its own
3114
+ * database and request context. It is registered globally, so `brick()`, the
3115
+ * OpenAPI generator, and `createServiceProxy` find it by name.
3116
+ *
3117
+ * Add actions with `service.action(...)`, tools with `service.tool(...)`,
3118
+ * resources with `service.resource(...)`, and plugins with `service.use(...)`.
3119
+ *
3120
+ * @param name - Unique name. It is the service's segment of every action route
3121
+ * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining a
3122
+ * second service with the same name replaces the first and logs a warning.
3123
+ * @param options - `database` (a handle from `defineDatabase`), `context` (adds
3124
+ * fields such as the signed-in user to every action's `ctx`), and `auth`,
3125
+ * `rateLimit`, `cache`, `resilience`, `telemetry`, and `lifecycle`.
3126
+ * @returns The service.
3127
+ * @example
3128
+ * import { defineDatabase, defineService, t } from "@brickkit/core";
3129
+ *
3130
+ * const database = defineDatabase({ tables: { pages } });
3131
+ *
3132
+ * export const pagesService = defineService("pages", {
3133
+ * database,
3134
+ * // Added to `ctx` in every action of this service.
3135
+ * context: async ({ request }) => ({ user: await readUser(request) }),
3136
+ * });
3137
+ *
3138
+ * pagesService.action({
3139
+ * name: "list",
3140
+ * input: t.Object({ limit: t.Optional(t.Number()) }),
3141
+ * output: t.Array(t.Object({ id: t.String(), title: t.String() })),
3142
+ * execute: ({ input, ctx }) =>
3143
+ * ctx.db.select().from(pages).limit(input.limit ?? 20),
3144
+ * });
3145
+ */
3146
+ function defineService(name, options) {
3147
+ const service = new ServiceImpl(name, options);
3148
+ getGlobalRegistry().register(service);
3149
+ return service;
3150
+ }
3151
+ //#endregion
3152
+ //#region src/rpc.ts
3153
+ /**
3154
+ * A typed way to call another service's actions in-process. Each property of
3155
+ * the proxy is an action of that service: call it with the action's input, and
3156
+ * optionally a call context.
3157
+ *
3158
+ * The call runs through the target's own validation and authorization, with the
3159
+ * target's database and context (never the caller's), and shows as an `rpc`
3160
+ * span in the trace. Only in-process dispatch exists: with `isMonolith: false`
3161
+ * a call throws. Use the typed client to call a service over HTTP.
3162
+ *
3163
+ * @param serviceName - The registered name of the service to call.
3164
+ * @param options - `from` (the calling service's name, which becomes `ctx.caller`
3165
+ * in the target and cannot be spoofed), `context` (defaults for every call), and
3166
+ * `isMonolith`.
3167
+ * @returns A proxy typed as `T`, usually the target's actions.
3168
+ * @throws On a call, when the service or the action is not registered.
3169
+ * @example
3170
+ * import { createServiceProxy } from "@brickkit/core";
3171
+ *
3172
+ * const pages = createServiceProxy<{ get(input: { id: string }): Promise<Page> }>(
3173
+ * "pages",
3174
+ * { from: "billing" },
3175
+ * );
3176
+ * const page = await pages.get({ id: "p_1" });
3177
+ */
3178
+ function createServiceProxy(serviceName, options = {}) {
3179
+ const isMonolith = options.isMonolith ?? true;
3180
+ return new Proxy({}, { get(_, actionName) {
3181
+ return async (payload, callCtx) => {
3182
+ if (isMonolith) {
3183
+ const service = getGlobalRegistry().get(serviceName);
3184
+ if (!service) throw new Error(`[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`);
3185
+ const action = service.getAction(actionName);
3186
+ if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
3187
+ const envelopeCtx = createRpcEnvelope(options.from, options.context, callCtx);
3188
+ const execute = () => action.execute({
3189
+ input: payload,
3190
+ ctx: envelopeCtx
3191
+ });
3192
+ return withCallSpan(`rpc ${serviceName}.${actionName}`, {
3193
+ "brick.service": serviceName,
3194
+ "brick.action": actionName
3195
+ }, execute);
3196
+ } else throw new Error(`[Brick-TS RPC] Remote microservice dispatch for '${serviceName}.${actionName}' is not configured. Use createClient({ baseUrl, contract }) for HTTP calls to remote services.`);
3197
+ };
3198
+ } });
3199
+ }
3200
+ /** Build the trusted envelope for a proxy call.
3201
+ *
3202
+ * When `from` is provided, it identifies the service that created the proxy
3203
+ * and always sets `caller` — any `caller` supplied via `options.context` or
3204
+ * the per-call context is ignored so it cannot be spoofed. When `from` is
3205
+ * omitted, an explicitly supplied `caller` still passes through for backward
3206
+ * compatibility; otherwise `caller` stays unset (never the target service).
3207
+ */
3208
+ function createRpcEnvelope(from, defaultContext, callContext) {
3209
+ const envelope = {
3210
+ ...pickContextEnvelope(defaultContext),
3211
+ ...pickContextEnvelope(callContext)
3212
+ };
3213
+ if (from !== void 0) envelope.caller = from;
3214
+ return envelope;
3215
+ }
3216
+ //#endregion
3217
+ //#region src/mcp.ts
3218
+ var UnknownToolError = class extends Error {
3219
+ constructor(name) {
3220
+ super(`unknown tool: ${name}`);
3221
+ this.name = "UnknownToolError";
3222
+ }
3223
+ };
3224
+ /** Collect only explicitly defined tools, without exposing ordinary actions. */
3225
+ function createMcpRegistry(options) {
3226
+ function toolsByName() {
3227
+ const tools = /* @__PURE__ */ new Map();
3228
+ for (const tool of [...options.tools ?? [], ...(options.services ?? []).flatMap((service) => service.listTools())]) {
3229
+ const existing = tools.get(tool.name);
3230
+ if (existing && existing !== tool) throw new Error(`Duplicate MCP tool: ${tool.name}`);
3231
+ tools.set(tool.name, tool);
3232
+ }
3233
+ return tools;
3234
+ }
3235
+ toolsByName();
3236
+ return {
3237
+ listTools: () => Array.from(toolsByName().values(), (tool) => ({
3238
+ name: tool.name,
3239
+ ...tool.config.title ?? tool.config.annotations?.title ? { title: tool.config.title ?? tool.config.annotations?.title } : {},
3240
+ description: tool.config.description ?? "",
3241
+ inputSchema: tool.config.input ?? {
3242
+ type: "object",
3243
+ properties: {},
3244
+ additionalProperties: false
3245
+ },
3246
+ annotations: tool.config.annotations ?? {}
3247
+ })),
3248
+ async callTool(name, args = {}, ctx) {
3249
+ const tool = toolsByName().get(name);
3250
+ if (!tool) throw new UnknownToolError(name);
3251
+ return tool({
3252
+ input: args,
3253
+ ctx
3254
+ });
3255
+ }
3256
+ };
3257
+ }
3258
+ function result(id, value) {
3259
+ return Response.json({
3260
+ jsonrpc: "2.0",
3261
+ id,
3262
+ result: value
3263
+ });
3264
+ }
3265
+ function rpcError(id, code, message) {
3266
+ return Response.json({
3267
+ jsonrpc: "2.0",
3268
+ id,
3269
+ error: {
3270
+ code,
3271
+ message
3272
+ }
3273
+ });
3274
+ }
3275
+ function isRecord(value) {
3276
+ return !!value && typeof value === "object" && !Array.isArray(value);
3277
+ }
3278
+ /** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
3279
+ function createMcpHandler(options) {
3280
+ const versions = options.protocolVersions ?? ["2025-06-18"];
3281
+ if (!versions.length) throw new Error("At least one MCP protocol version is required");
3282
+ return async (request, ctx) => {
3283
+ if (request.method !== "POST") return new Response(null, {
3284
+ status: 405,
3285
+ headers: { Allow: "POST" }
3286
+ });
3287
+ let body;
3288
+ try {
3289
+ body = await request.json();
3290
+ } catch {
3291
+ return rpcError(null, -32700, "parse error");
3292
+ }
3293
+ if (!isRecord(body) || body.jsonrpc !== "2.0" || typeof body.method !== "string" || body.id !== void 0 && body.id !== null && typeof body.id !== "string" && typeof body.id !== "number" || body.params !== void 0 && !isRecord(body.params)) return rpcError(null, -32600, "invalid request");
3294
+ if (body.id === void 0) return new Response(null, { status: 202 });
3295
+ const { id, method } = body;
3296
+ const params = body.params;
3297
+ switch (method) {
3298
+ case "initialize": {
3299
+ const requested = params?.protocolVersion;
3300
+ return result(id, {
3301
+ capabilities: { tools: {} },
3302
+ protocolVersion: typeof requested === "string" && versions.includes(requested) ? requested : versions[0],
3303
+ serverInfo: options.serverInfo
3304
+ });
3305
+ }
3306
+ case "ping": return result(id, {});
3307
+ case "tools/list": try {
3308
+ return result(id, { tools: options.registry.listTools() });
3309
+ } catch {
3310
+ return rpcError(id, -32603, "internal error");
3311
+ }
3312
+ case "tools/call":
3313
+ if (typeof params?.name !== "string" || params.arguments !== void 0 && !isRecord(params.arguments)) return rpcError(id, -32602, "invalid tool parameters");
3314
+ try {
3315
+ const value = await options.registry.callTool(params.name, params.arguments, {
3316
+ ...ctx,
3317
+ request
3318
+ });
3319
+ return result(id, { content: [{
3320
+ type: "text",
3321
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2) ?? "null"
3322
+ }] });
3323
+ } catch (error) {
3324
+ if (error instanceof UnknownToolError) return rpcError(id, -32602, error.message);
3325
+ return result(id, {
3326
+ content: [{
3327
+ type: "text",
3328
+ text: error instanceof Error ? error.message : String(error)
3329
+ }],
3330
+ isError: true
3331
+ });
3332
+ }
3333
+ default: return rpcError(id, -32601, `method not found: ${method}`);
3334
+ }
3335
+ };
3336
+ }
3337
+ //#endregion
3338
+ export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hoistAnchoredSchemas, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, traceRoute, uniqueIndex, validateWithSchema };
59
3339
 
60
3340
  //# sourceMappingURL=index.js.map