@brickkit/core
Services, actions, tools, resources, databases, secrets, the HTTP runtime, and the typed contract of a Brick application.
@brickkit/core exports 176 names: 63 functions, 8 classes, 68 interfaces, 34 types, 3 variables. It also re-exports 4 from @sinclair/typebox and 33 from drizzle-orm.
import { ACTION_ACCESS_KEY, ActionExecutionError, attachDatabase } from "@brickkit/core";Functions
| Function | Description |
|---|---|
attachDatabase | Attach a defined database. |
bindCompiledApplication | Build artifact binder: consumes emitted functions, with no runtime handler code generation. |
brick | Create the HTTP application: an Elysia app that serves every service's actions (and the tools that opt in with http: true) as routes, with /_health, an Ope… |
buildErrorHelpers | The error helpers an action receives: one function per error code that throws an ActionExecutionError with that code and status. |
buildFtsMatchQuery | Builds an FTS5 MATCH condition for a resource search term. |
compileBrickApplication | Startup compiler: analyzes once, then binds live callbacks. |
compileRoutePlan | Work out, once at startup, everything an action's route needs to answer a request: where its input comes from (body, query, or path), the validators, the autho… |
createActionHandler | An Elysia handler for one action: compileRoutePlan and executeCompiledRoute together. |
createBrickClient | Create an Eden/tRPC-style typed client for the application contract TApp. |
createDatabase | Creates a database instance based on the provided configuration. |
createEndpointHandler | Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. |
createMcpHandler | Stateless MCP JSON-RPC POST handler. |
createMcpRegistry | Collect only explicitly defined tools, without exposing ordinary actions. |
createPostgresDatabase | Creates a PostgreSQL Drizzle instance using postgres-js. |
createServiceProxy | A typed way to call another service's actions in-process. |
createSQLiteDatabase | Creates a zero-config SQLite database using Bun's native bun:sqlite engine and Drizzle ORM. |
defineAction | Define an action: a typed, validated function that Brick serves over HTTP, runs in-process, and exposes to the typed client and OpenAPI. |
defineDatabase | Declare a service's database: its engine, its Drizzle tables, and how to reach it. |
defineResource | Declares a plugin host without registering actions or changing the schema. |
defineResourcePlugin | Define a plugin that installs onto a resource (a table and its entity) with resource.use(plugin). |
defineService | Declare a service: a named group of actions, tools, and resources with its own database and request context. |
defineServicePlugin | Define a plugin that installs onto a service with service.use(plugin). |
defineTool | Define a tool: an action that AI agents can call through MCP. |
emitHandlerFactory | Emits framework code only. |
endpointPaths | OpenAPI paths fragment for declared endpoints (raw HTML included). |
ensureResourceIndexes | Ensures secondary indexes exist for a resource table. |
ensureSQLiteFts | Creates the FTS5 sidecar table + sync triggers + backfills existing rows. |
executeCompiledRoute | Answer one request for a compiled route: read the input, run the action, and return its output or the error response, with the x-trace-id and x-request-id … |
generateOpenApiSpec | Build the OpenAPI 3.1 document for the services: one path per action route, with request and response schemas from the actions' TypeBox schemas, their declared… |
generateSQLiteIndexDdl | Generates idempotent secondary index DDL for a Drizzle table. |
generateSQLiteTableDdl | Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition directly from a Drizzle table schema. |
getActionAccess | How an action is protected: "public" when nothing checks the caller, "authorized" when an authorize does, and "scoped" when the action also limits what… |
getCompiledCheck | The compiled validator for a TypeBox schema. |
getGlobalRegistry | The registry every defineService adds to: it is how brick(), the OpenAPI generator, createServiceProxy, and the dashboard find services by name. |
getPluginActionRoute | Where a plugin mounted an action over HTTP, for the OpenAPI generator, the compiler, and the typed client. |
getPluginEndpoints | The raw HTTP endpoints plugins registered on a service, ready to mount on the application. |
hoistAnchoredSchemas | TypeBox expresses recursive schemas with bare $id/$ref anchors (\{ $id: "T0", ..., \{ $ref: "T0" \} \}). |
isBrickApp | Whether a value is an application made by brick(). |
isBrickServerError | Whether an error from the typed client is a BrickServerError: the server answered with a 5xx that is not one of the contract's declared errors, and the error… |
isBrickTransportError | Whether an error from the typed client is a BrickTransportError: the request got no meaningful answer from the server (a network failure, a body that was not… |
isDatabaseHandle | Whether a value is a database handle made by defineDatabase. |
isTool | Whether a value was made with defineTool, as opposed to defineAction. |
listSecrets | Metadata for introspection (values never exposed — future dashboard use). |
loadCompiledBrickApp | Build artifact bootstrap: bind generated handlers while evaluating the original app. |
overrideSecret | Test/session override for one secret (undefined clears the override). |
overrideSecrets | Bulk overrides (test/session scoped). |
referencePlugin | Standalone Elysia plugin serving GET <path> with the Scalar HTML page. |
registerReferenceRoute | Mounts the Scalar reference route onto an existing app. |
requestLoggingPlugin | Elysia plugin that logs each request as METHOD path → status (elapsedms). |
requireBrickApp | Check that a module's default export is an application ready to be served, for tools that load an entry file. |
resetGlobalRegistry | Start over with an empty global registry. |
resetSecrets | Clear registry and overrides. |
resolveEndpointDb | Resolve the db for an endpoint: explicit service first, else first service holding one. |
resolveSecrets | Validate every registered secret at boot. |
scalarDocsHTML | Renders the Scalar API reference page for the given OpenAPI URL. |
secret | Declare a secret. |
setActionAccess | Record how an action is protected, for tools that cannot read it from the configuration: plugins such as crud enforce access inside execute, so the action … |
swaggerDocsHTML | Renders the Swagger UI page. |
syncSchema | Explicit SQLite development/test schema preparation helper. |
toErrorResponse | Turn what an action threw into the JSON body of its HTTP response, and record the failure on the active trace. |
toOpenApiPath | /p/:slug → /p/\{slug\} for OpenAPI. |
traceRoute | Wrap a raw route handler so each of its requests gets a server span. |
validateWithSchema | Check a value against a schema, the way actions check their input and output. |
attachDatabase
function attachDatabase<TDb>(
service: Service<TDb, any>,
database: DatabaseHandle<TDb>,
): TDbAttach a defined database. Schema changes remain the caller's responsibility.
Parameters
| Name | Type | Description |
|---|---|---|
service | Service<TDb, any> | |
database | DatabaseHandle<TDb> |
Returns TDb
Source: packages/core/src/db/index.ts:93
bindCompiledApplication
function bindCompiledApplication(
ir: BrickIR,
services: Service<any, any>[],
factories: readonly HandlerFactory[],
): CompiledApplicationBuild artifact binder: consumes emitted functions, with no runtime handler code generation.
Parameters
| Name | Type | Description |
|---|---|---|
ir | BrickIR | |
services | Service<any, any>[] | |
factories | readonly HandlerFactory[] |
Returns CompiledApplication
Source: packages/core/src/compiler.ts:103
brick
function brick(options: CreateServerOptions = {}): BrickAppCreate the HTTP application: an Elysia app that serves every service's
actions (and the tools that opt in with http: true) as routes, with
/_health, an OpenAPI document at /openapi.json, Scalar at /docs,
Swagger UI at /swagger, and the shape of the services at /_brick/services.
Services come from the global registry unless services is given. The app
does not listen by itself: export it from your entry file, where brick dev,
brick start, and the Vite plugin load it, or call app.listen(port) in your
own server bootstrap.
Parameters
| Name | Type | Description |
|---|---|---|
options? | CreateServerOptions default {} | prefix for action routes (default /api), services, title, version, and description for the OpenAPI document, docs and the paths of its pages, requestLogging, reference, endpoints, secrets, telemetry, documentation, and dashboard. See CreateServerOptions. |
Returns BrickApp — The app, with definition (its services, prefix, and routes),
endpoint() to add raw routes, and listEndpoints() to list them.
Throws
- When a required secret is missing, or
documentationordashboardis invalid.
Example
import { brick } from "@brickkit/core";
import { pagesService } from "./services/pages";
export default brick({
services: [pagesService],
title: "Pages API",
telemetry: true,
});Source: packages/core/src/server.ts:115
buildErrorHelpers
function buildErrorHelpers<
TErrors extends Record<string, ActionErrorDefinition>,
>(
errorsDef?: TErrors,
): ErrorBuilder<TErrors>The error helpers an action receives: one function per error code that
throws an ActionExecutionError with that code and status. The standard HTTP
codes (BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT,
INTERNAL_SERVER_ERROR) are always there; the action's own errors add to
them or replace one.
Parameters
| Name | Type | Description |
|---|---|---|
errorsDef? | TErrors | The action's errors: for each code, its message and status (default 400). |
Returns ErrorBuilder<TErrors> — Helpers that take an optional message, details, and ErrorOptions,
and always throw.
Source: packages/core/src/action.ts:70
buildFtsMatchQuery
function buildFtsMatchQuery(search: string): string | nullBuilds an FTS5 MATCH condition for a resource search term. Returns null when the term has no usable tokens or FTS errors. Caller falls back to LIKE in that case.
Parameters
| Name | Type | Description |
|---|---|---|
search | string |
Returns string \| null
Source: packages/core/src/db/index.ts:342
compileBrickApplication
function compileBrickApplication(
options: { services: Service<any, any>[]; prefix?: string; mode?: "specialized" | "generic"; },
): CompiledApplicationStartup compiler: analyzes once, then binds live callbacks.
Parameters
| Name | Type | Description |
|---|---|---|
options | { services: Service<any, any>[]; prefix?: string; mode?: "specialized" | "generic"; } |
Returns CompiledApplication
Source: packages/core/src/compiler.ts:79
compileRoutePlan
function compileRoutePlan(
service: Service,
action: Action,
routePath: string,
method?: string,
): CompiledRoutePlanWork out, once at startup, everything an action's route needs to answer a
request: where its input comes from (body, query, or path), the validators,
the authorization and execute functions, and its logger. Low level: brick()
does this for every route.
Parameters
| Name | Type | Description |
|---|---|---|
service | Service | The service the action belongs to. |
action | Action | The action. |
routePath | string | The route's path. |
method? | string | The HTTP method (POST by default). |
Returns CompiledRoutePlan — The plan executeCompiledRoute runs.
Source: packages/core/src/action-handler.ts:38
createActionHandler
function createActionHandler(
service: Service,
action: Action,
routePath: string,
method?: string,
): (elysiaCtx: any) => Promise<any>An Elysia handler for one action: compileRoutePlan and
executeCompiledRoute together. Use it to mount an action on your own
Elysia app; brick() does it for you.
Parameters
| Name | Type | Description |
|---|---|---|
service | Service | The service the action belongs to. |
action | Action | The action. |
routePath | string | The route's path. |
method? | string | The HTTP method (POST by default). |
Returns (elysiaCtx: any) => Promise<any> — A function from the Elysia context to the response.
Source: packages/core/src/action-handler.ts:324
createBrickClient
function createBrickClient<TApp extends Record<string, any>>(
options: BrickClientOptions & { contract: TApp },
): BrickClient<TApp>
function createBrickClient<TApp extends Record<string, any>>(
options: BrickClientOptions,
): BrickClient<TApp>Create an Eden/tRPC-style typed client for the application contract TApp.
TApp is a type-only parameter: import type { AppServer } keeps backend
implementations out of the frontend bundle.
Parameters
| Name | Type | Description |
|---|---|---|
options | BrickClientOptions & { contract: TApp } |
Returns BrickClient<TApp>
Source: packages/core/src/client.ts:572
createDatabase
function createDatabase<
TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
config: DatabaseConfig<TSchema> = {},
): BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>Creates a database instance based on the provided configuration.
Zero-config: calling createDatabase() returns an ultra-fast Bun-native SQLite
database in :memory: mode wrapped with Drizzle ORM.
Parameters
| Name | Type | Description |
|---|---|---|
config? | DatabaseConfig<TSchema> default {} |
Returns BunSQLiteDatabase<TSchema> \| PostgresDatabase<TSchema>
Source: packages/core/src/db/index.ts:70
createEndpointHandler
function createEndpointHandler(
def: EndpointDefinition,
services: Service<any, any>[],
): (elysiaCtx: any) => Promise<unknown>Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping.
Parameters
| Name | Type | Description |
|---|---|---|
def | EndpointDefinition | |
services | Service<any, any>[] |
Returns (elysiaCtx: any) => Promise<unknown>
Source: packages/core/src/endpoints.ts:71
createMcpHandler
function createMcpHandler(
options: McpHandlerOptions,
): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication.
Parameters
| Name | Type | Description |
|---|---|---|
options | McpHandlerOptions |
Returns (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>
Source: packages/core/src/mcp.ts:89
createMcpRegistry
function createMcpRegistry(options: McpRegistryOptions): McpRegistryCollect only explicitly defined tools, without exposing ordinary actions.
Parameters
| Name | Type | Description |
|---|---|---|
options | McpRegistryOptions |
Returns McpRegistry
Source: packages/core/src/mcp.ts:33
createPostgresDatabase
function createPostgresDatabase<
TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
config: PostgresDatabaseConfig<TSchema> = {},
): PostgresDatabase<TSchema>Creates a PostgreSQL Drizzle instance using postgres-js.
Static imports (both are hard dependencies in package.json) so bundlers
(Nitro/Rollup) trace and ship the driver. bun:sqlite stays lazy in
sqlite.ts since it only exists under Bun.
Parameters
| Name | Type | Description |
|---|---|---|
config? | PostgresDatabaseConfig<TSchema> default {} |
Returns PostgresDatabase<TSchema>
Source: packages/core/src/db/postgres.ts:46
createServiceProxy
function createServiceProxy<T extends Record<string, any>>(
serviceName: string,
options: ProxyOptions = {},
): TA typed way to call another service's actions in-process. Each property of the proxy is an action of that service: call it with the action's input, and optionally a call context.
The call runs through the target's own validation and authorization, with the
target's database and context (never the caller's), and shows as an rpc
span in the trace. Only in-process dispatch exists: with isMonolith: false
a call throws. Use the typed client to call a service over HTTP.
Parameters
| Name | Type | Description |
|---|---|---|
serviceName | string | The registered name of the service to call. |
options? | ProxyOptions default {} | from (the calling service's name, which becomes ctx.caller in the target and cannot be spoofed), context (defaults for every call), and isMonolith. |
Returns T — A proxy typed as T, usually the target's actions.
Throws
- On a call, when the service or the action is not registered.
Example
import { createServiceProxy } from "@brickkit/core";
const pages = createServiceProxy<{ get(input: { id: string }): Promise<Page> }>(
"pages",
{ from: "billing" },
);
const page = await pages.get({ id: "p_1" });Source: packages/core/src/rpc.ts:31
createSQLiteDatabase
function createSQLiteDatabase<
TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
config: SQLiteDatabaseConfig<TSchema> = {},
): BunSQLiteDatabase<TSchema>Creates a zero-config SQLite database using Bun's native bun:sqlite engine
and Drizzle ORM. Defaults to an ultra-fast in-memory database (:memory:).
Bun-only: the driver is loaded lazily so importing @brickkit/core on
other runtimes (e.g. Node) stays safe until this function is actually
called.
Parameters
| Name | Type | Description |
|---|---|---|
config? | SQLiteDatabaseConfig<TSchema> default {} |
Returns BunSQLiteDatabase<TSchema>
Source: packages/core/src/db/sqlite.ts:53
defineAction
function defineAction<
TInputSchema extends TSchema | undefined = undefined,
TOutputSchema extends TSchema | undefined = undefined,
TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
TContext extends ActionContext = ActionContext,
>(
config: ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Action<TInputSchema, TOutputSchema, TErrors, TContext>
function defineAction<
TInputSchema extends TSchema | undefined = undefined,
TOutputSchema extends TSchema | undefined = undefined,
TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
TContext extends ActionContext = ActionContext,
>(
config: ActionConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Action<TInputSchema, TOutputSchema, TErrors, TContext>Define an action: a typed, validated function that Brick serves over HTTP, runs in-process, and exposes to the typed client and OpenAPI.
A call runs in order: the input is validated against input (an invalid one
is a VALIDATION_FAILED error, HTTP 400); authorize runs, if there is one;
execute runs; and its result is validated against output (a mismatch is a
server error, HTTP 500). Throw error.CODE(...) from execute for a declared
failure or a standard one such as error.NOT_FOUND(). Any other thrown value
becomes INTERNAL_SERVER_ERROR (500), with the cause kept out of the response
and in the log.
authorize returns false to refuse: the call fails with UNAUTHORIZED
(401) when there is no ctx.user, and FORBIDDEN (403) when there is one.
Where it is given, execute can rely on what it checked.
Parameters
| Name | Type | Description |
|---|---|---|
config | ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext> | name, execute, and optionally description, input and output (TypeBox schemas), errors, authorize, method and path to change the route (POST by default), tags, and emits. |
Returns Action<TInputSchema, TOutputSchema, TErrors, TContext> — The action. Register it with service.action(action); call it
directly with action.run(input, ctx).
Example
import { defineAction, t } from "@brickkit/core";
export const getPage = defineAction({
name: "get",
method: "GET",
input: t.Object({ id: t.String() }),
output: t.Object({ id: t.String(), title: t.String() }),
errors: { PAGE_GONE: { message: "That page was removed", status: 410 } },
authorize: ({ user }) => user != null,
execute: async ({ input, ctx, error }) => {
const page = await findPage(ctx.db, input.id);
if (!page) throw error.NOT_FOUND("No such page");
return page;
},
});Source: packages/core/src/action.ts:144
defineDatabase
function defineDatabase<
TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
options?: SQLiteDefinition<TSchema>,
): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>
function defineDatabase<
TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
options: PostgresDefinition<TSchema>,
): DatabaseHandle<PostgresJsDatabase<TSchema> & { $client: Sql }, TSchema>Declare a service's database: its engine, its Drizzle tables, and how to
reach it. Nothing connects until the handle is used (getDb()), so defining
one has no side effects.
SQLite is the default and needs no options. Pass engine: "postgres" with a
url for Postgres. Options that belong to the other engine (such as url for
SQLite, or path for Postgres) are refused.
Parameters
| Name | Type | Description |
|---|---|---|
options? | SQLiteDefinition<TSchema> | engine ("sqlite" or "postgres"), tables, an optional name, and the engine's connection settings. |
Returns DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema> — A handle to give to defineService({ database }). getDb() returns
the Drizzle database.
Throws
- When the engine is unsupported, or an option does not suit the engine.
Example
import { defineDatabase } from "@brickkit/core";
import { sqliteTable, text } from "drizzle-orm/sqlite-core";
const pages = sqliteTable("pages", {
id: text("id").primaryKey(),
title: text("title").notNull(),
});
export const database = defineDatabase({ tables: { pages } });Source: packages/core/src/db/define.ts:109
defineResource
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>>Declares a plugin host without registering actions or changing the schema.
Parameters
| Name | Type | Description |
|---|---|---|
service | Service<any, any> | |
config | ResourceConfig<TTable, TCtx> & O |
Returns Resource<TTable, TCtx, ResourceIdentity<TTable, O>>
Source: packages/core/src/resource.ts:13
defineResourcePlugin
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 pluginKind> & { setup: (context: ResourcePluginContext<S, R>,) => A & (A extends PromiseLike<unknown> ? never …,
): ResourcePlugin<S, R, A>Define a plugin that installs onto a resource (a table and its entity) with
resource.use(plugin). Its setup receives the service, the resource, and a
routes registrar, whose routes are scoped under the resource's name, and
returns the typed API that resource.use hands back. crud is built this way.
Parameters
| Name | Type | Description |
|---|---|---|
definition | Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & { setup: (context: ResourcePluginContext<S, R>,) => A & (A extends PromiseLike<unknown> ? never : unknown); } | A unique name, optional routes controls, and setup, which must be synchronous. |
Returns ResourcePlugin<S, R, A> — The plugin descriptor, frozen.
Throws
- When the name is empty or has surrounding whitespace.
Source: packages/core/src/plugin.ts:191
defineService
function defineService<
TDb = BunSQLiteDatabase<Record<string, unknown>>,
TServiceContext extends Record<string, any> = Record<string, any>,
>(
name: string,
options?: ServiceOptions<TServiceContext, TDb>,
): Service<TDb, TServiceContext>Declare a service: a named group of actions, tools, and resources with its own
database and request context. It is registered globally, so brick(), the
OpenAPI generator, and createServiceProxy find it by name.
Add actions with service.action(...), tools with service.tool(...),
resources with service.resource(...), and plugins with service.use(...).
Parameters
| Name | Type | Description |
|---|---|---|
name | string | Unique name. It is the service's segment of every action route (/api/<name>/<action>) and appears in OpenAPI and the dashboard. Defining a second service with the same name replaces the first and logs a warning. |
options? | ServiceOptions<TServiceContext, TDb> | database (a handle from defineDatabase), context (adds fields such as the signed-in user to every action's ctx), and auth, rateLimit, cache, resilience, telemetry, and lifecycle. |
Returns Service<TDb, TServiceContext> — The service.
Example
import { defineDatabase, defineService, t } from "@brickkit/core";
const database = defineDatabase({ tables: { pages } });
export const pagesService = defineService("pages", {
database,
// Added to `ctx` in every action of this service.
context: async ({ request }) => ({ user: await readUser(request) }),
});
pagesService.action({
name: "list",
input: t.Object({ limit: t.Optional(t.Number()) }),
output: t.Array(t.Object({ id: t.String(), title: t.String() })),
execute: ({ input, ctx }) =>
ctx.db.select().from(pages).limit(input.limit ?? 20),
});Source: packages/core/src/service.ts:450
defineServicePlugin
function defineServicePlugin<
S extends Service<any, any> = Service<any, any>,
A = unknown,
>(
definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & { setup: (context: ServicePluginContext<S>,) => A & (A extends PromiseLike<unknown> ? never : unknow…,
): ServicePlugin<S, A>Define a plugin that installs onto a service with service.use(plugin). Its
setup receives the service and a routes registrar for adding actions and
raw HTTP endpoints, and returns the typed API that service.use hands back.
Parameters
| Name | Type | Description |
|---|---|---|
definition | Omit<ServicePlugin<S, A>, typeof pluginKind> & { setup: (context: ServicePluginContext<S>,) => A & (A extends PromiseLike<unknown> ? never : unknown); } | A unique name, optional routes controls that let the user move or switch off the plugin's routes, and setup, which must be synchronous. |
Returns ServicePlugin<S, A> — The plugin descriptor, frozen.
Throws
- When the name is empty or has surrounding whitespace.
Example
import { defineServicePlugin, t } from "@brickkit/core";
export const greeting = (salutation = "Hello") =>
defineServicePlugin({
name: "example/greeting",
setup({ routes }) {
const hello = routes.action({
name: "hello",
input: t.Object({ name: t.String() }),
output: t.String(),
execute: ({ input }) => `${salutation}, ${input.name}!`,
});
return { hello };
},
});
const api = greeterService.use(greeting("Welcome"));
await api.hello({ input: { name: "Ada" } });Source: packages/core/src/plugin.ts:163
defineTool
function defineTool<
TInputSchema extends TSchema | undefined = undefined,
TOutputSchema extends TSchema | undefined = undefined,
TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
TContext extends ActionContext = ActionContext,
>(
config: ToolConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Tool<TInputSchema, TOutputSchema, TErrors, TContext>
function defineTool<
TInputSchema extends TSchema | undefined = undefined,
TOutputSchema extends TSchema | undefined = undefined,
TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
TContext extends ActionContext = ActionContext,
>(
config: ToolConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Tool<TInputSchema, TOutputSchema, TErrors, TContext>Define a tool: an action that AI agents can call through MCP. It takes the
same configuration as defineAction (validation, authorize, errors), plus
title, annotations (the MCP hints about what the tool does), and http
to also serve it over HTTP and in OpenAPI (off by default).
Parameters
| Name | Type | Description |
|---|---|---|
config | ToolConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext> | An action configuration and tool options. input must be an object schema, since MCP passes arguments by name. |
Returns Tool<TInputSchema, TOutputSchema, TErrors, TContext> — The tool, which is also an action. Register it with service.tool(tool).
Throws
- When
inputis not an object schema.
Example
import { defineTool, t } from "@brickkit/core";
export const echoTool = defineTool({
name: "echo",
title: "Echo a message",
description: "Returns the message it is given.",
input: t.Object({ message: t.String() }),
output: t.String(),
execute: ({ input }) => `Echo: ${input.message}`,
});Source: packages/core/src/tool.ts:33
emitHandlerFactory
function emitHandlerFactory(route: RouteIR): stringEmits framework code only. User callbacks remain closures bound separately.
Parameters
| Name | Type | Description |
|---|---|---|
route | RouteIR |
Returns string
Source: packages/core/src/compiler/emit.ts:4
endpointPaths
function endpointPaths(defs: EndpointDefinition[]): Record<string, any>OpenAPI paths fragment for declared endpoints (raw HTML included).
Parameters
| Name | Type | Description |
|---|---|---|
defs | EndpointDefinition[] |
Returns Record<string, any>
Source: packages/core/src/endpoints.ts:152
ensureResourceIndexes
function ensureResourceIndexes(
db: any,
table: any,
opts: { ownerField?: string; sortFields?: string[]; searchFields?: string[]; } = {},
): voidEnsures secondary indexes exist for a resource table. SQLite: B-tree indexes for owner scope + sort + composite hot path. Postgres: same B-trees plus pg_trgm GIN indexes for substring search. Best-effort: failures warn and continue (e.g. read-only replicas).
Parameters
| Name | Type | Description |
|---|---|---|
db | any | |
table | any | |
opts? | { ownerField?: string; sortFields?: string[]; searchFields?: string[]; } default {} |
Source: packages/core/src/db/index.ts:204
ensureSQLiteFts
function ensureSQLiteFts(db: any, table: any, searchCols: string[]): voidCreates the FTS5 sidecar table + sync triggers + backfills existing rows. Idempotent; safe to call on every resource registration. No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.
Parameters
| Name | Type | Description |
|---|---|---|
db | any | |
table | any | |
searchCols | string[] |
Source: packages/core/src/db/index.ts:278
executeCompiledRoute
function executeCompiledRoute(
plan: CompiledRoutePlan,
elysiaCtx: any,
): Promise<any>Answer one request for a compiled route: read the input, run the action, and
return its output or the error response, with the x-trace-id and
x-request-id headers set. Low level: brick() mounts this for every route.
Parameters
| Name | Type | Description |
|---|---|---|
plan | CompiledRoutePlan | From compileRoutePlan. |
elysiaCtx | any | The Elysia request context: params, body, query, headers, request, and set. |
Returns Promise<any> — The action's output, or an error envelope with the status set on set.
Source: packages/core/src/action-handler.ts:149
generateOpenApiSpec
function generateOpenApiSpec(
options: OpenApiGeneratorOptions = {},
): Record<string, any>Build the OpenAPI 3.1 document for the services: one path per action route, with request and response schemas from the actions' TypeBox schemas, their declared errors, tags by service, and a bearer security scheme where any action needs authorization.
brick() calls this for /openapi.json; call it yourself to write the
document to a file or feed another tool.
Parameters
| Name | Type | Description |
|---|---|---|
options? | OpenApiGeneratorOptions default {} | title, version, and description for the info block, prefix (default /api), and the services or registry to describe (the global registry by default). |
Returns Record<string, any> — The document as a plain object.
Source: packages/core/src/openapi.ts:114
generateSQLiteIndexDdl
function generateSQLiteIndexDdl(
table: any,
opts: { ownerField?: string; sortFields?: string[] } = {},
): string[]Generates idempotent secondary index DDL for a Drizzle table. Covers owner scoping, sort columns, and exact-match filters. UNIQUE columns already carry an implicit index — skipped here. FTS/trigram indexes are handled separately by the search layer.
Parameters
| Name | Type | Description |
|---|---|---|
table | any | |
opts? | { ownerField?: string; sortFields?: string[] } default {} |
Returns string[]
Source: packages/core/src/db/index.ts:138
generateSQLiteTableDdl
function generateSQLiteTableDdl(table: any): stringGenerates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition directly from a Drizzle table schema.
Parameters
| Name | Type | Description |
|---|---|---|
table | any |
Returns string
Source: packages/core/src/db/index.ts:105
getActionAccess
function getActionAccess(action: Action | object): ActionAccessInfoHow an action is protected: "public" when nothing checks the caller,
"authorized" when an authorize does, and "scoped" when the action also
limits what rows the caller can reach. It reads what a plugin recorded with
setActionAccess, else the action's own authorize, and keeps the policy
consistent with the flags.
Parameters
| Name | Type | Description |
|---|---|---|
action | Action | object | An action, or any object a plugin described. |
Returns ActionAccessInfo — hasAuthorize, hasScope, and policy.
Source: packages/core/src/access.ts:48
getCompiledCheck
function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T>The compiled validator for a TypeBox schema. Compiling is slow and checking is fast, so each schema is compiled once and kept for as long as the schema object lives.
Parameters
| Name | Type | Description |
|---|---|---|
schema | T | A TypeBox schema. |
Returns TypeCheck<T> — Its TypeCheck, with Check(value) and Errors(value).
Source: packages/core/src/typebox.ts:18
getGlobalRegistry
function getGlobalRegistry(): ServiceRegistryThe registry every defineService adds to: it is how brick(), the OpenAPI
generator, createServiceProxy, and the dashboard find services by name.
Returns ServiceRegistry — The current global registry.
Source: packages/core/src/registry.ts:98
getPluginActionRoute
function getPluginActionRoute(
action: Action<any, any, any, any>,
prefix = "/api",
): false | { path: string; method: PluginRouteMethod; clientPath: string[] | undefined; plugin: string; resource: string | undefined; } | undefinedWhere a plugin mounted an action over HTTP, for the OpenAPI generator, the compiler, and the typed client.
Parameters
| Name | Type | Description |
|---|---|---|
action | Action<any, any, any, any> | An action. |
prefix? | string default "/api" | The application's route prefix (default /api). |
Returns false \| { path: string; method: PluginRouteMethod; clientPath: string[] \| undefined; plugin: string; resource: string \| undefined; } \| undefined — undefined when no plugin bound the action (it uses its own route),
false when the plugin's route was switched off, otherwise the route's
path and method, the clientPath the typed client uses, and the owning
plugin and resource.
Source: packages/core/src/plugin.ts:323
getPluginEndpoints
function getPluginEndpoints(
service: Service<any, any>,
prefix = "/api",
): { path: string; method: PluginRouteMethod; service: Service<any, any>; summary: string | undefined; description: string | undefined; tags: string[] | undefined…The raw HTTP endpoints plugins registered on a service, ready to mount on the application. Each handler resolves the service's context before it runs.
Parameters
| Name | Type | Description |
|---|---|---|
service | Service<any, any> | The service plugins were installed on. |
prefix? | string default "/api" | The application's route prefix (default /api). |
Returns { path: string; method: PluginRouteMethod; service: Service<any, any>; summary: string \| undefined; description: string \| undefined; tags: string[] \| undefined; handler: (context: Omit<PluginEndpointContext, "ctx">) => … — The enabled endpoints: path, method, handler, and the
summary, description, and tags for OpenAPI.
Source: packages/core/src/plugin.ts:350
hoistAnchoredSchemas
function hoistAnchoredSchemas(spec: Record<string, any>): string[]TypeBox expresses recursive schemas with bare $id/$ref anchors
({ $id: "T0", ..., { $ref: "T0" } }). OpenAPI interprets a bare $ref
as an external file reference, so downstream tooling tries to load a
file named T0 and fails. Hoist every anchored subschema into
#/components/schemas/ and rewrite the refs to local pointers.
First definition wins when one $id is declared twice.
Parameters
| Name | Type | Description |
|---|---|---|
spec | Record<string, any> |
Returns string[]
Source: packages/core/src/openapi.ts:47
isBrickApp
function isBrickApp(app: unknown): app is BrickAppWhether a value is an application made by brick(). It checks for the
methods and definition a BrickApp has, so it also recognizes one built by
another copy of the package.
Parameters
| Name | Type | Description |
|---|---|---|
app | unknown | Anything, such as the default export of an entry file. |
Returns app is BrickApp — true for a BrickApp, narrowing its type.
Source: packages/core/src/app-entry.ts:11
isBrickServerError
function isBrickServerError(err: unknown): err is BrickServerErrorWhether an error from the typed client is a BrickServerError: the server
answered with a 5xx that is not one of the contract's declared errors, and the
error carries its status, url, and body.
Parameters
| Name | Type | Description |
|---|---|---|
err | unknown | What a client call threw. |
Returns err is BrickServerError — true for a server error, narrowing its type.
Source: packages/core/src/client.ts:187
isBrickTransportError
function isBrickTransportError(err: unknown): err is BrickTransportErrorWhether an error from the typed client is a BrickTransportError: the request
got no meaningful answer from the server (a network failure, a body that was
not JSON, or a 4xx outside the declared contract).
Parameters
| Name | Type | Description |
|---|---|---|
err | unknown | What a client call threw. |
Returns err is BrickTransportError — true for a transport error, narrowing its type.
Source: packages/core/src/client.ts:173
isDatabaseHandle
function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>Whether a value is a database handle made by defineDatabase.
Parameters
| Name | Type | Description |
|---|---|---|
value | unknown | Anything. |
Returns value is DatabaseHandle<unknown> — true for a handle, narrowing its type.
Source: packages/core/src/db/define.ts:73
isTool
function isTool(value: unknown): value is Tool<any, any, any, any>Whether a value was made with defineTool, as opposed to defineAction.
Parameters
| Name | Type | Description |
|---|---|---|
value | unknown | Anything. |
Returns value is Tool<any, any, any, any> — true for a tool, narrowing its type.
Source: packages/core/src/tool.ts:82
listSecrets
function listSecrets(
opts: { source?: SecretSource } = {},
): Array<{ name: string; hasDefault: boolean; isSet: boolean }>Metadata for introspection (values never exposed — future dashboard use).
Parameters
| Name | Type | Description |
|---|---|---|
opts? | { source?: SecretSource } default {} |
Returns Array<{ name: string; hasDefault: boolean; isSet: boolean }>
Source: packages/core/src/secrets.ts:196
loadCompiledBrickApp
function loadCompiledBrickApp(
load: () => Promise<{ default: unknown }>,
ir: BrickIR,
bind: ApplicationBinder,
): Promise<BrickApp>Build artifact bootstrap: bind generated handlers while evaluating the original app.
Parameters
| Name | Type | Description |
|---|---|---|
load | () => Promise<{ default: unknown }> | |
ir | BrickIR | |
bind | ApplicationBinder |
Returns Promise<BrickApp>
Source: packages/core/src/compiler.ts:28
overrideSecret
function overrideSecret(name: string, value: string | undefined): voidTest/session override for one secret (undefined clears the override).
Parameters
| Name | Type | Description |
|---|---|---|
name | string | |
value | string | undefined |
Source: packages/core/src/secrets.ts:208
overrideSecrets
function overrideSecrets(values: Record<string, string | undefined>): voidBulk overrides (test/session scoped).
Parameters
| Name | Type | Description |
|---|---|---|
values | Record<string, string | undefined> |
Source: packages/core/src/secrets.ts:213
referencePlugin
function referencePlugin(opts: ReferenceOptions = {}): ElysiaStandalone Elysia plugin serving GET <path> with the Scalar HTML page.
Parameters
| Name | Type | Description |
|---|---|---|
opts? | ReferenceOptions default {} |
Returns Elysia
Source: packages/core/src/docs.ts:72
registerReferenceRoute
function registerReferenceRoute(
app: Elysia,
opts: ReferenceOptions = {},
): ElysiaMounts the Scalar reference route onto an existing app.
Parameters
| Name | Type | Description |
|---|---|---|
app | Elysia | |
opts? | ReferenceOptions default {} |
Returns Elysia
Source: packages/core/src/docs.ts:85
requestLoggingPlugin
function requestLoggingPlugin(opts: RequestLoggingOptions = {}): ElysiaElysia plugin that logs each request as METHOD path → status (elapsedms).
Timing is tracked per-Request via a WeakMap. The onError hook only logs and
returns undefined so existing error mapping is preserved. Logging only —
no CORS headers are set here.
Hooks are registered with the "global" scope so they propagate to the
parent app when mounted via app.use(...) — Elysia scopes plain instance
hooks to the plugin's own routes. Timing is captured in beforeHandle
because request hooks are not propagated from a
used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
Parameters
| Name | Type | Description |
|---|---|---|
opts? | RequestLoggingOptions default {} |
Returns Elysia
Source: packages/core/src/request-logger.ts:41
requireBrickApp
function requireBrickApp(app: unknown): BrickAppCheck that a module's default export is an application ready to be served, for tools that load an entry file.
Parameters
| Name | Type | Description |
|---|---|---|
app | unknown | The default export of an entry file. |
Returns BrickApp — The app.
Throws
- When it is not a
BrickApp, or it already called.listen(): the entry must only build the app, and leave listening to the server bootstrap.
Source: packages/core/src/app-entry.ts:39
resetGlobalRegistry
function resetGlobalRegistry(): voidStart over with an empty global registry. For tests, which define the same services again in each case; an application never needs it.
Source: packages/core/src/registry.ts:106
resetSecrets
function resetSecrets(): voidClear registry and overrides. Test-only.
Source: packages/core/src/secrets.ts:222
resolveEndpointDb
function resolveEndpointDb(
service: Service<any, any> | string | undefined,
services: Service<any, any>[],
): anyResolve the db for an endpoint: explicit service first, else first service holding one.
Parameters
Returns any
Source: packages/core/src/endpoints.ts:52
resolveSecrets
function resolveSecrets(
opts: { source?: SecretSource } = {},
): Record<string, unknown>Validate every registered secret at boot. Throws a single error listing all missing required secrets. Returns the resolved values.
Parameters
| Name | Type | Description |
|---|---|---|
opts? | { source?: SecretSource } default {} |
Returns Record<string, unknown>
Source: packages/core/src/secrets.ts:176
scalarDocsHTML
function scalarDocsHTML(specUrl: string, title: string): stringRenders the Scalar API reference page for the given OpenAPI URL.
Parameters
| Name | Type | Description |
|---|---|---|
specUrl | string | |
title | string |
Returns string
Source: packages/core/src/docs.ts:48
secret
function secret(name: string, options: SecretOptions = {}): SecretRef<string>Declare a secret. Idempotent: re-declaring the same name returns the original ref (first declaration wins) so module re-evaluation is safe.
Parameters
| Name | Type | Description |
|---|---|---|
name | string | |
options? | SecretOptions default {} |
Returns SecretRef<string>
Source: packages/core/src/secrets.ts:161
setActionAccess
function setActionAccess(action: object, info: ActionAccessInfo): voidRecord how an action is protected, for tools that cannot read it from the
configuration: plugins such as crud enforce access inside execute, so the
action has no authorize to find. Introspection, OpenAPI, and the dashboard
read what is recorded here.
Parameters
| Name | Type | Description |
|---|---|---|
action | object | The action to describe. |
info | ActionAccessInfo | Whether it checks authorization and whether it scopes queries, and the resulting policy. |
Source: packages/core/src/access.ts:30
swaggerDocsHTML
function swaggerDocsHTML(specUrl: string, title: string): stringRenders the Swagger UI page.
Parameters
| Name | Type | Description |
|---|---|---|
specUrl | string | |
title | string |
Returns string
Source: packages/core/src/docs.ts:93
syncSchema
function syncSchema(
tablesOrService: Map<string, any> | any[] | Record<string, any> | Service,
dbInstance?: any,
): Promise<void> | voidExplicit SQLite development/test schema preparation helper. Never called by services, resources, auth, or server startup. Not a migration runner; PostgreSQL schema management is caller-owned.
Parameters
| Name | Type | Description |
|---|---|---|
tablesOrService | Map<string, any> | any[] | Record<string, any> | Service | |
dbInstance? | any |
Returns Promise<void> \| void
Source: packages/core/src/db/index.ts:365
toErrorResponse
function toErrorResponse(err: unknown, context: ErrorContext): ErrorEnvelopeTurn what an action threw into the JSON body of its HTTP response, and record
the failure on the active trace. Declared failures and validation errors keep
their code, status, and details; anything else is logged and answered as a
generic INTERNAL_SERVER_ERROR (500) so internals are never exposed.
Parameters
| Name | Type | Description |
|---|---|---|
err | unknown | Whatever was thrown. |
context | ErrorContext | A logger with error(), and the requestId to put in the body. |
Returns ErrorEnvelope — The envelope: name, code, message, status, requestId, and
details or errors when there are any.
Source: packages/core/src/error-response.ts:46
toOpenApiPath
function toOpenApiPath(elysiaPath: string): string/p/:slug → /p/{slug} for OpenAPI.
Parameters
| Name | Type | Description |
|---|---|---|
elysiaPath | string |
Returns string
Source: packages/core/src/endpoints.ts:142
traceRoute
function traceRoute<T>(
route: string,
handler: (context: RawRouteContext) => T,
): (context: RawRouteContext) => TWrap a raw route handler so each of its requests gets a server span. Use it
for routes registered directly on the app, outside actions and endpoints,
such as auth or webhook routes. Spans are recorded whenever a tracer provider
is registered; brick({ telemetry }) does not apply to these routes.
The wrapper forwards only the fields listed in RawRouteContext. Elysia
decides what to parse from the handler's destructuring, and forwarding the
whole context would parse the body and leave request.json() with nothing.
Parameters
| Name | Type | Description |
|---|---|---|
route | string | |
handler | (context: RawRouteContext) => T |
Returns (context: RawRouteContext) => T
Source: packages/core/src/telemetry.ts:75
validateWithSchema
function validateWithSchema<T extends TSchema>(
schema: T | undefined,
value: unknown,
): | { success: true; data: Static<T> } | { success: false; errors: ValidationErrorItem[] }Check a value against a schema, the way actions check their input and output.
Parameters
| Name | Type | Description |
|---|---|---|
schema | T | undefined | A TypeBox schema, or undefined to accept anything. |
value | unknown | The value to check. |
Returns \| { success: true; data: Static<T> } \| { success: false; errors: ValidationErrorItem[] } — { success: true, data }, or { success: false, errors } with a
path, message, type, and the offending value for each problem.
Source: packages/core/src/typebox.ts:35
Classes
ActionExecutionError
class ActionExecutionError extends ErrorConstructor
| Name | Type | Description |
|---|---|---|
constructor | new ( code: string, message: string, status = 400, details?: unknown, options?: ErrorOptions, ) |
Properties
| Name | Type | Description |
|---|---|---|
readonly code | string | |
readonly status | number | |
readonly details? | unknown |
Methods
| Name | Type | Description |
|---|---|---|
toJSON | toJSON(): { name: string; code: string; message: string; status: number; details: unknown; } |
Source: packages/core/src/types.ts:101
BrickServerError
class BrickServerError extends ErrorThe server answered 5xx without a declared code / ValidationError shape,
i.e. an unexpected failure rather than a modelled domain error.
Constructor
| Name | Type | Description |
|---|---|---|
constructor | new (message: string, opts: { status: number; url: string; body: unknown }) |
Properties
| Name | Type | Description |
|---|---|---|
readonly kind | "server" | |
readonly status | number | |
readonly url | string | |
readonly body | unknown |
Source: packages/core/src/client.ts:147
BrickTransportError
class BrickTransportError extends ErrorThe request never received a meaningful server answer: DNS / connection
failure, a malformed body, or a 4xx response outside the declared contract
(no code and no ValidationError shape).
Constructor
| Name | Type | Description |
|---|---|---|
constructor | new ( message: string, opts: { status?: number; url: string; body?: unknown; cause?: unknown }, ) |
Properties
| Name | Type | Description |
|---|---|---|
readonly kind | "transport" | |
readonly status? | number | |
readonly url | string | |
readonly body? | unknown | |
readonly cause? | unknown |
Source: packages/core/src/client.ts:123
SecretRef
class SecretRef<T = string>Constructor
| Name | Type | Description |
|---|---|---|
constructor | new (name: string, options: SecretOptions = {}) |
Properties
| Name | Type | Description |
|---|---|---|
readonly name | string | |
readonly options | SecretOptions | |
hasDefault | boolean | True when a default was declared (i.e. the secret is optional). |
Methods
| Name | Type | Description |
|---|---|---|
default | default(value: string): this | Fallback used when the source has no value. Makes the secret optional. |
transform | transform<U>(fn: (raw: string) => U): SecretRef<U> | Convert the raw string (e.g. Number, JSON.parse, v === "true"). Runs before validators; a throwing transform fails resolution. |
validate | validate(fn: SecretValidator<T>): this | Run a custom check on the (transformed) value at every resolution. |
url | url(this: SecretRef<string>): SecretRef<string> | Shorthand validator: value must parse as a URL. String refs only. |
value | value(source: SecretSource = envSource): T | undefined | Resolved (transformed, validated) value or undefined. Never throws on missing. |
require | require(source: SecretSource = envSource): T | Resolved value, or throws naming the missing/invalid secret. |
isSet | isSet(source: SecretSource = envSource): boolean | True when a value would resolve (override, source, or default). |
Source: packages/core/src/secrets.ts:42
ServiceImpl
class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> implements Service<TDb, TServiceContext>Constructor
| Name | Type | Description |
|---|---|---|
constructor | new (name: string, options: ServiceOptions<TServiceContext, TDb> = {}) |
Properties
| Name | Type | Description |
|---|---|---|
readonly name | string | |
readonly options | ServiceOptions<TServiceContext, TDb> | |
readonly actions | Map<string, Action<any, any, any, any>> | |
readonly tools | Map<string, Tool<any, any, any, any>> | |
readonly tables | Map<string, any> | |
readonly resources | Map<string, Resource<any, BaseContext<TDb> & TServiceContext, {}>> | |
readonly preparations | Map<string, PreparationContribution> | |
db | TDb | undefined | |
isBuilt | boolean | |
resource | <TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions & Record<Exclude<keyof TOptions, keyof ResourceConfig>, neve… |
Methods
| Name | Type | Description |
|---|---|---|
use | use<A>(plugin: ServicePlugin<this, A>): A | |
build | build(): this | Closes declarations after plugins have registered their actions and preparations. |
contributePreparation | contributePreparation(contribution: PreparationContribution): void | |
listPreparations | listPreparations(): PreparationContribution[] | |
prepareContributions | prepareContributions(): void | |
registerTable | registerTable(table: any): this | |
getResource | getResource( name: string, ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined | |
listResources | listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[] | |
action | action(actionOrConfig: any): any | |
tool | tool(toolOrConfig: any): any | |
getTool | getTool(name: string): Tool<any, any, any, any> | undefined | |
listTools | listTools(): Tool<any, any, any, any>[] | |
getAction | getAction(name: string): Action<any, any, any, any> | undefined | |
listActions | listActions(): Action<any, any, any, any>[] | |
getDb | getDb(): TDb | undefined | |
setDb | setDb(database: DatabaseHandle<TDb>): void | |
resolveContext | resolveContext( callCtx?: Partial<BaseContext<TDb> & TServiceContext>, ): Promise<BaseContext<TDb> & TServiceContext> | Resolves the complete service execution context once per incoming request. Merges framework BaseContext with the service's custom context hook. Always rebuilds context for this service to prevent caller context from overriding. |
introspect | introspect(): ServiceSchema |
Source: packages/core/src/service.ts:46
ServiceRegistry
class ServiceRegistryProperties
| Name | Type | Description |
|---|---|---|
revision | number | Definition revision for invalidating serialized architecture snapshots. |
Methods
| Name | Type | Description |
|---|---|---|
touch | touch(): void | |
setApplicationRoutes | setApplicationRoutes(application: ArchitectureApplication): void | Remember the actual registered routes for subsequent registry exports. |
register | register(service: Service): void | |
get | get(name: string): Service | undefined | |
has | has(name: string): boolean | |
list | list(): Service[] | |
clear | clear(): void | |
exportArchitecture | exportArchitecture(application?: ArchitectureApplication): ArchitectureSchema |
Source: packages/core/src/registry.ts:9
UnknownToolError
class UnknownToolError extends ErrorConstructor
| Name | Type | Description |
|---|---|---|
constructor | new (name: string) |
Source: packages/core/src/mcp.ts:25
ValidationError
class ValidationError extends ErrorConstructor
| Name | Type | Description |
|---|---|---|
constructor | new (message: string, errors: ValidationErrorItem[] = [], status = 400) |
Properties
| Name | Type | Description |
|---|---|---|
readonly code | "VALIDATION_FAILED" | |
readonly status | number | |
readonly errors | ValidationErrorItem[] |
Methods
| Name | Type | Description |
|---|---|---|
toJSON | toJSON(): { name: string; code: string; message: string; status: number; errors: ValidationErrorItem[]; } |
Source: packages/core/src/types.ts:74
Interfaces
Action
interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>Properties
| Name | Type | Description |
|---|---|---|
(call) | (params: { input?: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx?: Partial<TContext>; }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | |
name | string | |
serviceName? | string | |
plugin? | string | Owning plugin descriptor name for plugin actions (e.g. @brickkit/crud). |
resource? | string | Owning resource name for resource-plugin actions (e.g. page). |
config | ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext> | |
outputValidationSchema? | TSchema | Optional runtime-only output schema. When present, validateOutput and HTTP output checking validate against it instead of config.output, while config.output remains the published contract (client types, OpenAPI). Lets projected/subset responses validate at runtime without leaking optionality into the generated contract. |
errorHelpers? | ErrorBuilder<TErrors> |
Methods
| Name | Type | Description |
|---|---|---|
run | run( input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>, ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | |
execute | execute( params: { input?: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx?: Partial<TContext>; }, ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | |
executeResolved? | executeResolved( params: { input?: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: TContext; }, ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | |
validateInput | validateInput( input: unknown, ): | { success: true; data: any } | { success: false; errors: ValidationErrorItem[] } | |
validateOutput | validateOutput( output: unknown, ): | { success: true; data: any } | { success: false; errors: ValidationErrorItem[] } |
Source: packages/core/src/types.ts:261
ActionAccessInfo
interface ActionAccessInfoProperties
| Name | Type | Description |
|---|---|---|
hasAuthorize | boolean | |
hasScope | boolean | |
policy | ActionAccessPolicy |
Source: packages/core/src/access.ts:4
ActionConfigWithAuthorize
interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors>Properties
| Name | Type | Description |
|---|---|---|
authorize | (params: { user?: TContext extends { user: infer U } ? U : any; input: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: TContext; }) => boolean | Promise<boolean> | |
execute | (params: { input: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: NarrowAuthorizedContext<TContext>; error: ErrorBuilder<TErrors>; }) => | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : … |
Source: packages/core/src/types.ts:202
ActionConfigWithoutAuthorize
interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors>Properties
| Name | Type | Description |
|---|---|---|
authorize? | undefined | |
execute | (params: { input: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: TContext; error: ErrorBuilder<TErrors>; }) => | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema ext… |
Source: packages/core/src/types.ts:225
ActionErrorDefinition
interface ActionErrorDefinitionProperties
| Name | Type | Description |
|---|---|---|
status? | number | |
message | string |
Source: packages/core/src/types.ts:62
ActionSchema
interface ActionSchemaProperties
| Name | Type | Description |
|---|---|---|
name | string | |
method? | "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | Present only when this action has a registered HTTP route. |
path? | string | |
serviceName? | string | |
plugin? | string | Owning plugin descriptor name for plugin actions (e.g. @brickkit/crud). |
resource? | string | Owning resource name for resource-plugin actions (e.g. page). |
description? | string | |
inputSchema? | unknown | |
outputSchema? | unknown | |
hasAuthorize | boolean | |
hasScope? | boolean | |
accessPolicy? | ActionAccessPolicy | |
errors? | Record<string, ActionErrorDefinition> | |
emits? | string[] | |
tags? | string[] |
Source: packages/core/src/types.ts:480
ApiDocument
interface ApiDocumentA named OpenAPI document ready to render.
Properties
| Name | Type | Description |
|---|---|---|
title | string | |
document | OpenApiDocument |
Source: packages/core/src/docs.ts:17
ArchitectureSchema
interface ArchitectureSchemaProperties
| Name | Type | Description |
|---|---|---|
version | string | |
services | ServiceSchema[] |
Source: packages/core/src/types.ts:517
BaseActionConfig
interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>Properties
| Name | Type | Description |
|---|---|---|
name | string | |
description? | string | |
path? | string | Effective HTTP path, including the prefix; replaces the default action path. |
method? | "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | Single HTTP method exposed for this action (default POST). |
input? | TInputSchema | |
output? | TOutputSchema | |
errors? | TErrors | |
emits? | string[] | |
tags? | string[] |
Source: packages/core/src/types.ts:181
BaseContext
interface BaseContext<TDb = any>Base framework context supplied to all service resolvers and action executions.
Properties
| Name | Type | Description |
|---|---|---|
request | Request | |
db | TDb | |
logger | Logger | |
traceId | string | |
requestId? | string | |
caller? | string | |
tenantId? | string | |
services? | Record<string, any> | |
metadata? | Record<string, unknown> |
Source: packages/core/src/types.ts:23
BrickCallOptions
interface BrickCallOptionsProperties
| Name | Type | Description |
|---|---|---|
headers? | Record<string, string> | Extra headers merged over the client defaults for this call only. |
signal? | AbortSignal | Abort signal for this call only. Never wrapped: aborts reject with AbortError. |
timeoutMs? | number | Per-call timeout in milliseconds. Implemented with AbortSignal.timeout. |
Source: packages/core/src/client.ts:109
BrickClientAction
interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}>Browser-safe action metadata generated by the Brick Vite plugin.
Properties
| Name | Type | Description |
|---|---|---|
kind | "action" | |
name | string | |
serviceName | string | |
plugin? | string | Owning plugin descriptor name for plugin actions (e.g. @brickkit/crud). |
resource? | string | Owning resource name for resource-plugin actions (e.g. page). |
config | { path: string; method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" } | |
readonly __types? | { input: TInput; output: TOutput; errors: TErrors } | Type information only; never emitted at runtime. |
Source: packages/core/src/client.ts:92
BrickClientOptions
interface BrickClientOptionsEden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.
The frontend imports only the contract type — never a backend implementation:
import { createBrickClient } from "@brickkit/core/client";
import type { AppServer } from "./server"; // `import type`: erased at build
const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
const pages = await api.page.list({ limit: 10, sort: "-createdAt" });
const created = await api.page.create({ title: "Hello", content: "World" });Build the contract from individually-typed actions (each defineAction call
preserves its input/output/error literal types):
// server.ts (backend)
export const listPages = pagesService.action({ name: "page.list", ... });
export const createPage = pagesService.action({ name: "page.create", ... });
export const contract = { page: { list: listPages, create: createPage } };
export type AppServer = typeof contract;Result / error convention
The client uses a throw-based convention that mirrors local action.execute
semantics, because TypeScript promises cannot encode thrown exception types:
- Success → the promise resolves with the action output.
- Declared domain failures (your
errors: { SLUG_EXISTS: ... }) and framework guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected withActionExecutionErrorcarrying the declaredcode,status,message, anddetails. Narrow withinstanceofand readerr.code. - Input/output validation failures → rejected with
ValidationError, exactly as local execution throws. - Network failures, unparsable bodies, and non-OK responses outside the
declared contract →
BrickTransportError(4xx) orBrickServerError(5xx). - Cancellation via
AbortSignal→ the nativeAbortErrorpropagates unwrapped soerr.name === "AbortError"keeps working.
URL mapping
A client path is a namespace walk ending in an action call. The leaf segment
decides the route, matching the server compiler (packages/cli/src/compiler):
| Client call | HTTP request |
|---|---|
| Generated browser contracts carry each action's HTTP method and path, | |
| including plugin routes and consumer overrides. Without runtime metadata, | |
callers use POST /api/<service>/<action> with dotted action names. | |
| GET/DELETE input is serialized as a query string; other methods send JSON. |
Properties
| Name | Type | Description |
|---|---|---|
baseUrl | string | Server origin, e.g. "http://localhost:4000". No trailing slash required. |
prefix? | string | Route prefix the server was mounted with (default "/api"). Must match the prefix passed to brick({ prefix }). |
headers? | | Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>) | Default headers sent with every call (e.g. an Authorization bearer). A thunk is re-evaluated per call, so rotated tokens stay fresh. |
fetch? | (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> | fetch implementation. Defaults to globalThis.fetch. |
signal? | AbortSignal | Default signal applied to every call (per-call signal wins). |
timeoutMs? | number | Default per-call timeout in milliseconds (per-call timeoutMs wins). |
contract? | Record<string, any> | Browser-safe route metadata generated by the Brick Vite plugin. Required for custom methods/paths and plugin routes. Without a contract, calls use POST and service/action names inferred from namespace keys. |
Source: packages/core/src/client.ts:62
BrickIR
interface BrickIRProperties
| Name | Type | Description |
|---|---|---|
readonly version | 1 | |
readonly target | "bun-elysia" | |
readonly prefix | string | |
readonly services | readonly string[] | |
readonly routes | readonly RouteIR[] | |
readonly preparations | readonly { service: string; name: string; metadata: unknown; }[] | |
readonly diagnostics | readonly string[] |
Source: packages/core/src/compiler/ir.ts:24
CacheOptions
interface CacheOptionsProperties
| Name | Type | Description |
|---|---|---|
driver? | "memory" | "redis" | |
defaultTtl? | number |
Source: packages/core/src/types.ts:433
CompiledApplication
interface CompiledApplicationProperties
| Name | Type | Description |
|---|---|---|
readonly ir | BrickIR | |
readonly routes | readonly CompiledRoute[] |
Source: packages/core/src/compiler.ts:55
CompiledRoute
interface CompiledRouteProperties
| Name | Type | Description |
|---|---|---|
readonly ir | RouteIR | |
readonly handler | CompiledHandler |
Source: packages/core/src/compiler.ts:51
CompiledRoutePlan
interface CompiledRoutePlanProperties
| Name | Type | Description |
|---|---|---|
service | Service<any, any> | |
action | Action<any, any, any, any> | |
actionName | string | |
serviceName | string | |
routePath | string | |
method? | string | |
isGetLike | boolean | |
hasInput | boolean | |
hasContextHook | boolean | |
contextHook? | (baseCtx: any) => Promise<any> | any | |
hasAuthorize | boolean | |
authorize? | (params: any) => boolean | Promise<boolean> | |
execute | (params: any) => Promise<any> | any | |
inputChecker? | { Check: (val: any) => boolean; Errors: (val: any) => Iterable<any>; } | |
outputChecker? | { Check: (val: any) => boolean; Errors: (val: any) => Iterable<any>; } | |
coercions? | Array<{ key: string; isNumber: boolean; isBoolean: boolean; isArray?: boolean; }> | |
logger | Logger | |
errorBuilder | any | |
cachedDb | any |
Source: packages/core/src/types.ts:522
CreateServerOptions
interface CreateServerOptionsProperties
| Name | Type | Description |
|---|---|---|
port? | number | |
compiler? | boolean | Generate specialized handlers once at startup (default true). |
compilation? | CompiledApplication | Ahead-of-time handlers already bound to the supplied services. |
services? | Service<any, any>[] | |
prefix? | string | |
title? | string | |
version? | string | |
description? | string | |
docs? | boolean | |
openApiPath? | string | |
docsPath? | string | |
swaggerPath? | string | |
requestLogging? | boolean | RequestLoggingOptions | |
reference? | boolean | ReferenceOptions | true serves a Scalar page at /reference. Options serve one only with a path; documents adds OpenAPI documents to the dashboard's APIs view. |
secrets? | { source?: SecretSource; validate?: boolean } | |
endpoints? | EndpointDefinition[] | Raw endpoints (outside the JSON action mesh), mounted at startup. |
telemetry? | boolean | Record request, action, and RPC spans with OpenTelemetry (default false). Spans go to the globally registered tracer provider; without one they are no-ops. brick dev shows them in its dashboard. |
documentation? | string | DocumentationOptions | Developer documentation for the brick dev dashboard (its Docs tab): a folder of .md/.mdx pages in Fumadocs' layout, with frontmatter and meta.json for ordering. A string is the folder. Relative paths start at the folder of the app entry, as they read in the file that sets them (from src/app.ts, "../docs" is docs/ at the project root). Needs fumadocs-core and @mdx-js/mdx installed. |
dashboard? | DashboardOptions | Monitoring dashboard for brick start, on a port of its own and behind auth. Setting it turns on telemetry. See DashboardOptions. |
Source: packages/core/src/server.ts:34
DashboardAuth
interface DashboardAuthWho may open the dashboard that brick start serves for monitoring.
Properties
| Name | Type | Description |
|---|---|---|
token? | string | readonly string[] | Secrets that let a request in. A browser asks for one in its sign-in prompt (any user name, the secret as the password), and monitors and scripts send Authorization: Bearer <secret>. Give several to rotate one while the other still works. Each is at least 16 characters long; openssl rand -base64 32 makes a good one. |
authorize? | (request: Request,) => boolean | Response | Promise<boolean | Response> | Your own check, to sign people in with the auth the app already has: read a session cookie, verify a Better Auth or Clerk session, look at a header a proxy adds. It receives the request (method, URL, and headers; no body) and returns true to let it in, false to refuse it with 401, or a Response to send instead, such as a redirect to your login page. If it throws or takes longer than five seconds, the request is refused with 503. A request is let in when it carries a valid token, or when this returns true; give both to let monitors in by token and people in by sign-in. |
Source: packages/core/src/dashboard.ts:2
DashboardOptions
interface DashboardOptionsThe monitoring dashboard brick start serves beside the app, on a port of
its own: live requests, logs, errors, and the shape of the service, so it
stays reachable when the app's own routes are not. brick dev has its own
dashboard, set by command line options, and ignores this.
Setting it turns on telemetry, since the dashboard shows what is traced.
While it is on, ctx.logger and console lines written during a request
go to the dashboard instead of the console.
Properties
| Name | Type | Description |
|---|---|---|
port? | number | Default 9400. |
host? | string | The address to listen on. Default 127.0.0.1, reachable only from the same machine. In a container use 0.0.0.0, which needs auth: the dashboard will not start on any other address without it. |
auth? | DashboardAuth | |
historyDays? | number | Days of finished requests to keep on disk, in .brick/ of the working folder. Default 0: only what happened since the process started, which is lost when it restarts. Needs a folder that outlives the container. |
Source: packages/core/src/dashboard.ts:38
DatabaseAdapter
interface DatabaseAdapter<TDb = any, TConfig = any>Methods
| Name | Type | Description |
|---|---|---|
createDatabase | createDatabase(config?: TConfig): TDb |
Source: packages/core/src/db/postgres.ts:36
DatabaseConfig
interface DatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> extends Omit<SQLiteDatabaseConfig<TSchema>, "client">, Omit<PostgresDatabaseConfig<TSchema>, "client">Properties
| Name | Type | Description |
|---|---|---|
client? | | SQLiteDatabaseConfig<TSchema>["client"] | PostgresDatabaseConfig<TSchema>["client"] | |
engine? | "sqlite" | "postgres" | "clickhouse" | Database engine. Default: 'sqlite' |
name? | string | Optional service name associated with this database |
Source: packages/core/src/db/index.ts:46
DatabaseHandle
interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>>Properties
| Name | Type | Description |
|---|---|---|
readonly kind | "brick-database" | |
readonly name? | string | |
readonly engine | "sqlite" | "postgres" | |
readonly tables | Readonly<Record<string, Table>> | |
readonly schema | TSchema |
Methods
| Name | Type | Description |
|---|---|---|
getDb | getDb(): TDb | |
close? | close(): void | Promise<void> |
Source: packages/core/src/db/define.ts:54
DefaultServiceContext
interface DefaultServiceContextDefault fallback service context for untyped or simple services.
Properties
| Name | Type | Description |
|---|---|---|
user? | any | |
session? | any | |
[index] | [key: string]: any |
Source: packages/core/src/types.ts:38
DocumentationOptions
interface DocumentationOptionsDeveloper documentation for the brick dev dashboard.
Properties
| Name | Type | Description |
|---|---|---|
dir | string | Folder of .md/.mdx pages. A relative path starts at the folder of the app entry, as it reads in the file that sets it. |
components? | string | Module whose exports are React components for MDX, added to the built-in ones; a relative path starts where dir does. A default export or a components export holds the name-to-component map. The dashboard bundles it, so it may import anything the project has. |
Source: packages/core/src/docs.ts:23
EndpointContext
interface EndpointContextContext for raw endpoint handlers: Elysia route fields + Brick extras.
Properties
| Name | Type | Description |
|---|---|---|
params | Record<string, string> | |
query | Record<string, string | undefined> | |
body | unknown | |
headers | Record<string, string> | |
request | Request | |
set | { status?: number; headers: Record<string, string> } | Elysia response setter (status/headers). Mutate like in app.get. |
db | any | Drizzle db from service (or first service with one); undefined when none. |
logger | EndpointLogger | |
traceId | string | |
requestId | string |
Source: packages/core/src/endpoints.ts:22
EndpointDefinition
interface EndpointDefinitionProperties
| Name | Type | Description |
|---|---|---|
method | EndpointMethod | |
path | string | Elysia-style path, e.g. /p/:slug. |
handler | (ctx: EndpointContext) => unknown | Promise<unknown> | |
service? | Service<any, any> | string | Db source: instance or registered service name. Defaults to first service with a db. |
database? | DatabaseHandle<unknown> | Explicit database handle, independent of a service. |
summary? | string | |
description? | string | |
tags? | string[] |
Source: packages/core/src/endpoints.ts:37
EndpointLogger
interface EndpointLoggerLogger subset handed to endpoint handlers (mirrors action context loggers).
Properties
| Name | Type | Description |
|---|---|---|
info | (...args: any[]) => void | |
warn | (...args: any[]) => void | |
error | (...args: any[]) => void | |
debug | (...args: any[]) => void |
Source: packages/core/src/endpoints.ts:14
ErrorEnvelope
interface ErrorEnvelopeProperties
| Name | Type | Description |
|---|---|---|
name | string | |
code | string | |
message | string | |
status | number | |
requestId | string | |
details? | unknown | |
errors? | ValidationError["errors"] |
Source: packages/core/src/error-response.ts:4
LifecycleOptions
interface LifecycleOptionsProperties
| Name | Type | Description |
|---|---|---|
onInit? | (ctx: { db?: any; logger?: Logger }) => Promise<void> | |
onDestroy? | () => Promise<void> |
Source: packages/core/src/types.ts:457
Logger
interface LoggerThe logger on action, tool, and endpoint contexts. While a dashboard is on
(brick dev, or brick start with the dashboard option) a line logged
during a traced request appears in the dashboard with that request, instead
of on the console (as does a plain console.log); anywhere else it prints
to the console.
Properties
| Name | Type | Description |
|---|---|---|
info | (...args: any[]) => void | |
warn | (...args: any[]) => void | |
error | (...args: any[]) => void | |
debug | (...args: any[]) => void |
Source: packages/core/src/types.ts:13
McpHandlerOptions
interface McpHandlerOptionsProperties
| Name | Type | Description |
|---|---|---|
registry | McpRegistry | |
serverInfo | { name: string; version: string; title?: string } | |
protocolVersions? | readonly string[] | Versions supported by this transport, newest first. |
Source: packages/core/src/mcp.ts:71
McpRegistry
interface McpRegistryMethods
| Name | Type | Description |
|---|---|---|
listTools | listTools(): McpToolDefinition[] | |
callTool | callTool( name: string, args?: Record<string, unknown>, ctx?: Partial<ActionContext>, ): Promise<unknown> |
Source: packages/core/src/mcp.ts:16
McpRegistryOptions
interface McpRegistryOptionsProperties
| Name | Type | Description |
|---|---|---|
services? | readonly Pick<Service<any, any>, "listTools">[] | |
tools? | readonly Tool<any, any, any, any>[] |
Source: packages/core/src/mcp.ts:11
McpToolDefinition
interface McpToolDefinitionProperties
| Name | Type | Description |
|---|---|---|
name | string | |
title? | string | |
description | string | |
inputSchema | unknown | |
annotations | ToolAnnotations |
Source: packages/core/src/mcp.ts:3
OpenApiGeneratorOptions
interface OpenApiGeneratorOptionsProperties
| Name | Type | Description |
|---|---|---|
title? | string | |
version? | string | |
description? | string | |
prefix? | string | |
services? | Service<any, any>[] | |
registry? | ServiceRegistry |
Source: packages/core/src/openapi.ts:7
PluginEndpointContext
interface PluginEndpointContext<C extends ActionContext = ActionContext>Properties
| Name | Type | Description |
|---|---|---|
params | Record<string, string> | |
query | Record<string, string | undefined> | |
body | unknown | |
headers | Record<string, string> | |
request | Request | |
set | { status?: number; headers: Record<string, string> } | |
ctx | C |
Source: packages/core/src/plugin.ts:24
PluginRouteRegistrar
interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extends PluginRouteScope = PluginRouteScope>Methods
| Name | Type | Description |
|---|---|---|
action | action< I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithAuthorize<I, O, E, C> & { path: string; method: PluginRouteMethod; scope?: S; }, ): Action<I, O, E, C> | |
action | action< I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithoutAuthorize<I, O, E, C> & { path: string; method: PluginRouteMethod; scope?: S; }, ): Action<I, O, E, C> | |
endpoint | endpoint( config: { name: string; path: string; method: PluginRouteMethod; scope?: S; handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>; summary…, ): void |
Source: packages/core/src/plugin.ts:36
PostgresDatabaseConfig
interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>>Properties
| Name | Type | Description |
|---|---|---|
client? | Sql | Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. |
url? | string | Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) |
connectionString? | string | Connection string alias |
host? | string | |
port? | number | |
user? | string | |
password? | string | |
database? | string | |
ssl? | boolean | "require" | "allow" | "prefer" | "verify-full" | |
max? | number | |
prepare? | boolean | Disable prepared statements (required for transaction-mode poolers such as Supabase's Supavisor on :6543, which cannot hold named prepared statements across transactions). |
schema? | TSchema | Optional Drizzle schema for relational queries |
schemaName? | string | Custom schema name for Encore-style isolated schemas |
Source: packages/core/src/db/postgres.ts:4
PreparationContribution
interface PreparationContributionGeneric preparation declarations consumed by the application compiler.
Properties
| Name | Type | Description |
|---|---|---|
readonly name | string |
Methods
| Name | Type | Description |
|---|---|---|
describe | describe(): unknown | |
prepare | prepare(): void |
Source: packages/core/src/types.ts:389
ProxyOptions
interface ProxyOptionsProperties
| Name | Type | Description |
|---|---|---|
isMonolith? | boolean | |
from? | string | Name of the service creating this proxy. Populates ctx.caller on the target's envelope. |
context? | Partial<ActionContext> |
Source: packages/core/src/types.ts:695
RateLimitOptions
interface RateLimitOptionsProperties
| Name | Type | Description |
|---|---|---|
maxRequests | number | |
window | number | string | |
scope? | "ip" | "user" | "tenant" |
Source: packages/core/src/types.ts:427
ReferenceDocument
interface ReferenceDocumentAn extra OpenAPI document for the API reference, such as Better Auth's.
Properties
| Name | Type | Description |
|---|---|---|
title | string | Name in the reference's list of documents. |
document | | OpenApiDocument | (() => OpenApiDocument | Promise<OpenApiDocument>) | The document, or a function returning it; called each time the app starts. |
Source: packages/core/src/docs.ts:7
ReferenceOptions
interface ReferenceOptionsProperties
| Name | Type | Description |
|---|---|---|
path? | string | Also serve a standalone Scalar page here. Without a path, no page is served. |
title? | string | |
specUrl? | string | |
documents? | ReferenceDocument[] | More OpenAPI documents for the brick dev dashboard's APIs view. |
Source: packages/core/src/docs.ts:38
RequestLoggingOptions
interface RequestLoggingOptionsProperties
| Name | Type | Description |
|---|---|---|
enabled? | boolean | |
logger? | (msg: string) => void |
Source: packages/core/src/request-logger.ts:3
ResilienceOptions
interface ResilienceOptionsProperties
| Name | Type | Description |
|---|---|---|
timeoutMs? | number | |
retry? | { attempts: number; backoff: "linear" | "exponential"; delayMs: number; } | |
circuitBreaker? | { errorThresholdPercentage: number; resetTimeoutMs: number; } |
Source: packages/core/src/types.ts:438
Resource
interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}>Properties
| Name | Type | Description |
|---|---|---|
readonly name | string | |
readonly serviceName | string | |
readonly table | TTable | |
readonly id | TOptions extends { id: infer I extends Column; } ? I : Column | |
readonly idField | string | |
readonly config | ResourceConfig<TTable, TCtx> & TOptions |
Methods
| Name | Type | Description |
|---|---|---|
use | use< P extends ResourcePlugin<Service<TCtx["db"], Omit<TCtx, keyof BaseContext>>, this, any>, >( plugin: P, ): this & ResourcePluginAPI<P, TTable, TCtx, this> |
Source: packages/core/src/types.ts:395
ResourceConfig
interface ResourceConfig<TTable = any, _TCtx = any>A resource declares identity and a table; plugins supply behavior.
Properties
| Name | Type | Description |
|---|---|---|
name | string | |
table | TTable | |
id? | Column |
Source: packages/core/src/types.ts:363
ResourcePlugin
interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object>Properties
| Name | Type | Description |
|---|---|---|
readonly [pluginKind] | "resource" | |
readonly name | string | |
readonly routes? | PluginRoutes | |
readonly setup | (context: ResourcePluginContext<S, R>) => A |
Source: packages/core/src/plugin.ts:122
ResourcePluginContext
interface ResourcePluginContext<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>>Properties
| Name | Type | Description |
|---|---|---|
service | S | |
resource | R | |
routes | PluginRouteRegistrar<ContextOf<S>> |
Source: packages/core/src/plugin.ts:86
ResourcePluginTypes
interface ResourcePluginTypesPlugins may specialize their returned API for the installation host.
Properties
| Name | Type | Description |
|---|---|---|
readonly table | unknown | |
readonly context | unknown | |
readonly resource | unknown | |
readonly api | object |
Source: packages/core/src/plugin.ts:96
RouteIR
interface RouteIRProperties
| Name | Type | Description |
|---|---|---|
readonly method | RouteMethod | |
readonly path | string | |
readonly service | string | |
readonly action | string | |
readonly kind | "action" | |
readonly input | boolean | |
readonly output | boolean | |
readonly context | boolean | |
readonly authorize | boolean | |
readonly inputPrecedence | readonly ("query" | "params" | "body")[] | |
readonly coercions | readonly { readonly key: string; readonly type: "number" | "boolean" | "array"; }[] | |
readonly inputSchema? | unknown | JSON projection for inspection and stale-artifact detection, not runtime validation. |
readonly outputSchema? | unknown |
Source: packages/core/src/compiler/ir.ts:5
SecretOptions
interface SecretOptionsProperties
| Name | Type | Description |
|---|---|---|
default? | string | Fallback when the source has no value. Secrets without a default are required. |
Source: packages/core/src/secrets.ts:31
SecretSource
interface SecretSourceType-safe secrets & environment variables.
Declare each secret once at module scope instead of scattering untyped
process.env.FOO reads:
const port = secret("PORT").default("3333").transform(Number).require(); const baseUrl = secret("BASE_URL").url().require(); const key = secret("STRIPE_KEY").validate((v) => v.startsWith("sk_") || "must start with sk_" ).require();
Values resolve from the environment (Bun populates process.env from
.env locally; in prod the same env source applies — a future
SecretSource such as AWS can slot in without touching call sites).
Resolution order per secret: test/session override → source (process.env
by default) → declared default. resolveSecrets() validates every
registered secret at boot and throws listing all missing required ones.
Methods
| Name | Type | Description |
|---|---|---|
get | get(name: string): string | undefined |
Source: packages/core/src/secrets.ts:22
Service
interface Service<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>>Properties
| Name | Type | Description |
|---|---|---|
readonly name | string | |
readonly options | ServiceOptions<TServiceContext, TDb> | |
readonly actions | Map<string, Action<any, any, any, any>> | |
readonly tools | Map<string, Tool<any, any, any, any>> | |
readonly tables | Map<string, any> | |
readonly resources | Map<string, Resource<any, BaseContext<TDb> & TServiceContext>> | |
readonly db? | TDb | |
readonly isBuilt? | boolean | |
readonly preparations | Map<string, PreparationContribution> |
Methods
| Name | Type | Description |
|---|---|---|
use | use<A>(plugin: ServicePlugin<this, A>): A | |
build | build(): this | |
action | action< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): this | |
action | action< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext> | |
action | action< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext> | |
tool | tool< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): this | |
tool | tool< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ToolConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext> | |
tool | tool< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ToolConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext> | |
resource | 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>> | |
contributePreparation | contributePreparation(contribution: PreparationContribution): void | |
listPreparations | listPreparations(): PreparationContribution[] | |
prepareContributions | prepareContributions(): void | |
registerTable | registerTable(table: any): this | |
getAction | getAction(name: string): Action<any, any, any, any> | undefined | |
listActions | listActions(): Action<any, any, any, any>[] | |
getTool | getTool(name: string): Tool<any, any, any, any> | undefined | |
listTools | listTools(): Tool<any, any, any, any>[] | |
getResource | getResource( name: string, ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined | |
listResources | listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[] | |
getDb | getDb(): TDb | undefined | |
setDb | setDb(database: DatabaseHandle<TDb>): void | |
resolveContext | resolveContext( callCtx?: Partial<BaseContext<TDb> & TServiceContext>, ): Promise<BaseContext<TDb> & TServiceContext> | |
introspect | introspect(): ServiceSchema |
Source: packages/core/src/types.ts:555
ServiceAuthOptions
interface ServiceAuthOptionsProperties
| Name | Type | Description |
|---|---|---|
requireAuth? | boolean | |
allowedRoles? | string[] | |
policy? | (ctx: ActionContext) => boolean | Promise<boolean> |
Source: packages/core/src/types.ts:421
ServiceOptions
interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any>Properties
| Name | Type | Description |
|---|---|---|
database? | DatabaseHandle<TDb> | |
context? | (baseCtx: BaseContext<TDb> & { user?: unknown },) => Promise<TServiceContext> | TServiceContext | |
auth? | ServiceAuthOptions | |
rateLimit? | RateLimitOptions | |
cache? | CacheOptions | |
resilience? | ResilienceOptions | |
telemetry? | TelemetryOptions | |
lifecycle? | LifecycleOptions |
Source: packages/core/src/types.ts:462
ServicePlugin
interface ServicePlugin<S extends Service<any, any>, A>Properties
| Name | Type | Description |
|---|---|---|
readonly [pluginKind] | "service" | |
readonly name | string | |
readonly routes? | PluginRoutes<"app" | "service"> | |
readonly setup | (context: ServicePluginContext<S>) => A |
Source: packages/core/src/plugin.ts:116
ServicePluginContext
interface ServicePluginContext<S extends Service<any, any> = Service<any, any>>Properties
| Name | Type | Description |
|---|---|---|
service | S | |
routes | PluginRouteRegistrar<ContextOf<S>, "app" | "service"> |
Source: packages/core/src/plugin.ts:80
ServiceSchema
interface ServiceSchemaProperties
| Name | Type | Description |
|---|---|---|
name | string | |
options | Record<string, unknown> | The service options as JSON: functions, such as context and hooks, are left out. |
hasDatabase | boolean | |
databaseConfig? | { name?: string; engine: "sqlite" | "postgres"; tables: string[]; } | |
actions | ActionSchema[] | |
tools? | { name: string }[] | MCP tools. A tool with an HTTP route is also listed under actions. |
resources? | { name: string }[] |
Source: packages/core/src/types.ts:501
SQLiteDatabaseConfig
interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>>Properties
| Name | Type | Description |
|---|---|---|
path? | string | Database file path or ':memory:' (default: ':memory:') |
filename? | string | Alias for path |
wal? | boolean | Whether to enable WAL journal mode for file-based DBs (default: true) |
foreignKeys? | boolean | Whether to enforce foreign key constraints (default: true) |
client? | Database | Optional existing bun:sqlite Database instance |
schema? | TSchema | Optional Drizzle schema object for typed relational queries |
Source: packages/core/src/db/sqlite.ts:22
StandardErrorMap
interface StandardErrorMapProperties
| Name | Type | Description |
|---|---|---|
BAD_REQUEST | (overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never | |
UNAUTHORIZED | (overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never | |
FORBIDDEN | (overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never | |
NOT_FOUND | (overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never | |
CONFLICT | (overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never | |
INTERNAL_SERVER_ERROR | (overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never | |
[index] | [key: string]: | ((overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never) | undefined |
Source: packages/core/src/types.ts:131
TelemetryOptions
interface TelemetryOptionsProperties
| Name | Type | Description |
|---|---|---|
traceQueries? | boolean | |
auditLog? | boolean | |
tags? | Record<string, string> |
Source: packages/core/src/types.ts:451
Tool
interface Tool<I extends TSchema | undefined = any, O extends TSchema | undefined = any, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> extends Action<I, O, E, C>Properties
| Name | Type | Description |
|---|---|---|
readonly kind | "tool" | |
config | | ToolConfigWithAuthorize<I, O, E, C> | ToolConfigWithoutAuthorize<I, O, E, C> |
Source: packages/core/src/types.ts:347
ToolAnnotations
interface ToolAnnotationsMCP tool metadata, kept with the executable definition.
Properties
| Name | Type | Description |
|---|---|---|
title? | string | |
readOnlyHint? | boolean | |
destructiveHint? | boolean | |
idempotentHint? | boolean | |
openWorldHint? | boolean |
Source: packages/core/src/types.ts:316
ToolOptions
interface ToolOptionsProperties
| Name | Type | Description |
|---|---|---|
title? | string | |
annotations? | ToolAnnotations | |
http? | boolean | Also register HTTP routes and OpenAPI. Defaults to false. |
Source: packages/core/src/types.ts:323
ValidationErrorItem
interface ValidationErrorItemProperties
| Name | Type | Description |
|---|---|---|
path | string | |
message | string | |
value? | unknown | |
type? | number |
Source: packages/core/src/types.ts:67
Types
ActionAccessPolicy
type ActionAccessPolicy = "public" | "authorized" | "scoped";Source: packages/core/src/types.ts:478
ActionConfig
type ActionConfig<
TInputSchema extends TSchema | undefined = any,
TOutputSchema extends TSchema | undefined = any,
TErrors extends Record<string, ActionErrorDefinition> = Record<
string,
ActionErrorDefinition
>,
TContext extends ActionContext = ActionContext,
> =
| ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>
| ActionConfigWithoutAuthorize<
TInputSchema,
TOutputSchema,
TErrors,
TContext
>;Source: packages/core/src/types.ts:244
ActionContext
type ActionContext<
TDb = any,
TServiceContext = DefaultServiceContext,
> = BaseContext<TDb> & TServiceContext;The combined execution context: BaseContext & TServiceContext.
Source: packages/core/src/types.ts:47
BrickActionCaller
type BrickActionCaller<A> =
undefined extends InferActionInput<A>
? (
input?: InferActionInput<A>,
options?: BrickCallOptions,
) => Promise<InferActionOutput<A>>
: (
input: InferActionInput<A>,
options?: BrickCallOptions,
) => Promise<InferActionOutput<A>>;Typed caller for one action. Required inputs stay required; actions whose
input includes undefined (no schema / all-optional) can be called bare.
Source: packages/core/src/client.ts:259
BrickApp
type BrickApp = Elysia<any, any, any, any, any, any, any> & {
/** Service definitions, prefix, and telemetry setting chosen at construction. */
readonly definition: {
readonly routes: readonly RouteIR[];
readonly services: readonly Service<any, any>[];
readonly prefix: string;
readonly telemetry: boolean;
readonly documentation?: DocumentationOptions;
/** What `brick start` serves for monitoring; its `auth` is not enumerable. */
readonly dashboard?: DashboardOptions;
};
/** Register a raw endpoint (outside the JSON action mesh). */
endpoint(def: EndpointDefinition): void;
/**
* The OpenAPI documents behind the dashboard's APIs view: this app's own
* unless `docs` is false, then those from `reference.documents`.
*/
referenceDocuments(): Promise<ApiDocument[]>;
/** All endpoints registered via `endpoint()` (declaration order). */
listEndpoints(): EndpointDefinition[];
};The app object returned by brick: Elysia plus endpoint().
Source: packages/core/src/endpoints.ts:175
BrickClient
type BrickClient<T> = T extends
| BrickClientAction<any, any, any>
| Action<any, any, any, any>
? BrickActionCaller<T>
: T extends (...args: any[]) => any
? BrickActionCaller<T>
: T extends object
? { [K in keyof T]: BrickClient<T[K]> }
: T;Recursively maps action leaves and their namespaces to browser callers.
Source: packages/core/src/client.ts:271
BrickDatabase
type BrickDatabase<
TSchema extends Record<string, unknown> = Record<string, unknown>,
> = BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;Source: packages/core/src/db/index.ts:61
BrickSQLiteDatabase
type BrickSQLiteDatabase<
TSchema extends Record<string, unknown> = Record<string, unknown>,
> = BunSQLiteDatabase<TSchema> & {
$client: Database;
};Source: packages/core/src/db/sqlite.ts:39
CompiledHandler
type CompiledHandler = (context: any) => unknown | Promise<unknown>;Source: packages/core/src/compiler/runtime.ts:10
DatabaseDefinition
type DatabaseDefinition<
TSchema extends Record<string, unknown> = Record<string, unknown>,
> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;Source: packages/core/src/db/define.ts:50
EndpointMethod
type EndpointMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";Source: packages/core/src/endpoints.ts:11
EnvInput
type EnvInput<T> = T | SecretRef<T>;Source: packages/core/src/db/define.ts:18
ErrorBuilder
type ErrorBuilder<
TErrors extends Record<string, ActionErrorDefinition>,
> = StandardErrorMap & {
[K in keyof TErrors]: (
overrideMessage?: string,
details?: unknown,
options?: ErrorOptions,
) => never;
};Source: packages/core/src/types.ts:171
HandlerFactory
type HandlerFactory = (
binding: CompiledRoutePlan,
runtime: typeof compilerRuntime,
) => CompiledHandler;Source: packages/core/src/compiler/runtime.ts:11
InferActionErrorCodes
type InferActionErrorCodes<A> =
A extends BrickClientAction<any, any, infer E>
? Extract<keyof E, string>
: A extends {
config: { errors?: infer E };
}
? E extends Record<string, ActionErrorDefinition>
? Extract<keyof E, string>
: never
: never;Union of error codes declared in an action's errors map.
Source: packages/core/src/client.ts:220
InferActionFailure
type InferActionFailure<A> = ActionExecutionError & {
code:
| InferActionErrorCodes<A>
| "BAD_REQUEST"
| "UNAUTHORIZED"
| "FORBIDDEN"
| "NOT_FOUND"
| "CONFLICT"
| "INTERNAL_SERVER_ERROR"
| "VALIDATION_FAILED";
};The declared failure shape of an action for catch narrowing:
try { await api.page.create(input); }
catch (err) {
if (err instanceof ActionExecutionError) {
const code: InferActionErrorCodes<typeof createPage> | "UNAUTHORIZED" | ... = err.code;
}
}(Standard framework codes are always possible alongside declared ones.)
Source: packages/core/src/client.ts:243
InferActionInput
type InferActionInput<A> =
A extends BrickClientAction<infer I, any, any>
? I
: A extends {
config: { input?: infer S extends TSchema };
}
? Static<S>
: A extends {
execute(params: { input?: infer I; ctx?: any }): any;
}
? I
: A extends { run(input?: infer I, ctx?: any): any }
? I
: A extends (params: { input?: infer I; ctx?: any }) => any
? I
: unknown;Static input type from the schema, with a fallback for structural actions.
Source: packages/core/src/client.ts:192
InferActionOutput
type InferActionOutput<A> =
A extends BrickClientAction<any, infer O, any>
? O
: A extends (...args: any[]) => Promise<infer O>
? O
: A extends { execute(params: any): Promise<infer O> }
? O
: unknown;Resolved output type of an action.
Source: packages/core/src/client.ts:210
InferTableInsert
type InferTableInsert<TTable> = TTable extends { $inferInsert: infer S }
? S
: any;Source: packages/core/src/types.ts:372
InferTableRow
type InferTableRow<TTable> = TTable extends { $inferSelect: infer S }
? S
: any;Source: packages/core/src/types.ts:369
NarrowAuthorizedContext
type NarrowAuthorizedContext<TCtx> = TCtx extends { user: infer U }
? [U] extends [null | undefined]
? TCtx
: Omit<TCtx, "user"> & { user: NonNullable<U> }
: TCtx;Type utility that automatically narrows ctx.user from User | null to User in execute() when authorize() is declared on the action.
Source: packages/core/src/types.ts:56
OpenApiDocument
type OpenApiDocument = Record<string, unknown>;An OpenAPI document as plain JSON.
Source: packages/core/src/docs.ts:4
PluginRouteMethod
type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";Source: packages/core/src/plugin.ts:15
PluginRoutes
type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =
| false
| Readonly<Record<string, false | { path?: string; scope?: S }>>;Source: packages/core/src/plugin.ts:17
PluginRouteScope
type PluginRouteScope = "app" | "service" | "resource";Source: packages/core/src/plugin.ts:16
PostgresDatabase
type PostgresDatabase<
_TSchema extends Record<string, unknown> = Record<string, unknown>,
> = any;Source: packages/core/src/db/postgres.ts:32
PostgresDefinition
type PostgresDefinition<
TSchema extends Record<string, unknown> = Record<string, unknown>,
> = DefinitionOptions<TSchema> &
EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
engine: "postgres";
path?: never;
filename?: never;
wal?: never;
foreignKeys?: never;
client?: PostgresDatabaseConfig<TSchema>["client"];
};Source: packages/core/src/db/define.ts:38
ResourceIdentity
type ResourceIdentity<T, O> = O & {
id: O extends { id: infer I extends import("drizzle-orm").Column }
? I
: PrimaryColumn<T>;
};Source: packages/core/src/types.ts:382
ResourcePluginAPI
type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
readonly types: infer H extends ResourcePluginTypes;
}
? (H & {
readonly table: T;
readonly context: C;
readonly resource: R;
})["api"]
: P extends ResourcePlugin<any, any, infer A>
? A
: never;Source: packages/core/src/plugin.ts:102
ResourceTypeOptions
type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id">;Source: packages/core/src/types.ts:375
RouteMethod
type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";Source: packages/core/src/compiler/ir.ts:4
SQLiteDefinition
type SQLiteDefinition<
TSchema extends Record<string, unknown> = Record<string, unknown>,
> = DefinitionOptions<TSchema> &
EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
engine?: "sqlite";
client?: SQLiteDatabaseConfig<TSchema>["client"];
url?: never;
connectionString?: never;
};Source: packages/core/src/db/define.ts:28
ToolConfigWithAuthorize
type ToolConfigWithAuthorize<
I extends TSchema | undefined = undefined,
O extends TSchema | undefined = undefined,
E extends Record<string, ActionErrorDefinition> = Record<
string,
ActionErrorDefinition
>,
C extends ActionContext = ActionContext,
> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;Source: packages/core/src/types.ts:329
ToolConfigWithoutAuthorize
type ToolConfigWithoutAuthorize<
I extends TSchema | undefined = undefined,
O extends TSchema | undefined = undefined,
E extends Record<string, ActionErrorDefinition> = Record<
string,
ActionErrorDefinition
>,
C extends ActionContext = ActionContext,
> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;Source: packages/core/src/types.ts:338
Variables
ACTION_ACCESS_KEY
const ACTION_ACCESS_KEY: typeof ACTION_ACCESS_KEYCross-copy access metadata protocol. CRUD enforces its access policy
inside execute, so config.authorize is absent and introspection
can't see it. The plugin stamps each action under this process-global
symbol; introspection and OpenAPI read it back. Uses Symbol.for so
the binding survives a second copy of core (bundler SSR, Vitest),
same as the plugin action-binding key.
Source: packages/core/src/access.ts:18
compilerRuntime
const compilerRuntime: Readonly<{ emptyServices: Readonly<{}>; defaultRequest: Request; nextSequence: () => string; mergeInput: typeof mergeInput; checkDepth: typeof checkDepth; validate: typeof validate; mapError: typeof mapError; isThenable…Source: packages/core/src/compiler/runtime.ts:97
envSource
const envSource: SecretSourceDefault source: process.env (Bun loads .env into it automatically).
Source: packages/core/src/secrets.ts:27
Re-exported from @sinclair/typebox
These come from @sinclair/typebox, which documents them. They are exported here so one import covers them.
| Name | Kind | Description |
|---|---|---|
Static | type | Creates a static type from a TypeBox type |
t | variable | JavaScript Type Builder with Static Resolution for TypeScript |
TSchema | interface | |
Type | variable | JavaScript Type Builder with Static Resolution for TypeScript |
Re-exported from drizzle-orm
These come from drizzle-orm, which documents them. They are exported here so one import covers them.
| Name | Kind | Description |
|---|---|---|
and | function | Combine a list of conditions with the and operator. |
asc | function | Used in sorting, this specifies that the given column or expression should be sorted in ascending order. |
blob | function | It's recommended to use text('...', \{ mode: 'json' \}) instead of blob in JSON mode, because it supports JSON functions: >All JSON functions currently throw… |
BunSQLiteDatabase | class | |
desc | function | Used in sorting, this specifies that the given column or expression should be sorted in descending order. |
eq | variable | Test that two values are equal. |
foreignKey | function | |
getTableColumns | function | |
getTableName | function | |
gt | variable | Test that the first expression passed is greater than the second expression. |
gte | variable | Test that the first expression passed is greater than or equal to the second expression. |
ilike | function | Case-insensitively compare a column to a pattern, which can include % and _ characters to match multiple variations. |
inArray | function | Test whether the first parameter, a column or expression, has a value from a list passed as the second argument. |
index | function | |
integer | function | |
is | function | |
isNotNull | function | Test whether an expression is not NULL. |
isNull | function | Test whether an expression is NULL. |
like | function | Compare a column to a pattern, which can include % and _ characters to match multiple variations. |
lt | variable | Test that the first expression passed is less than the second expression. |
lte | variable | Test that the first expression passed is less than or equal to the second expression. |
ne | variable | Test that two values are not equal. |
not | function | Negate the meaning of an expression using the not keyword. |
notInArray | function | Test whether the first parameter, a column or expression, has a value that is not present in a list passed as the second argument. |
or | function | Combine a list of conditions with the or operator. |
primaryKey | function | |
real | function | |
relations | function | |
sql | function | |
sqliteTable | variable | |
Table | interface | |
text | function | |
uniqueIndex | function |