@brickkit/core 0.12.0 → 0.13.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,5 +1,766 @@
1
- import { $n as WorkflowEvent, $t as getPluginEndpoints, A as Resource, An as satisfiesRange, At as createSQLiteDatabase, B as ServiceSchema, Bn as resolveSecrets, Bt as PluginRouteMethod, C as ErrorDetails, Cn as PluginManifest, Ct as PostgresDatabase, D as NarrowAuthorizedContext, Dn as brickVersion, Dt as BunSQLiteDatabase, E as Logger, En as PluginTableBuilders, Et as BrickSQLiteDatabase, F as ResourceConfig, Fn as envSource, Ft as real, G as ToolConfigWithoutAuthorize, Gn as EventListener, Gt as ResourcePluginAPI, H as Tool, Hn as DispatchOptions, Ht as PluginRouteScope, I as ResourceIdentity, In as listSecrets, It as sqliteTable, J as ValidationErrorItem, Jn as EventsOptions, Jt as ServicePlugin, K as ToolOptions, Kn as EventRecorder, Kt as ResourcePluginContext, L as ResourceTypeOptions, Ln as overrideSecret, Lt as text, M as ResourceActionConfig, Mn as SecretRef, Mt as index, N as ResourceActionInput, Nn as SecretSource, Nt as integer, O as PreparationContribution, On as definePlugin, Ot as SQLiteDatabaseConfig, P as ResourceChild, Pn as defineSecret, Pt as primaryKey, Q as BrickSocketConfig, Qn as ServiceEvents, Qt as getPluginActionRoute, R as Service, Rn as overrideSecrets, Rt as uniqueIndex, S as ErrorBuilder, Sn as PluginLifecycleContext, St as DatabaseAdapter, T as InferTableRow, Tn as PluginSetupContext, Tt as createPostgresDatabase, U as ToolAnnotations, Un as EventDelivery, Ut as PluginRoutes, V as StandardErrorMap, Vn as CrudEventPayload, Vt as PluginRouteRegistrar, W as ToolConfigWithAuthorize, Wn as EventEnvelope, Wt as ResourcePlugin, Xn as ListenerFailure, Xt as defineResourcePlugin, Yn as EventsWorld, Yt as ServicePluginContext, Zn as RetryDecision, Zt as defineServicePlugin, _ as CommandDecision, _n as PluginFactory, _t as EnvInput, a as ActionConfigWithoutAuthorize, an as OutboxCounts, ar as DepsOf, at as BrickSocketSender, b as CompiledRoutePlan, bn as PluginInstallOptions, bt as defineDatabase, c as ActionExecutionError, cn as PostgresOutboxTable, cr as port, ct as SocketBrokerMessage, d as BaseActionConfig, dn as outboxTable, dt as SocketEventArgs, en as resolveWorkflowPaths, er as WorkflowsOptions, f as BaseContext, fn as emitEvent, ft as SocketPayloads, g as CommandConfig, gn as PluginContext, gt as DatabaseHandle, h as CommandChildren, hn as PluginAppContext, ht as DatabaseDefinition, i as ActionConfigWithAuthorize, in as Dispatcher, ir as isEventRef, it as BrickSocketSchema, j as ResourceActionAccess, jn as SecretOptions, jt as foreignKey, k as ProxyOptions, kn as isPluginInstance, kt as blob, l as ActionSchema, ln as SQLiteOutboxTable, lr as useDeps, lt as SocketEmitArgs, m as Command, mn as InstalledPlugin, mt as SocketSchemas, n as ActionAccessPolicy, nn as EventsHub, nr as EventRef, o as ActionContext, on as OutboxStatus, or as Port, p as ChildChanges, pn as defineListener, pt as SocketReplay, q as ValidationError, qn as EventWorkflow, qt as ResourcePluginTypes, r as ActionConfig, rn as stopAllEvents, rr as EventRefs, 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, un as isOutboxTable, ut as SocketEmitOptions, v as CommandErrors, vn as PluginHooks, vt as PostgresDefinition, w as InferTableInsert, wn as PluginServiceContext, wt as PostgresDatabaseConfig, x as DefaultServiceContext, xn as PluginInstance, xt as isDatabaseHandle, y as CommandRow, yn as PluginInfo, yt as SQLiteDefinition, z as ServiceOptions, zn as resetSecrets, zt as PluginEndpointContext } from "./chunks/types.js";
2
- import { $ as desc, $t as endpointPaths, A as defineAction, At as CreateServerOptions, B as defineService, Bt as CompiledRoute, C as defineResource, Ct as relations, D as getActionRoute, Dt as traceRoute, E as ResourceActionInfo, Et as emitHandlerFactory, F as setActionAccess, Ft as CorsOptions, G as BrickDatabase, Gt as HandlerFactory, H as ServiceClient, Ht as compileBrickApplication, I as RedisBrokerOptions, It as CorsOrigin, J as and, Jt as EndpointContext, K as DatabaseConfig, Kt as compilerRuntime, L as redisBroker, Lt as RequestLoggingOptions, M as ACTION_ACCESS_KEY, Mt as compileRoutePlan, N as ActionAccessInfo, Nt as createActionHandler, O as kebabCase, Ot as isBrickApp, P as getActionAccess, Pt as executeCompiledRoute, Q as createDatabase, Qt as createEndpointHandler, R as serializeSocketSchema, Rt as requestLoggingPlugin, S as resetGlobalRegistry, St as or, T as ActionRoute, Tt as syncSchema, U as UntypedServiceClient, Ut as loadCompiledBrickApp, V as ServiceActionCaller, Vt as bindCompiledApplication, W as useService, Wt as CompiledHandler, X as attachDatabase, Xt as EndpointLogger, Y as asc, Yt as EndpointDefinition, Z as buildFtsMatchQuery, Zt as EndpointMethod, _ as Type, _n as runInTransaction, _t as lte, a as McpRegistryOptions, an as DocumentationOptions, at as generateSQLiteTableDdl, b as ServiceRegistry, bt as not, c as createMcpHandler, cn as ReferenceOptions, ct as gt, d as isTool, dn as scalarDocsHTML, dt as inArray, en as resolveEndpointDb, et as drizzleSchema, f as OpenApiGeneratorOptions, fn as swaggerDocsHTML, ft as is, g as TSchema, gn as onTransactionCommit, gt as lt, h as Static, hn as RouteMethod, ht as like, i as McpRegistry, in as ApiDocument, it as generateSQLiteIndexDdl, j as errorsOf, jt as brick, k as buildErrorHelpers, kt as requireBrickApp, l as createMcpRegistry, ln as referencePlugin, lt as gte, m as hoistAnchoredSchemas, mn as RouteIR, mt as isNull, n as toErrorResponse, nn as DashboardAuth, nt as ensureSQLiteFts, o as McpToolDefinition, on as OpenApiDocument, ot as getTableColumns, p as generateOpenApiSpec, pn as BrickIR, pt as isNotNull, q as Table, qt as BrickApp, r as McpHandlerOptions, rn as DashboardOptions, rt as eq, s as UnknownToolError, sn as ReferenceDocument, st as getTableName, t as ErrorEnvelope, tn as toOpenApiPath, tt as ensureResourceIndexes, u as defineTool, un as registerReferenceRoute, ut as ilike, v as getCompiledCheck, vt as migrateDatabase, w as loadRecord, wt as sql, x as getGlobalRegistry, xt as notInArray, y as validateWithSchema, yt as ne, z as ServiceImpl, zt as CompiledApplication } from "./chunks/index.js";
3
- import { a as BrickClientOptions, c as BrickTransportError, d as InferActionInput, f as InferActionOutput, h as isBrickTransportError, i as BrickClientAction, l as InferActionErrorCodes, m as isBrickServerError, n as BrickCallOptions, o as BrickServerError, p as createBrickClient, r as BrickClient, s as BrickServices, t as BrickActionCaller, u as InferActionFailure } from "./chunks/client.js";
4
- import { i as stepFailure, n as defineError, r as stepErrors, t as StepErrorBuilder } from "./chunks/workflow.js";
5
- export { ACTION_ACCESS_KEY, Action, type ActionAccessInfo, ActionAccessPolicy, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, type ActionRoute, ActionSchema, type ApiDocument, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickApp, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, BrickDatabase, type BrickIR, BrickSQLiteDatabase, BrickServerError, type BrickServices, type BrickSocketConfig, type BrickSocketHandle, type BrickSocketSchema, type BrickSocketSender, BrickTransportError, type BunSQLiteDatabase, ChildChanges, Command, CommandChildren, CommandConfig, CommandDecision, CommandErrors, CommandRow, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CorsOptions, type CorsOrigin, type CreateServerOptions, type CrudEventPayload, type DashboardAuth, type DashboardOptions, DatabaseAdapter, DatabaseConfig, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type DepsOf, type DispatchOptions, Dispatcher, type DocumentationOptions, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, EnvInput, ErrorBuilder, ErrorDetails, type ErrorEnvelope, type EventCatalog, type EventDelivery, type EventEnvelope, type EventListener, type EventRecorder, type EventRef, type EventRefs, type EventWorkflow, type EventsDefinition, EventsHub, type EventsOptions, type EventsWorld, type HandlerFactory, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, type InstalledPlugin, type ListenerFailure, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiDocument, type OpenApiGeneratorOptions, type OutboxCounts, type OutboxStatus, type OutboxTable, type PluginAppContext, type PluginContext, type PluginEndpointContext, type PluginFactory, type PluginHooks, type PluginInfo, type PluginInstallOptions, type PluginInstance, type PluginLifecycleContext, type PluginManifest, type PluginRouteMethod, type PluginRouteRegistrar, type PluginRouteScope, type PluginRoutes, type PluginServiceContext, type PluginSetupContext, type PluginTableBuilders, type Port, type Ports, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, type PostgresOutboxTable, PreparationContribution, ProxyOptions, type RedisBrokerOptions, type ReferenceDocument, type ReferenceOptions, type RequestLoggingOptions, Resource, ResourceActionAccess, ResourceActionConfig, type ResourceActionInfo, ResourceActionInput, ResourceChild, ResourceConfig, ResourceIdentity, type ResourcePlugin, type ResourcePluginAPI, type ResourcePluginContext, type ResourcePluginTypes, ResourceTypeOptions, type RetryDecision, type RouteIR, type RouteMethod, SQLiteDatabaseConfig, SQLiteDefinition, type SQLiteOutboxTable, type SecretOptions, SecretRef, type SecretSource, Service, type ServiceActionCaller, type ServiceClient, type ServiceEvents, ServiceImpl, ServiceOptions, type ServicePlugin, type ServicePluginContext, ServiceRegistry, ServiceSchema, type SocketBroker, type SocketBrokerMessage, type SocketEmitArgs, type SocketEmitOptions, type SocketEventArgs, type SocketPayloads, type SocketReplay, type SocketSchemas, StandardErrorMap, type Static, type StepErrorBuilder, type TSchema, type Table, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, UnknownToolError, type UntypedServiceClient, ValidationError, ValidationErrorItem, type WorkflowEvent, type WorkflowsOptions, and, asc, attachDatabase, bindCompiledApplication, blob, brick, brickVersion, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, defineAction, defineDatabase, defineError, defineListener, definePlugin, defineResource, defineResourcePlugin, defineSecret, defineService, defineServicePlugin, defineTool, desc, drizzleSchema, emitEvent, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, errorsOf, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getActionRoute, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hoistAnchoredSchemas, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isEventRef, isNotNull, isNull, isOutboxTable, isPluginInstance, isTool, kebabCase, like, listSecrets, loadCompiledBrickApp, loadRecord, lt, lte, migrateDatabase, ne, not, notInArray, onTransactionCommit, or, outboxTable, overrideSecret, overrideSecrets, port, primaryKey, real, redisBroker, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, resolveWorkflowPaths, runInTransaction, satisfiesRange, scalarDocsHTML, serializeSocketSchema, setActionAccess, sql, sqliteTable, stepErrors, stepFailure, stopAllEvents, swaggerDocsHTML, syncSchema, text, toErrorResponse, toOpenApiPath, traceRoute, uniqueIndex, useDeps, useService, validateWithSchema };
1
+ import { $n as CrudEventOperation, $t as PluginRoutes, A as Resource, An as listSecrets, At as PostgresDatabase, B as ServiceSchema, Bn as DispatchOptions, Bt as integer, C as ErrorDetails, Cn as PluginSetupContext, Ct as DatabaseDefinition, D as NarrowAuthorizedContext, Dn as SecretSource, Dt as SQLiteDefinition, E as Logger, En as SecretRef, Et as PostgresDefinition, F as ResourceConfig, Fn as HostHooks, Ft as SQLiteDatabaseConfig, G as ToolConfigWithoutAuthorize, Gn as EventWorkflow, Gt as uniqueIndex, H as Tool, Hn as EventEnvelope, Ht as real, I as ResourceIdentity, In as PluginHookArgs, It as blob, J as ValidationErrorItem, Jn as ListenerFailure, Jt as PLUGIN_KIND, K as ToolOptions, Kn as EventsOptions, Kt as ContextOf, L as ResourceTypeOptions, Ln as PluginHooks, Lt as createSQLiteDatabase, M as ResourceActionConfig, Mn as resetSecrets, Mt as createPostgresDatabase, N as ResourceActionInput, Nn as resolveSecrets, Nt as BrickSQLiteDatabase, O as PreparationContribution, On as defineSecret, Ot as defineDatabase, P as ResourceChild, Pn as PluginTableBuilders, Pt as BunSQLiteDatabase, Qn as WorkflowsOptions, Qt as PluginRouteScope, R as Service, Rn as getHostHooks, Rt as foreignKey, S as ErrorBuilder, Sn as PluginServiceContext, T as InferTableRow, Tn as SecretOptions, Tt as EnvInput, U as ToolAnnotations, Un as EventListener, Ut as sqliteTable, V as StandardErrorMap, Vn as EventDelivery, Vt as primaryKey, W as ToolConfigWithAuthorize, Wn as EventRecorder, Wt as text, Xn as ServiceEvents, Xt as PluginRouteMethod, Y as BrickClientSocket, Yn as RetryDecision, Yt as PluginEndpointContext, Z as BrickSocketConfig, Zn as WorkflowEvent, Zt as PluginRouteRegistrar, _ as CommandDecision, _n as PluginInfo, _t as Dispatcher, a as ActionConfigWithoutAuthorize, an as ServicePluginContext, ar as isCrudEvent, b as DefaultServiceContext, bn as PluginLifecycleContext, c as ActionExecutionError, cr as Ports, ct as SocketEmitArgs, d as BaseActionConfig, dn as PostgresOutboxTable, dr as HttpMethod, dt as SocketPayloads, en as ResourcePlugin, er as EventCatalog, et as BrickSocketHandle, f as BaseContext, fn as SQLiteOutboxTable, ft as SocketReplay, g as CommandConfig, gn as PluginFactory, gt as stopAllEvents, h as CommandChildren, hn as PluginContext, ht as EventsHub, i as ActionConfigWithAuthorize, in as ServicePlugin, ir as crudEventSource, it as BrickSocketSender, j as ResourceActionAccess, jn as overrideSecret, jt as PostgresDatabaseConfig, k as ProxyOptions, kn as envSource, kt as isDatabaseHandle, l as ActionSchema, ln as OutboxStatus, lr as port, lt as SocketEmitOptions, m as Command, mn as PluginAppContext, mt as EventsDefinition, n as ActionAccessPolicy, nn as ResourcePluginContext, nr as EventRefs, o as ActionContext, on as ActionAccessInfo, or as DepsOf, ot as SocketBroker, p as ChildChanges, pn as outboxTable, pt as SocketSchemas, q as ValidationError, qn as EventsWorld, qt as InstalledPlugin, r as ActionConfig, rn as ResourcePluginTypes, rr as crudEventName, rt as BrickSocketSchema, s as ActionErrorDefinition, sn as ResourceActionInfo, sr as Port, st as SocketBrokerMessage, t as Action, tn as ResourcePluginAPI, tr as EventRef, u as ArchitectureSchema, un as OutboxTable, ur as useDeps, ut as SocketEventArgs, v as CommandErrors, vn as PluginInstallOptions, vt as OutboxCounts, w as InferTableInsert, wn as definePlugin, wt as DatabaseHandle, x as DuplicateNameError, xn as PluginManifest, xt as WireError, y as CommandRow, yn as PluginInstance, z as ServiceOptions, zn as CrudEventPayload, zt as index } from "./chunks/types.js";
2
+ import { A as scalarDocsHTML, C as ApiDocument, D as ReferenceOptions, E as ReferenceDocument, M as RouteIR, N as RouteMethod, O as referencePlugin, S as DashboardOptions, T as OpenApiDocument, _ as EndpointContext, a as RequestLoggingOptions, b as EndpointMethod, c as CompiledRoute, d as loadCompiledBrickApp, f as CompiledHandler, g as BrickApp, h as deny, i as CorsOrigin, j as BrickIR, k as registerReferenceRoute, l as bindCompiledApplication, m as HandlerFactory, n as brick, o as requestLoggingPlugin, p as CompiledRoutePlan, r as CorsOptions, s as CompiledApplication, t as CreateServerOptions, u as compileBrickApplication, v as EndpointDefinition, w as DocumentationOptions, x as DashboardAuth, y as EndpointLogger } from "./chunks/server.js";
3
+ import { _ as GLOBAL_SYMBOL, a as BrickClientOptions, c as BrickTransportError, d as InferActionInput, f as InferActionOutput, g as ATTR, h as isBrickTransportError, i as BrickClientAction, l as InferActionErrorCodes, m as isBrickServerError, n as BrickCallOptions, o as BrickServerError, p as createBrickClient, r as BrickClient, s as BrickServices, t as BrickActionCaller, u as InferActionFailure, v as SPAN, y as kebabCase } from "./chunks/client.js";
4
+ import { StepErrorBuilder, defineError, stepErrors, stepFailure } from "./workflow.js";
5
+ import { SpanKind } from "@opentelemetry/api";
6
+ import { Static, TSchema, TSchema as TSchema$1, Type } from "@sinclair/typebox";
7
+ import "@sinclair/typebox/compiler";
8
+ import { Column, Table, Table as Table$1, 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";
9
+ /**
10
+ * Define a plugin that installs onto a service with `service.use(plugin)`. Its
11
+ * `setup` receives the service and a `routes` registrar for adding actions and
12
+ * raw HTTP endpoints, and returns the typed API that `service.use` hands back.
13
+ *
14
+ * @param definition - A unique `name`, optional `routes` controls that let the
15
+ * user move or switch off the plugin's routes, and `setup`, which must be
16
+ * synchronous.
17
+ * @returns The plugin descriptor, frozen.
18
+ * @throws When the name is empty or has surrounding whitespace.
19
+ * @example
20
+ * import { defineServicePlugin, t } from "@brickkit/core";
21
+ *
22
+ * export const greeting = (salutation = "Hello") =>
23
+ * defineServicePlugin({
24
+ * name: "example/greeting",
25
+ * setup({ routes }) {
26
+ * const hello = routes.action({
27
+ * name: "hello",
28
+ * input: t.Object({ name: t.String() }),
29
+ * output: t.String(),
30
+ * execute: ({ input }) => `${salutation}, ${input.name}!`,
31
+ * });
32
+ * return { hello };
33
+ * },
34
+ * });
35
+ *
36
+ * const api = greeterService.use(greeting("Welcome"));
37
+ * await api.hello({ input: { name: "Ada" } });
38
+ */
39
+ export declare function defineServicePlugin<S extends Service<any, any> = Service<any, any>, A = unknown>(definition: Omit<ServicePlugin<S, A>, typeof PLUGIN_KIND> & {
40
+ setup: (context: ServicePluginContext<S>) => A & (A extends PromiseLike<unknown> ? never : unknown);
41
+ }): ServicePlugin<S, A>;
42
+ /**
43
+ * Define a plugin that installs onto a resource (a table and its entity) with
44
+ * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
45
+ * `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and
46
+ * returns the typed API that `resource.use` hands back. `crud` is built this way.
47
+ *
48
+ * @param definition - A unique `name`, optional `routes` controls, and `setup`,
49
+ * which must be synchronous.
50
+ * @returns The plugin descriptor, frozen.
51
+ * @throws When the name is empty or has surrounding whitespace.
52
+ */
53
+ export declare function defineResourcePlugin<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>, A extends object = object>(definition: Omit<ResourcePlugin<S, R, A>, typeof PLUGIN_KIND> & {
54
+ setup: (context: ResourcePluginContext<S, R>) => A & (A extends PromiseLike<unknown> ? never : unknown);
55
+ }): ResourcePlugin<S, R, A>;
56
+ /**
57
+ * The raw HTTP endpoints plugins registered on a service, ready to mount on the
58
+ * application. Each handler resolves the service's context before it runs.
59
+ *
60
+ * @param service - The service plugins were installed on.
61
+ * @param prefix - The application's route prefix (default `/api`).
62
+ * @returns The enabled endpoints: `path`, `method`, `handler`, and the
63
+ * `summary`, `description`, and `tags` for OpenAPI.
64
+ */
65
+ export declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
66
+ path: string;
67
+ method: "DELETE" | "GET" | "PATCH" | "POST" | "PUT";
68
+ service: Service<any, any, EventCatalog>;
69
+ plugin: string;
70
+ summary: string | undefined;
71
+ description: string | undefined;
72
+ tags: string[] | undefined;
73
+ handler: (context: Omit<PluginEndpointContext, "ctx">) => Promise<unknown>;
74
+ }[];
75
+ /**
76
+ * An Elysia handler for one action. Use it to mount an action on your own
77
+ * Elysia app; `brick()` does it for you.
78
+ *
79
+ * @deprecated Serve actions with `brick()`, or bind every route at once with
80
+ * `compileBrickApplication`.
81
+ * @param service - The service the action belongs to.
82
+ * @param action - The action.
83
+ * @param routePath - The route's path.
84
+ * @param method - The HTTP method (POST by default).
85
+ * @returns A function from the Elysia context to the response.
86
+ */
87
+ export declare function createActionHandler(service: Service, action: Action, routePath: string, method?: string): CompiledHandler;
88
+ /**
89
+ * Whether a value is an application made by `brick()`. It checks for the
90
+ * methods and `definition` a `BrickApp` has, so it also recognizes one built by
91
+ * another copy of the package.
92
+ *
93
+ * @param app - Anything, such as the default export of an entry file.
94
+ * @returns `true` for a `BrickApp`, narrowing its type.
95
+ */
96
+ export declare function isBrickApp(app: unknown): app is BrickApp;
97
+ /**
98
+ * Check that a module's default export is an application ready to be served,
99
+ * for tools that load an entry file.
100
+ *
101
+ * @param app - The default export of an entry file.
102
+ * @returns The app.
103
+ * @throws When it is not a `BrickApp`, or it already called `.listen()`: the
104
+ * entry must only build the app, and leave listening to the server bootstrap.
105
+ */
106
+ export declare function requireBrickApp(app: unknown): BrickApp;
107
+ /** What a raw route handler receives from `traceRoute`. Read the body from `request`. */
108
+ interface RawRouteContext {
109
+ request: Request;
110
+ headers: Record<string, string | undefined>;
111
+ set: {
112
+ status?: unknown;
113
+ headers?: Record<string, unknown>;
114
+ };
115
+ params: Record<string, string>;
116
+ query: Record<string, string | undefined>;
117
+ }
118
+ /**
119
+ * Wrap a raw route handler so each of its requests gets a server span. Use it
120
+ * for routes registered directly on the app, outside actions and endpoints,
121
+ * such as auth or webhook routes. Spans are recorded whenever a tracer provider
122
+ * is registered; `brick({ telemetry })` does not apply to these routes.
123
+ *
124
+ * The wrapper forwards only the fields listed in `RawRouteContext`. Elysia
125
+ * decides what to parse from the handler's destructuring, and forwarding the
126
+ * whole context would parse the body and leave `request.json()` with nothing.
127
+ */
128
+ export declare function traceRoute<T>(route: string, handler: (context: RawRouteContext) => T): (context: RawRouteContext) => T;
129
+ /**
130
+ * A JSON value as its column stores it: an ISO string becomes a Date for a date
131
+ * column, an integer string a BigInt for a bigint column. Other values pass
132
+ * through.
133
+ *
134
+ * @returns `undefined` when the string can't be a value of the column.
135
+ */
136
+ export declare function columnValue(column: Column, value: unknown): unknown;
137
+ /**
138
+ * Apply the migrations in a folder that have not run yet, in order, and record
139
+ * them in the database's `__drizzle_migrations` table. The folder is the one
140
+ * `brick db generate` (or drizzle-kit) writes: `<out>/<database name>`.
141
+ *
142
+ * @param database - A handle from `defineDatabase`.
143
+ * @param migrationsFolder - The folder holding `meta/_journal.json`.
144
+ * @example
145
+ * await migrateDatabase(database, "./drizzle/pages");
146
+ */
147
+ export declare function migrateDatabase(database: DatabaseHandle<unknown>, migrationsFolder: string): Promise<void>;
148
+ /** Attach a defined database. Schema changes remain the caller's responsibility. */
149
+ export declare function attachDatabase<TDb>(service: Service<TDb, any>, database: DatabaseHandle<TDb>): TDb;
150
+ /**
151
+ * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition
152
+ * directly from a Drizzle table schema.
153
+ */
154
+ export declare function generateSQLiteTableDdl(table: any): string;
155
+ /**
156
+ * Generates idempotent secondary index DDL for a Drizzle table.
157
+ * Covers owner scoping, sort columns, and exact-match filters.
158
+ * UNIQUE columns already carry an implicit index — skipped here.
159
+ * FTS/trigram indexes are handled separately by the search layer.
160
+ */
161
+ export declare function generateSQLiteIndexDdl(table: any, opts?: {
162
+ ownerField?: string;
163
+ sortFields?: string[];
164
+ }): string[];
165
+ /**
166
+ * Ensures secondary indexes exist for a resource table.
167
+ * SQLite: B-tree indexes for owner scope + sort + composite hot path.
168
+ * Postgres: same B-trees plus pg_trgm GIN indexes for substring search,
169
+ * created one after another (each GIN index needs the extension).
170
+ * Best-effort: a failed statement warns and the rest still run (e.g. a
171
+ * read-only replica, or no right to create pg_trgm); queries still work, only
172
+ * slower. On SQLite every statement has run when it returns.
173
+ */
174
+ export declare function ensureResourceIndexes(db: any, table: any, opts?: {
175
+ ownerField?: string;
176
+ sortFields?: string[];
177
+ searchFields?: string[];
178
+ }): Promise<void>;
179
+ /**
180
+ * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.
181
+ * Idempotent; safe to call on every resource registration.
182
+ * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.
183
+ */
184
+ export declare function ensureSQLiteFts(db: any, table: any, searchCols: string[]): void;
185
+ /**
186
+ * Builds an FTS5 MATCH condition for a resource search term.
187
+ * Returns null when the term has no usable tokens or FTS errors.
188
+ * Caller falls back to LIKE in that case.
189
+ */
190
+ export declare function buildFtsMatchQuery(search: string): string | null;
191
+ /**
192
+ * The schema drizzle-kit reads: the tables, plus the Postgres schemas
193
+ * (namespaces) and enums they use, which drizzle-kit only creates when handed.
194
+ *
195
+ * @param tables - Drizzle tables, all of one engine.
196
+ * @returns A record to pass to drizzle-kit's API (`pushSchema`, `generateDrizzleJson`).
197
+ */
198
+ export declare function drizzleSchema(tables: readonly Table$1[]): Record<string, unknown>;
199
+ /**
200
+ * Create the declared tables that do not exist yet. A development and test
201
+ * helper: never called by services, resources or server startup, and never
202
+ * changes a table that exists. Use `brick db generate` / `brick db migrate`
203
+ * for production schema changes.
204
+ *
205
+ * SQLite: `CREATE TABLE IF NOT EXISTS` per table, synchronously.
206
+ * Postgres: drizzle-kit (an optional peer dependency) writes the DDL for the
207
+ * missing tables, their enums, indexes and foreign keys, applied in one
208
+ * transaction. Returns a promise to await.
209
+ */
210
+ export declare function syncSchema(tablesOrService: Map<string, any> | any[] | Record<string, any> | Service, dbInstance?: any): Promise<void> | void;
211
+ /** An in-process caller for one action: its input, then an optional call context. */
212
+ 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>>;
213
+ /**
214
+ * What `useService` returns: the service's actions as methods, with each
215
+ * resource's actions under the resource's name. Sockets are left out.
216
+ */
217
+ 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]>; };
218
+ declare const serviceNameType: unique symbol;
219
+ /** Type only: the literal name of a service, which `useService` finds its contract by. */
220
+ interface NamedService<N extends string> {
221
+ readonly [serviceNameType]?: N;
222
+ }
223
+ /** What `useService` returns while the contract does not describe the service yet. */
224
+ type UntypedServiceClient = {
225
+ [name: string]: any;
226
+ };
227
+ /**
228
+ * Call another service's actions in-process, typed from that service. Each
229
+ * action is a method, and each resource's actions sit under the resource's
230
+ * name: `billing.charge(input)`, `billing.invoice.list()`.
231
+ *
232
+ * The types come from the app's generated contract (`_brick/contract.ts`, which
233
+ * `brick dev` and `brick gen client` keep current), so renaming an action or
234
+ * changing its input is a compile error at every caller. Until the contract
235
+ * describes the service, the client is untyped.
236
+ *
237
+ * A call runs through the target's own validation and authorization, with the
238
+ * target's database, context and deps (never the caller's), and shows as an
239
+ * `rpc` span in the trace.
240
+ *
241
+ * @param service - The service to call, as `defineService` returned it.
242
+ * @param options - `from` (the calling service's name, which becomes `ctx.caller`
243
+ * in the target and cannot be spoofed) and `context` (defaults for every call).
244
+ * Each call also takes an optional call context after its input.
245
+ * @returns The client.
246
+ * @throws On a call, when the service is not registered or has no such action.
247
+ * @example
248
+ * import { useService } from "@brickkit/core";
249
+ * import { billingService } from "../billing/billing.service";
250
+ *
251
+ * const billing = useService(billingService, { from: "orders" });
252
+ * await billing.charge({ orderId, amountCents });
253
+ * await billing.invoice.list({ limit: 10 });
254
+ */
255
+ export declare function useService<const N extends string = string>(service: {
256
+ readonly name: string;
257
+ } & NamedService<N>, options?: ProxyOptions): N extends keyof BrickServices ? ServiceClient<BrickServices[N]> : UntypedServiceClient;
258
+ /**
259
+ * Declare a service: a named group of actions, tools, and resources with its own
260
+ * database and request context. It is registered globally, so `brick()`, the
261
+ * OpenAPI generator, and `useService` find it by name.
262
+ *
263
+ * Add actions with `service.action(...)`, tools with `service.tool(...)`,
264
+ * resources with `service.resource(...)`, and plugins with `service.use(...)`.
265
+ *
266
+ * @param name - Unique name. It is the service's segment of every action route
267
+ * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it
268
+ * again from the same file (a dev reload) replaces it; from another file throws.
269
+ * @param options - `database` (a handle from `defineDatabase`), `deps` (typed
270
+ * slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),
271
+ * `context` (adds fields such as the signed-in user to every action's `ctx`),
272
+ * `events` (the event catalog: a payload schema per event name, recorded as
273
+ * `<service>.<name>` and offered as `service.events.<name>`).
274
+ * @returns The service.
275
+ * @example
276
+ * import { defineDatabase, defineService, t } from "@brickkit/core";
277
+ *
278
+ * const database = defineDatabase({ tables: { pages } });
279
+ *
280
+ * export const pagesService = defineService("pages", {
281
+ * database,
282
+ * // Added to `ctx` in every action of this service.
283
+ * context: async ({ request }) => ({ user: await readUser(request) }),
284
+ * });
285
+ *
286
+ * pagesService.action({
287
+ * name: "list",
288
+ * input: t.Object({ limit: t.Optional(t.Number()) }),
289
+ * output: t.Array(t.Object({ id: t.String(), title: t.String() })),
290
+ * execute: ({ input, ctx }) =>
291
+ * ctx.db.select().from(pages).limit(input.limit ?? 20),
292
+ * });
293
+ */
294
+ export 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> & {
295
+ events?: TEvents;
296
+ deps?: TPorts;
297
+ }): Service<TDb, {} extends TPorts ? TServiceContext : TServiceContext & {
298
+ deps: DepsOf<TPorts>;
299
+ }, TEvents> & NamedService<TName>;
300
+ /** Keep validators browser-safe and reject schemas whose behavior cannot cross JSON. */
301
+ export declare function serializeSocketSchema(schema: TSchema$1): unknown;
302
+ interface RedisBrokerOptions {
303
+ /** Defaults to `REDIS_URL`, then `redis://localhost:6379`. */
304
+ url?: string;
305
+ /** Emits held while Redis is unreachable; older ones are dropped. Default 1000. */
306
+ queue?: number;
307
+ }
308
+ /**
309
+ * Fans socket emits and kicks out across processes through Redis pub/sub, one
310
+ * channel per room topic. An emit is a PUBLISH only: every process, the emitting
311
+ * one included, delivers it once to its own connections. Uses Bun's built-in
312
+ * Redis client and two connections, one to publish and one to subscribe.
313
+ */
314
+ export declare function redisBroker(options?: RedisBrokerOptions): SocketBroker;
315
+ /**
316
+ * Record how an action is protected, for tools that cannot read it from the
317
+ * configuration: plugins such as `crud` enforce access inside `execute`, so the
318
+ * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
319
+ * read what is recorded here.
320
+ *
321
+ * @param action - The action to describe.
322
+ * @param info - Whether it checks authorization and whether it scopes queries,
323
+ * and the resulting policy.
324
+ */
325
+ export declare function setActionAccess(action: object, info: ActionAccessInfo): void;
326
+ /**
327
+ * How an action is protected: `"public"` when nothing checks the caller,
328
+ * `"authorized"` when an `authorize` does, and `"scoped"` when the action also
329
+ * limits what rows the caller can reach. It reads what a plugin recorded with
330
+ * `setActionAccess`, else the action's own `authorize`, and keeps the policy
331
+ * consistent with the flags.
332
+ *
333
+ * @param action - An action, or any object a plugin described.
334
+ * @returns `hasAuthorize`, `hasScope`, and `policy`.
335
+ */
336
+ export declare function getActionAccess(action: Action | object): ActionAccessInfo;
337
+ /**
338
+ * The `error` helpers an action receives: one function per error code that
339
+ * throws an `ActionExecutionError` with that code and status. The standard HTTP
340
+ * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
341
+ * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
342
+ * them or replace one.
343
+ *
344
+ * @param errorsDef - The action's `errors`: for each code, its `message` and
345
+ * `status` (default 400).
346
+ * @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
347
+ * and always throw.
348
+ */
349
+ export declare function buildErrorHelpers<TErrors extends Record<string, ActionErrorDefinition>>(errorsDef?: TErrors): ErrorBuilder<TErrors>;
350
+ /** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */
351
+ export declare function errorsOf<TErrors extends Record<string, ActionErrorDefinition>>(action: {
352
+ config: {
353
+ errors?: TErrors;
354
+ };
355
+ }): TErrors;
356
+ /**
357
+ * Define an action: a typed, validated function that Brick serves over HTTP,
358
+ * runs in-process, and exposes to the typed client and OpenAPI.
359
+ *
360
+ * A call runs in order: the input is validated against `input` (an invalid one
361
+ * is a `VALIDATION_FAILED` error, HTTP 400); `authorize` runs, if there is one;
362
+ * `execute` runs; and its result is validated against `output` (a mismatch is a
363
+ * server error, HTTP 500). Throw `error.CODE(...)` from `execute` for a declared
364
+ * failure or a standard one such as `error.NOT_FOUND()`. Any other thrown value
365
+ * becomes `INTERNAL_SERVER_ERROR` (500), with the cause kept out of the response
366
+ * and in the log.
367
+ *
368
+ * `authorize` returns `false` to refuse: the call fails with `UNAUTHORIZED`
369
+ * (401) when there is no `ctx.user`, and `FORBIDDEN` (403) when there is one.
370
+ * Where it is given, `execute` can rely on what it checked.
371
+ *
372
+ * @param config - `name`, `execute`, and optionally `description`, `input` and
373
+ * `output` (TypeBox schemas), `errors`, `authorize`, `method` and `path` to
374
+ * change the route (POST by default), `tags`, and `emits`.
375
+ * @returns The action. Register it with `service.action(action)`; call it
376
+ * directly with `action.run(input, ctx)`.
377
+ * @example
378
+ * import { defineAction, t } from "@brickkit/core";
379
+ *
380
+ * export const getPage = defineAction({
381
+ * name: "get",
382
+ * method: "GET",
383
+ * input: t.Object({ id: t.String() }),
384
+ * output: t.Object({ id: t.String(), title: t.String() }),
385
+ * errors: { PAGE_GONE: { message: "That page was removed", status: 410 } },
386
+ * authorize: ({ user }) => user != null,
387
+ * execute: async ({ input, ctx, error }) => {
388
+ * const page = await findPage(ctx.db, input.id);
389
+ * if (!page) throw error.NOT_FOUND("No such page");
390
+ * return page;
391
+ * },
392
+ * });
393
+ */
394
+ 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>;
395
+ 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>;
396
+ /**
397
+ * Load the row a record action (or command) works on, through its `access`.
398
+ *
399
+ * @returns The row, or `undefined` when it is missing or hidden.
400
+ * @throws When `access` is missing.
401
+ */
402
+ export declare function loadRecord(resource: Resource<any, any, any>, args: {
403
+ id: unknown;
404
+ ctx: any;
405
+ db?: any;
406
+ access?: ResourceActionAccess;
407
+ }): Promise<Record<string, unknown> | undefined>;
408
+ /** The schema of a resource's `:id`. */
409
+ export declare function idSchema(column: Column): TSchema$1;
410
+ /** Declares a resource: a plugin host over a table, with its own `action()` and `command()`. */
411
+ 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>>;
412
+ interface ActionRoute {
413
+ method: HttpMethod;
414
+ path: string;
415
+ }
416
+ /**
417
+ * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
418
+ * compiler, and the typed client.
419
+ *
420
+ * @param action - An action.
421
+ * @param prefix - The application's route prefix (default `/api`).
422
+ * @returns `undefined` when no plugin bound the action (it uses its own route),
423
+ * `false` when the plugin's route was switched off, otherwise the route's
424
+ * `path`, `method`, the `clientPath` the typed client uses, and the owning
425
+ * `plugin` and `resource`.
426
+ */
427
+ export declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix?: string): false | {
428
+ path: string;
429
+ method: "DELETE" | "GET" | "PATCH" | "POST" | "PUT";
430
+ clientPath: string[] | undefined;
431
+ plugin: string;
432
+ resource: string | undefined;
433
+ } | undefined;
434
+ /**
435
+ * Where an action is served over HTTP: its method and its path under the owner
436
+ * tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource
437
+ * action's `${prefix}/${service}/${resource}[/:id]/${action}`).
438
+ *
439
+ * @param action - An action registered on a service.
440
+ * @param prefix - The application's route prefix (default `/api`).
441
+ * @returns `false` when a plugin switched the route off, otherwise the route.
442
+ */
443
+ export declare function getActionRoute(action: Action<any, any, any, any>, prefix?: string): ActionRoute | false;
444
+ /** The owning plugin and resource of an action, for OpenAPI, introspection and the client contract. */
445
+ export declare function actionOwners(action: Action<any, any, any, any>): {
446
+ plugin?: string;
447
+ resource?: string;
448
+ };
449
+ type EventOn = EventRef<any> | readonly EventRef<any>[];
450
+ type PayloadOf<O> = O extends EventRef<infer P> ? P : O extends readonly EventRef<infer P>[] ? P : never;
451
+ type ListenerConfig<TPayload, TOn = string | readonly string[], TErrors extends Record<string, ActionErrorDefinition> = {}> = {
452
+ name: string;
453
+ on: TOn;
454
+ maxAttempts?: number;
455
+ /** Errors `run` may raise with `error.CODE()`. Spread `defineError(...)` results or `errorsOf(action)` here. */
456
+ errors?: TErrors;
457
+ /** Decides what a failure does next. Without it every failure retries until `maxAttempts`. */
458
+ retry?: (error: ListenerFailure<TErrors>) => RetryDecision;
459
+ } & ({
460
+ run: (delivery: EventDelivery<TPayload>, helpers: {
461
+ error: ErrorBuilder<TErrors>;
462
+ }) => void | Promise<void>;
463
+ workflow?: never;
464
+ } | {
465
+ workflow: EventWorkflow<TPayload>;
466
+ run?: never;
467
+ });
468
+ /**
469
+ * Define a listener: code that runs for each event it listens for, after the write
470
+ * that caused the event has been committed. Pass it to `brick({ events: {
471
+ * listeners } })`.
472
+ *
473
+ * It either runs a handler (`run`) in the process that delivers events, or starts
474
+ * a durable workflow (`workflow`) on the app's `events.world`. Delivery is at
475
+ * least once. A handler that throws is retried later with a growing delay, then
476
+ * parked as dead, so it can run again for the same event: use
477
+ * `delivery.deliveryId` to make its work idempotent. A workflow needs no such
478
+ * care: a delivery starts one run however often it is tried, and the workflow
479
+ * retries its own steps.
480
+ *
481
+ * A listener can declare `errors`, as an action does, and raise them in `run` with
482
+ * `error.CODE()`. `retry(error)` then picks `"retry"` or `"dead"` from the typed
483
+ * `error.code`; anything not declared arrives as `{ code: "UNKNOWN", cause }`.
484
+ *
485
+ * @param config - `name` (unique; it is part of each delivery's id), `on` (a
486
+ * declared event such as `orders.events.shipped`, which types the payload, or an
487
+ * event name; or a list of either; a trailing `*` matches a prefix, as in
488
+ * `user.*`), `run` or `workflow`, and optionally `maxAttempts`.
489
+ * @returns The listener.
490
+ * @throws When the name is empty or contains `:`, `on` is empty, or the listener
491
+ * has both or neither of `run` and `workflow`.
492
+ * @example
493
+ * import { brick, defineListener } from "@brickkit/core";
494
+ *
495
+ * const welcome = defineListener({
496
+ * name: "welcome-email",
497
+ * on: "user.create",
498
+ * run: async ({ payload, deliveryId }) => {
499
+ * await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });
500
+ * },
501
+ * });
502
+ *
503
+ * export default brick({ services, events: { listeners: [welcome] } });
504
+ * @example
505
+ * // src/workflows/onboard.ts
506
+ * export async function onboard(event: WorkflowEvent<CrudEventPayload>) {
507
+ * "use workflow";
508
+ * await sendWelcome(event.payload.row.email);
509
+ * }
510
+ *
511
+ * defineListener({ name: "onboard", on: "user.create", workflow: onboard });
512
+ * @example
513
+ * // payload is { id: string; trackingId: string }, from the orders catalog.
514
+ * defineListener({
515
+ * name: "notify-shipped",
516
+ * on: orders.events.shipped,
517
+ * run: ({ payload }) => notify(payload.id, payload.trackingId),
518
+ * });
519
+ */
520
+ export declare function defineListener<const TOn extends EventOn, const TErrors extends Record<string, ActionErrorDefinition> = {}>(config: ListenerConfig<PayloadOf<TOn>, TOn, TErrors>): EventListener<PayloadOf<TOn>>;
521
+ export declare function defineListener<TPayload = any, const TErrors extends Record<string, ActionErrorDefinition> = {}>(config: ListenerConfig<TPayload, string | EventRef<any> | readonly (string | EventRef<any>)[], TErrors>): EventListener<TPayload>;
522
+ /**
523
+ * Record an event of your own from an action, a tool or a hook. Listeners get it
524
+ * as they get a generated CRUD event, with the payload you give.
525
+ *
526
+ * By default the event is committed in a transaction of its own. Pass the `tx`
527
+ * of a transaction you have open to commit it with your writes instead: then it
528
+ * is delivered at the dispatcher's next poll, because Brick does not see your
529
+ * commit. Nothing is recorded when no listener wants the event.
530
+ *
531
+ * @param ctx - The action context: its `db` finds the service's outbox, and its
532
+ * `traceId` follows the event to its listeners.
533
+ * @param event - A declared event, such as `orders.events.shipped`, whose payload
534
+ * is typed and checked against its schema; or an event name such as
535
+ * `orders.refunded`. A service with an event catalog only records names from it
536
+ * (and the CRUD events of its resources).
537
+ * @param payload - JSON data for the listeners.
538
+ * @param options - `tx`: an open transaction on the service's database. `source`:
539
+ * what emitted it, shown to listeners.
540
+ * @throws When the context's database has no outbox table, or the app has no
541
+ * `events`; when the event is not in the service's catalog, or its payload does
542
+ * not match the declared schema.
543
+ * @example
544
+ * refund: service.action({
545
+ * name: "refund",
546
+ * execute: async ({ ctx, input }) => {
547
+ * await ctx.db.update(orders).set({ status: "refunded" }).where(eq(orders.id, input.id));
548
+ * await emitEvent(ctx, orders.events.refunded, { id: input.id });
549
+ * },
550
+ * });
551
+ */
552
+ export declare function emitEvent<TPayload>(ctx: {
553
+ db?: unknown;
554
+ traceId?: string;
555
+ }, event: EventRef<TPayload>, payload: NoInfer<TPayload>, options?: {
556
+ tx?: unknown;
557
+ source?: string;
558
+ }): Promise<void>;
559
+ export declare function emitEvent(ctx: {
560
+ db?: unknown;
561
+ traceId?: string;
562
+ }, name: string, payload: unknown, options?: {
563
+ tx?: unknown;
564
+ source?: string;
565
+ }): Promise<void>;
566
+ /**
567
+ * Run `fn` in a database transaction: everything it writes through the `tx` it is
568
+ * given is committed together when it returns, or undone if it throws.
569
+ *
570
+ * Postgres uses a real transaction on one connection. SQLite has one connection
571
+ * and a synchronous driver, which Drizzle's own `transaction` cannot use with an
572
+ * async callback (it would commit before the callback finished). So transactions
573
+ * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
574
+ * A write made elsewhere in the process during that time, outside this helper,
575
+ * would join the transaction; use Postgres where that matters.
576
+ *
577
+ * A call made inside `fn` with the `tx` it was given (on SQLite, the database
578
+ * itself) joins the open transaction as a savepoint instead of waiting for it: a
579
+ * nested failure undoes only the nested work, and the outer transaction decides
580
+ * the commit. Nested calls must run one at a time.
581
+ *
582
+ * @param db - A Drizzle database, from `service.getDb()`.
583
+ * @param fn - Receives the transaction handle to run queries on.
584
+ * @returns What `fn` returned.
585
+ * @throws What `fn` threw, after rolling back.
586
+ */
587
+ export declare function runInTransaction<T>(db: any, fn: (tx: any) => Promise<T>): Promise<T>;
588
+ /**
589
+ * Run `fn` once the transaction that `db` belongs to has committed, or now when
590
+ * `db` is not in one opened by `runInTransaction`. It never runs when that
591
+ * transaction, or the savepoint it was queued in, rolls back. An error it throws
592
+ * reaches the caller of the outermost `runInTransaction`, after the commit.
593
+ *
594
+ * @param db - The handle the work ran on: a `tx`, or a database.
595
+ * @param fn - The side effect, such as clearing a cache.
596
+ */
597
+ export declare function onTransactionCommit(db: unknown, fn: () => unknown): Promise<void>;
598
+ /** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */
599
+ export declare const WORKFLOW_BUNDLE: {
600
+ readonly dir: ".well-known/workflow/v1";
601
+ readonly flow: "flow.mjs";
602
+ readonly steps: "__step_registrations.mjs";
603
+ readonly webhook: "webhook.mjs";
604
+ readonly manifest: "manifest.json";
605
+ };
606
+ /**
607
+ * Where the workflow bundle is read from, and the project it is built from.
608
+ *
609
+ * @param options - The `events.workflows` option.
610
+ * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the
611
+ * builder finds the SDK from where it writes, and skips only this directory when it
612
+ * looks for workflows.
613
+ */
614
+ export declare function resolveWorkflowPaths(options?: WorkflowsOptions): {
615
+ root: string;
616
+ dir: string;
617
+ };
618
+ interface ArchitectureApplication {
619
+ services: readonly Service<any, any>[];
620
+ routes: readonly RouteIR[];
621
+ events?: EventsDefinition;
622
+ sockets?: readonly (BrickSocketSchema & {
623
+ service: string;
624
+ path: string;
625
+ })[];
626
+ plugins?: readonly InstalledPlugin[];
627
+ }
628
+ declare class ServiceRegistry {
629
+ private _revision;
630
+ /** Definition revision for invalidating serialized architecture snapshots. */
631
+ get revision(): number;
632
+ touch(): void;
633
+ private services;
634
+ private sites;
635
+ /** @throws When a different file already registered a service with this name. */
636
+ register(service: Service, site?: string | undefined): void;
637
+ get(name: string): Service | undefined;
638
+ has(name: string): boolean;
639
+ list(): Service[];
640
+ /**
641
+ * The architecture of an app (`app.definition`): its mounted routes. Without
642
+ * one, every registered service with its default routes under `/api`.
643
+ */
644
+ exportArchitecture(application?: ArchitectureApplication): ArchitectureSchema;
645
+ }
646
+ /**
647
+ * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
648
+ * generator, `useService`, and the dashboard find services by name.
649
+ *
650
+ * @returns The current global registry.
651
+ */
652
+ export declare function getGlobalRegistry(): ServiceRegistry;
653
+ /**
654
+ * Start over with an empty global registry. For tests, which define the same
655
+ * services again in each case; an application never needs it.
656
+ */
657
+ export declare function resetGlobalRegistry(): void;
658
+ /**
659
+ * Check a value against a schema, the way actions check their input and output.
660
+ *
661
+ * @param schema - A TypeBox schema, or `undefined` to accept anything.
662
+ * @param value - The value to check.
663
+ * @returns `{ success: true, data }`, or `{ success: false, errors }` with a
664
+ * `path`, `message`, `type`, and the offending `value` for each problem.
665
+ */
666
+ export declare function validateWithSchema<T extends TSchema>(schema: T | undefined, value: unknown): {
667
+ success: true;
668
+ data: Static<T>;
669
+ } | {
670
+ success: false;
671
+ errors: ValidationErrorItem[];
672
+ };
673
+ interface OpenApiGeneratorOptions {
674
+ title?: string;
675
+ version?: string;
676
+ description?: string;
677
+ prefix?: string;
678
+ services?: Service<any, any>[];
679
+ }
680
+ /**
681
+ * Build the OpenAPI 3.1 document for the services: one path per action route,
682
+ * with request and response schemas from the actions' TypeBox schemas, their
683
+ * declared errors, tags by service, and a bearer security scheme where any
684
+ * action needs authorization. Declared events are listed under `x-brick-events`,
685
+ * by wire name, with their service and payload schema.
686
+ *
687
+ * `brick()` calls this for `/openapi.json`; call it yourself to write the
688
+ * document to a file or feed another tool.
689
+ *
690
+ * @param options - `title`, `version`, and `description` for the `info` block,
691
+ * `prefix` (default `/api`), and the `services` to describe (the global
692
+ * registry's by default).
693
+ * @returns The document as a plain object.
694
+ */
695
+ export declare function generateOpenApiSpec(options?: OpenApiGeneratorOptions): Record<string, any>;
696
+ /**
697
+ * Define a tool: an action that AI agents can call through MCP. It takes the
698
+ * same configuration as `defineAction` (validation, `authorize`, errors), plus
699
+ * `title`, `annotations` (the MCP hints about what the tool does), and `http`
700
+ * to also serve it over HTTP and in OpenAPI (off by default).
701
+ *
702
+ * @param config - An action configuration and tool options. `input` must be an
703
+ * object schema, since MCP passes arguments by name.
704
+ * @returns The tool, which is also an action. Register it with `service.tool(tool)`.
705
+ * @throws When `input` is not an object schema.
706
+ * @example
707
+ * import { defineTool, t } from "@brickkit/core";
708
+ *
709
+ * export const echoTool = defineTool({
710
+ * name: "echo",
711
+ * title: "Echo a message",
712
+ * description: "Returns the message it is given.",
713
+ * input: t.Object({ message: t.String() }),
714
+ * output: t.String(),
715
+ * execute: ({ input }) => `Echo: ${input.message}`,
716
+ * });
717
+ */
718
+ 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>;
719
+ 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>;
720
+ /**
721
+ * Whether a value was made with `defineTool`, as opposed to `defineAction`.
722
+ *
723
+ * @param value - Anything.
724
+ * @returns `true` for a tool, narrowing its type.
725
+ */
726
+ export declare function isTool(value: unknown): value is Tool<any, any, any, any>;
727
+ interface McpToolDefinition {
728
+ name: string;
729
+ title?: string;
730
+ description: string;
731
+ inputSchema: unknown;
732
+ /** The tool's `output` schema; a non-object one is wrapped as `{ result }`. */
733
+ outputSchema?: unknown;
734
+ annotations: ToolAnnotations;
735
+ }
736
+ interface McpRegistryOptions {
737
+ services?: readonly Pick<Service<any, any>, "listTools">[];
738
+ tools?: readonly Tool<any, any, any, any>[];
739
+ }
740
+ interface McpRegistry {
741
+ listTools(): McpToolDefinition[];
742
+ callTool(name: string, args?: Record<string, unknown>, ctx?: Partial<ActionContext>): Promise<unknown>;
743
+ }
744
+ export declare class UnknownToolError extends Error {
745
+ constructor(name: string);
746
+ }
747
+ /** Collect only explicitly defined tools, without exposing ordinary actions. */
748
+ export declare function createMcpRegistry(options: McpRegistryOptions): McpRegistry;
749
+ interface McpHandlerOptions {
750
+ registry: McpRegistry;
751
+ serverInfo: {
752
+ name: string;
753
+ version: string;
754
+ title?: string;
755
+ };
756
+ /** Versions supported by this transport, newest first. */
757
+ protocolVersions?: readonly string[];
758
+ }
759
+ /** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
760
+ export declare function createMcpHandler(options: McpHandlerOptions): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>;
761
+ /** The JSON body of a failed HTTP call. */
762
+ interface ErrorEnvelope extends WireError {
763
+ requestId: string;
764
+ }
765
+ export { ATTR, Action, type ActionAccessInfo, ActionAccessPolicy, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, type ActionRoute, ActionSchema, type ApiDocument, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickApp, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, type BrickIR, BrickSQLiteDatabase, BrickServerError, type BrickServices, type BrickSocketConfig, type BrickSocketHandle, type BrickSocketSchema, type BrickSocketSender, BrickTransportError, type BunSQLiteDatabase, ChildChanges, Command, CommandChildren, CommandConfig, CommandDecision, CommandErrors, CommandRow, type CompiledApplication, type CompiledHandler, type CompiledRoute, type CompiledRoutePlan, type CorsOptions, type CorsOrigin, type CreateServerOptions, type CrudEventOperation, type CrudEventPayload, type DashboardAuth, type DashboardOptions, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type DepsOf, type DispatchOptions, Dispatcher, type DocumentationOptions, DuplicateNameError, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, EnvInput, ErrorBuilder, ErrorDetails, type ErrorEnvelope, type EventCatalog, type EventDelivery, type EventEnvelope, type EventListener, type EventRecorder, type EventRef, type EventRefs, type EventWorkflow, type EventsDefinition, type EventsHub, type EventsOptions, type EventsWorld, GLOBAL_SYMBOL, type HandlerFactory, type HostHooks, type HttpMethod, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, type InstalledPlugin, type ListenerFailure, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiDocument, type OpenApiGeneratorOptions, type OutboxCounts, type OutboxStatus, type OutboxTable, type PluginAppContext, type PluginContext, type PluginEndpointContext, type PluginFactory, type PluginHookArgs, type PluginHooks, type PluginInfo, type PluginInstallOptions, type PluginInstance, type PluginLifecycleContext, type PluginManifest, type PluginRouteMethod, type PluginRouteRegistrar, type PluginRouteScope, type PluginRoutes, type PluginServiceContext, type PluginSetupContext, type PluginTableBuilders, type Port, type Ports, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, type PostgresOutboxTable, PreparationContribution, ProxyOptions, type RedisBrokerOptions, type ReferenceDocument, type ReferenceOptions, type RequestLoggingOptions, Resource, ResourceActionAccess, ResourceActionConfig, type ResourceActionInfo, ResourceActionInput, ResourceChild, ResourceConfig, ResourceIdentity, type ResourcePlugin, type ResourcePluginAPI, type ResourcePluginContext, type ResourcePluginTypes, ResourceTypeOptions, type RetryDecision, type RouteIR, type RouteMethod, SPAN, SQLiteDatabaseConfig, SQLiteDefinition, type SQLiteOutboxTable, type SecretOptions, SecretRef, type SecretSource, Service, type ServiceActionCaller, type ServiceClient, type ServiceEvents, ServiceOptions, type ServicePlugin, type ServicePluginContext, type ServiceRegistry, ServiceSchema, type SocketBroker, type SocketBrokerMessage, type SocketEmitArgs, type SocketEmitOptions, type SocketEventArgs, type SocketPayloads, type SocketReplay, type SocketSchemas, StandardErrorMap, type Static, type StepErrorBuilder, type TSchema, type Table, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, type UntypedServiceClient, ValidationError, ValidationErrorItem, type WorkflowEvent, type WorkflowsOptions, and, asc, bindCompiledApplication, blob, brick, compileBrickApplication, createBrickClient, createPostgresDatabase, createSQLiteDatabase, crudEventName, crudEventSource, defineDatabase, defineError, definePlugin, defineSecret, deny, desc, envSource, eq, foreignKey, getHostHooks, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickServerError, isBrickTransportError, isCrudEvent, isDatabaseHandle, isNotNull, isNull, kebabCase, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, outboxTable, overrideSecret, port, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, resetSecrets, resolveSecrets, scalarDocsHTML, sql, sqliteTable, stepErrors, stepFailure, stopAllEvents, text, uniqueIndex, useDeps };
766
+ //# sourceMappingURL=index.d.ts.map