@brickkit/core 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1860 +1,5 @@
1
+ import { $ as BrickSocketConnectOptions, X as BrickClientSocket, Z as BrickSocketClient, c as ActionExecutionError, s as ActionErrorDefinition, t as Action } from "./types.js";
1
2
  import { Static, TSchema } from "@sinclair/typebox";
2
- import { Elysia } from "elysia";
3
- import { Table } from "drizzle-orm";
4
- import { blob, foreignKey, index as index$1, integer as integer$1, primaryKey, real, sqliteTable as sqliteTable$1, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
5
- import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
6
- import { Sql } from "postgres";
7
- import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
8
- import { Database } from "bun:sqlite";
9
- //#region src/plugin.d.ts
10
- type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
11
- type PluginRouteScope = "app" | "service" | "resource";
12
- type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> = false | Readonly<Record<string, false | {
13
- path?: string;
14
- scope?: S;
15
- }>>;
16
- type ContextOf<S> = S extends Service<infer D, infer C> ? BaseContext<D> & C : never;
17
- interface PluginEndpointContext<C extends ActionContext = ActionContext> {
18
- params: Record<string, string>;
19
- query: Record<string, string | undefined>;
20
- body: unknown;
21
- headers: Record<string, string>;
22
- request: Request;
23
- set: {
24
- status?: number;
25
- headers: Record<string, string>;
26
- };
27
- ctx: C;
28
- }
29
- interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extends PluginRouteScope = PluginRouteScope> {
30
- 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> & {
31
- path: string;
32
- method: PluginRouteMethod;
33
- scope?: S;
34
- }): Action<I, O, E, C>;
35
- 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> & {
36
- path: string;
37
- method: PluginRouteMethod;
38
- scope?: S;
39
- }): Action<I, O, E, C>;
40
- endpoint(config: {
41
- name: string;
42
- path: string;
43
- method: PluginRouteMethod;
44
- scope?: S;
45
- handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;
46
- summary?: string;
47
- description?: string;
48
- tags?: string[];
49
- }): void;
50
- }
51
- interface ServicePluginContext<S extends Service<any, any> = Service<any, any>> {
52
- service: S;
53
- routes: PluginRouteRegistrar<ContextOf<S>, "app" | "service">;
54
- }
55
- interface ResourcePluginContext<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>> {
56
- service: S;
57
- resource: R;
58
- routes: PluginRouteRegistrar<ContextOf<S>>;
59
- }
60
- /** Plugins may specialize their returned API for the installation host. */
61
- interface ResourcePluginTypes {
62
- readonly table: unknown;
63
- readonly context: unknown;
64
- readonly resource: unknown;
65
- readonly api: object;
66
- }
67
- type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
68
- readonly types: infer H extends ResourcePluginTypes;
69
- } ? (H & {
70
- readonly table: T;
71
- readonly context: C;
72
- readonly resource: R;
73
- })["api"] : P extends ResourcePlugin<any, any, infer A> ? A : never;
74
- declare const pluginKind: unique symbol;
75
- interface ServicePlugin<S extends Service<any, any>, A> {
76
- readonly [pluginKind]: "service";
77
- readonly name: string;
78
- readonly routes?: PluginRoutes<"app" | "service">;
79
- readonly setup: (context: ServicePluginContext<S>) => A;
80
- }
81
- interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object> {
82
- readonly [pluginKind]: "resource";
83
- readonly name: string;
84
- readonly routes?: PluginRoutes;
85
- readonly setup: (context: ResourcePluginContext<S, R>) => A;
86
- }
87
- /**
88
- * Define a plugin that installs onto a service with `service.use(plugin)`. Its
89
- * `setup` receives the service and a `routes` registrar for adding actions and
90
- * raw HTTP endpoints, and returns the typed API that `service.use` hands back.
91
- *
92
- * @param definition - A unique `name`, optional `routes` controls that let the
93
- * user move or switch off the plugin's routes, and `setup`, which must be
94
- * synchronous.
95
- * @returns The plugin descriptor, frozen.
96
- * @throws When the name is empty or has surrounding whitespace.
97
- * @example
98
- * import { defineServicePlugin, t } from "@brickkit/core";
99
- *
100
- * export const greeting = (salutation = "Hello") =>
101
- * defineServicePlugin({
102
- * name: "example/greeting",
103
- * setup({ routes }) {
104
- * const hello = routes.action({
105
- * name: "hello",
106
- * input: t.Object({ name: t.String() }),
107
- * output: t.String(),
108
- * execute: ({ input }) => `${salutation}, ${input.name}!`,
109
- * });
110
- * return { hello };
111
- * },
112
- * });
113
- *
114
- * const api = greeterService.use(greeting("Welcome"));
115
- * await api.hello({ input: { name: "Ada" } });
116
- */
117
- declare function defineServicePlugin<S extends Service<any, any> = Service<any, any>, A = unknown>(definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & {
118
- setup: (context: ServicePluginContext<S>) => A & (A extends PromiseLike<unknown> ? never : unknown);
119
- }): ServicePlugin<S, A>;
120
- /**
121
- * Define a plugin that installs onto a resource (a table and its entity) with
122
- * `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
123
- * `routes` registrar, whose routes are scoped under the resource's name, and
124
- * returns the typed API that `resource.use` hands back. `crud` is built this way.
125
- *
126
- * @param definition - A unique `name`, optional `routes` controls, and `setup`,
127
- * which must be synchronous.
128
- * @returns The plugin descriptor, frozen.
129
- * @throws When the name is empty or has surrounding whitespace.
130
- */
131
- declare function defineResourcePlugin<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>, A extends object = object>(definition: Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & {
132
- setup: (context: ResourcePluginContext<S, R>) => A & (A extends PromiseLike<unknown> ? never : unknown);
133
- }): ResourcePlugin<S, R, A>;
134
- /**
135
- * Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
136
- * compiler, and the typed client.
137
- *
138
- * @param action - An action.
139
- * @param prefix - The application's route prefix (default `/api`).
140
- * @returns `undefined` when no plugin bound the action (it uses its own route),
141
- * `false` when the plugin's route was switched off, otherwise the route's
142
- * `path` and `method`, the `clientPath` the typed client uses, and the owning
143
- * `plugin` and `resource`.
144
- */
145
- declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix?: string): false | {
146
- path: string;
147
- method: PluginRouteMethod;
148
- clientPath: string[] | undefined;
149
- plugin: string;
150
- resource: string | undefined;
151
- } | undefined;
152
- /**
153
- * The raw HTTP endpoints plugins registered on a service, ready to mount on the
154
- * application. Each handler resolves the service's context before it runs.
155
- *
156
- * @param service - The service plugins were installed on.
157
- * @param prefix - The application's route prefix (default `/api`).
158
- * @returns The enabled endpoints: `path`, `method`, `handler`, and the
159
- * `summary`, `description`, and `tags` for OpenAPI.
160
- */
161
- declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
162
- path: string;
163
- method: PluginRouteMethod;
164
- service: Service<any, any>;
165
- summary: string | undefined;
166
- description: string | undefined;
167
- tags: string[] | undefined;
168
- handler: (context: Omit<PluginEndpointContext, "ctx">) => Promise<unknown>;
169
- }[];
170
- //#endregion
171
- //#region src/db/sqlite.d.ts
172
- interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
173
- /** Database file path or ':memory:' (default: ':memory:') */
174
- path?: string;
175
- /** Alias for path */
176
- filename?: string;
177
- /** Whether to enable WAL journal mode for file-based DBs (default: true) */
178
- wal?: boolean;
179
- /** Whether to enforce foreign key constraints (default: true) */
180
- foreignKeys?: boolean;
181
- /** Optional existing bun:sqlite Database instance */
182
- client?: Database;
183
- /** Optional Drizzle schema object for typed relational queries */
184
- schema?: TSchema;
185
- }
186
- type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> & {
187
- $client: Database;
188
- };
189
- /**
190
- * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
191
- * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
192
- *
193
- * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
194
- * other runtimes (e.g. Node) stays safe until this function is actually
195
- * called.
196
- */
197
- declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema>;
198
- //#endregion
199
- //#region src/secrets.d.ts
200
- /**
201
- * Type-safe secrets & environment variables.
202
- *
203
- * Declare each secret once at module scope instead of scattering untyped
204
- * `process.env.FOO` reads:
205
- *
206
- * const port = secret("PORT").default("3333").transform(Number).require();
207
- * const baseUrl = secret("BASE_URL").url().require();
208
- * const key = secret("STRIPE_KEY").validate((v) =>
209
- * v.startsWith("sk_") || "must start with sk_"
210
- * ).require();
211
- *
212
- * Values resolve from the environment (Bun populates `process.env` from
213
- * `.env` locally; in prod the same env source applies — a future
214
- * `SecretSource` such as AWS can slot in without touching call sites).
215
- *
216
- * Resolution order per secret: test/session override → source (`process.env`
217
- * by default) → declared `default`. `resolveSecrets()` validates every
218
- * registered secret at boot and throws listing all missing required ones.
219
- */
220
- interface SecretSource {
221
- get(name: string): string | undefined;
222
- }
223
- /** Default source: `process.env` (Bun loads `.env` into it automatically). */
224
- declare const envSource: SecretSource;
225
- interface SecretOptions {
226
- /** Fallback when the source has no value. Secrets without a default are required. */
227
- default?: string;
228
- }
229
- /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
230
- type SecretValidator<T> = (value: T) => void | boolean | string;
231
- declare class SecretRef<T = string> {
232
- readonly name: string;
233
- readonly options: SecretOptions;
234
- private transformFn?;
235
- private validators;
236
- constructor(name: string, options?: SecretOptions);
237
- /** True when a default was declared (i.e. the secret is optional). */
238
- get hasDefault(): boolean;
239
- /** Fallback used when the source has no value. Makes the secret optional. */
240
- default(value: string): this;
241
- /**
242
- * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
243
- * Runs before validators; a throwing transform fails resolution.
244
- */
245
- transform<U>(fn: (raw: string) => U): SecretRef<U>;
246
- /** Run a custom check on the (transformed) value at every resolution. */
247
- validate(fn: SecretValidator<T>): this;
248
- /** Shorthand validator: value must parse as a URL. String refs only. */
249
- url(this: SecretRef<string>): SecretRef<string>;
250
- private resolveRaw;
251
- private coerce;
252
- /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
253
- value(source?: SecretSource): T | undefined;
254
- /** Resolved value, or throws naming the missing/invalid secret. */
255
- require(source?: SecretSource): T;
256
- /** True when a value would resolve (override, source, or default). */
257
- isSet(source?: SecretSource): boolean;
258
- }
259
- /**
260
- * Declare a secret. Idempotent: re-declaring the same name returns the
261
- * original ref (first declaration wins) so module re-evaluation is safe.
262
- */
263
- declare function secret(name: string, options?: SecretOptions): SecretRef<string>;
264
- /**
265
- * Validate every registered secret at boot. Throws a single error listing
266
- * all missing required secrets. Returns the resolved values.
267
- */
268
- declare function resolveSecrets(opts?: {
269
- source?: SecretSource;
270
- }): Record<string, unknown>;
271
- /** Metadata for introspection (values never exposed — future dashboard use). */
272
- declare function listSecrets(opts?: {
273
- source?: SecretSource;
274
- }): Array<{
275
- name: string;
276
- hasDefault: boolean;
277
- isSet: boolean;
278
- }>;
279
- /** Test/session override for one secret (`undefined` clears the override). */
280
- declare function overrideSecret(name: string, value: string | undefined): void;
281
- /** Bulk overrides (test/session scoped). */
282
- declare function overrideSecrets(values: Record<string, string | undefined>): void;
283
- /** Clear registry and overrides. Test-only. */
284
- declare function resetSecrets(): void;
285
- //#endregion
286
- //#region src/db/postgres.d.ts
287
- interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
288
- /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
289
- client?: Sql;
290
- /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
291
- url?: string;
292
- /** Connection string alias */
293
- connectionString?: string;
294
- host?: string;
295
- port?: number;
296
- user?: string;
297
- password?: string;
298
- database?: string;
299
- ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
300
- max?: number;
301
- /**
302
- * Disable prepared statements (required for transaction-mode poolers such
303
- * as Supabase's Supavisor on :6543, which cannot hold named prepared
304
- * statements across transactions).
305
- */
306
- prepare?: boolean;
307
- /** Optional Drizzle schema for relational queries */
308
- schema?: TSchema;
309
- /** Custom schema name for Encore-style isolated schemas */
310
- schemaName?: string;
311
- }
312
- type PostgresDatabase<_TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
313
- interface DatabaseAdapter<TDb = any, TConfig = any> {
314
- createDatabase(config?: TConfig): TDb;
315
- }
316
- /**
317
- * Creates a PostgreSQL Drizzle instance using postgres-js.
318
- * Static imports (both are hard dependencies in package.json) so bundlers
319
- * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
320
- * `sqlite.ts` since it only exists under Bun.
321
- */
322
- declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
323
- //#endregion
324
- //#region src/db/define.d.ts
325
- type EnvInput<T> = T | SecretRef<T>;
326
- type EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>>; };
327
- interface DefinitionOptions<TSchema extends Record<string, unknown>> {
328
- name?: string;
329
- /** Drizzle tables retained for schema tooling. Never applied at runtime. */
330
- tables?: (TSchema & Record<string, Table>) | readonly Table[];
331
- schema?: TSchema;
332
- }
333
- type SQLiteDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
334
- engine?: "sqlite";
335
- client?: SQLiteDatabaseConfig<TSchema>["client"];
336
- url?: never;
337
- connectionString?: never;
338
- };
339
- type PostgresDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
340
- engine: "postgres";
341
- path?: never;
342
- filename?: never;
343
- wal?: never;
344
- foreignKeys?: never;
345
- client?: PostgresDatabaseConfig<TSchema>["client"];
346
- };
347
- type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
348
- interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
349
- readonly kind: "brick-database";
350
- readonly name?: string;
351
- readonly engine: "sqlite" | "postgres";
352
- readonly tables: Readonly<Record<string, Table>>;
353
- readonly schema: TSchema;
354
- getDb(): TDb;
355
- close?(): void | Promise<void>;
356
- }
357
- /**
358
- * Whether a value is a database handle made by `defineDatabase`.
359
- *
360
- * @param value - Anything.
361
- * @returns `true` for a handle, narrowing its type.
362
- */
363
- declare function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>;
364
- /**
365
- * Declare a service's database: its engine, its Drizzle tables, and how to
366
- * reach it. Nothing connects until the handle is used (`getDb()`), so defining
367
- * one has no side effects.
368
- *
369
- * SQLite is the default and needs no options. Pass `engine: "postgres"` with a
370
- * `url` for Postgres. Options that belong to the other engine (such as `url` for
371
- * SQLite, or `path` for Postgres) are refused.
372
- *
373
- * @param options - `engine` (`"sqlite"` or `"postgres"`), `tables`, an optional
374
- * `name`, and the engine's connection settings.
375
- * @returns A handle to give to `defineService({ database })`. `getDb()` returns
376
- * the Drizzle database.
377
- * @throws When the engine is unsupported, or an option does not suit the engine.
378
- * @example
379
- * import { defineDatabase } from "@brickkit/core";
380
- * import { sqliteTable, text } from "drizzle-orm/sqlite-core";
381
- *
382
- * const pages = sqliteTable("pages", {
383
- * id: text("id").primaryKey(),
384
- * title: text("title").notNull(),
385
- * });
386
- *
387
- * export const database = defineDatabase({ tables: { pages } });
388
- */
389
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
390
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
391
- $client: Sql;
392
- }, TSchema>;
393
- //#endregion
394
- //#region src/events/outbox.d.ts
395
- /** What the outbox rows are in, by state. */
396
- type OutboxStatus = "pending" | "claimed" | "delivered" | "dead";
397
- declare function sqliteOutbox(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
398
- name: string;
399
- schema: undefined;
400
- columns: {
401
- seq: import("drizzle-orm/sqlite-core").SQLiteColumn<{
402
- name: "seq";
403
- tableName: string;
404
- dataType: "number";
405
- columnType: "SQLiteInteger";
406
- data: number;
407
- driverParam: number;
408
- notNull: true;
409
- hasDefault: true;
410
- isPrimaryKey: true;
411
- isAutoincrement: false;
412
- hasRuntimeDefault: false;
413
- enumValues: undefined;
414
- baseColumn: never;
415
- identity: undefined;
416
- generated: undefined;
417
- }, {}, {}>;
418
- id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
419
- name: "id";
420
- tableName: string;
421
- dataType: "string";
422
- columnType: "SQLiteText";
423
- data: string;
424
- driverParam: string;
425
- notNull: true;
426
- hasDefault: false;
427
- isPrimaryKey: false;
428
- isAutoincrement: false;
429
- hasRuntimeDefault: false;
430
- enumValues: [string, ...string[]];
431
- baseColumn: never;
432
- identity: undefined;
433
- generated: undefined;
434
- }, {}, {
435
- length: number | undefined;
436
- }>;
437
- eventId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
438
- name: "event_id";
439
- tableName: string;
440
- dataType: "string";
441
- columnType: "SQLiteText";
442
- data: string;
443
- driverParam: string;
444
- notNull: true;
445
- hasDefault: false;
446
- isPrimaryKey: false;
447
- isAutoincrement: false;
448
- hasRuntimeDefault: false;
449
- enumValues: [string, ...string[]];
450
- baseColumn: never;
451
- identity: undefined;
452
- generated: undefined;
453
- }, {}, {
454
- length: number | undefined;
455
- }>;
456
- listener: import("drizzle-orm/sqlite-core").SQLiteColumn<{
457
- name: "listener";
458
- tableName: string;
459
- dataType: "string";
460
- columnType: "SQLiteText";
461
- data: string;
462
- driverParam: string;
463
- notNull: true;
464
- hasDefault: false;
465
- isPrimaryKey: false;
466
- isAutoincrement: false;
467
- hasRuntimeDefault: false;
468
- enumValues: [string, ...string[]];
469
- baseColumn: never;
470
- identity: undefined;
471
- generated: undefined;
472
- }, {}, {
473
- length: number | undefined;
474
- }>;
475
- name: import("drizzle-orm/sqlite-core").SQLiteColumn<{
476
- name: "name";
477
- tableName: string;
478
- dataType: "string";
479
- columnType: "SQLiteText";
480
- data: string;
481
- driverParam: string;
482
- notNull: true;
483
- hasDefault: false;
484
- isPrimaryKey: false;
485
- isAutoincrement: false;
486
- hasRuntimeDefault: false;
487
- enumValues: [string, ...string[]];
488
- baseColumn: never;
489
- identity: undefined;
490
- generated: undefined;
491
- }, {}, {
492
- length: number | undefined;
493
- }>;
494
- payload: import("drizzle-orm/sqlite-core").SQLiteColumn<{
495
- name: "payload";
496
- tableName: string;
497
- dataType: "json";
498
- columnType: "SQLiteTextJson";
499
- data: unknown;
500
- driverParam: string;
501
- notNull: true;
502
- hasDefault: false;
503
- isPrimaryKey: false;
504
- isAutoincrement: false;
505
- hasRuntimeDefault: false;
506
- enumValues: undefined;
507
- baseColumn: never;
508
- identity: undefined;
509
- generated: undefined;
510
- }, {}, {}>;
511
- traceId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
512
- name: "trace_id";
513
- tableName: string;
514
- dataType: "string";
515
- columnType: "SQLiteText";
516
- data: string;
517
- driverParam: string;
518
- notNull: false;
519
- hasDefault: false;
520
- isPrimaryKey: false;
521
- isAutoincrement: false;
522
- hasRuntimeDefault: false;
523
- enumValues: [string, ...string[]];
524
- baseColumn: never;
525
- identity: undefined;
526
- generated: undefined;
527
- }, {}, {
528
- length: number | undefined;
529
- }>;
530
- source: import("drizzle-orm/sqlite-core").SQLiteColumn<{
531
- name: "source";
532
- tableName: string;
533
- dataType: "string";
534
- columnType: "SQLiteText";
535
- data: string;
536
- driverParam: string;
537
- notNull: false;
538
- hasDefault: false;
539
- isPrimaryKey: false;
540
- isAutoincrement: false;
541
- hasRuntimeDefault: false;
542
- enumValues: [string, ...string[]];
543
- baseColumn: never;
544
- identity: undefined;
545
- generated: undefined;
546
- }, {}, {
547
- length: number | undefined;
548
- }>;
549
- occurredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
550
- name: string;
551
- tableName: string;
552
- dataType: "date";
553
- columnType: "SQLiteTimestamp";
554
- data: Date;
555
- driverParam: number;
556
- notNull: true;
557
- hasDefault: false;
558
- isPrimaryKey: false;
559
- isAutoincrement: false;
560
- hasRuntimeDefault: false;
561
- enumValues: undefined;
562
- baseColumn: never;
563
- identity: undefined;
564
- generated: undefined;
565
- }, {}, {}>;
566
- status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
567
- name: "status";
568
- tableName: string;
569
- dataType: "string";
570
- columnType: "SQLiteText";
571
- data: OutboxStatus;
572
- driverParam: string;
573
- notNull: true;
574
- hasDefault: false;
575
- isPrimaryKey: false;
576
- isAutoincrement: false;
577
- hasRuntimeDefault: false;
578
- enumValues: [string, ...string[]];
579
- baseColumn: never;
580
- identity: undefined;
581
- generated: undefined;
582
- }, {}, {
583
- length: number | undefined;
584
- $type: OutboxStatus;
585
- }>;
586
- attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
587
- name: "attempts";
588
- tableName: string;
589
- dataType: "number";
590
- columnType: "SQLiteInteger";
591
- data: number;
592
- driverParam: number;
593
- notNull: true;
594
- hasDefault: true;
595
- isPrimaryKey: false;
596
- isAutoincrement: false;
597
- hasRuntimeDefault: false;
598
- enumValues: undefined;
599
- baseColumn: never;
600
- identity: undefined;
601
- generated: undefined;
602
- }, {}, {}>;
603
- lastError: import("drizzle-orm/sqlite-core").SQLiteColumn<{
604
- name: "last_error";
605
- tableName: string;
606
- dataType: "string";
607
- columnType: "SQLiteText";
608
- data: string;
609
- driverParam: string;
610
- notNull: false;
611
- hasDefault: false;
612
- isPrimaryKey: false;
613
- isAutoincrement: false;
614
- hasRuntimeDefault: false;
615
- enumValues: [string, ...string[]];
616
- baseColumn: never;
617
- identity: undefined;
618
- generated: undefined;
619
- }, {}, {
620
- length: number | undefined;
621
- }>;
622
- availableAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
623
- name: string;
624
- tableName: string;
625
- dataType: "date";
626
- columnType: "SQLiteTimestamp";
627
- data: Date;
628
- driverParam: number;
629
- notNull: true;
630
- hasDefault: false;
631
- isPrimaryKey: false;
632
- isAutoincrement: false;
633
- hasRuntimeDefault: false;
634
- enumValues: undefined;
635
- baseColumn: never;
636
- identity: undefined;
637
- generated: undefined;
638
- }, {}, {}>;
639
- claimedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
640
- name: string;
641
- tableName: string;
642
- dataType: "date";
643
- columnType: "SQLiteTimestamp";
644
- data: Date;
645
- driverParam: number;
646
- notNull: false;
647
- hasDefault: false;
648
- isPrimaryKey: false;
649
- isAutoincrement: false;
650
- hasRuntimeDefault: false;
651
- enumValues: undefined;
652
- baseColumn: never;
653
- identity: undefined;
654
- generated: undefined;
655
- }, {}, {}>;
656
- deliveredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
657
- name: string;
658
- tableName: string;
659
- dataType: "date";
660
- columnType: "SQLiteTimestamp";
661
- data: Date;
662
- driverParam: number;
663
- notNull: false;
664
- hasDefault: false;
665
- isPrimaryKey: false;
666
- isAutoincrement: false;
667
- hasRuntimeDefault: false;
668
- enumValues: undefined;
669
- baseColumn: never;
670
- identity: undefined;
671
- generated: undefined;
672
- }, {}, {}>;
673
- };
674
- dialect: "sqlite";
675
- }>;
676
- declare function postgresOutbox(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
677
- name: string;
678
- schema: undefined;
679
- columns: {
680
- seq: import("drizzle-orm/pg-core").PgColumn<{
681
- name: "seq";
682
- tableName: string;
683
- dataType: "number";
684
- columnType: "PgBigSerial53";
685
- data: number;
686
- driverParam: number;
687
- notNull: true;
688
- hasDefault: true;
689
- isPrimaryKey: true;
690
- isAutoincrement: false;
691
- hasRuntimeDefault: false;
692
- enumValues: undefined;
693
- baseColumn: never;
694
- identity: undefined;
695
- generated: undefined;
696
- }, {}, {}>;
697
- id: import("drizzle-orm/pg-core").PgColumn<{
698
- name: "id";
699
- tableName: string;
700
- dataType: "string";
701
- columnType: "PgText";
702
- data: string;
703
- driverParam: string;
704
- notNull: true;
705
- hasDefault: false;
706
- isPrimaryKey: false;
707
- isAutoincrement: false;
708
- hasRuntimeDefault: false;
709
- enumValues: [string, ...string[]];
710
- baseColumn: never;
711
- identity: undefined;
712
- generated: undefined;
713
- }, {}, {}>;
714
- eventId: import("drizzle-orm/pg-core").PgColumn<{
715
- name: "event_id";
716
- tableName: string;
717
- dataType: "string";
718
- columnType: "PgText";
719
- data: string;
720
- driverParam: string;
721
- notNull: true;
722
- hasDefault: false;
723
- isPrimaryKey: false;
724
- isAutoincrement: false;
725
- hasRuntimeDefault: false;
726
- enumValues: [string, ...string[]];
727
- baseColumn: never;
728
- identity: undefined;
729
- generated: undefined;
730
- }, {}, {}>;
731
- listener: import("drizzle-orm/pg-core").PgColumn<{
732
- name: "listener";
733
- tableName: string;
734
- dataType: "string";
735
- columnType: "PgText";
736
- data: string;
737
- driverParam: string;
738
- notNull: true;
739
- hasDefault: false;
740
- isPrimaryKey: false;
741
- isAutoincrement: false;
742
- hasRuntimeDefault: false;
743
- enumValues: [string, ...string[]];
744
- baseColumn: never;
745
- identity: undefined;
746
- generated: undefined;
747
- }, {}, {}>;
748
- name: import("drizzle-orm/pg-core").PgColumn<{
749
- name: "name";
750
- tableName: string;
751
- dataType: "string";
752
- columnType: "PgText";
753
- data: string;
754
- driverParam: string;
755
- notNull: true;
756
- hasDefault: false;
757
- isPrimaryKey: false;
758
- isAutoincrement: false;
759
- hasRuntimeDefault: false;
760
- enumValues: [string, ...string[]];
761
- baseColumn: never;
762
- identity: undefined;
763
- generated: undefined;
764
- }, {}, {}>;
765
- payload: import("drizzle-orm/pg-core").PgColumn<{
766
- name: "payload";
767
- tableName: string;
768
- dataType: "json";
769
- columnType: "PgJsonb";
770
- data: unknown;
771
- driverParam: unknown;
772
- notNull: true;
773
- hasDefault: false;
774
- isPrimaryKey: false;
775
- isAutoincrement: false;
776
- hasRuntimeDefault: false;
777
- enumValues: undefined;
778
- baseColumn: never;
779
- identity: undefined;
780
- generated: undefined;
781
- }, {}, {}>;
782
- traceId: import("drizzle-orm/pg-core").PgColumn<{
783
- name: "trace_id";
784
- tableName: string;
785
- dataType: "string";
786
- columnType: "PgText";
787
- data: string;
788
- driverParam: string;
789
- notNull: false;
790
- hasDefault: false;
791
- isPrimaryKey: false;
792
- isAutoincrement: false;
793
- hasRuntimeDefault: false;
794
- enumValues: [string, ...string[]];
795
- baseColumn: never;
796
- identity: undefined;
797
- generated: undefined;
798
- }, {}, {}>;
799
- source: import("drizzle-orm/pg-core").PgColumn<{
800
- name: "source";
801
- tableName: string;
802
- dataType: "string";
803
- columnType: "PgText";
804
- data: string;
805
- driverParam: string;
806
- notNull: false;
807
- hasDefault: false;
808
- isPrimaryKey: false;
809
- isAutoincrement: false;
810
- hasRuntimeDefault: false;
811
- enumValues: [string, ...string[]];
812
- baseColumn: never;
813
- identity: undefined;
814
- generated: undefined;
815
- }, {}, {}>;
816
- occurredAt: import("drizzle-orm/pg-core").PgColumn<{
817
- name: string;
818
- tableName: string;
819
- dataType: "date";
820
- columnType: "PgTimestamp";
821
- data: Date;
822
- driverParam: string;
823
- notNull: true;
824
- hasDefault: false;
825
- isPrimaryKey: false;
826
- isAutoincrement: false;
827
- hasRuntimeDefault: false;
828
- enumValues: undefined;
829
- baseColumn: never;
830
- identity: undefined;
831
- generated: undefined;
832
- }, {}, {}>;
833
- status: import("drizzle-orm/pg-core").PgColumn<{
834
- name: "status";
835
- tableName: string;
836
- dataType: "string";
837
- columnType: "PgText";
838
- data: OutboxStatus;
839
- driverParam: string;
840
- notNull: true;
841
- hasDefault: false;
842
- isPrimaryKey: false;
843
- isAutoincrement: false;
844
- hasRuntimeDefault: false;
845
- enumValues: [string, ...string[]];
846
- baseColumn: never;
847
- identity: undefined;
848
- generated: undefined;
849
- }, {}, {
850
- $type: OutboxStatus;
851
- }>;
852
- attempts: import("drizzle-orm/pg-core").PgColumn<{
853
- name: "attempts";
854
- tableName: string;
855
- dataType: "number";
856
- columnType: "PgInteger";
857
- data: number;
858
- driverParam: string | number;
859
- notNull: true;
860
- hasDefault: true;
861
- isPrimaryKey: false;
862
- isAutoincrement: false;
863
- hasRuntimeDefault: false;
864
- enumValues: undefined;
865
- baseColumn: never;
866
- identity: undefined;
867
- generated: undefined;
868
- }, {}, {}>;
869
- lastError: import("drizzle-orm/pg-core").PgColumn<{
870
- name: "last_error";
871
- tableName: string;
872
- dataType: "string";
873
- columnType: "PgText";
874
- data: string;
875
- driverParam: string;
876
- notNull: false;
877
- hasDefault: false;
878
- isPrimaryKey: false;
879
- isAutoincrement: false;
880
- hasRuntimeDefault: false;
881
- enumValues: [string, ...string[]];
882
- baseColumn: never;
883
- identity: undefined;
884
- generated: undefined;
885
- }, {}, {}>;
886
- availableAt: import("drizzle-orm/pg-core").PgColumn<{
887
- name: string;
888
- tableName: string;
889
- dataType: "date";
890
- columnType: "PgTimestamp";
891
- data: Date;
892
- driverParam: string;
893
- notNull: true;
894
- hasDefault: false;
895
- isPrimaryKey: false;
896
- isAutoincrement: false;
897
- hasRuntimeDefault: false;
898
- enumValues: undefined;
899
- baseColumn: never;
900
- identity: undefined;
901
- generated: undefined;
902
- }, {}, {}>;
903
- claimedAt: import("drizzle-orm/pg-core").PgColumn<{
904
- name: string;
905
- tableName: string;
906
- dataType: "date";
907
- columnType: "PgTimestamp";
908
- data: Date;
909
- driverParam: string;
910
- notNull: false;
911
- hasDefault: false;
912
- isPrimaryKey: false;
913
- isAutoincrement: false;
914
- hasRuntimeDefault: false;
915
- enumValues: undefined;
916
- baseColumn: never;
917
- identity: undefined;
918
- generated: undefined;
919
- }, {}, {}>;
920
- deliveredAt: import("drizzle-orm/pg-core").PgColumn<{
921
- name: string;
922
- tableName: string;
923
- dataType: "date";
924
- columnType: "PgTimestamp";
925
- data: Date;
926
- driverParam: string;
927
- notNull: false;
928
- hasDefault: false;
929
- isPrimaryKey: false;
930
- isAutoincrement: false;
931
- hasRuntimeDefault: false;
932
- enumValues: undefined;
933
- baseColumn: never;
934
- identity: undefined;
935
- generated: undefined;
936
- }, {}, {}>;
937
- };
938
- dialect: "pg";
939
- }>;
940
- /** The outbox table of a SQLite database. */
941
- type SQLiteOutboxTable = ReturnType<typeof sqliteOutbox>;
942
- /** The outbox table of a Postgres database. */
943
- type PostgresOutboxTable = ReturnType<typeof postgresOutbox>;
944
- /** An outbox table, made by `outboxTable`. */
945
- type OutboxTable = SQLiteOutboxTable | PostgresOutboxTable;
946
- /**
947
- * The outbox table: where recorded events wait, one row per listener, until they
948
- * are delivered. A write and the events it causes are inserted in one transaction,
949
- * so an event is neither lost when the process dies after the write nor sent for a
950
- * write that was rolled back.
951
- *
952
- * Brick does not create tables for you. Put this in the schema of the database
953
- * whose writes emit events, and your migration tool (such as drizzle-kit) creates
954
- * it. A service whose database holds the table records events; one without it does
955
- * not.
956
- *
957
- * @param engine - The database engine, `"sqlite"` or `"postgres"`.
958
- * @param options - `name` to call the table something other than `brick_outbox`.
959
- * @returns A Drizzle table.
960
- * @example
961
- * import { defineDatabase, outboxTable } from "@brickkit/core";
962
- *
963
- * export const outbox = outboxTable("postgres");
964
- * export const database = defineDatabase({
965
- * engine: "postgres",
966
- * tables: { users, outbox },
967
- * });
968
- */
969
- declare function outboxTable(engine: "sqlite", options?: {
970
- name?: string;
971
- }): SQLiteOutboxTable;
972
- declare function outboxTable(engine: "postgres", options?: {
973
- name?: string;
974
- }): PostgresOutboxTable;
975
- /**
976
- * Whether a value is an outbox table made by `outboxTable`.
977
- *
978
- * @param value - Anything.
979
- * @returns `true` for an outbox table, narrowing its type.
980
- */
981
- declare function isOutboxTable(value: unknown): value is OutboxTable;
982
- //#endregion
983
- //#region src/events/types.d.ts
984
- /**
985
- * An event, as it was recorded. It is the same for every listener of it.
986
- */
987
- interface EventEnvelope<TPayload = unknown> {
988
- /** Unique per event. Every listener's delivery of the event shares it. */
989
- id: string;
990
- /** The event name, such as `user.create`. */
991
- name: string;
992
- /** What happened. JSON data. */
993
- payload: TPayload;
994
- /** When it happened, as an ISO timestamp. */
995
- occurredAt: string;
996
- /** The trace of the request that caused it, so a listener continues the same trace. */
997
- traceId?: string;
998
- /** What emitted it, such as `identity.user` for a generated CRUD write. */
999
- source?: string;
1000
- }
1001
- /**
1002
- * One listener's delivery of an event: the envelope, plus which listener it is for
1003
- * and which attempt this is.
1004
- */
1005
- interface EventDelivery<TPayload = unknown> extends EventEnvelope<TPayload> {
1006
- /** The name of the listener this delivery is for. */
1007
- listener: string;
1008
- /**
1009
- * `<event id>:<listener>`. It is the same on every retry, so a listener can use
1010
- * it to avoid doing the work twice: delivery is at least once.
1011
- */
1012
- deliveryId: string;
1013
- /** 1 on the first try, 2 on the first retry, and so on. */
1014
- attempt: number;
1015
- }
1016
- /**
1017
- * The CRUD events of a resource called `user`, by operation. Listeners of
1018
- * `user.create`, `user.update` and `user.delete` receive these payloads.
1019
- */
1020
- type CrudEventPayload<TRow = Record<string, unknown>> = {
1021
- id: unknown;
1022
- row: TRow;
1023
- } | {
1024
- id: unknown;
1025
- before: TRow;
1026
- after: TRow;
1027
- };
1028
- /**
1029
- * A listener: code that runs when an event it listens for has been recorded.
1030
- */
1031
- interface EventListener<TPayload = any> {
1032
- /** Unique among the app's listeners. It is part of each delivery's id. */
1033
- readonly name: string;
1034
- /**
1035
- * The event names to listen for. A trailing `*` matches a prefix (`user.*`),
1036
- * and `*` alone matches every event.
1037
- */
1038
- readonly on: readonly string[];
1039
- /**
1040
- * A handler that runs in the dispatching process for each delivery. Throwing
1041
- * retries the delivery with a growing delay. A listener has this or `workflow`.
1042
- */
1043
- readonly run?: (delivery: EventDelivery<TPayload>) => void | Promise<void>;
1044
- /**
1045
- * A durable workflow that runs for each delivery, on the app's `events.world`.
1046
- * The delivery counts as done once its run has started; the workflow retries
1047
- * its own steps from there. A listener has this or `run`.
1048
- */
1049
- readonly workflow?: EventWorkflow<TPayload>;
1050
- /** Attempts before the delivery is parked as dead. Defaults to the dispatcher's. */
1051
- readonly maxAttempts?: number;
1052
- }
1053
- /**
1054
- * What a workflow listener's workflow receives: the event and which listener it
1055
- * is for. It has no `attempt`, because one delivery starts one run however many
1056
- * times it is tried.
1057
- */
1058
- type WorkflowEvent<TPayload = any> = Omit<EventDelivery<TPayload>, "attempt">;
1059
- /**
1060
- * A function marked `"use workflow"`, run once per delivery of the listener it is
1061
- * given to.
1062
- */
1063
- type EventWorkflow<TPayload = any> = (event: WorkflowEvent<TPayload>) => Promise<unknown>;
1064
- /**
1065
- * The world workflow listeners run on: the queue and storage behind the Workflow
1066
- * SDK. `createWorld()` from `@brickkit/redis-world` or `@brickkit/bullmq-world`
1067
- * makes one. Brick starts it with the app's events and closes it when they stop.
1068
- */
1069
- interface EventsWorld {
1070
- /**
1071
- * Names a run after its key so that starting it twice makes one run. A world
1072
- * without it would start a second run when an event is delivered again, so
1073
- * Brick refuses such a world.
1074
- */
1075
- createRunId?(options?: Readonly<Record<string, unknown>>): string;
1076
- start?(): Promise<void>;
1077
- close?(): Promise<void>;
1078
- registerHandler?(prefix: any, handler: (request: Request) => Promise<Response>): void;
1079
- }
1080
- /**
1081
- * Where the workflows of an app are built from. The CLI (`brick dev`,
1082
- * `brick start`) writes the bundle to `<root>/.well-known/workflow/v1` before
1083
- * events start, and events read it from there.
1084
- */
1085
- interface WorkflowsOptions {
1086
- /** The project root: where the Workflow SDK is installed. Default: the working directory. */
1087
- root?: string;
1088
- }
1089
- /**
1090
- * How the dispatcher delivers recorded events.
1091
- */
1092
- interface DispatchOptions {
1093
- /**
1094
- * Whether to look for due deliveries on a timer, and right after a commit.
1095
- * Default `true`. With `false`, deliveries run only when something calls
1096
- * `app.events.drain()`: a cron job, a worker you drive yourself, or a test.
1097
- */
1098
- timer?: boolean;
1099
- /** How often to look for deliveries that are due, in milliseconds. Default 1000. */
1100
- intervalMs?: number;
1101
- /** Most deliveries claimed at once. Default 50. */
1102
- batchSize?: number;
1103
- /** Attempts before a delivery is parked as dead. Default 8. */
1104
- maxAttempts?: number;
1105
- /** How long a claimed delivery may run before another dispatcher takes it, in milliseconds. Default 60000. */
1106
- claimTimeoutMs?: number;
1107
- /** Longest wait before a retry, in milliseconds. Default 300000. */
1108
- maxBackoffMs?: number;
1109
- /** How long delivered rows are kept, in milliseconds. Default 86400000 (one day). 0 keeps none. */
1110
- retainDeliveredMs?: number;
1111
- }
1112
- /**
1113
- * The `events` option of `brick()`.
1114
- */
1115
- interface EventsOptions {
1116
- /** The listeners of the app. */
1117
- listeners?: readonly EventListener[];
1118
- /**
1119
- * Whether this process delivers recorded events. `true` (the default) starts a
1120
- * dispatcher with the default settings, an object tunes it, and `false` only
1121
- * records events, for an app whose events are delivered by another process.
1122
- */
1123
- dispatch?: boolean | DispatchOptions;
1124
- /**
1125
- * The world that runs `workflow` listeners. Required when any listener has one.
1126
- * Brick starts it when the app's events start and closes it when they stop.
1127
- */
1128
- world?: EventsWorld;
1129
- /** Where the workflow bundle lives. Only used with workflow listeners. */
1130
- workflows?: WorkflowsOptions;
1131
- }
1132
- /**
1133
- * Records an event inside the transaction it was given. The event is committed
1134
- * with the write, or not at all.
1135
- */
1136
- type EventRecorder = (name: string, payload: unknown) => Promise<void>;
1137
- /**
1138
- * What a service with events offers the code that writes to its database. A
1139
- * service has it once `brick({ events })` is set up and its database holds an
1140
- * outbox table.
1141
- */
1142
- interface ServiceEvents {
1143
- /** Whether any listener wants the event, so a write can skip recording one. */
1144
- wants(name: string): boolean;
1145
- /**
1146
- * Run `fn` in a database transaction. Events it records are committed with
1147
- * whatever else it wrote, or not at all, and are delivered after the commit.
1148
- */
1149
- transaction<T>(db: unknown, context: {
1150
- traceId?: string;
1151
- source?: string;
1152
- }, fn: (tx: any, record: EventRecorder) => Promise<T>): Promise<T>;
1153
- /**
1154
- * Record an event in a transaction the caller already has open. It is
1155
- * committed with that transaction. Nothing tells Brick when the caller commits,
1156
- * so delivery waits for the dispatcher's next poll.
1157
- */
1158
- record(tx: unknown, context: {
1159
- traceId?: string;
1160
- source?: string;
1161
- }, name: string, payload: unknown): Promise<void>;
1162
- }
1163
- //#endregion
1164
- //#region src/events/dispatcher.d.ts
1165
- /** How many outbox rows are in each state. */
1166
- type OutboxCounts = Record<OutboxStatus, number>;
1167
- /**
1168
- * Delivers the events recorded in one outbox table to the app's listeners.
1169
- *
1170
- * It claims a batch of due rows, runs each listener, and marks the row delivered.
1171
- * A listener that throws is retried later with a growing delay, and parked as
1172
- * dead after its attempts run out. Several dispatchers can share a table: on
1173
- * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
1174
- * finished within `claimTimeoutMs` (the process died) is taken by another.
1175
- * Delivery is at least once, so a listener should tolerate running twice for the
1176
- * same `deliveryId`.
1177
- */
1178
- declare class Dispatcher {
1179
- private readonly db;
1180
- private readonly table;
1181
- private readonly listeners;
1182
- private readonly onError;
1183
- private readonly engine;
1184
- private readonly options;
1185
- private readonly inFlight;
1186
- private timer?;
1187
- private tickQueue?;
1188
- private lastPurge;
1189
- constructor(db: any, table: OutboxTable, listeners: (name: string) => Deliverable | undefined, options?: DispatchOptions, onError?: (error: unknown) => void);
1190
- /** Whether the dispatcher is looking for work on a timer. */
1191
- get running(): boolean;
1192
- /** Start looking for due deliveries on a timer. Does nothing if it already is. */
1193
- start(): void;
1194
- /**
1195
- * Stop the timer and wait for the deliveries that are running to finish.
1196
- */
1197
- stop(): Promise<void>;
1198
- /** Look for work soon, without waiting for the timer. Safe to call often. */
1199
- notify(): void;
1200
- /**
1201
- * Claim what is due and run it, once. Used by the timer, and by tests and
1202
- * workers that drive delivery themselves.
1203
- *
1204
- * @returns How many deliveries it started.
1205
- */
1206
- tick(): Promise<number>;
1207
- /**
1208
- * Deliver everything that is due now and wait until those deliveries are done.
1209
- * Deliveries that fail and are rescheduled are not waited for again.
1210
- *
1211
- * @returns How many deliveries it ran.
1212
- */
1213
- drain(): Promise<number>;
1214
- /**
1215
- * How many rows are in each state.
1216
- */
1217
- counts(): Promise<OutboxCounts>;
1218
- /**
1219
- * Put parked deliveries back in line, with their attempts reset.
1220
- *
1221
- * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
1222
- * @returns How many deliveries were put back.
1223
- */
1224
- retryDead(deliveryId?: string): Promise<number>;
1225
- private claimAndRun;
1226
- private claim;
1227
- private deliver;
1228
- private markDelivered;
1229
- private fail;
1230
- private park;
1231
- private purgeDelivered;
1232
- }
1233
- //#endregion
1234
- //#region src/events/hub.d.ts
1235
- interface EventsHost {
1236
- readonly name: string;
1237
- getDb(): unknown;
1238
- getOutbox?(): OutboxTable | undefined;
1239
- setEvents?(events: ServiceEvents | undefined): void;
1240
- }
1241
- /**
1242
- * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1243
- * and wait for their deliveries. A hub that fails to stop does not cut the wait
1244
- * for the others: the first failure is thrown once every hub is done.
1245
- */
1246
- declare function stopAllEvents(): Promise<void>;
1247
- /**
1248
- * What an app's `events` option describes, as plain data. It goes in the app
1249
- * definition, which is sent to the dev dashboard, so it holds no functions.
1250
- */
1251
- interface EventsDefinition {
1252
- listeners: {
1253
- name: string;
1254
- on: string[];
1255
- kind: "handler" | "workflow";
1256
- }[];
1257
- dispatch: boolean;
1258
- /** Names of the services whose writes record events. */
1259
- recorders: string[];
1260
- }
1261
- /** What the dispatcher runs for a delivery. */
1262
- interface Deliverable {
1263
- readonly maxAttempts?: number;
1264
- run(delivery: EventDelivery): void | Promise<void>;
1265
- }
1266
- /**
1267
- * The events of one app: who listens, where events are recorded, and the
1268
- * dispatchers that deliver them. `brick({ events })` makes one and puts it on
1269
- * `app.events`.
1270
- */
1271
- declare class EventsHub {
1272
- private readonly byName;
1273
- private readonly dispatchers;
1274
- private readonly deliverables;
1275
- private readonly dispatchOptions;
1276
- private readonly runtime;
1277
- private readonly recorderNames;
1278
- private started;
1279
- private stopping;
1280
- constructor(options: EventsOptions);
1281
- /**
1282
- * Give each service whose database holds an outbox table a recorder, and a
1283
- * dispatcher for that table. Call it before the first request: a service has no
1284
- * recorder until then.
1285
- *
1286
- * @param services - The app's services.
1287
- * @returns The hub, for chaining.
1288
- */
1289
- attach(services: readonly EventsHost[]): this;
1290
- /** The listeners that want an event. */
1291
- matching(name: string): EventListener[];
1292
- /** The listeners and settings, as plain data. */
1293
- describe(): EventsDefinition;
1294
- /**
1295
- * Where the workflow bundle is read from, the project it is built from, and
1296
- * the world the workflows run on. Only set when a listener runs a workflow.
1297
- * The CLI builds the bundle there before events start, and shows the world's
1298
- * runs in the dev dashboard.
1299
- */
1300
- get workflows(): {
1301
- root: string;
1302
- dir: string;
1303
- world: EventsWorld;
1304
- } | undefined;
1305
- /**
1306
- * Resume the workflow that waits on a webhook. The server mounts this on the
1307
- * route the Workflow SDK puts in webhook URLs.
1308
- */
1309
- webhook(request: Request): Promise<Response>;
1310
- /**
1311
- * Start delivering recorded events from this process, and start the world that
1312
- * runs workflow listeners. Does nothing if this process only records events
1313
- * (`dispatch: false`), already started, or a stop is still waiting.
1314
- */
1315
- start(): void;
1316
- /**
1317
- * Stop delivering, wait for the deliveries that are running, and close the
1318
- * world. A world cannot be started again, so workflow listeners stop for good.
1319
- * A stop that arrives while another runs waits for that one.
1320
- */
1321
- stop(): Promise<void>;
1322
- private shutDown;
1323
- /**
1324
- * Deliver everything that is due now and wait for it. For tests and for
1325
- * workers that drive delivery themselves.
1326
- *
1327
- * @returns How many deliveries ran.
1328
- */
1329
- drain(): Promise<number>;
1330
- /** How many rows are in each state, across the app's outbox tables. */
1331
- counts(): Promise<OutboxCounts>;
1332
- /**
1333
- * Put parked deliveries back in line.
1334
- *
1335
- * @param deliveryId - One delivery. Omit it to retry every dead one.
1336
- * @returns How many deliveries were put back.
1337
- */
1338
- retryDead(deliveryId?: string): Promise<number>;
1339
- private deliverable;
1340
- private bind;
1341
- }
1342
- //#endregion
1343
- //#region src/socket-types.d.ts
1344
- type SocketSchemas = Record<string, TSchema>;
1345
- type SocketPayloads<S extends SocketSchemas> = { [K in keyof S]: Static<S[K]>; };
1346
- type SocketEventArgs<Events> = { [K in keyof Events & string]: [event: K, payload: Events[K]]; }[keyof Events & string];
1347
- interface BrickSocketSender<Events> {
1348
- /** Locally accepts a message. Does not acknowledge remote delivery. */
1349
- send(...args: SocketEventArgs<Events>): void;
1350
- close(): void;
1351
- }
1352
- interface BrickSocketConfig<I extends SocketSchemas, O extends SocketSchemas, Ctx> {
1353
- name: string;
1354
- path?: string;
1355
- description?: string;
1356
- input: I;
1357
- output: O;
1358
- /** Defaults to the upgrade request's origin. */
1359
- allowedOrigins?: readonly string[];
1360
- allowMissingOrigin?: boolean;
1361
- authorize?: (params: {
1362
- ctx: Ctx;
1363
- }) => boolean | Promise<boolean>;
1364
- handlers: { [K in keyof I]: (params: {
1365
- input: Static<I[K]>;
1366
- ctx: Ctx;
1367
- socket: BrickSocketSender<SocketPayloads<O>>;
1368
- }) => void | Promise<void>; };
1369
- open?: (params: {
1370
- ctx: Ctx;
1371
- socket: BrickSocketSender<SocketPayloads<O>>;
1372
- }) => void | Promise<void>;
1373
- close?: (params: {
1374
- ctx: Ctx;
1375
- socket: BrickSocketSender<SocketPayloads<O>>;
1376
- code: number;
1377
- reason: string;
1378
- }) => void | Promise<void>;
1379
- }
1380
- interface BrickSocketConnectOptions {
1381
- signal?: AbortSignal;
1382
- timeoutMs?: number;
1383
- }
1384
- declare class BrickSocketError extends Error {
1385
- readonly kind: "connection" | "protocol" | "backpressure";
1386
- constructor(kind: "connection" | "protocol" | "backpressure", message: string, options?: ErrorOptions);
1387
- }
1388
- interface BrickSocketClient<Input, Output> extends BrickSocketSender<Input> {
1389
- readonly ready: Promise<void>;
1390
- on<K extends keyof Output & string>(event: K, listener: (payload: Output[K]) => void): () => void;
1391
- onError(listener: (error: BrickSocketError) => void): () => void;
1392
- onClose(listener: (info: {
1393
- code: number;
1394
- reason: string;
1395
- }) => void): () => void;
1396
- }
1397
- /** Browser metadata. Schemas retain TypeBox kinds as JSON-safe annotations. */
1398
- interface BrickClientSocket<Input = unknown, Output = unknown> {
1399
- kind: "socket";
1400
- name: string;
1401
- serviceName: string;
1402
- config: {
1403
- path: string;
1404
- };
1405
- output: Record<string, unknown>;
1406
- readonly __types?: {
1407
- input: Input;
1408
- output: Output;
1409
- };
1410
- }
1411
- interface BrickSocketSchema {
1412
- name: string;
1413
- path?: string;
1414
- description?: string;
1415
- input: string[];
1416
- output: string[];
1417
- hasAuthorize: boolean;
1418
- }
1419
- //#endregion
1420
- //#region src/socket.d.ts
1421
- interface SocketSender {
1422
- readonly isOpen: boolean;
1423
- send(event: string, payload: unknown): void;
1424
- close(): void;
1425
- }
1426
- interface SocketSession {
1427
- open(socket: SocketSender): Promise<void>;
1428
- message(event: string, data: unknown, socket: SocketSender): Promise<void>;
1429
- close(socket: SocketSender, code: number, reason: string): Promise<void>;
1430
- }
1431
- interface RegisteredSocket {
1432
- schema: BrickSocketSchema;
1433
- input: SocketSchemas;
1434
- output: SocketSchemas;
1435
- allowedOrigins?: readonly string[];
1436
- allowMissingOrigin?: boolean;
1437
- connect(request: Request): Promise<SocketSession>;
1438
- }
1439
- //#endregion
1440
- //#region src/types.d.ts
1441
- /**
1442
- * The logger on action, tool, and endpoint contexts. While a dashboard is on
1443
- * (`brick dev`, or `brick start` with the `dashboard` option) a line logged
1444
- * during a traced request appears in the dashboard with that request, instead
1445
- * of on the console (as does a plain `console.log`); anywhere else it prints
1446
- * to the console.
1447
- */
1448
- interface Logger {
1449
- info: (...args: any[]) => void;
1450
- warn: (...args: any[]) => void;
1451
- error: (...args: any[]) => void;
1452
- debug: (...args: any[]) => void;
1453
- }
1454
- /**
1455
- * Base framework context supplied to all service resolvers and action executions.
1456
- */
1457
- interface BaseContext<TDb = any> {
1458
- request: Request;
1459
- db: TDb;
1460
- logger: Logger;
1461
- traceId: string;
1462
- requestId?: string;
1463
- caller?: string;
1464
- tenantId?: string;
1465
- services?: Record<string, any>;
1466
- metadata?: Record<string, unknown>;
1467
- }
1468
- /**
1469
- * Default fallback service context for untyped or simple services.
1470
- */
1471
- interface DefaultServiceContext {
1472
- user?: any;
1473
- session?: any;
1474
- [key: string]: any;
1475
- }
1476
- /**
1477
- * The combined execution context: BaseContext & TServiceContext.
1478
- */
1479
- type ActionContext<TDb = any, TServiceContext = DefaultServiceContext> = BaseContext<TDb> & TServiceContext;
1480
- /**
1481
- * Type utility that automatically narrows ctx.user from User | null to User
1482
- * in execute() when authorize() is declared on the action.
1483
- */
1484
- type NarrowAuthorizedContext<TCtx> = TCtx extends {
1485
- user: infer U;
1486
- } ? [U] extends [null | undefined] ? TCtx : Omit<TCtx, "user"> & {
1487
- user: NonNullable<U>;
1488
- } : TCtx;
1489
- interface ActionErrorDefinition {
1490
- status?: number;
1491
- message: string;
1492
- }
1493
- interface ValidationErrorItem {
1494
- path: string;
1495
- message: string;
1496
- value?: unknown;
1497
- type?: number;
1498
- }
1499
- declare class ValidationError extends Error {
1500
- readonly code = "VALIDATION_FAILED";
1501
- readonly status: number;
1502
- readonly errors: ValidationErrorItem[];
1503
- constructor(message: string, errors?: ValidationErrorItem[], status?: number);
1504
- toJSON(): {
1505
- name: string;
1506
- code: string;
1507
- message: string;
1508
- status: number;
1509
- errors: ValidationErrorItem[];
1510
- };
1511
- }
1512
- declare class ActionExecutionError extends Error {
1513
- readonly code: string;
1514
- readonly status: number;
1515
- readonly details?: unknown;
1516
- constructor(code: string, message: string, status?: number, details?: unknown, options?: ErrorOptions);
1517
- toJSON(): {
1518
- name: string;
1519
- code: string;
1520
- message: string;
1521
- status: number;
1522
- details: unknown;
1523
- };
1524
- }
1525
- interface StandardErrorMap {
1526
- BAD_REQUEST: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1527
- UNAUTHORIZED: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1528
- FORBIDDEN: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1529
- NOT_FOUND: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1530
- CONFLICT: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1531
- INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
1532
- [key: string]: ((overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never) | undefined;
1533
- }
1534
- type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never; };
1535
- interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
1536
- name: string;
1537
- description?: string;
1538
- /** Effective HTTP path, including the prefix; replaces the default action path. */
1539
- path?: string;
1540
- /** Single HTTP method exposed for this action (default POST). */
1541
- method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1542
- input?: TInputSchema;
1543
- output?: TOutputSchema;
1544
- errors?: TErrors;
1545
- emits?: string[];
1546
- tags?: string[];
1547
- }
1548
- 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> {
1549
- authorize: (params: {
1550
- user?: TContext extends {
1551
- user: infer U;
1552
- } ? U : any;
1553
- input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
1554
- ctx: TContext;
1555
- }) => boolean | Promise<boolean>;
1556
- execute: (params: {
1557
- input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
1558
- ctx: NarrowAuthorizedContext<TContext>;
1559
- error: ErrorBuilder<TErrors>;
1560
- }) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
1561
- }
1562
- 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> {
1563
- authorize?: undefined;
1564
- execute: (params: {
1565
- input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
1566
- ctx: TContext;
1567
- error: ErrorBuilder<TErrors>;
1568
- }) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
1569
- }
1570
- 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>;
1571
- interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> {
1572
- (params: {
1573
- input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
1574
- ctx?: Partial<TContext>;
1575
- }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
1576
- name: string;
1577
- serviceName?: string;
1578
- /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
1579
- plugin?: string;
1580
- /** Owning resource name for resource-plugin actions (e.g. `page`). */
1581
- resource?: string;
1582
- config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
1583
- /**
1584
- * Optional runtime-only output schema. When present, `validateOutput` and
1585
- * HTTP output checking validate against it instead of `config.output`,
1586
- * while `config.output` remains the published contract (client types,
1587
- * OpenAPI). Lets projected/subset responses validate at runtime without
1588
- * leaking optionality into the generated contract.
1589
- */
1590
- outputValidationSchema?: TSchema;
1591
- run(input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
1592
- execute(params: {
1593
- input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
1594
- ctx?: Partial<TContext>;
1595
- }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
1596
- executeResolved?(params: {
1597
- input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
1598
- ctx: TContext;
1599
- }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
1600
- validateInput(input: unknown): {
1601
- success: true;
1602
- data: any;
1603
- } | {
1604
- success: false;
1605
- errors: ValidationErrorItem[];
1606
- };
1607
- validateOutput(output: unknown): {
1608
- success: true;
1609
- data: any;
1610
- } | {
1611
- success: false;
1612
- errors: ValidationErrorItem[];
1613
- };
1614
- errorHelpers?: ErrorBuilder<TErrors>;
1615
- }
1616
- /** MCP tool metadata, kept with the executable definition. */
1617
- interface ToolAnnotations {
1618
- title?: string;
1619
- readOnlyHint?: boolean;
1620
- destructiveHint?: boolean;
1621
- idempotentHint?: boolean;
1622
- openWorldHint?: boolean;
1623
- }
1624
- interface ToolOptions {
1625
- title?: string;
1626
- annotations?: ToolAnnotations;
1627
- /** Also register HTTP routes and OpenAPI. Defaults to false. */
1628
- http?: boolean;
1629
- }
1630
- 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;
1631
- 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;
1632
- 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> {
1633
- readonly kind: "tool";
1634
- config: ToolConfigWithAuthorize<I, O, E, C> | ToolConfigWithoutAuthorize<I, O, E, C>;
1635
- }
1636
- /** A resource declares identity and a table; plugins supply behavior. */
1637
- interface ResourceConfig<TTable = any, _TCtx = any> {
1638
- name: string;
1639
- table: TTable;
1640
- id?: import("drizzle-orm").Column;
1641
- }
1642
- type InferTableRow<TTable> = TTable extends {
1643
- $inferSelect: infer S;
1644
- } ? S : any;
1645
- type InferTableInsert<TTable> = TTable extends {
1646
- $inferInsert: infer S;
1647
- } ? S : any;
1648
- type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id">;
1649
- type PrimaryColumn<T> = T extends {
1650
- _: {
1651
- columns: infer C;
1652
- };
1653
- } ? { [K in keyof C]: C[K] extends {
1654
- _: {
1655
- isPrimaryKey: true;
1656
- };
1657
- } ? C[K] : never; }[keyof C] : import("drizzle-orm").Column;
1658
- type ResourceIdentity<T, O> = O & {
1659
- id: O extends {
1660
- id: infer I extends import("drizzle-orm").Column;
1661
- } ? I : PrimaryColumn<T>;
1662
- };
1663
- /** Generic preparation declarations consumed by the application compiler. */
1664
- interface PreparationContribution {
1665
- readonly name: string;
1666
- describe(): unknown;
1667
- prepare(): void;
1668
- }
1669
- interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}> {
1670
- use<P extends ResourcePlugin<Service<TCtx["db"], Omit<TCtx, keyof BaseContext>>, this, any>>(plugin: P): this & ResourcePluginAPI<P, TTable, TCtx, this>;
1671
- readonly name: string;
1672
- readonly serviceName: string;
1673
- readonly table: TTable;
1674
- readonly id: TOptions extends {
1675
- id: infer I extends import("drizzle-orm").Column;
1676
- } ? I : import("drizzle-orm").Column;
1677
- readonly idField: string;
1678
- readonly config: ResourceConfig<TTable, TCtx> & TOptions;
1679
- }
1680
- interface ServiceAuthOptions {
1681
- requireAuth?: boolean;
1682
- allowedRoles?: string[];
1683
- policy?: (ctx: ActionContext) => boolean | Promise<boolean>;
1684
- }
1685
- interface RateLimitOptions {
1686
- maxRequests: number;
1687
- window: number | string;
1688
- scope?: "ip" | "user" | "tenant";
1689
- }
1690
- interface CacheOptions {
1691
- driver?: "memory" | "redis";
1692
- defaultTtl?: number;
1693
- }
1694
- interface ResilienceOptions {
1695
- timeoutMs?: number;
1696
- retry?: {
1697
- attempts: number;
1698
- backoff: "linear" | "exponential";
1699
- delayMs: number;
1700
- };
1701
- circuitBreaker?: {
1702
- errorThresholdPercentage: number;
1703
- resetTimeoutMs: number;
1704
- };
1705
- }
1706
- interface TelemetryOptions {
1707
- traceQueries?: boolean;
1708
- auditLog?: boolean;
1709
- tags?: Record<string, string>;
1710
- }
1711
- interface LifecycleOptions {
1712
- onInit?: (ctx: {
1713
- db?: any;
1714
- logger?: Logger;
1715
- }) => Promise<void>;
1716
- onDestroy?: () => Promise<void>;
1717
- }
1718
- interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
1719
- database?: DatabaseHandle<TDb>;
1720
- context?: (baseCtx: BaseContext<TDb> & {
1721
- user?: unknown;
1722
- }) => Promise<TServiceContext> | TServiceContext;
1723
- auth?: ServiceAuthOptions;
1724
- rateLimit?: RateLimitOptions;
1725
- cache?: CacheOptions;
1726
- resilience?: ResilienceOptions;
1727
- telemetry?: TelemetryOptions;
1728
- lifecycle?: LifecycleOptions;
1729
- }
1730
- type ActionAccessPolicy = "public" | "authorized" | "scoped";
1731
- interface ActionSchema {
1732
- name: string;
1733
- /** Present only when this action has a registered HTTP route. */
1734
- method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1735
- path?: string;
1736
- serviceName?: string;
1737
- /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
1738
- plugin?: string;
1739
- /** Owning resource name for resource-plugin actions (e.g. `page`). */
1740
- resource?: string;
1741
- description?: string;
1742
- inputSchema?: unknown;
1743
- outputSchema?: unknown;
1744
- hasAuthorize: boolean;
1745
- hasScope?: boolean;
1746
- accessPolicy?: ActionAccessPolicy;
1747
- errors?: Record<string, ActionErrorDefinition>;
1748
- emits?: string[];
1749
- tags?: string[];
1750
- }
1751
- interface ServiceSchema {
1752
- name: string;
1753
- /** The service options as JSON: functions, such as `context` and hooks, are left out. */
1754
- options: Record<string, unknown>;
1755
- hasDatabase: boolean;
1756
- databaseConfig?: {
1757
- name?: string;
1758
- engine: "sqlite" | "postgres";
1759
- tables: string[];
1760
- };
1761
- actions: ActionSchema[];
1762
- sockets?: BrickSocketSchema[];
1763
- /** MCP tools. A tool with an HTTP route is also listed under `actions`. */
1764
- tools?: {
1765
- name: string;
1766
- }[];
1767
- resources?: {
1768
- name: string;
1769
- }[];
1770
- }
1771
- interface ArchitectureSchema {
1772
- version: string;
1773
- services: ServiceSchema[];
1774
- /** Present when the app has an `events` option. */
1775
- events?: EventsDefinition;
1776
- }
1777
- interface CompiledRoutePlan {
1778
- service: Service<any, any>;
1779
- action: Action<any, any, any, any>;
1780
- actionName: string;
1781
- serviceName: string;
1782
- routePath: string;
1783
- method?: string;
1784
- isGetLike: boolean;
1785
- hasInput: boolean;
1786
- hasContextHook: boolean;
1787
- contextHook?: (baseCtx: any) => Promise<any> | any;
1788
- hasAuthorize: boolean;
1789
- authorize?: (params: any) => boolean | Promise<boolean>;
1790
- execute: (params: any) => Promise<any> | any;
1791
- inputChecker?: {
1792
- Check: (val: any) => boolean;
1793
- Errors: (val: any) => Iterable<any>;
1794
- };
1795
- outputChecker?: {
1796
- Check: (val: any) => boolean;
1797
- Errors: (val: any) => Iterable<any>;
1798
- };
1799
- coercions?: Array<{
1800
- key: string;
1801
- isNumber: boolean;
1802
- isBoolean: boolean;
1803
- isArray?: boolean;
1804
- }>;
1805
- logger: Logger;
1806
- errorBuilder: any;
1807
- cachedDb: any;
1808
- }
1809
- interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> {
1810
- readonly name: string;
1811
- readonly options: ServiceOptions<TServiceContext, TDb>;
1812
- readonly actions: Map<string, Action<any, any, any, any>>;
1813
- readonly tools: Map<string, Tool<any, any, any, any>>;
1814
- readonly tables: Map<string, any>;
1815
- readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext>>;
1816
- readonly db?: TDb;
1817
- readonly isBuilt?: boolean;
1818
- use<A>(plugin: ServicePlugin<this, A>): A;
1819
- build(): this;
1820
- socket<const I extends SocketSchemas, const O extends SocketSchemas>(config: BrickSocketConfig<I, O, BaseContext<TDb> & TServiceContext>): this;
1821
- listSockets(): RegisteredSocket[];
1822
- 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;
1823
- 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>;
1824
- 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>;
1825
- 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;
1826
- 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>;
1827
- 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>;
1828
- 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>>;
1829
- readonly preparations: Map<string, PreparationContribution>;
1830
- contributePreparation(contribution: PreparationContribution): void;
1831
- listPreparations(): PreparationContribution[];
1832
- prepareContributions(): void;
1833
- registerTable(table: any): this;
1834
- getAction(name: string): Action<any, any, any, any> | undefined;
1835
- listActions(): Action<any, any, any, any>[];
1836
- getTool(name: string): Tool<any, any, any, any> | undefined;
1837
- listTools(): Tool<any, any, any, any>[];
1838
- getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
1839
- listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
1840
- getDb(): TDb | undefined;
1841
- setDb(database: DatabaseHandle<TDb>): void;
1842
- /** The outbox table of this service's database, if it holds one (see `outboxTable`). */
1843
- getOutbox?(): OutboxTable | undefined;
1844
- /** What a write needs to record events. Set by `brick({ events })`; absent otherwise. */
1845
- readonly events?: ServiceEvents;
1846
- setEvents?(events: ServiceEvents | undefined): void;
1847
- resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
1848
- introspect(): ServiceSchema;
1849
- }
1850
- interface ProxyOptions {
1851
- isMonolith?: boolean;
1852
- /** Name of the service creating this proxy. Populates ctx.caller on the target's envelope. */
1853
- from?: string;
1854
- context?: Partial<ActionContext>;
1855
- }
1856
- //#endregion
1857
- //#region src/client.d.ts
1858
3
  /**
1859
4
  * Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.
1860
5
  *
@@ -1906,8 +51,10 @@ interface ProxyOptions {
1906
51
  * | Client call | HTTP request |
1907
52
  * |---|---|
1908
53
  * Generated browser contracts carry each action's HTTP method and path,
1909
- * including plugin routes and consumer overrides. Without runtime metadata,
1910
- * callers use `POST /api/<service>/<action>` with dotted action names.
54
+ * including plugin routes, resource routes and consumer overrides. Without
55
+ * runtime metadata, callers use `POST /api/<service>/<action>` with the names
56
+ * in kebab-case (`getSummary` → `get-summary`); resource and plugin routes
57
+ * need the contract.
1911
58
  * GET/DELETE input is serialized as a query string; other methods send JSON.
1912
59
 
1913
60
  */
@@ -1937,6 +84,11 @@ interface BrickClientOptions {
1937
84
  */
1938
85
  contract?: Record<string, any>;
1939
86
  }
87
+ /**
88
+ * The contract of each service by name, which types `useService`. The generated
89
+ * contract (`_brick/contract.ts`) fills it in; nothing needs to be written by hand.
90
+ */
91
+ interface BrickServices {}
1940
92
  /** Browser-safe action metadata generated by the Brick Vite plugin. */
1941
93
  interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
1942
94
  kind: "action";
@@ -2063,8 +215,8 @@ type InferActionFailure<A> = ActionExecutionError & {
2063
215
  */
2064
216
  type BrickActionCaller<A> = undefined extends InferActionInput<A> ? (input?: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>> : (input: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>>;
2065
217
  /** Recursively maps action leaves and their namespaces to browser callers. */
2066
- type BrickClient<T> = T extends BrickClientSocket<infer I, infer O> ? {
2067
- connect(options?: BrickSocketConnectOptions): BrickSocketClient<I, O>;
218
+ type BrickClient<T> = T extends BrickClientSocket<infer I, infer O, infer E> ? {
219
+ connect(options?: BrickSocketConnectOptions): BrickSocketClient<I, O, E>;
2068
220
  } : 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;
2069
221
  /**
2070
222
  * Create an Eden/tRPC-style typed client for the application contract `TApp`.
@@ -2075,6 +227,5 @@ declare function createBrickClient<TApp extends Record<string, any>>(options: Br
2075
227
  contract: TApp;
2076
228
  }): BrickClient<TApp>;
2077
229
  declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
2078
- //#endregion
2079
- export { ToolConfigWithoutAuthorize as $, overrideSecret as $t, ErrorBuilder as A, getPluginActionRoute as An, WorkflowsOptions as At, Resource as B, PostgresDefinition as Bt, ActionSchema as C, ResourcePluginAPI as Cn, EventListener as Ct, CacheOptions as D, ServicePluginContext as Dn, EventsWorld as Dt, BaseContext as E, ServicePlugin as En, EventsOptions as Et, NarrowAuthorizedContext as F, isOutboxTable as Ft, ServiceAuthOptions as G, PostgresDatabase as Gt, ResourceIdentity as H, defineDatabase as Ht, PreparationContribution as I, outboxTable as It, StandardErrorMap as J, SecretOptions as Jt, ServiceOptions as K, PostgresDatabaseConfig as Kt, ProxyOptions as L, DatabaseDefinition as Lt, InferTableRow as M, OutboxTable as Mt, LifecycleOptions as N, PostgresOutboxTable as Nt, CompiledRoutePlan as O, defineResourcePlugin as On, ServiceEvents as Ot, Logger as P, SQLiteOutboxTable as Pt, ToolConfigWithAuthorize as Q, listSecrets as Qt, RateLimitOptions as R, DatabaseHandle as Rt, ActionExecutionError as S, ResourcePlugin as Sn, EventEnvelope as St, BaseActionConfig as T, ResourcePluginTypes as Tn, EventWorkflow as Tt, ResourceTypeOptions as U, isDatabaseHandle as Ut, ResourceConfig as V, SQLiteDefinition as Vt, Service as W, DatabaseAdapter as Wt, Tool as X, SecretSource as Xt, TelemetryOptions as Y, SecretRef as Yt, ToolAnnotations as Z, envSource as Zt, ActionConfig as _, PluginEndpointContext as _n, Dispatcher as _t, BrickClientOptions as a, BunSQLiteDatabase$1 as an, BrickSocketClient as at, ActionContext as b, PluginRouteScope as bn, DispatchOptions as bt, InferActionErrorCodes as c, createSQLiteDatabase as cn, BrickSocketError as ct, InferActionOutput as d, integer$1 as dn, SocketEventArgs as dt, overrideSecrets as en, ToolOptions as et, createBrickClient as f, primaryKey as fn, SocketPayloads as ft, ActionAccessPolicy as g, uniqueIndex as gn, stopAllEvents as gt, Action as h, text$1 as hn, EventsHub as ht, BrickClientAction as i, BrickSQLiteDatabase as in, BrickClientSocket as it, InferTableInsert as j, getPluginEndpoints as jn, OutboxStatus as jt, DefaultServiceContext as k, defineServicePlugin as kn, WorkflowEvent as kt, InferActionFailure as l, foreignKey as ln, BrickSocketSchema as lt, isBrickTransportError as m, sqliteTable$1 as mn, EventsDefinition as mt, BrickCallOptions as n, resolveSecrets as nn, ValidationErrorItem as nt, BrickServerError as o, SQLiteDatabaseConfig as on, BrickSocketConfig as ot, isBrickServerError as p, real as pn, SocketSchemas as pt, ServiceSchema as q, createPostgresDatabase as qt, BrickClient as r, secret as rn, RegisteredSocket as rt, BrickTransportError as s, blob as sn, BrickSocketConnectOptions as st, BrickActionCaller as t, resetSecrets as tn, ValidationError as tt, InferActionInput as u, index$1 as un, BrickSocketSender as ut, ActionConfigWithAuthorize as v, PluginRouteMethod as vn, OutboxCounts as vt, ArchitectureSchema as w, ResourcePluginContext as wn, EventRecorder as wt, ActionErrorDefinition as x, PluginRoutes as xn, EventDelivery as xt, ActionConfigWithoutAuthorize as y, PluginRouteRegistrar as yn, CrudEventPayload as yt, ResilienceOptions as z, EnvInput as zt };
230
+ export { BrickClientOptions as a, BrickTransportError as c, InferActionInput as d, InferActionOutput as f, isBrickTransportError as h, BrickClientAction as i, InferActionErrorCodes as l, isBrickServerError as m, BrickCallOptions as n, BrickServerError as o, createBrickClient as p, BrickClient as r, BrickServices as s, BrickActionCaller as t, InferActionFailure as u };
2080
231
  //# sourceMappingURL=client.d.ts.map