@brickkit/core 0.7.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,903 @@
1
1
  import { $ as ToolConfigWithoutAuthorize, A as ErrorBuilder, At as index, B as Resource, Bt as PluginRouteScope, C as ActionSchema, Ct as secret, D as CacheOptions, Dt as blob, E as BaseContext, Et as SQLiteDatabaseConfig, F as NarrowAuthorizedContext, Ft as text, G as ServiceAuthOptions, Gt as ResourcePluginTypes, H as ResourceIdentity, Ht as ResourcePlugin, I as PreparationContribution, It as uniqueIndex, J as StandardErrorMap, Jt as defineResourcePlugin, K as ServiceOptions, Kt as ServicePlugin, L as ProxyOptions, Lt as PluginEndpointContext, M as InferTableRow, Mt as primaryKey, N as LifecycleOptions, Nt as real, O as CompiledRoutePlan, Ot as createSQLiteDatabase, P as Logger, Pt as sqliteTable, Q as ToolConfigWithAuthorize, R as RateLimitOptions, Rt as PluginRouteMethod, S as ActionExecutionError, St as resolveSecrets, T as BaseActionConfig, Tt as BunSQLiteDatabase, U as ResourceTypeOptions, Ut as ResourcePluginAPI, V as ResourceConfig, Vt as PluginRoutes, W as Service, Wt as ResourcePluginContext, X as Tool, Xt as getPluginActionRoute, Y as TelemetryOptions, Yt as defineServicePlugin, Z as ToolAnnotations, Zt as getPluginEndpoints, _ as ActionConfig, _t as envSource, a as BrickClientOptions, at as EnvInput, b as ActionContext, bt as overrideSecrets, c as InferActionErrorCodes, ct as defineDatabase, d as InferActionOutput, dt as PostgresDatabase, et as ToolOptions, f as createBrickClient, ft as PostgresDatabaseConfig, g as ActionAccessPolicy, gt as SecretSource, h as Action, ht as SecretRef, i as BrickClientAction, it as DatabaseHandle, j as InferTableInsert, jt as integer, k as DefaultServiceContext, kt as foreignKey, l as InferActionFailure, lt as isDatabaseHandle, m as isBrickTransportError, mt as SecretOptions, n as BrickCallOptions, nt as ValidationErrorItem, o as BrickServerError, ot as PostgresDefinition, p as isBrickServerError, pt as createPostgresDatabase, q as ServiceSchema, qt as ServicePluginContext, r as BrickClient, rt as DatabaseDefinition, s as BrickTransportError, st as SQLiteDefinition, t as BrickActionCaller, tt as ValidationError, u as InferActionInput, ut as DatabaseAdapter, v as ActionConfigWithAuthorize, vt as listSecrets, w as ArchitectureSchema, wt as BrickSQLiteDatabase, x as ActionErrorDefinition, xt as resetSecrets, y as ActionConfigWithoutAuthorize, yt as overrideSecret, z as ResilienceOptions, zt as PluginRouteRegistrar } from "./chunks/client.js";
2
- import { $ as setActionAccess, $t as createEndpointHandler, A as McpToolDefinition, At as notInArray, B as TSchema, Bt as swaggerDocsHTML, C as HandlerFactory, Ct as isNotNull, D as McpHandlerOptions, Dt as lte, E as toErrorResponse, Et as lt, F as isTool, Ft as emitHandlerFactory, G as getGlobalRegistry, Gt as compileRoutePlan, H as getCompiledCheck, Ht as requestLoggingPlugin, I as OpenApiGeneratorOptions, It as ReferenceOptions, J as buildErrorHelpers, Jt as BrickApp, K as resetGlobalRegistry, Kt as createActionHandler, L as generateOpenApiSpec, Lt as referencePlugin, M as createMcpHandler, Mt as relations, N as createMcpRegistry, Nt as sql, O as McpRegistry, Ot as ne, P as defineTool, Pt as syncSchema, Q as getActionAccess, Qt as EndpointMethod, R as hoistAnchoredSchemas, Rt as registerReferenceRoute, S as CompiledHandler, St as is, T as ErrorEnvelope, Tt as like, U as validateWithSchema, Ut as isBrickApp, V as Type, Vt as RequestLoggingOptions, W as ServiceRegistry, Wt as requireBrickApp, X as ACTION_ACCESS_KEY, Xt as EndpointDefinition, Y as defineAction, Yt as EndpointContext, Z as ActionAccessInfo, Zt as EndpointLogger, _ as CompiledApplication, _t as getTableName, an as RouteMethod, at as and, b as compileBrickApplication, bt as ilike, cn as defineResource, ct as buildFtsMatchQuery, dn as defineEffectService, dt as ensureResourceIndexes, en as endpointPaths, et as ServiceImpl, f as EffectBrickApp, ft as ensureSQLiteFts, g as brick, gt as getTableColumns, h as CreateServerOptions, ht as generateSQLiteTableDdl, i as EffectTool, in as RouteIR, it as Table, j as UnknownToolError, jt as or, k as McpRegistryOptions, kt as not, ln as EffectService, lt as createDatabase, m as effectBrick, mt as generateSQLiteIndexDdl, nn as toOpenApiPath, nt as BrickDatabase, o as defineEffectAction, on as defineEffectResourcePlugin, ot as asc, p as EffectServerOptions, pt as eq, q as createServiceProxy, qt as executeCompiledRoute, rn as BrickIR, rt as DatabaseConfig, s as defineEffectTool, sn as defineEffectServicePlugin, st as attachDatabase, t as EffectAction, tn as resolveEndpointDb, tt as defineService, un as EffectServiceOptions, ut as desc, v as CompiledRoute, vt as gt, w as compilerRuntime, wt as isNull, x as loadCompiledBrickApp, xt as inArray, y as bindCompiledApplication, yt as gte, z as Static, zt as scalarDocsHTML } from "./chunks/effect.js";
3
- export { ACTION_ACCESS_KEY, Action, type ActionAccessInfo, ActionAccessPolicy, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, ActionSchema, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickApp, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, BrickDatabase, type BrickIR, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CreateServerOptions, DatabaseAdapter, DatabaseConfig, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type EffectAction, type EffectBrickApp, type EffectServerOptions, type EffectService, type EffectServiceOptions, type EffectTool, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, EnvInput, ErrorBuilder, type ErrorEnvelope, type HandlerFactory, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, LifecycleOptions, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiGeneratorOptions, type PluginEndpointContext, type PluginRouteMethod, type PluginRouteRegistrar, type PluginRouteScope, type PluginRoutes, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, PreparationContribution, ProxyOptions, RateLimitOptions, type ReferenceOptions, type RequestLoggingOptions, ResilienceOptions, Resource, ResourceConfig, ResourceIdentity, type ResourcePlugin, type ResourcePluginAPI, type ResourcePluginContext, type ResourcePluginTypes, ResourceTypeOptions, type RouteIR, type RouteMethod, SQLiteDatabaseConfig, SQLiteDefinition, type SecretOptions, SecretRef, type SecretSource, Service, ServiceAuthOptions, ServiceImpl, ServiceOptions, type ServicePlugin, type ServicePluginContext, ServiceRegistry, ServiceSchema, StandardErrorMap, type Static, type TSchema, Table, TelemetryOptions, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, UnknownToolError, ValidationError, ValidationErrorItem, 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, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
2
+ import { SpanKind } from "@opentelemetry/api";
3
+ import { Static, TSchema, TSchema as TSchema$1, Type } from "@sinclair/typebox";
4
+ import { TypeCheck } from "@sinclair/typebox/compiler";
5
+ import { Elysia } from "elysia";
6
+ import { Table, and, asc, desc, eq, getTableColumns, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql } from "drizzle-orm";
7
+ //#region src/compiler/ir.d.ts
8
+ type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
9
+ interface RouteIR {
10
+ readonly method: RouteMethod;
11
+ readonly path: string;
12
+ readonly service: string;
13
+ readonly action: string;
14
+ readonly kind: "action";
15
+ readonly input: boolean;
16
+ readonly output: boolean;
17
+ readonly context: boolean;
18
+ readonly authorize: boolean;
19
+ readonly inputPrecedence: readonly ("query" | "params" | "body")[];
20
+ readonly coercions: readonly {
21
+ readonly key: string;
22
+ readonly type: "number" | "boolean" | "array";
23
+ }[];
24
+ /** JSON projection for inspection and stale-artifact detection, not runtime validation. */
25
+ readonly inputSchema?: unknown;
26
+ readonly outputSchema?: unknown;
27
+ }
28
+ interface BrickIR {
29
+ readonly version: 1;
30
+ readonly target: "bun-elysia";
31
+ readonly prefix: string;
32
+ readonly services: readonly string[];
33
+ readonly routes: readonly RouteIR[];
34
+ readonly preparations: readonly {
35
+ service: string;
36
+ name: string;
37
+ metadata: unknown;
38
+ }[];
39
+ readonly diagnostics: readonly string[];
40
+ }
41
+ //#endregion
42
+ //#region src/docs.d.ts
43
+ /** An OpenAPI document as plain JSON. */
44
+ type OpenApiDocument = Record<string, unknown>;
45
+ /** An extra OpenAPI document for the API reference, such as Better Auth's. */
46
+ interface ReferenceDocument {
47
+ /** Name in the reference's list of documents. */
48
+ title: string;
49
+ /** The document, or a function returning it; called each time the app starts. */
50
+ document: OpenApiDocument | (() => OpenApiDocument | Promise<OpenApiDocument>);
51
+ }
52
+ /** A named OpenAPI document ready to render. */
53
+ interface ApiDocument {
54
+ title: string;
55
+ document: OpenApiDocument;
56
+ }
57
+ /** Developer documentation for the `brick dev` dashboard. */
58
+ interface DocumentationOptions {
59
+ /**
60
+ * Folder of `.md`/`.mdx` pages. A relative path starts at the folder of the
61
+ * app entry, as it reads in the file that sets it.
62
+ */
63
+ dir: string;
64
+ /**
65
+ * Module whose exports are React components for MDX, added to the built-in
66
+ * ones; a relative path starts where `dir` does. A default export or a
67
+ * `components` export holds the name-to-component map. The dashboard bundles
68
+ * it, so it may import anything the project has.
69
+ */
70
+ components?: string;
71
+ }
72
+ interface ReferenceOptions {
73
+ /** Also serve a standalone Scalar page here. Without a path, no page is served. */
74
+ path?: string;
75
+ title?: string;
76
+ specUrl?: string;
77
+ /** More OpenAPI documents for the `brick dev` dashboard's APIs view. */
78
+ documents?: ReferenceDocument[];
79
+ }
80
+ /** Renders the Scalar API reference page for the given OpenAPI URL. */
81
+ export declare function scalarDocsHTML(specUrl: string, title: string): string;
82
+ /** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
83
+ export declare function referencePlugin(opts?: ReferenceOptions): Elysia;
84
+ /** Mounts the Scalar reference route onto an existing app. */
85
+ export declare function registerReferenceRoute(app: Elysia, opts?: ReferenceOptions): Elysia;
86
+ /** Renders the Swagger UI page. */
87
+ export declare function swaggerDocsHTML(specUrl: string, title: string): string;
88
+ //#endregion
89
+ //#region src/dashboard.d.ts
90
+ /** Who may open the dashboard that `brick start` serves for monitoring. */
91
+ interface DashboardAuth {
92
+ /**
93
+ * Secrets that let a request in. A browser asks for one in its sign-in
94
+ * prompt (any user name, the secret as the password), and monitors and
95
+ * scripts send `Authorization: Bearer <secret>`. Give several to rotate one
96
+ * while the other still works. Each is at least 16 characters long;
97
+ * `openssl rand -base64 32` makes a good one.
98
+ */
99
+ token?: string | readonly string[];
100
+ /**
101
+ * Your own check, to sign people in with the auth the app already has: read
102
+ * a session cookie, verify a Better Auth or Clerk session, look at a header
103
+ * a proxy adds. It receives the request (method, URL, and headers; no body)
104
+ * and returns `true` to let it in, `false` to refuse it with 401, or a
105
+ * `Response` to send instead, such as a redirect to your login page. If it
106
+ * throws or takes longer than five seconds, the request is refused with 503.
107
+ *
108
+ * A request is let in when it carries a valid `token`, or when this
109
+ * returns `true`; give both to let monitors in by token and people in by
110
+ * sign-in.
111
+ */
112
+ authorize?: (request: Request) => boolean | Response | Promise<boolean | Response>;
113
+ }
114
+ /**
115
+ * The monitoring dashboard `brick start` serves beside the app, on a port of
116
+ * its own: live requests, logs, errors, and the shape of the service, so it
117
+ * stays reachable when the app's own routes are not. `brick dev` has its own
118
+ * dashboard, set by command line options, and ignores this.
119
+ *
120
+ * Setting it turns on `telemetry`, since the dashboard shows what is traced.
121
+ * While it is on, `ctx.logger` and `console` lines written during a request
122
+ * go to the dashboard instead of the console.
123
+ */
124
+ interface DashboardOptions {
125
+ /** Default 9400. */
126
+ port?: number;
127
+ /**
128
+ * The address to listen on. Default `127.0.0.1`, reachable only from the same
129
+ * machine. In a container use `0.0.0.0`, which needs `auth`: the dashboard
130
+ * will not start on any other address without it.
131
+ */
132
+ host?: string;
133
+ auth?: DashboardAuth;
134
+ /**
135
+ * Days of finished requests to keep on disk, in `.brick/` of the working
136
+ * folder. Default 0: only what happened since the process started, which is
137
+ * lost when it restarts. Needs a folder that outlives the container.
138
+ */
139
+ historyDays?: number;
140
+ }
141
+ //#endregion
142
+ //#region src/endpoints.d.ts
143
+ type EndpointMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
144
+ /** Logger subset handed to endpoint handlers (mirrors action context loggers). */
145
+ interface EndpointLogger {
146
+ info: (...args: any[]) => void;
147
+ warn: (...args: any[]) => void;
148
+ error: (...args: any[]) => void;
149
+ debug: (...args: any[]) => void;
150
+ }
151
+ /** Context for raw endpoint handlers: Elysia route fields + Brick extras. */
152
+ interface EndpointContext {
153
+ params: Record<string, string>;
154
+ query: Record<string, string | undefined>;
155
+ body: unknown;
156
+ headers: Record<string, string>;
157
+ request: Request;
158
+ /** Elysia response setter (status/headers). Mutate like in `app.get`. */
159
+ set: {
160
+ status?: number;
161
+ headers: Record<string, string>;
162
+ };
163
+ /** Drizzle db from `service` (or first service with one); `undefined` when none. */
164
+ db: any;
165
+ logger: EndpointLogger;
166
+ traceId: string;
167
+ requestId: string;
168
+ }
169
+ interface EndpointDefinition {
170
+ method: EndpointMethod;
171
+ /** Elysia-style path, e.g. `/p/:slug`. */
172
+ path: string;
173
+ handler: (ctx: EndpointContext) => unknown | Promise<unknown>;
174
+ /** Db source: instance or registered service name. Defaults to first service with a db. */
175
+ service?: Service<any, any> | string;
176
+ /** Explicit database handle, independent of a service. */
177
+ database?: DatabaseHandle<unknown>;
178
+ summary?: string;
179
+ description?: string;
180
+ tags?: string[];
181
+ }
182
+ /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
183
+ export declare function resolveEndpointDb(service: Service<any, any> | string | undefined, services: Service<any, any>[]): any;
184
+ /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
185
+ export declare function createEndpointHandler(def: EndpointDefinition, services: Service<any, any>[]): (elysiaCtx: any) => Promise<unknown>;
186
+ /** `/p/:slug` → `/p/{slug}` for OpenAPI. */
187
+ export declare function toOpenApiPath(elysiaPath: string): string;
188
+ /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
189
+ export declare function endpointPaths(defs: EndpointDefinition[]): Record<string, any>;
190
+ /** The app object returned by `brick`: Elysia plus `endpoint()`. */
191
+ type BrickApp = Elysia<any, any, any, any, any, any, any> & {
192
+ /** Service definitions, prefix, and telemetry setting chosen at construction. */
193
+ readonly definition: {
194
+ readonly routes: readonly RouteIR[];
195
+ readonly services: readonly Service<any, any>[];
196
+ readonly prefix: string;
197
+ readonly telemetry: boolean;
198
+ readonly documentation?: DocumentationOptions;
199
+ /** What `brick start` serves for monitoring; its `auth` is not enumerable. */
200
+ readonly dashboard?: DashboardOptions;
201
+ };
202
+ /** Register a raw endpoint (outside the JSON action mesh). */
203
+ endpoint(def: EndpointDefinition): void;
204
+ /**
205
+ * The OpenAPI documents behind the dashboard's APIs view: this app's own
206
+ * unless `docs` is false, then those from `reference.documents`.
207
+ */
208
+ referenceDocuments(): Promise<ApiDocument[]>;
209
+ /** All endpoints registered via `endpoint()` (declaration order). */
210
+ listEndpoints(): EndpointDefinition[];
211
+ };
212
+ //#endregion
213
+ //#region src/compiler/runtime.d.ts
214
+ type CompiledHandler = (context: any) => unknown | Promise<unknown>;
215
+ type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRuntime) => CompiledHandler;
216
+ /** Retains Brick's existing source precedence and treatment of empty bodies. */
217
+ declare function mergeInput(first: any, second: any, third: any): any;
218
+ declare function checkDepth(value: unknown, action: string): void;
219
+ declare function validate(check: NonNullable<CompiledRoutePlan["inputChecker"]>, value: unknown, action: string, stage: "input" | "output"): void;
220
+ declare function mapError(err: unknown, set: any, options: {
221
+ logger: Logger;
222
+ requestId: string;
223
+ }): ErrorEnvelope;
224
+ export declare const compilerRuntime: Readonly<{
225
+ emptyServices: Readonly<{}>;
226
+ defaultRequest: Request;
227
+ nextSequence: () => string;
228
+ mergeInput: typeof mergeInput;
229
+ checkDepth: typeof checkDepth;
230
+ validate: typeof validate;
231
+ mapError: typeof mapError;
232
+ isThenable: (value: any) => boolean;
233
+ deny: (action: string, user: unknown) => never;
234
+ }>;
235
+ //#endregion
236
+ //#region src/compiler.d.ts
237
+ type ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;
238
+ /** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
239
+ export declare function loadCompiledBrickApp(load: () => Promise<{
240
+ default: unknown;
241
+ }>, ir: BrickIR, bind: ApplicationBinder): Promise<BrickApp>;
242
+ interface CompiledRoute {
243
+ readonly ir: RouteIR;
244
+ readonly handler: CompiledHandler;
245
+ }
246
+ interface CompiledApplication {
247
+ readonly ir: BrickIR;
248
+ readonly routes: readonly CompiledRoute[];
249
+ }
250
+ /** Startup compiler: analyzes once, then binds live callbacks. */
251
+ export declare function compileBrickApplication(options: {
252
+ services: Service<any, any>[];
253
+ prefix?: string;
254
+ mode?: "specialized" | "generic";
255
+ }): CompiledApplication;
256
+ /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
257
+ export declare function bindCompiledApplication(ir: BrickIR, services: Service<any, any>[], factories: readonly HandlerFactory[]): CompiledApplication;
258
+ //#endregion
259
+ //#region src/request-logger.d.ts
260
+ interface RequestLoggingOptions {
261
+ enabled?: boolean;
262
+ logger?: (msg: string) => void;
263
+ }
264
+ /**
265
+ * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
266
+ * Timing is tracked per-Request via a WeakMap. The onError hook only logs and
267
+ * returns undefined so existing error mapping is preserved. Logging only —
268
+ * no CORS headers are set here.
269
+ *
270
+ * Hooks are registered with the "global" scope so they propagate to the
271
+ * parent app when mounted via `app.use(...)` — Elysia scopes plain instance
272
+ * hooks to the plugin's own routes. Timing is captured in beforeHandle
273
+ * because request hooks are not propagated from a
274
+ * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
275
+ */
276
+ export declare function requestLoggingPlugin(opts?: RequestLoggingOptions): Elysia;
277
+ //#endregion
278
+ //#region src/action-handler.d.ts
279
+ /**
280
+ * Work out, once at startup, everything an action's route needs to answer a
281
+ * request: where its input comes from (body, query, or path), the validators,
282
+ * the authorization and execute functions, and its logger. Low level: `brick()`
283
+ * does this for every route.
284
+ *
285
+ * @param service - The service the action belongs to.
286
+ * @param action - The action.
287
+ * @param routePath - The route's path.
288
+ * @param method - The HTTP method (POST by default).
289
+ * @returns The plan `executeCompiledRoute` runs.
290
+ */
291
+ export declare function compileRoutePlan(service: Service, action: Action, routePath: string, method?: string): CompiledRoutePlan;
292
+ /**
293
+ * Answer one request for a compiled route: read the input, run the action, and
294
+ * return its output or the error response, with the `x-trace-id` and
295
+ * `x-request-id` headers set. Low level: `brick()` mounts this for every route.
296
+ *
297
+ * @param plan - From `compileRoutePlan`.
298
+ * @param elysiaCtx - The Elysia request context: `params`, `body`, `query`,
299
+ * `headers`, `request`, and `set`.
300
+ * @returns The action's output, or an error envelope with the status set on `set`.
301
+ */
302
+ export declare function executeCompiledRoute(plan: CompiledRoutePlan, elysiaCtx: any): Promise<any>;
303
+ /**
304
+ * An Elysia handler for one action: `compileRoutePlan` and
305
+ * `executeCompiledRoute` together. Use it to mount an action on your own
306
+ * Elysia app; `brick()` does it for you.
307
+ *
308
+ * @param service - The service the action belongs to.
309
+ * @param action - The action.
310
+ * @param routePath - The route's path.
311
+ * @param method - The HTTP method (POST by default).
312
+ * @returns A function from the Elysia context to the response.
313
+ */
314
+ export declare function createActionHandler(service: Service, action: Action, routePath: string, method?: string): (elysiaCtx: any) => Promise<any>;
315
+ //#endregion
316
+ //#region src/server.d.ts
317
+ interface CreateServerOptions {
318
+ port?: number;
319
+ /** Generate specialized handlers once at startup (default true). */
320
+ compiler?: boolean;
321
+ /** Ahead-of-time handlers already bound to the supplied services. */
322
+ compilation?: CompiledApplication;
323
+ services?: Service<any, any>[];
324
+ prefix?: string;
325
+ title?: string;
326
+ version?: string;
327
+ description?: string;
328
+ docs?: boolean;
329
+ openApiPath?: string;
330
+ docsPath?: string;
331
+ swaggerPath?: string;
332
+ requestLogging?: boolean | RequestLoggingOptions;
333
+ /**
334
+ * `true` serves a Scalar page at /reference. Options serve one only with a
335
+ * `path`; `documents` adds OpenAPI documents to the dashboard's APIs view.
336
+ */
337
+ reference?: boolean | ReferenceOptions;
338
+ secrets?: {
339
+ source?: SecretSource;
340
+ validate?: boolean;
341
+ };
342
+ /** Raw endpoints (outside the JSON action mesh), mounted at startup. */
343
+ endpoints?: EndpointDefinition[];
344
+ /**
345
+ * Record request, action, and RPC spans with OpenTelemetry (default false).
346
+ * Spans go to the globally registered tracer provider; without one they are
347
+ * no-ops. `brick dev` shows them in its dashboard.
348
+ */
349
+ telemetry?: boolean;
350
+ /**
351
+ * Developer documentation for the `brick dev` dashboard (its Docs tab): a
352
+ * folder of `.md`/`.mdx` pages in Fumadocs' layout, with frontmatter and
353
+ * `meta.json` for ordering. A string is the folder. Relative paths start at
354
+ * the folder of the app entry, as they read in the file that sets them (from
355
+ * `src/app.ts`, `"../docs"` is `docs/` at the project root). Needs
356
+ * `fumadocs-core` and `@mdx-js/mdx` installed.
357
+ */
358
+ documentation?: string | DocumentationOptions;
359
+ /**
360
+ * Monitoring dashboard for `brick start`, on a port of its own and behind
361
+ * `auth`. Setting it turns on `telemetry`. See `DashboardOptions`.
362
+ */
363
+ dashboard?: DashboardOptions;
364
+ }
365
+ /**
366
+ * Create the HTTP application: an Elysia app that serves every service's
367
+ * actions (and the tools that opt in with `http: true`) as routes, with
368
+ * `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,
369
+ * Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.
370
+ *
371
+ * Services come from the global registry unless `services` is given. The app
372
+ * does not listen by itself: export it from your entry file, where `brick dev`,
373
+ * `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your
374
+ * own server bootstrap.
375
+ *
376
+ * @param options - `prefix` for action routes (default `/api`), `services`,
377
+ * `title`, `version`, and `description` for the OpenAPI document, `docs` and the
378
+ * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
379
+ * `telemetry`, `documentation`, and `dashboard`. See `CreateServerOptions`.
380
+ * @returns The app, with `definition` (its services, prefix, and routes),
381
+ * `endpoint()` to add raw routes, and `listEndpoints()` to list them.
382
+ * @throws When a required secret is missing, or `documentation` or `dashboard`
383
+ * is invalid.
384
+ * @example
385
+ * import { brick } from "@brickkit/core";
386
+ * import { pagesService } from "./services/pages";
387
+ *
388
+ * export default brick({
389
+ * services: [pagesService],
390
+ * title: "Pages API",
391
+ * telemetry: true,
392
+ * });
393
+ */
394
+ export declare function brick(options?: CreateServerOptions): BrickApp;
395
+ //#endregion
396
+ //#region src/app-entry.d.ts
397
+ /**
398
+ * Whether a value is an application made by `brick()`. It checks for the
399
+ * methods and `definition` a `BrickApp` has, so it also recognizes one built by
400
+ * another copy of the package.
401
+ *
402
+ * @param app - Anything, such as the default export of an entry file.
403
+ * @returns `true` for a `BrickApp`, narrowing its type.
404
+ */
405
+ export declare function isBrickApp(app: unknown): app is BrickApp;
406
+ /**
407
+ * Check that a module's default export is an application ready to be served,
408
+ * for tools that load an entry file.
409
+ *
410
+ * @param app - The default export of an entry file.
411
+ * @returns The app.
412
+ * @throws When it is not a `BrickApp`, or it already called `.listen()`: the
413
+ * entry must only build the app, and leave listening to the server bootstrap.
414
+ */
415
+ export declare function requireBrickApp(app: unknown): BrickApp;
416
+ //#endregion
417
+ //#region src/telemetry.d.ts
418
+ /** What a raw route handler receives from `traceRoute`. Read the body from `request`. */
419
+ interface RawRouteContext {
420
+ request: Request;
421
+ headers: Record<string, string | undefined>;
422
+ set: {
423
+ status?: unknown;
424
+ headers?: Record<string, unknown>;
425
+ };
426
+ params: Record<string, string>;
427
+ query: Record<string, string | undefined>;
428
+ }
429
+ /**
430
+ * Wrap a raw route handler so each of its requests gets a server span. Use it
431
+ * for routes registered directly on the app, outside actions and endpoints,
432
+ * such as auth or webhook routes. Spans are recorded whenever a tracer provider
433
+ * is registered; `brick({ telemetry })` does not apply to these routes.
434
+ *
435
+ * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia
436
+ * decides what to parse from the handler's destructuring, and forwarding the
437
+ * whole context would parse the body and leave `request.json()` with nothing.
438
+ */
439
+ export declare function traceRoute<T>(route: string, handler: (context: RawRouteContext) => T): (context: RawRouteContext) => T;
440
+ //#endregion
441
+ //#region src/compiler/emit.d.ts
442
+ /** Emits framework code only. User callbacks remain closures bound separately. */
443
+ export declare function emitHandlerFactory(route: RouteIR): string;
444
+ //#endregion
445
+ //#region src/db/index.d.ts
446
+ export interface DatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> extends Omit<SQLiteDatabaseConfig<TSchema>, "client">, Omit<PostgresDatabaseConfig<TSchema>, "client"> {
447
+ client?: SQLiteDatabaseConfig<TSchema>["client"] | PostgresDatabaseConfig<TSchema>["client"];
448
+ /** Database engine. Default: 'sqlite' */
449
+ engine?: "sqlite" | "postgres" | "clickhouse";
450
+ /** Optional service name associated with this database */
451
+ name?: string;
452
+ }
453
+ export type BrickDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;
454
+ /**
455
+ * Creates a database instance based on the provided configuration.
456
+ * Zero-config: calling `createDatabase()` returns an ultra-fast Bun-native SQLite
457
+ * database in `:memory:` mode wrapped with Drizzle ORM.
458
+ */
459
+ export declare function createDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: DatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;
460
+ /** Attach a defined database. Schema changes remain the caller's responsibility. */
461
+ export declare function attachDatabase<TDb>(service: Service<TDb, any>, database: DatabaseHandle<TDb>): TDb;
462
+ /**
463
+ * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition
464
+ * directly from a Drizzle table schema.
465
+ */
466
+ export declare function generateSQLiteTableDdl(table: any): string;
467
+ /**
468
+ * Generates idempotent secondary index DDL for a Drizzle table.
469
+ * Covers owner scoping, sort columns, and exact-match filters.
470
+ * UNIQUE columns already carry an implicit index — skipped here.
471
+ * FTS/trigram indexes are handled separately by the search layer.
472
+ */
473
+ export declare function generateSQLiteIndexDdl(table: any, opts?: {
474
+ ownerField?: string;
475
+ sortFields?: string[];
476
+ }): string[];
477
+ /**
478
+ * Ensures secondary indexes exist for a resource table.
479
+ * SQLite: B-tree indexes for owner scope + sort + composite hot path.
480
+ * Postgres: same B-trees plus pg_trgm GIN indexes for substring search.
481
+ * Best-effort: failures warn and continue (e.g. read-only replicas).
482
+ */
483
+ export declare function ensureResourceIndexes(db: any, table: any, opts?: {
484
+ ownerField?: string;
485
+ sortFields?: string[];
486
+ searchFields?: string[];
487
+ }): void;
488
+ /**
489
+ * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.
490
+ * Idempotent; safe to call on every resource registration.
491
+ * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.
492
+ */
493
+ export declare function ensureSQLiteFts(db: any, table: any, searchCols: string[]): void;
494
+ /**
495
+ * Builds an FTS5 MATCH condition for a resource search term.
496
+ * Returns null when the term has no usable tokens or FTS errors.
497
+ * Caller falls back to LIKE in that case.
498
+ */
499
+ export declare function buildFtsMatchQuery(search: string): string | null;
500
+ /**
501
+ * Explicit SQLite development/test schema preparation helper.
502
+ * Never called by services, resources, auth, or server startup.
503
+ * Not a migration runner; PostgreSQL schema management is caller-owned.
504
+ */
505
+ export declare function syncSchema(tablesOrService: Map<string, any> | any[] | Record<string, any> | Service, dbInstance?: any): Promise<void> | void;
506
+ //#endregion
507
+ //#region src/service.d.ts
508
+ export declare class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> implements Service<TDb, TServiceContext> {
509
+ readonly name: string;
510
+ readonly options: ServiceOptions<TServiceContext, TDb>;
511
+ readonly actions: Map<string, Action<any, any, any, any>>;
512
+ readonly tools: Map<string, Tool<any, any, any, any>>;
513
+ readonly tables: Map<string, any>;
514
+ readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext, {}>>;
515
+ readonly preparations: Map<string, PreparationContribution>;
516
+ private database?;
517
+ private _isBuilt;
518
+ constructor(name: string, options?: ServiceOptions<TServiceContext, TDb>);
519
+ use<A>(plugin: ServicePlugin<this, A>): A;
520
+ get db(): TDb | undefined;
521
+ get isBuilt(): boolean;
522
+ /**
523
+ * Closes declarations after plugins have registered their actions and preparations.
524
+ */
525
+ build(): this;
526
+ contributePreparation(contribution: PreparationContribution): void;
527
+ listPreparations(): PreparationContribution[];
528
+ prepareContributions(): void;
529
+ registerTable(table: any): this;
530
+ 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>>;
531
+ getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
532
+ listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
533
+ action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
534
+ action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | 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>;
535
+ action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | 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>;
536
+ tool<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
537
+ tool<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | 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>;
538
+ tool<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | 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>;
539
+ getTool(name: string): Tool<any, any, any, any> | undefined;
540
+ listTools(): Tool<any, any, any, any>[];
541
+ getAction(name: string): Action<any, any, any, any> | undefined;
542
+ listActions(): Action<any, any, any, any>[];
543
+ getDb(): TDb | undefined;
544
+ setDb(database: DatabaseHandle<TDb>): void;
545
+ /**
546
+ * Resolves the complete service execution context once per incoming request.
547
+ * Merges framework BaseContext with the service's custom context hook.
548
+ * Always rebuilds context for this service to prevent caller context from overriding.
549
+ */
550
+ resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
551
+ introspect(): ServiceSchema;
552
+ }
553
+ /**
554
+ * Declare a service: a named group of actions, tools, and resources with its own
555
+ * database and request context. It is registered globally, so `brick()`, the
556
+ * OpenAPI generator, and `createServiceProxy` find it by name.
557
+ *
558
+ * Add actions with `service.action(...)`, tools with `service.tool(...)`,
559
+ * resources with `service.resource(...)`, and plugins with `service.use(...)`.
560
+ *
561
+ * @param name - Unique name. It is the service's segment of every action route
562
+ * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining a
563
+ * second service with the same name replaces the first and logs a warning.
564
+ * @param options - `database` (a handle from `defineDatabase`), `context` (adds
565
+ * fields such as the signed-in user to every action's `ctx`), and `auth`,
566
+ * `rateLimit`, `cache`, `resilience`, `telemetry`, and `lifecycle`.
567
+ * @returns The service.
568
+ * @example
569
+ * import { defineDatabase, defineService, t } from "@brickkit/core";
570
+ *
571
+ * const database = defineDatabase({ tables: { pages } });
572
+ *
573
+ * export const pagesService = defineService("pages", {
574
+ * database,
575
+ * // Added to `ctx` in every action of this service.
576
+ * context: async ({ request }) => ({ user: await readUser(request) }),
577
+ * });
578
+ *
579
+ * pagesService.action({
580
+ * name: "list",
581
+ * input: t.Object({ limit: t.Optional(t.Number()) }),
582
+ * output: t.Array(t.Object({ id: t.String(), title: t.String() })),
583
+ * execute: ({ input, ctx }) =>
584
+ * ctx.db.select().from(pages).limit(input.limit ?? 20),
585
+ * });
586
+ */
587
+ export declare function defineService<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>>(name: string, options?: ServiceOptions<TServiceContext, TDb>): Service<TDb, TServiceContext>;
588
+ //#endregion
589
+ //#region src/access.d.ts
590
+ interface ActionAccessInfo {
591
+ hasAuthorize: boolean;
592
+ hasScope: boolean;
593
+ policy: ActionAccessPolicy;
594
+ }
595
+ /**
596
+ * Cross-copy access metadata protocol. CRUD enforces its access policy
597
+ * inside `execute`, so `config.authorize` is absent and introspection
598
+ * can't see it. The plugin stamps each action under this process-global
599
+ * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
600
+ * the binding survives a second copy of core (bundler SSR, Vitest),
601
+ * same as the plugin action-binding key.
602
+ */
603
+ export declare const ACTION_ACCESS_KEY: unique symbol;
604
+ /**
605
+ * Record how an action is protected, for tools that cannot read it from the
606
+ * configuration: plugins such as `crud` enforce access inside `execute`, so the
607
+ * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
608
+ * read what is recorded here.
609
+ *
610
+ * @param action - The action to describe.
611
+ * @param info - Whether it checks authorization and whether it scopes queries,
612
+ * and the resulting policy.
613
+ */
614
+ export declare function setActionAccess(action: object, info: ActionAccessInfo): void;
615
+ /**
616
+ * How an action is protected: `"public"` when nothing checks the caller,
617
+ * `"authorized"` when an `authorize` does, and `"scoped"` when the action also
618
+ * limits what rows the caller can reach. It reads what a plugin recorded with
619
+ * `setActionAccess`, else the action's own `authorize`, and keeps the policy
620
+ * consistent with the flags.
621
+ *
622
+ * @param action - An action, or any object a plugin described.
623
+ * @returns `hasAuthorize`, `hasScope`, and `policy`.
624
+ */
625
+ export declare function getActionAccess(action: Action | object): ActionAccessInfo;
626
+ //#endregion
627
+ //#region src/action.d.ts
628
+ /**
629
+ * The `error` helpers an action receives: one function per error code that
630
+ * throws an `ActionExecutionError` with that code and status. The standard HTTP
631
+ * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
632
+ * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
633
+ * them or replace one.
634
+ *
635
+ * @param errorsDef - The action's `errors`: for each code, its `message` and
636
+ * `status` (default 400).
637
+ * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
638
+ * and always throw.
639
+ */
640
+ export declare function buildErrorHelpers<TErrors extends Record<string, ActionErrorDefinition>>(errorsDef?: TErrors): ErrorBuilder<TErrors>;
641
+ /**
642
+ * Define an action: a typed, validated function that Brick serves over HTTP,
643
+ * runs in-process, and exposes to the typed client and OpenAPI.
644
+ *
645
+ * A call runs in order: the input is validated against `input` (an invalid one
646
+ * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;
647
+ * `execute` runs; and its result is validated against `output` (a mismatch is a
648
+ * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared
649
+ * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value
650
+ * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response
651
+ * and in the log.
652
+ *
653
+ * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`
654
+ * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.
655
+ * Where it is given, `execute` can rely on what it checked.
656
+ *
657
+ * @param config - `name`, `execute`, and optionally `description`, `input` and
658
+ * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to
659
+ * change the route (POST by default), `tags`, and `emits`.
660
+ * @returns The action. Register it with `service.action(action)`; call it
661
+ * directly with `action.run(input, ctx)`.
662
+ * @example
663
+ * import { defineAction, t } from "@brickkit/core";
664
+ *
665
+ * export const getPage = defineAction({
666
+ * name: "get",
667
+ * method: "GET",
668
+ * input: t.Object({ id: t.String() }),
669
+ * output: t.Object({ id: t.String(), title: t.String() }),
670
+ * errors: { PAGE_GONE: { message: "That page was removed", status: 410 } },
671
+ * authorize: ({ user }) => user != null,
672
+ * execute: async ({ input, ctx, error }) => {
673
+ * const page = await findPage(ctx.db, input.id);
674
+ * if (!page) throw error.NOT_FOUND("No such page");
675
+ * return page;
676
+ * },
677
+ * });
678
+ */
679
+ export declare function defineAction<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | 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>;
680
+ export declare function defineAction<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | 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>;
681
+ //#endregion
682
+ //#region src/resource.d.ts
683
+ /** Declares a plugin host without registering actions or changing the schema. */
684
+ export 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>>;
685
+ //#endregion
686
+ //#region src/rpc.d.ts
687
+ /**
688
+ * A typed way to call another service's actions in-process. Each property of
689
+ * the proxy is an action of that service: call it with the action's input, and
690
+ * optionally a call context.
691
+ *
692
+ * The call runs through the target's own validation and authorization, with the
693
+ * target's database and context (never the caller's), and shows as an `rpc`
694
+ * span in the trace. Only in-process dispatch exists: with `isMonolith: false`
695
+ * a call throws. Use the typed client to call a service over HTTP.
696
+ *
697
+ * @param serviceName - The registered name of the service to call.
698
+ * @param options - `from` (the calling service's name, which becomes `ctx.caller`
699
+ * in the target and cannot be spoofed), `context` (defaults for every call), and
700
+ * `isMonolith`.
701
+ * @returns A proxy typed as `T`, usually the target's actions.
702
+ * @throws On a call, when the service or the action is not registered.
703
+ * @example
704
+ * import { createServiceProxy } from "@brickkit/core";
705
+ *
706
+ * const pages = createServiceProxy<{ get(input: { id: string }): Promise<Page> }>(
707
+ * "pages",
708
+ * { from: "billing" },
709
+ * );
710
+ * const page = await pages.get({ id: "p_1" });
711
+ */
712
+ export declare function createServiceProxy<T extends Record<string, any>>(serviceName: string, options?: ProxyOptions): T;
713
+ //#endregion
714
+ //#region src/registry.d.ts
715
+ interface ArchitectureApplication {
716
+ services: readonly Service[];
717
+ routes: readonly RouteIR[];
718
+ }
719
+ export declare class ServiceRegistry {
720
+ private _revision;
721
+ /** Definition revision for invalidating serialized architecture snapshots. */
722
+ get revision(): number;
723
+ touch(): void;
724
+ private services;
725
+ private routes;
726
+ /** Remember the actual registered routes for subsequent registry exports. */
727
+ setApplicationRoutes(application: ArchitectureApplication): void;
728
+ register(service: Service): void;
729
+ get(name: string): Service | undefined;
730
+ has(name: string): boolean;
731
+ list(): Service[];
732
+ clear(): void;
733
+ exportArchitecture(application?: ArchitectureApplication): ArchitectureSchema;
734
+ }
735
+ /**
736
+ * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
737
+ * generator, `createServiceProxy`, and the dashboard find services by name.
738
+ *
739
+ * @returns The current global registry.
740
+ */
741
+ export declare function getGlobalRegistry(): ServiceRegistry;
742
+ /**
743
+ * Start over with an empty global registry. For tests, which define the same
744
+ * services again in each case; an application never needs it.
745
+ */
746
+ export declare function resetGlobalRegistry(): void;
747
+ //#endregion
748
+ //#region src/typebox.d.ts
749
+ /**
750
+ * The compiled validator for a TypeBox schema. Compiling is slow and checking
751
+ * is fast, so each schema is compiled once and kept for as long as the schema
752
+ * object lives.
753
+ *
754
+ * @param schema - A TypeBox schema.
755
+ * @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.
756
+ */
757
+ export declare function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T>;
758
+ /**
759
+ * Check a value against a schema, the way actions check their input and output.
760
+ *
761
+ * @param schema - A TypeBox schema, or `undefined` to accept anything.
762
+ * @param value - The value to check.
763
+ * @returns `{ success: true, data }`, or `{ success: false, errors }` with a
764
+ * `path`, `message`, `type`, and the offending `value` for each problem.
765
+ */
766
+ export declare function validateWithSchema<T extends TSchema>(schema: T | undefined, value: unknown): {
767
+ success: true;
768
+ data: Static<T>;
769
+ } | {
770
+ success: false;
771
+ errors: ValidationErrorItem[];
772
+ };
773
+ //#endregion
774
+ //#region src/openapi.d.ts
775
+ interface OpenApiGeneratorOptions {
776
+ title?: string;
777
+ version?: string;
778
+ description?: string;
779
+ prefix?: string;
780
+ services?: Service<any, any>[];
781
+ registry?: ServiceRegistry;
782
+ }
783
+ /**
784
+ * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors
785
+ * (`{ $id: "T0", ..., { $ref: "T0" } }`). OpenAPI interprets a bare `$ref`
786
+ * as an external file reference, so downstream tooling tries to load a
787
+ * file named `T0` and fails. Hoist every anchored subschema into
788
+ * `#/components/schemas/` and rewrite the refs to local pointers.
789
+ * First definition wins when one `$id` is declared twice.
790
+ */
791
+ export declare function hoistAnchoredSchemas(spec: Record<string, any>): string[];
792
+ /**
793
+ * Build the OpenAPI 3.1 document for the services: one path per action route,
794
+ * with request and response schemas from the actions' TypeBox schemas, their
795
+ * declared errors, tags by service, and a bearer security scheme where any
796
+ * action needs authorization.
797
+ *
798
+ * `brick()` calls this for `/openapi.json`; call it yourself to write the
799
+ * document to a file or feed another tool.
800
+ *
801
+ * @param options - `title`, `version`, and `description` for the `info` block,
802
+ * `prefix` (default `/api`), and the `services` or `registry` to describe
803
+ * (the global registry by default).
804
+ * @returns The document as a plain object.
805
+ */
806
+ export declare function generateOpenApiSpec(options?: OpenApiGeneratorOptions): Record<string, any>;
807
+ //#endregion
808
+ //#region src/tool.d.ts
809
+ /**
810
+ * Define a tool: an action that AI agents can call through MCP. It takes the
811
+ * same configuration as `defineAction` (validation, `authorize`, errors), plus
812
+ * `title`, `annotations` (the MCP hints about what the tool does), and `http`
813
+ * to also serve it over HTTP and in OpenAPI (off by default).
814
+ *
815
+ * @param config - An action configuration and tool options. `input` must be an
816
+ * object schema, since MCP passes arguments by name.
817
+ * @returns The tool, which is also an action. Register it with `service.tool(tool)`.
818
+ * @throws When `input` is not an object schema.
819
+ * @example
820
+ * import { defineTool, t } from "@brickkit/core";
821
+ *
822
+ * export const echoTool = defineTool({
823
+ * name: "echo",
824
+ * title: "Echo a message",
825
+ * description: "Returns the message it is given.",
826
+ * input: t.Object({ message: t.String() }),
827
+ * output: t.String(),
828
+ * execute: ({ input }) => `Echo: ${input.message}`,
829
+ * });
830
+ */
831
+ export declare function defineTool<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | 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>;
832
+ export declare function defineTool<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | 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>;
833
+ /**
834
+ * Whether a value was made with `defineTool`, as opposed to `defineAction`.
835
+ *
836
+ * @param value - Anything.
837
+ * @returns `true` for a tool, narrowing its type.
838
+ */
839
+ export declare function isTool(value: unknown): value is Tool<any, any, any, any>;
840
+ //#endregion
841
+ //#region src/mcp.d.ts
842
+ interface McpToolDefinition {
843
+ name: string;
844
+ title?: string;
845
+ description: string;
846
+ inputSchema: unknown;
847
+ annotations: ToolAnnotations;
848
+ }
849
+ interface McpRegistryOptions {
850
+ services?: readonly Pick<Service<any, any>, "listTools">[];
851
+ tools?: readonly Tool<any, any, any, any>[];
852
+ }
853
+ interface McpRegistry {
854
+ listTools(): McpToolDefinition[];
855
+ callTool(name: string, args?: Record<string, unknown>, ctx?: Partial<ActionContext>): Promise<unknown>;
856
+ }
857
+ export declare class UnknownToolError extends Error {
858
+ constructor(name: string);
859
+ }
860
+ /** Collect only explicitly defined tools, without exposing ordinary actions. */
861
+ export declare function createMcpRegistry(options: McpRegistryOptions): McpRegistry;
862
+ interface McpHandlerOptions {
863
+ registry: McpRegistry;
864
+ serverInfo: {
865
+ name: string;
866
+ version: string;
867
+ title?: string;
868
+ };
869
+ /** Versions supported by this transport, newest first. */
870
+ protocolVersions?: readonly string[];
871
+ }
872
+ /** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
873
+ export declare function createMcpHandler(options: McpHandlerOptions): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>;
874
+ //#endregion
875
+ //#region src/error-response.d.ts
876
+ interface ErrorEnvelope {
877
+ name: string;
878
+ code: string;
879
+ message: string;
880
+ status: number;
881
+ requestId: string;
882
+ details?: unknown;
883
+ errors?: ValidationError["errors"];
884
+ }
885
+ type ErrorContext = {
886
+ logger: Pick<Logger, "error">;
887
+ requestId: string;
888
+ };
889
+ /**
890
+ * Turn what an action threw into the JSON body of its HTTP response, and record
891
+ * the failure on the active trace. Declared failures and validation errors keep
892
+ * their code, status, and details; anything else is logged and answered as a
893
+ * generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.
894
+ *
895
+ * @param err - Whatever was thrown.
896
+ * @param context - A `logger` with `error()`, and the `requestId` to put in the body.
897
+ * @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and
898
+ * `details` or `errors` when there are any.
899
+ */
900
+ export declare function toErrorResponse(err: unknown, context: ErrorContext): ErrorEnvelope;
901
+ //#endregion
902
+ export { Action, type ActionAccessInfo, ActionAccessPolicy, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, ActionSchema, type ApiDocument, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickApp, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, type BrickIR, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CreateServerOptions, type DashboardAuth, type DashboardOptions, DatabaseAdapter, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type DocumentationOptions, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, EnvInput, ErrorBuilder, type ErrorEnvelope, type HandlerFactory, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, LifecycleOptions, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiDocument, type OpenApiGeneratorOptions, type PluginEndpointContext, type PluginRouteMethod, type PluginRouteRegistrar, type PluginRouteScope, type PluginRoutes, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, PreparationContribution, ProxyOptions, RateLimitOptions, type ReferenceDocument, type ReferenceOptions, type RequestLoggingOptions, ResilienceOptions, Resource, ResourceConfig, ResourceIdentity, type ResourcePlugin, type ResourcePluginAPI, type ResourcePluginContext, type ResourcePluginTypes, ResourceTypeOptions, type RouteIR, type RouteMethod, SQLiteDatabaseConfig, SQLiteDefinition, type SecretOptions, SecretRef, type SecretSource, Service, ServiceAuthOptions, ServiceOptions, type ServicePlugin, type ServicePluginContext, ServiceSchema, StandardErrorMap, type Static, type TSchema, Table, TelemetryOptions, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, ValidationError, ValidationErrorItem, and, asc, blob, createBrickClient, createPostgresDatabase, createSQLiteDatabase, defineDatabase, defineResourcePlugin, defineServicePlugin, desc, envSource, eq, foreignKey, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, like, listSecrets, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, relations, resetSecrets, resolveSecrets, secret, sql, sqliteTable, text, uniqueIndex };
903
+ //# sourceMappingURL=index.d.ts.map