@brickkit/core 0.12.0 → 0.13.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.
@@ -1,1106 +0,0 @@
1
- import { A as Resource, B as ServiceSchema, Ct as PostgresDatabase, Dt as BunSQLiteDatabase, E as Logger, F as ResourceConfig, G as ToolConfigWithoutAuthorize, H as Tool, I as ResourceIdentity, J as ValidationErrorItem, Jn as EventsOptions, Jt as ServicePlugin, L as ResourceTypeOptions, Nn as SecretSource, O as PreparationContribution, Ot as SQLiteDatabaseConfig, Q as BrickSocketConfig, Qn as ServiceEvents, R as Service, S as ErrorBuilder, U as ToolAnnotations, W as ToolConfigWithAuthorize, X as BrickClientSocket, Y as RegisteredSocket, a as ActionConfigWithoutAuthorize, ar as DepsOf, b as CompiledRoutePlan, f as BaseContext, ft as SocketPayloads, gt as DatabaseHandle, i as ActionConfigWithAuthorize, it as BrickSocketSchema, j as ResourceActionAccess, k as ProxyOptions, mn as InstalledPlugin, mt as SocketSchemas, n as ActionAccessPolicy, nn as EventsHub, nr as EventRef, o as ActionContext, q as ValidationError, s as ActionErrorDefinition, sn as OutboxTable, sr as Ports, st as SocketBroker, t as Action, tn as EventsDefinition, tr as EventCatalog, tt as BrickSocketHandle, u as ArchitectureSchema, wt as PostgresDatabaseConfig, xn as PluginInstance, z as ServiceOptions } from "./types.js";
2
- import { d as InferActionInput, f as InferActionOutput, i as BrickClientAction, s as BrickServices } from "./client.js";
3
- import "./workflow.js";
4
- import { SpanKind } from "@opentelemetry/api";
5
- import { Static as Static$1, TSchema, TSchema as TSchema$1, Type } from "@sinclair/typebox";
6
- import { TypeCheck } from "@sinclair/typebox/compiler";
7
- import { Table, Table as Table$1, and as and$1, asc as asc$1, desc, eq as eq$1, getTableColumns as getTableColumns$1, getTableName as getTableName$1, gt, gte, ilike, inArray as inArray$1, is, isNotNull, isNull, like, lt as lt$1, lte as lte$1, ne, not, notInArray, or as or$1, relations, sql as sql$1 } from "drizzle-orm";
8
- import { Elysia } from "elysia";
9
- /**
10
- * Run `fn` in a database transaction: everything it writes through the `tx` it is
11
- * given is committed together when it returns, or undone if it throws.
12
- *
13
- * Postgres uses a real transaction on one connection. SQLite has one connection
14
- * and a synchronous driver, which Drizzle's own `transaction` cannot use with an
15
- * async callback (it would commit before the callback finished). So transactions
16
- * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
17
- * A write made elsewhere in the process during that time, outside this helper,
18
- * would join the transaction; use Postgres where that matters.
19
- *
20
- * A call made inside `fn` with the `tx` it was given (on SQLite, the database
21
- * itself) joins the open transaction as a savepoint instead of waiting for it: a
22
- * nested failure undoes only the nested work, and the outer transaction decides
23
- * the commit. Nested calls must run one at a time.
24
- *
25
- * @param db - A Drizzle database, from `service.getDb()`.
26
- * @param fn - Receives the transaction handle to run queries on.
27
- * @returns What `fn` returned.
28
- * @throws What `fn` threw, after rolling back.
29
- */
30
- declare function runInTransaction<T>(db: any, fn: (tx: any) => Promise<T>): Promise<T>;
31
- /**
32
- * Run `fn` once the transaction that `db` belongs to has committed, or now when
33
- * `db` is not in one opened by `runInTransaction`. It never runs when that
34
- * transaction, or the savepoint it was queued in, rolls back. An error it throws
35
- * reaches the caller of the outermost `runInTransaction`, after the commit.
36
- *
37
- * @param db - The handle the work ran on: a `tx`, or a database.
38
- * @param fn - The side effect, such as clearing a cache.
39
- */
40
- declare function onTransactionCommit(db: unknown, fn: () => unknown): Promise<void>;
41
- type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
42
- interface RouteIR {
43
- readonly method: RouteMethod;
44
- readonly path: string;
45
- readonly service: string;
46
- readonly action: string;
47
- readonly kind: "action";
48
- readonly input: boolean;
49
- readonly output: boolean;
50
- readonly context: boolean;
51
- readonly authorize: boolean;
52
- readonly inputPrecedence: readonly ("query" | "params" | "body")[];
53
- readonly coercions: readonly {
54
- readonly key: string;
55
- readonly type: "number" | "boolean" | "array";
56
- }[];
57
- /** JSON projection for inspection and stale-artifact detection, not runtime validation. */
58
- readonly inputSchema?: unknown;
59
- readonly outputSchema?: unknown;
60
- }
61
- interface BrickIR {
62
- readonly version: 1;
63
- readonly target: "bun-elysia";
64
- readonly prefix: string;
65
- readonly services: readonly string[];
66
- readonly routes: readonly RouteIR[];
67
- readonly preparations: readonly {
68
- service: string;
69
- name: string;
70
- metadata: unknown;
71
- }[];
72
- readonly diagnostics: readonly string[];
73
- }
74
- /** An OpenAPI document as plain JSON. */
75
- type OpenApiDocument = Record<string, unknown>;
76
- /** An extra OpenAPI document for the API reference, such as Better Auth's. */
77
- interface ReferenceDocument {
78
- /** Name in the reference's list of documents. */
79
- title: string;
80
- /** The document, or a function returning it; called each time the app starts. */
81
- document: OpenApiDocument | (() => OpenApiDocument | Promise<OpenApiDocument>);
82
- }
83
- /** A named OpenAPI document ready to render. */
84
- interface ApiDocument {
85
- title: string;
86
- document: OpenApiDocument;
87
- }
88
- /** Developer documentation for the `brick dev` dashboard. */
89
- interface DocumentationOptions {
90
- /**
91
- * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the
92
- * app entry, as it reads in the file that sets it.
93
- */
94
- dir: string;
95
- /**
96
- * Module whose exports are React components for MDX, added to the built-in
97
- * ones; a relative path starts where `dir` does. A default export or a
98
- * `components` export holds the name-to-component map. The dashboard bundles
99
- * it, so it may import anything the project has.
100
- */
101
- components?: string;
102
- }
103
- interface ReferenceOptions {
104
- /** Also serve a standalone Scalar page here. Without a path, no page is served. */
105
- path?: string;
106
- title?: string;
107
- specUrl?: string;
108
- /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */
109
- documents?: ReferenceDocument[];
110
- }
111
- /** Renders the Scalar API reference page for the given OpenAPI URL. */
112
- declare function scalarDocsHTML(specUrl: string, title: string): string;
113
- /** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
114
- declare function referencePlugin(opts?: ReferenceOptions): Elysia;
115
- /** Mounts the Scalar reference route onto an existing app. */
116
- declare function registerReferenceRoute(app: Elysia, opts?: ReferenceOptions): Elysia;
117
- /** Renders the Swagger UI page. */
118
- declare function swaggerDocsHTML(specUrl: string, title: string): string;
119
- /** Who may open the dashboard that `brick start` serves for monitoring. */
120
- interface DashboardAuth {
121
- /**
122
- * Secrets that let a request in. A browser asks for one in its sign-in
123
- * prompt (any user name, the secret as the password), and monitors and
124
- * scripts send `Authorization: Bearer <secret>`. Give several to rotate one
125
- * while the other still works. Each is at least 16 characters long;
126
- * `openssl rand -base64 32` makes a good one.
127
- */
128
- token?: string | readonly string[];
129
- /**
130
- * Your own check, to sign people in with the auth the app already has: read
131
- * a session cookie, verify a Better Auth or Clerk session, look at a header
132
- * a proxy adds. It receives the request (method, URL, and headers; no body)
133
- * and returns `true` to let it in, `false` to refuse it with 401, or a
134
- * `Response` to send instead, such as a redirect to your login page. If it
135
- * throws or takes longer than five seconds, the request is refused with 503.
136
- *
137
- * A request is let in when it carries a valid `token`, or when this
138
- * returns `true`; give both to let monitors in by token and people in by
139
- * sign-in.
140
- */
141
- authorize?: (request: Request) => boolean | Response | Promise<boolean | Response>;
142
- }
143
- /**
144
- * The monitoring dashboard `brick start` serves beside the app, on a port of
145
- * its own: live requests, logs, errors, and the shape of the service, so it
146
- * stays reachable when the app's own routes are not. `brick dev` has its own
147
- * dashboard, set by command line options, and ignores this.
148
- *
149
- * Setting it turns on `telemetry`, since the dashboard shows what is traced.
150
- * While it is on, `ctx.logger` and `console` lines written during a request
151
- * go to the dashboard instead of the console.
152
- */
153
- interface DashboardOptions {
154
- /** Default 9400. */
155
- port?: number;
156
- /**
157
- * The address to listen on. Default `127.0.0.1`, reachable only from the same
158
- * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard
159
- * will not start on any other address without it.
160
- */
161
- host?: string;
162
- auth?: DashboardAuth;
163
- /**
164
- * Days of finished requests to keep on disk, in `.brick/` of the working
165
- * folder. Default 0: only what happened since the process started, which is
166
- * lost when it restarts. Needs a folder that outlives the container.
167
- */
168
- historyDays?: number;
169
- }
170
- type EndpointMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
171
- /** Logger subset handed to endpoint handlers (mirrors action context loggers). */
172
- interface EndpointLogger {
173
- info: (...args: any[]) => void;
174
- warn: (...args: any[]) => void;
175
- error: (...args: any[]) => void;
176
- debug: (...args: any[]) => void;
177
- }
178
- /** Context for raw endpoint handlers: Elysia route fields + Brick extras. */
179
- interface EndpointContext {
180
- params: Record<string, string>;
181
- query: Record<string, string | undefined>;
182
- body: unknown;
183
- headers: Record<string, string>;
184
- request: Request;
185
- /** Elysia response setter (status/headers). Mutate like in `app.get`. */
186
- set: {
187
- status?: number;
188
- headers: Record<string, string>;
189
- };
190
- /** Drizzle db from `service` (or first service with one); `undefined` when none. */
191
- db: any;
192
- logger: EndpointLogger;
193
- traceId: string;
194
- requestId: string;
195
- }
196
- interface EndpointDefinition {
197
- method: EndpointMethod;
198
- /** Elysia-style path, e.g. `/p/:slug`. */
199
- path: string;
200
- handler: (ctx: EndpointContext) => unknown | Promise<unknown>;
201
- /** Db source: instance or registered service name. Defaults to first service with a db. */
202
- service?: Service<any, any> | string;
203
- /** Explicit database handle, independent of a service. */
204
- database?: DatabaseHandle<unknown>;
205
- summary?: string;
206
- description?: string;
207
- tags?: string[];
208
- /** The plugin that contributed it; OpenAPI labels it `x-brick-plugin`. */
209
- plugin?: string;
210
- }
211
- /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
212
- declare function resolveEndpointDb(service: Service<any, any> | string | undefined, services: Service<any, any>[]): any;
213
- /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
214
- declare function createEndpointHandler(def: EndpointDefinition, services: Service<any, any>[]): (elysiaCtx: any) => Promise<unknown>;
215
- /** `/p/:slug` → `/p/{slug}` for OpenAPI. */
216
- declare function toOpenApiPath(elysiaPath: string): string;
217
- /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
218
- declare function endpointPaths(defs: EndpointDefinition[]): Record<string, any>;
219
- /** The app object returned by `brick`: Elysia plus `endpoint()`. */
220
- type BrickApp = Elysia<any, any, any, any, any, any, any> & {
221
- /** Service definitions, prefix, and telemetry setting chosen at construction. */
222
- readonly definition: {
223
- readonly routes: readonly RouteIR[];
224
- readonly sockets: readonly (BrickSocketSchema & {
225
- service: string;
226
- path: string;
227
- })[];
228
- readonly services: readonly Service<any, any>[];
229
- readonly prefix: string;
230
- readonly telemetry: boolean;
231
- readonly documentation?: DocumentationOptions;
232
- /** What `brick start` serves for monitoring; its `auth` is not enumerable. */
233
- readonly dashboard?: DashboardOptions;
234
- /** The listeners and settings of `events`, as plain data. */
235
- readonly events?: EventsDefinition;
236
- /** Every `definePlugin` installation, in install order. */
237
- readonly plugins?: readonly InstalledPlugin[];
238
- };
239
- /**
240
- * Run the plugins' `on("start")` handlers in install order, once. `listen`
241
- * calls it; `brick dev` and `brick start` await it before serving. `stop()`
242
- * runs their `on("stop")` handlers in reverse order.
243
- */
244
- start(): Promise<void>;
245
- /**
246
- * The events of this app, when `events` is set: start and stop delivery, drain
247
- * what is due, and see or retry what is parked. `brick dev` and `brick start`
248
- * start it for you.
249
- */
250
- readonly events?: EventsHub;
251
- /** Register a raw endpoint (outside the JSON action mesh). */
252
- endpoint(def: EndpointDefinition): void;
253
- /**
254
- * The OpenAPI documents behind the dashboard's APIs view: this app's own
255
- * unless `docs` is false, then those from `reference.documents`.
256
- */
257
- referenceDocuments(): Promise<ApiDocument[]>;
258
- /** All endpoints registered via `endpoint()` (declaration order). */
259
- listEndpoints(): EndpointDefinition[];
260
- };
261
- type CompiledHandler = (context: any) => unknown | Promise<unknown>;
262
- type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRuntime) => CompiledHandler;
263
- /** Retains Brick's existing source precedence and treatment of empty bodies. */
264
- declare function mergeInput(first: any, second: any, third: any): any;
265
- declare function checkDepth(value: unknown, action: string): void;
266
- declare function validate(check: NonNullable<CompiledRoutePlan["inputChecker"]>, value: unknown, action: string, stage: "input" | "output"): void;
267
- declare function mapError(err: unknown, set: any, options: {
268
- logger: Logger;
269
- requestId: string;
270
- }): ErrorEnvelope;
271
- declare const compilerRuntime: Readonly<{
272
- emptyServices: Readonly<{}>;
273
- defaultRequest: Request;
274
- nextSequence: () => string;
275
- mergeInput: typeof mergeInput;
276
- checkDepth: typeof checkDepth;
277
- validate: typeof validate;
278
- mapError: typeof mapError;
279
- isThenable: (value: any) => boolean;
280
- deny: (action: string, user: unknown) => never;
281
- }>;
282
- type ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;
283
- /** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
284
- declare function loadCompiledBrickApp(load: () => Promise<{
285
- default: unknown;
286
- }>, ir: BrickIR, bind: ApplicationBinder): Promise<BrickApp>;
287
- interface CompiledRoute {
288
- readonly ir: RouteIR;
289
- readonly handler: CompiledHandler;
290
- }
291
- interface CompiledApplication {
292
- readonly ir: BrickIR;
293
- readonly routes: readonly CompiledRoute[];
294
- }
295
- /** Startup compiler: analyzes once, then binds live callbacks. */
296
- declare function compileBrickApplication(options: {
297
- services: Service<any, any>[];
298
- prefix?: string;
299
- mode?: "specialized" | "generic";
300
- }): CompiledApplication;
301
- /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
302
- declare function bindCompiledApplication(ir: BrickIR, services: Service<any, any>[], factories: readonly HandlerFactory[]): CompiledApplication;
303
- interface RequestLoggingOptions {
304
- enabled?: boolean;
305
- logger?: (msg: string) => void;
306
- }
307
- /**
308
- * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
309
- * Timing is tracked per-Request via a WeakMap. The onError hook only logs and
310
- * returns undefined so existing error mapping is preserved. Logging only —
311
- * no CORS headers are set here.
312
- *
313
- * Hooks are registered with the "global" scope so they propagate to the
314
- * parent app when mounted via `app.use(...)` — Elysia scopes plain instance
315
- * hooks to the plugin's own routes. Timing is captured in beforeHandle
316
- * because request hooks are not propagated from a
317
- * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
318
- */
319
- declare function requestLoggingPlugin(opts?: RequestLoggingOptions): Elysia;
320
- /**
321
- * Which origins may call the app: an exact origin (`"https://app.example.com"`),
322
- * a list of them, or a predicate. `true` allows only the app's own origin.
323
- */
324
- type CorsOrigin = true | string | readonly string[] | ((origin: string, request: Request) => boolean);
325
- /** `brick({ cors })`: an origin rule, or the rule plus `credentials`. */
326
- type CorsOptions = CorsOrigin | {
327
- /** Default `true`: the app's own origin only. */
328
- origin?: CorsOrigin;
329
- /** Send `Access-Control-Allow-Credentials: true` to allowed origins (cookies, auth headers). */
330
- credentials?: boolean;
331
- };
332
- /**
333
- * Work out, once at startup, everything an action's route needs to answer a
334
- * request: where its input comes from (body, query, or path), the validators,
335
- * the authorization and execute functions, and its logger. Low level: `brick()`
336
- * does this for every route.
337
- *
338
- * @param service - The service the action belongs to.
339
- * @param action - The action.
340
- * @param routePath - The route's path.
341
- * @param method - The HTTP method (POST by default).
342
- * @returns The plan `executeCompiledRoute` runs.
343
- */
344
- declare function compileRoutePlan(service: Service, action: Action, routePath: string, method?: string): CompiledRoutePlan;
345
- /**
346
- * Answer one request for a compiled route: read the input, run the action, and
347
- * return its output or the error response, with the `x-trace-id` and
348
- * `x-request-id` headers set. Low level: `brick()` mounts this for every route.
349
- *
350
- * @param plan - From `compileRoutePlan`.
351
- * @param elysiaCtx - The Elysia request context: `params`, `body`, `query`,
352
- * `headers`, `request`, and `set`.
353
- * @returns The action's output, or an error envelope with the status set on `set`.
354
- */
355
- declare function executeCompiledRoute(plan: CompiledRoutePlan, elysiaCtx: any): Promise<any>;
356
- /**
357
- * An Elysia handler for one action: `compileRoutePlan` and
358
- * `executeCompiledRoute` together. Use it to mount an action on your own
359
- * Elysia app; `brick()` does it for you.
360
- *
361
- * @param service - The service the action belongs to.
362
- * @param action - The action.
363
- * @param routePath - The route's path.
364
- * @param method - The HTTP method (POST by default).
365
- * @returns A function from the Elysia context to the response.
366
- */
367
- declare function createActionHandler(service: Service, action: Action, routePath: string, method?: string): (elysiaCtx: any) => Promise<any>;
368
- interface CreateServerOptions {
369
- port?: number;
370
- /** Generate specialized handlers once at startup (default true). */
371
- compiler?: boolean;
372
- /** Ahead-of-time handlers already bound to the supplied services. */
373
- compilation?: CompiledApplication;
374
- services?: Service<any, any>[];
375
- prefix?: string;
376
- title?: string;
377
- version?: string;
378
- description?: string;
379
- docs?: boolean;
380
- openApiPath?: string;
381
- docsPath?: string;
382
- swaggerPath?: string;
383
- requestLogging?: boolean | RequestLoggingOptions;
384
- /**
385
- * `true` serves a Scalar page at /reference. Options serve one only with a
386
- * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.
387
- */
388
- reference?: boolean | ReferenceOptions;
389
- secrets?: {
390
- source?: SecretSource;
391
- validate?: boolean;
392
- };
393
- /** Raw endpoints (outside the JSON action mesh), mounted at startup. */
394
- endpoints?: EndpointDefinition[];
395
- /**
396
- * Record request, action, and RPC spans with OpenTelemetry (default false).
397
- * Spans go to the globally registered tracer provider; without one they are
398
- * no-ops. `brick dev` shows them in its dashboard.
399
- */
400
- telemetry?: boolean;
401
- /**
402
- * Developer documentation for the `brick dev` dashboard (its Docs tab): a
403
- * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and
404
- * `meta.json` for ordering. A string is the folder. Relative paths start at
405
- * the folder of the app entry, as they read in the file that sets them (from
406
- * `src/app.ts`, `"../docs"` is `docs/` at the project root). Needs
407
- * `fumadocs-core` and `@mdx-js/mdx` installed.
408
- */
409
- documentation?: string | DocumentationOptions;
410
- /**
411
- * Monitoring dashboard for `brick start`, on a port of its own and behind
412
- * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.
413
- */
414
- dashboard?: DashboardOptions;
415
- /**
416
- * Record events in the same database transaction as the writes that cause them,
417
- * and deliver them to listeners after the commit. Generated CRUD writes emit
418
- * `<resource>.create`, `<resource>.update` and `<resource>.delete`. A service
419
- * records events once its database holds an `outboxTable()`. Reads emit nothing,
420
- * and an app without this option behaves exactly as before. See `EventsOptions`.
421
- */
422
- events?: EventsOptions;
423
- /**
424
- * Socket fan-out. `broker` carries emits and kicks between processes
425
- * (default: this process only). See `redisBroker`. The app closes it on stop.
426
- * `secret` signs replay sequences; give every process the same one so a
427
- * client can resume on any of them (default: random per process).
428
- */
429
- sockets?: {
430
- broker?: SocketBroker;
431
- secret?: string;
432
- };
433
- /**
434
- * The values of the services' declared `deps` (`port<T>()`), by name. Every
435
- * declared dep must be provided, and every provided one declared. Actions read
436
- * them as `ctx.deps`, listeners and workflow steps with `useDeps()`.
437
- */
438
- deps?: Record<string, unknown>;
439
- /**
440
- * App-wide plugins from `definePlugin`, in install order: their `app` part
441
- * adds start/stop lifecycle, middleware and listeners. Plugins installed with
442
- * `service.use()` or `resource.use()` take part too, before these.
443
- */
444
- plugins?: readonly PluginInstance<any, any>[];
445
- /**
446
- * CORS for browser callers on other origins. `true` allows the app's own
447
- * origin; a string, list or predicate names the allowed origins, compared
448
- * exactly. `{ origin, credentials }` adds `credentials: true` for cookies.
449
- * Other origins get no `Access-Control-Allow-Origin`. Preflights are answered.
450
- */
451
- cors?: false | CorsOptions;
452
- }
453
- /**
454
- * Create the HTTP application: an Elysia app that serves every service's
455
- * actions (and the tools that opt in with `http: true`) as routes, with
456
- * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,
457
- * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.
458
- *
459
- * Services come from the global registry unless `services` is given. The app
460
- * does not listen by itself: export it from your entry file, where `brick dev`,
461
- * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your
462
- * own server bootstrap.
463
- *
464
- * @param options - `prefix` for action routes (default `/api`), `services`,
465
- * `title`, `version`, and `description` for the OpenAPI document, `docs` and the
466
- * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
467
- * `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.
468
- * @returns The app, with `definition` (its services, prefix, and routes),
469
- * `endpoint()` to add raw routes, and `listEndpoints()` to list them.
470
- * @throws When a required secret is missing, `documentation` or `dashboard`
471
- * is invalid, or `deps` misses a dep a service declares or has one none declares.
472
- * @example
473
- * import { brick } from "@brickkit/core";
474
- * import { pagesService } from "./services/pages";
475
- *
476
- * export default brick({
477
- * services: [pagesService],
478
- * title: "Pages API",
479
- * telemetry: true,
480
- * });
481
- */
482
- declare function brick(options?: CreateServerOptions): BrickApp;
483
- /**
484
- * Whether a value is an application made by `brick()`. It checks for the
485
- * methods and `definition` a `BrickApp` has, so it also recognizes one built by
486
- * another copy of the package.
487
- *
488
- * @param app - Anything, such as the default export of an entry file.
489
- * @returns `true` for a `BrickApp`, narrowing its type.
490
- */
491
- declare function isBrickApp(app: unknown): app is BrickApp;
492
- /**
493
- * Check that a module's default export is an application ready to be served,
494
- * for tools that load an entry file.
495
- *
496
- * @param app - The default export of an entry file.
497
- * @returns The app.
498
- * @throws When it is not a `BrickApp`, or it already called `.listen()`: the
499
- * entry must only build the app, and leave listening to the server bootstrap.
500
- */
501
- declare function requireBrickApp(app: unknown): BrickApp;
502
- /** What a raw route handler receives from `traceRoute`. Read the body from `request`. */
503
- interface RawRouteContext {
504
- request: Request;
505
- headers: Record<string, string | undefined>;
506
- set: {
507
- status?: unknown;
508
- headers?: Record<string, unknown>;
509
- };
510
- params: Record<string, string>;
511
- query: Record<string, string | undefined>;
512
- }
513
- /**
514
- * Wrap a raw route handler so each of its requests gets a server span. Use it
515
- * for routes registered directly on the app, outside actions and endpoints,
516
- * such as auth or webhook routes. Spans are recorded whenever a tracer provider
517
- * is registered; `brick({ telemetry })` does not apply to these routes.
518
- *
519
- * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia
520
- * decides what to parse from the handler's destructuring, and forwarding the
521
- * whole context would parse the body and leave `request.json()` with nothing.
522
- */
523
- declare function traceRoute<T>(route: string, handler: (context: RawRouteContext) => T): (context: RawRouteContext) => T;
524
- /** Emits framework code only. User callbacks remain closures bound separately. */
525
- declare function emitHandlerFactory(route: RouteIR): string;
526
- interface DatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> extends Omit<SQLiteDatabaseConfig<TSchema>, "client">, Omit<PostgresDatabaseConfig<TSchema>, "client"> {
527
- client?: SQLiteDatabaseConfig<TSchema>["client"] | PostgresDatabaseConfig<TSchema>["client"];
528
- /** Database engine. Default: 'sqlite' */
529
- engine?: "sqlite" | "postgres" | "clickhouse";
530
- /** Optional service name associated with this database */
531
- name?: string;
532
- }
533
- type BrickDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;
534
- /**
535
- * Creates a database instance based on the provided configuration.
536
- * Zero-config: calling `createDatabase()` returns an ultra-fast Bun-native SQLite
537
- * database in `:memory:` mode wrapped with Drizzle ORM.
538
- */
539
- declare function createDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: DatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;
540
- /**
541
- * Apply the migrations in a folder that have not run yet, in order, and record
542
- * them in the database's `__drizzle_migrations` table. The folder is the one
543
- * `brick db generate` (or drizzle-kit) writes: `<out>/<database name>`.
544
- *
545
- * @param database - A handle from `defineDatabase`.
546
- * @param migrationsFolder - The folder holding `meta/_journal.json`.
547
- * @example
548
- * await migrateDatabase(database, "./drizzle/pages");
549
- */
550
- declare function migrateDatabase(database: DatabaseHandle<unknown>, migrationsFolder: string): Promise<void>;
551
- /** Attach a defined database. Schema changes remain the caller's responsibility. */
552
- declare function attachDatabase<TDb>(service: Service<TDb, any>, database: DatabaseHandle<TDb>): TDb;
553
- /**
554
- * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition
555
- * directly from a Drizzle table schema.
556
- */
557
- declare function generateSQLiteTableDdl(table: any): string;
558
- /**
559
- * Generates idempotent secondary index DDL for a Drizzle table.
560
- * Covers owner scoping, sort columns, and exact-match filters.
561
- * UNIQUE columns already carry an implicit index — skipped here.
562
- * FTS/trigram indexes are handled separately by the search layer.
563
- */
564
- declare function generateSQLiteIndexDdl(table: any, opts?: {
565
- ownerField?: string;
566
- sortFields?: string[];
567
- }): string[];
568
- /**
569
- * Ensures secondary indexes exist for a resource table.
570
- * SQLite: B-tree indexes for owner scope + sort + composite hot path.
571
- * Postgres: same B-trees plus pg_trgm GIN indexes for substring search.
572
- * Best-effort: failures warn and continue (e.g. read-only replicas).
573
- */
574
- declare function ensureResourceIndexes(db: any, table: any, opts?: {
575
- ownerField?: string;
576
- sortFields?: string[];
577
- searchFields?: string[];
578
- }): void;
579
- /**
580
- * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.
581
- * Idempotent; safe to call on every resource registration.
582
- * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.
583
- */
584
- declare function ensureSQLiteFts(db: any, table: any, searchCols: string[]): void;
585
- /**
586
- * Builds an FTS5 MATCH condition for a resource search term.
587
- * Returns null when the term has no usable tokens or FTS errors.
588
- * Caller falls back to LIKE in that case.
589
- */
590
- declare function buildFtsMatchQuery(search: string): string | null;
591
- /**
592
- * The schema drizzle-kit reads: the tables, plus the Postgres schemas
593
- * (namespaces) and enums they use, which drizzle-kit only creates when handed.
594
- *
595
- * @param tables - Drizzle tables, all of one engine.
596
- * @returns A record to pass to drizzle-kit's API (`pushSchema`, `generateDrizzleJson`).
597
- */
598
- declare function drizzleSchema(tables: readonly Table[]): Record<string, unknown>;
599
- /**
600
- * Create the declared tables that do not exist yet. A development and test
601
- * helper: never called by services, resources or server startup, and never
602
- * changes a table that exists. Use `brick db generate` / `brick db migrate`
603
- * for production schema changes.
604
- *
605
- * SQLite: `CREATE TABLE IF NOT EXISTS` per table, synchronously.
606
- * Postgres: drizzle-kit (an optional peer dependency) writes the DDL for the
607
- * missing tables, their enums, indexes and foreign keys, applied in one
608
- * transaction. Returns a promise to await.
609
- */
610
- declare function syncSchema(tablesOrService: Map<string, any> | any[] | Record<string, any> | Service, dbInstance?: any): Promise<void> | void;
611
- /** An in-process caller for one action: its input, then an optional call context. */
612
- type ServiceActionCaller<A> = undefined extends InferActionInput<A> ? (input?: InferActionInput<A>, ctx?: Partial<ActionContext>) => Promise<InferActionOutput<A>> : (input: InferActionInput<A>, ctx?: Partial<ActionContext>) => Promise<InferActionOutput<A>>;
613
- /**
614
- * What `useService` returns: the service's actions as methods, with each
615
- * resource's actions under the resource's name. Sockets are left out.
616
- */
617
- type ServiceClient<T> = { [K in keyof T as T[K] extends BrickClientSocket<any, any> ? never : K]: T[K] extends BrickClientAction<any, any, any> | Action<any, any, any, any> | ((...args: any[]) => any) ? ServiceActionCaller<T[K]> : ServiceClient<T[K]>; };
618
- declare const serviceNameType: unique symbol;
619
- /** Type only: the literal name of a service, which `useService` finds its contract by. */
620
- interface NamedService<N extends string> {
621
- readonly [serviceNameType]?: N;
622
- }
623
- /** What `useService` returns while the contract does not describe the service yet. */
624
- type UntypedServiceClient = {
625
- [name: string]: any;
626
- };
627
- /**
628
- * Call another service's actions in-process, typed from that service. Each
629
- * action is a method, and each resource's actions sit under the resource's
630
- * name: `billing.charge(input)`, `billing.invoice.list()`.
631
- *
632
- * The types come from the app's generated contract (`_brick/contract.ts`, which
633
- * `brick dev` and `brick gen client` keep current), so renaming an action or
634
- * changing its input is a compile error at every caller. Until the contract
635
- * describes the service, the client is untyped.
636
- *
637
- * A call runs through the target's own validation and authorization, with the
638
- * target's database, context and deps (never the caller's), and shows as an
639
- * `rpc` span in the trace.
640
- *
641
- * @param service - The service to call, as `defineService` returned it.
642
- * @param options - `from` (the calling service's name, which becomes `ctx.caller`
643
- * in the target and cannot be spoofed) and `context` (defaults for every call).
644
- * Each call also takes an optional call context after its input.
645
- * @returns The client.
646
- * @throws On a call, when the service is not registered or has no such action.
647
- * @example
648
- * import { useService } from "@brickkit/core";
649
- * import { billingService } from "../billing/billing.service";
650
- *
651
- * const billing = useService(billingService, { from: "orders" });
652
- * await billing.charge({ orderId, amountCents });
653
- * await billing.invoice.list({ limit: 10 });
654
- */
655
- declare function useService<const N extends string = string>(service: {
656
- readonly name: string;
657
- } & NamedService<N>, options?: ProxyOptions): N extends keyof BrickServices ? ServiceClient<BrickServices[N]> : UntypedServiceClient;
658
- declare class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> implements Service<TDb, TServiceContext> {
659
- readonly name: string;
660
- readonly options: ServiceOptions<TServiceContext, TDb>;
661
- readonly actions: Map<string, Action<any, any, any, any>>;
662
- readonly tools: Map<string, Tool<any, any, any, any>>;
663
- readonly tables: Map<string, any>;
664
- private readonly sockets;
665
- readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext, {}, EventCatalog>>;
666
- readonly preparations: Map<string, PreparationContribution>;
667
- /** Where each `kind:name` was defined, to reject duplicates from another file. */
668
- private readonly sites;
669
- private database?;
670
- private _isBuilt;
671
- /** The declared events: `service.events.<name>`. */
672
- readonly events: Readonly<Record<string, EventRef>>;
673
- constructor(name: string, options?: ServiceOptions<TServiceContext, TDb>);
674
- use<A>(plugin: ServicePlugin<this, A>): A;
675
- get db(): TDb | undefined;
676
- get isBuilt(): boolean;
677
- /**
678
- * Closes declarations after plugins have registered their actions and preparations.
679
- */
680
- build(): this;
681
- private claim;
682
- contributePreparation(contribution: PreparationContribution): void;
683
- listPreparations(): PreparationContribution[];
684
- prepareContributions(): void;
685
- registerTable(table: any): this;
686
- resource: <TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions & Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>) => Resource<TTable, BaseContext<TDb> & TServiceContext, ResourceIdentity<TTable, TOptions>>;
687
- getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
688
- listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
689
- action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
690
- action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
691
- action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
692
- tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
693
- tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
694
- tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
695
- getTool(name: string): Tool<any, any, any, any> | undefined;
696
- socket<const I extends SocketSchemas, const O extends SocketSchemas, const E extends Record<string, ActionErrorDefinition> = {}>(config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext, E>): BrickSocketHandle<SocketPayloads<O>>;
697
- listSockets(): RegisteredSocket[];
698
- listTools(): Tool<any, any, any, any>[];
699
- getAction(name: string): Action<any, any, any, any> | undefined;
700
- listActions(): Action<any, any, any, any>[];
701
- getDb(): TDb | undefined;
702
- /** The handle from `defineDatabase`, without connecting. */
703
- getDatabaseHandle(): DatabaseHandle<TDb> | undefined;
704
- /** What a write needs to record events. Set by `brick({ events })`. */
705
- recorder?: ServiceEvents;
706
- getOutbox(): OutboxTable | undefined;
707
- setRecorder(recorder: ServiceEvents | undefined): void;
708
- /** Whether the service declares an event catalog. */
709
- get hasCatalog(): boolean;
710
- /** @throws When the event is not in the catalog or its payload does not match. */
711
- checkEvent(name: string, payload: unknown): void;
712
- /** The values of this service's `deps`. Set by `brick({ deps })`. */
713
- deps?: Readonly<Record<string, unknown>>;
714
- setDeps(deps: Readonly<Record<string, unknown>>): void;
715
- setDb(database: DatabaseHandle<TDb>): void;
716
- /**
717
- * Resolves the complete service execution context once per incoming request.
718
- * Merges framework BaseContext with the service's custom context hook.
719
- * Always rebuilds context for this service to prevent caller context from overriding.
720
- */
721
- resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
722
- introspect(): ServiceSchema;
723
- }
724
- /**
725
- * Declare a service: a named group of actions, tools, and resources with its own
726
- * database and request context. It is registered globally, so `brick()`, the
727
- * OpenAPI generator, and `useService` find it by name.
728
- *
729
- * Add actions with `service.action(...)`, tools with `service.tool(...)`,
730
- * resources with `service.resource(...)`, and plugins with `service.use(...)`.
731
- *
732
- * @param name - Unique name. It is the service's segment of every action route
733
- * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it
734
- * again from the same file (a dev reload) replaces it; from another file throws.
735
- * @param options - `database` (a handle from `defineDatabase`), `deps` (typed
736
- * slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),
737
- * `context` (adds fields such as the signed-in user to every action's `ctx`),
738
- * `events` (the event catalog: a payload schema per event name, recorded as
739
- * `<service>.<name>` and offered as `service.events.<name>`).
740
- * @returns The service.
741
- * @example
742
- * import { defineDatabase, defineService, t } from "@brickkit/core";
743
- *
744
- * const database = defineDatabase({ tables: { pages } });
745
- *
746
- * export const pagesService = defineService("pages", {
747
- * database,
748
- * // Added to `ctx` in every action of this service.
749
- * context: async ({ request }) => ({ user: await readUser(request) }),
750
- * });
751
- *
752
- * pagesService.action({
753
- * name: "list",
754
- * input: t.Object({ limit: t.Optional(t.Number()) }),
755
- * output: t.Array(t.Object({ id: t.String(), title: t.String() })),
756
- * execute: ({ input, ctx }) =>
757
- * ctx.db.select().from(pages).limit(input.limit ?? 20),
758
- * });
759
- */
760
- declare function defineService<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>, const TEvents extends EventCatalog = {}, const TName extends string = string, TPorts extends Ports = {}>(name: TName, options?: ServiceOptions<TServiceContext, TDb> & {
761
- events?: TEvents;
762
- deps?: TPorts;
763
- }): Service<TDb, {} extends TPorts ? TServiceContext : TServiceContext & {
764
- deps: DepsOf<TPorts>;
765
- }, TEvents> & NamedService<TName>;
766
- /** Keep validators browser-safe and reject schemas whose behavior cannot cross JSON. */
767
- declare function serializeSocketSchema(schema: TSchema): unknown;
768
- interface RedisBrokerOptions {
769
- /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */
770
- url?: string;
771
- /** Emits held while Redis is unreachable; older ones are dropped. Default 1000. */
772
- queue?: number;
773
- }
774
- /**
775
- * Fans socket emits and kicks out across processes through Redis pub/sub, one
776
- * channel per room topic. An emit is a PUBLISH only: every process, the emitting
777
- * one included, delivers it once to its own connections. Uses Bun's built-in
778
- * Redis client and two connections, one to publish and one to subscribe.
779
- */
780
- declare function redisBroker(options?: RedisBrokerOptions): SocketBroker;
781
- interface ActionAccessInfo {
782
- hasAuthorize: boolean;
783
- hasScope: boolean;
784
- policy: ActionAccessPolicy;
785
- }
786
- /**
787
- * Cross-copy access metadata protocol. CRUD enforces its access policy
788
- * inside `execute`, so `config.authorize` is absent and introspection
789
- * can't see it. The plugin stamps each action under this process-global
790
- * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
791
- * the binding survives a second copy of core (bundler SSR, Vitest),
792
- * same as the plugin action-binding key.
793
- */
794
- declare const ACTION_ACCESS_KEY: unique symbol;
795
- /**
796
- * Record how an action is protected, for tools that cannot read it from the
797
- * configuration: plugins such as `crud` enforce access inside `execute`, so the
798
- * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
799
- * read what is recorded here.
800
- *
801
- * @param action - The action to describe.
802
- * @param info - Whether it checks authorization and whether it scopes queries,
803
- * and the resulting policy.
804
- */
805
- declare function setActionAccess(action: object, info: ActionAccessInfo): void;
806
- /**
807
- * How an action is protected: `"public"` when nothing checks the caller,
808
- * `"authorized"` when an `authorize` does, and `"scoped"` when the action also
809
- * limits what rows the caller can reach. It reads what a plugin recorded with
810
- * `setActionAccess`, else the action's own `authorize`, and keeps the policy
811
- * consistent with the flags.
812
- *
813
- * @param action - An action, or any object a plugin described.
814
- * @returns `hasAuthorize`, `hasScope`, and `policy`.
815
- */
816
- declare function getActionAccess(action: Action | object): ActionAccessInfo;
817
- /**
818
- * The `error` helpers an action receives: one function per error code that
819
- * throws an `ActionExecutionError` with that code and status. The standard HTTP
820
- * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
821
- * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
822
- * them or replace one.
823
- *
824
- * @param errorsDef - The action's `errors`: for each code, its `message` and
825
- * `status` (default 400).
826
- * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
827
- * and always throw.
828
- */
829
- declare function buildErrorHelpers<TErrors extends Record<string, ActionErrorDefinition>>(errorsDef?: TErrors): ErrorBuilder<TErrors>;
830
- /** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */
831
- declare function errorsOf<TErrors extends Record<string, ActionErrorDefinition>>(action: {
832
- config: {
833
- errors?: TErrors;
834
- };
835
- }): TErrors;
836
- /**
837
- * Define an action: a typed, validated function that Brick serves over HTTP,
838
- * runs in-process, and exposes to the typed client and OpenAPI.
839
- *
840
- * A call runs in order: the input is validated against `input` (an invalid one
841
- * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;
842
- * `execute` runs; and its result is validated against `output` (a mismatch is a
843
- * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared
844
- * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value
845
- * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response
846
- * and in the log.
847
- *
848
- * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`
849
- * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.
850
- * Where it is given, `execute` can rely on what it checked.
851
- *
852
- * @param config - `name`, `execute`, and optionally `description`, `input` and
853
- * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to
854
- * change the route (POST by default), `tags`, and `emits`.
855
- * @returns The action. Register it with `service.action(action)`; call it
856
- * directly with `action.run(input, ctx)`.
857
- * @example
858
- * import { defineAction, t } from "@brickkit/core";
859
- *
860
- * export const getPage = defineAction({
861
- * name: "get",
862
- * method: "GET",
863
- * input: t.Object({ id: t.String() }),
864
- * output: t.Object({ id: t.String(), title: t.String() }),
865
- * errors: { PAGE_GONE: { message: "That page was removed", status: 410 } },
866
- * authorize: ({ user }) => user != null,
867
- * execute: async ({ input, ctx, error }) => {
868
- * const page = await findPage(ctx.db, input.id);
869
- * if (!page) throw error.NOT_FOUND("No such page");
870
- * return page;
871
- * },
872
- * });
873
- */
874
- declare function defineAction<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>(config: ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>): Action<TInputSchema, TOutputSchema, TErrors, TContext>;
875
- declare function defineAction<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>(config: ActionConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>): Action<TInputSchema, TOutputSchema, TErrors, TContext>;
876
- /**
877
- * The URL segment for a declared name: `orderBilling` becomes `order-billing`,
878
- * `importCSV` becomes `import-csv`. Dots and existing dashes stay.
879
- */
880
- declare function kebabCase(name: string): string;
881
- interface ActionRoute {
882
- method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
883
- path: string;
884
- }
885
- /**
886
- * Where an action is served over HTTP: its method and its path under the owner
887
- * tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource
888
- * action's `${prefix}/${service}/${resource}[/:id]/${action}`).
889
- *
890
- * @param action - An action registered on a service.
891
- * @param prefix - The application's route prefix (default `/api`).
892
- * @returns `false` when a plugin switched the route off, otherwise the route.
893
- */
894
- declare function getActionRoute(action: Action<any, any, any, any>, prefix?: string): ActionRoute | false;
895
- /** Stamped on actions declared with `resource.action(...)`. */
896
- interface ResourceActionInfo {
897
- resource: string;
898
- /** The declared name, without the `resource.` prefix. */
899
- name: string;
900
- record: boolean;
901
- /** A record action's own access rule. */
902
- access?: ResourceActionAccess;
903
- }
904
- /**
905
- * Load the row a record action (or command) works on, through its `access`.
906
- *
907
- * @returns The row, or `undefined` when it is missing or hidden.
908
- * @throws When `access` is missing.
909
- */
910
- declare function loadRecord(resource: Resource<any, any, any>, args: {
911
- id: unknown;
912
- ctx: any;
913
- db?: any;
914
- access?: ResourceActionAccess;
915
- }): Promise<Record<string, unknown> | undefined>;
916
- /** Declares a plugin host without registering actions or changing the schema. */
917
- declare function defineResource<TTable = any, TCtx extends ActionContext = ActionContext, const O extends ResourceTypeOptions = ResourceTypeOptions>(service: Service<any, any>, config: ResourceConfig<TTable, TCtx> & O): Resource<TTable, TCtx, ResourceIdentity<TTable, O>>;
918
- interface ArchitectureApplication {
919
- services: readonly Service[];
920
- routes: readonly RouteIR[];
921
- events?: EventsDefinition;
922
- sockets?: readonly (BrickSocketSchema & {
923
- service: string;
924
- path: string;
925
- })[];
926
- plugins?: readonly InstalledPlugin[];
927
- }
928
- declare class ServiceRegistry {
929
- private _revision;
930
- /** Definition revision for invalidating serialized architecture snapshots. */
931
- get revision(): number;
932
- touch(): void;
933
- private services;
934
- private sites;
935
- private routes;
936
- /** Remember the actual registered routes for subsequent registry exports. */
937
- setApplicationRoutes(application: ArchitectureApplication): void;
938
- /** @throws When a different file already registered a service with this name. */
939
- register(service: Service, site?: string | undefined): void;
940
- get(name: string): Service | undefined;
941
- has(name: string): boolean;
942
- list(): Service[];
943
- clear(): void;
944
- exportArchitecture(application?: ArchitectureApplication): ArchitectureSchema;
945
- }
946
- /**
947
- * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
948
- * generator, `useService`, and the dashboard find services by name.
949
- *
950
- * @returns The current global registry.
951
- */
952
- declare function getGlobalRegistry(): ServiceRegistry;
953
- /**
954
- * Start over with an empty global registry. For tests, which define the same
955
- * services again in each case; an application never needs it.
956
- */
957
- declare function resetGlobalRegistry(): void;
958
- /**
959
- * The compiled validator for a TypeBox schema. Compiling is slow and checking
960
- * is fast, so each schema is compiled once and kept for as long as the schema
961
- * object lives.
962
- *
963
- * @param schema - A TypeBox schema.
964
- * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.
965
- */
966
- declare function getCompiledCheck<T extends TSchema$1>(schema: T): TypeCheck<T>;
967
- /**
968
- * Check a value against a schema, the way actions check their input and output.
969
- *
970
- * @param schema - A TypeBox schema, or `undefined` to accept anything.
971
- * @param value - The value to check.
972
- * @returns `{ success: true, data }`, or `{ success: false, errors }` with a
973
- * `path`, `message`, `type`, and the offending `value` for each problem.
974
- */
975
- declare function validateWithSchema<T extends TSchema$1>(schema: T | undefined, value: unknown): {
976
- success: true;
977
- data: Static$1<T>;
978
- } | {
979
- success: false;
980
- errors: ValidationErrorItem[];
981
- };
982
- interface OpenApiGeneratorOptions {
983
- title?: string;
984
- version?: string;
985
- description?: string;
986
- prefix?: string;
987
- services?: Service<any, any>[];
988
- registry?: ServiceRegistry;
989
- }
990
- /**
991
- * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors
992
- * (`{ $id: "T0", ..., { $ref: "T0" } }`). OpenAPI interprets a bare `$ref`
993
- * as an external file reference, so downstream tooling tries to load a
994
- * file named `T0` and fails. Hoist every anchored subschema into
995
- * `#/components/schemas/` and rewrite the refs to local pointers.
996
- * First definition wins when one `$id` is declared twice.
997
- */
998
- declare function hoistAnchoredSchemas(spec: Record<string, any>): string[];
999
- /**
1000
- * Build the OpenAPI 3.1 document for the services: one path per action route,
1001
- * with request and response schemas from the actions' TypeBox schemas, their
1002
- * declared errors, tags by service, and a bearer security scheme where any
1003
- * action needs authorization. Declared events are listed under `x-brick-events`,
1004
- * by wire name, with their service and payload schema.
1005
- *
1006
- * `brick()` calls this for `/openapi.json`; call it yourself to write the
1007
- * document to a file or feed another tool.
1008
- *
1009
- * @param options - `title`, `version`, and `description` for the `info` block,
1010
- * `prefix` (default `/api`), and the `services` or `registry` to describe
1011
- * (the global registry by default).
1012
- * @returns The document as a plain object.
1013
- */
1014
- declare function generateOpenApiSpec(options?: OpenApiGeneratorOptions): Record<string, any>;
1015
- /**
1016
- * Define a tool: an action that AI agents can call through MCP. It takes the
1017
- * same configuration as `defineAction` (validation, `authorize`, errors), plus
1018
- * `title`, `annotations` (the MCP hints about what the tool does), and `http`
1019
- * to also serve it over HTTP and in OpenAPI (off by default).
1020
- *
1021
- * @param config - An action configuration and tool options. `input` must be an
1022
- * object schema, since MCP passes arguments by name.
1023
- * @returns The tool, which is also an action. Register it with `service.tool(tool)`.
1024
- * @throws When `input` is not an object schema.
1025
- * @example
1026
- * import { defineTool, t } from "@brickkit/core";
1027
- *
1028
- * export const echoTool = defineTool({
1029
- * name: "echo",
1030
- * title: "Echo a message",
1031
- * description: "Returns the message it is given.",
1032
- * input: t.Object({ message: t.String() }),
1033
- * output: t.String(),
1034
- * execute: ({ input }) => `Echo: ${input.message}`,
1035
- * });
1036
- */
1037
- declare function defineTool<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>(config: ToolConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;
1038
- declare function defineTool<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>(config: ToolConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;
1039
- /**
1040
- * Whether a value was made with `defineTool`, as opposed to `defineAction`.
1041
- *
1042
- * @param value - Anything.
1043
- * @returns `true` for a tool, narrowing its type.
1044
- */
1045
- declare function isTool(value: unknown): value is Tool<any, any, any, any>;
1046
- interface McpToolDefinition {
1047
- name: string;
1048
- title?: string;
1049
- description: string;
1050
- inputSchema: unknown;
1051
- /** The tool's `output` schema; a non-object one is wrapped as `{ result }`. */
1052
- outputSchema?: unknown;
1053
- annotations: ToolAnnotations;
1054
- }
1055
- interface McpRegistryOptions {
1056
- services?: readonly Pick<Service<any, any>, "listTools">[];
1057
- tools?: readonly Tool<any, any, any, any>[];
1058
- }
1059
- interface McpRegistry {
1060
- listTools(): McpToolDefinition[];
1061
- callTool(name: string, args?: Record<string, unknown>, ctx?: Partial<ActionContext>): Promise<unknown>;
1062
- }
1063
- declare class UnknownToolError extends Error {
1064
- constructor(name: string);
1065
- }
1066
- /** Collect only explicitly defined tools, without exposing ordinary actions. */
1067
- declare function createMcpRegistry(options: McpRegistryOptions): McpRegistry;
1068
- interface McpHandlerOptions {
1069
- registry: McpRegistry;
1070
- serverInfo: {
1071
- name: string;
1072
- version: string;
1073
- title?: string;
1074
- };
1075
- /** Versions supported by this transport, newest first. */
1076
- protocolVersions?: readonly string[];
1077
- }
1078
- /** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
1079
- declare function createMcpHandler(options: McpHandlerOptions): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>;
1080
- interface ErrorEnvelope {
1081
- name: string;
1082
- code: string;
1083
- message: string;
1084
- status: number;
1085
- requestId: string;
1086
- details?: unknown;
1087
- errors?: ValidationError["errors"];
1088
- }
1089
- type ErrorContext = {
1090
- logger: Pick<Logger, "error">;
1091
- requestId: string;
1092
- };
1093
- /**
1094
- * Turn what an action threw into the JSON body of its HTTP response, and record
1095
- * the failure on the active trace. Declared failures and validation errors keep
1096
- * their code, status, and details; anything else is logged and answered as a
1097
- * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.
1098
- *
1099
- * @param err - Whatever was thrown.
1100
- * @param context - A `logger` with `error()`, and the `requestId` to put in the body.
1101
- * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and
1102
- * `details` or `errors` when there are any.
1103
- */
1104
- declare function toErrorResponse(err: unknown, context: ErrorContext): ErrorEnvelope;
1105
- export { desc as $, endpointPaths as $t, defineAction as A, CreateServerOptions as At, defineService as B, CompiledRoute as Bt, defineResource as C, relations as Ct, getActionRoute as D, traceRoute as Dt, ResourceActionInfo as E, emitHandlerFactory as Et, setActionAccess as F, CorsOptions as Ft, BrickDatabase as G, HandlerFactory as Gt, ServiceClient as H, compileBrickApplication as Ht, RedisBrokerOptions as I, CorsOrigin as It, and$1 as J, EndpointContext as Jt, DatabaseConfig as K, compilerRuntime as Kt, redisBroker as L, RequestLoggingOptions as Lt, ACTION_ACCESS_KEY as M, compileRoutePlan as Mt, ActionAccessInfo as N, createActionHandler as Nt, kebabCase as O, isBrickApp as Ot, getActionAccess as P, executeCompiledRoute as Pt, createDatabase as Q, createEndpointHandler as Qt, serializeSocketSchema as R, requestLoggingPlugin as Rt, resetGlobalRegistry as S, or$1 as St, ActionRoute as T, syncSchema as Tt, UntypedServiceClient as U, loadCompiledBrickApp as Ut, ServiceActionCaller as V, bindCompiledApplication as Vt, useService as W, CompiledHandler as Wt, attachDatabase as X, EndpointLogger as Xt, asc$1 as Y, EndpointDefinition as Yt, buildFtsMatchQuery as Z, EndpointMethod as Zt, Type as _, runInTransaction as _n, lte$1 as _t, McpRegistryOptions as a, DocumentationOptions as an, generateSQLiteTableDdl as at, ServiceRegistry as b, not as bt, createMcpHandler as c, ReferenceOptions as cn, gt as ct, isTool as d, scalarDocsHTML as dn, inArray$1 as dt, resolveEndpointDb as en, drizzleSchema as et, OpenApiGeneratorOptions as f, swaggerDocsHTML as fn, is as ft, TSchema$1 as g, onTransactionCommit as gn, lt$1 as gt, Static$1 as h, RouteMethod as hn, like as ht, McpRegistry as i, ApiDocument as in, generateSQLiteIndexDdl as it, errorsOf as j, brick as jt, buildErrorHelpers as k, requireBrickApp as kt, createMcpRegistry as l, referencePlugin as ln, gte as lt, hoistAnchoredSchemas as m, RouteIR as mn, isNull as mt, toErrorResponse as n, DashboardAuth as nn, ensureSQLiteFts as nt, McpToolDefinition as o, OpenApiDocument as on, getTableColumns$1 as ot, generateOpenApiSpec as p, BrickIR as pn, isNotNull as pt, Table$1 as q, BrickApp as qt, McpHandlerOptions as r, DashboardOptions as rn, eq$1 as rt, UnknownToolError as s, ReferenceDocument as sn, getTableName$1 as st, ErrorEnvelope as t, toOpenApiPath as tn, ensureResourceIndexes as tt, defineTool as u, registerReferenceRoute as un, ilike as ut, getCompiledCheck as v, migrateDatabase as vt, loadRecord as w, sql$1 as wt, getGlobalRegistry as x, notInArray as xt, validateWithSchema as y, ne as yt, ServiceImpl as z, CompiledApplication as zt };
1106
- //# sourceMappingURL=index.d.ts.map