@brickkit/core 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,634 +1,10 @@
1
- import { Static, Static as Static$1, TSchema, TSchema as TSchema$1, Type } from "@sinclair/typebox";
1
+ import { $ as ServiceAuthOptions, A as ErrorBuilder, At as resolveSecrets, B as ResourceActions, Bt as primaryKey, C as ActionSchema, Ct as SecretRef, D as CacheOptions, Dt as overrideSecret, E as BaseContext, Et as listSecrets, F as NarrowAuthorizedContext, Ft as blob, G as ResourceListInput, H as ResourceCreateInput, Ht as sqliteTable, I as ProxyOptions, It as createSQLiteDatabase, J as ResourcePlan, K as ResourceListResult, L as RateLimitOptions, Lt as foreignKey, M as InferTableRow, Mt as BrickSQLiteDatabase, N as LifecycleOptions, Nt as BunSQLiteDatabase, O as CompiledRoutePlan, Ot as overrideSecrets, P as Logger, Pt as SQLiteDatabaseConfig, Q as Service, R as ResilienceOptions, Rt as index, S as ActionExecutionError, St as SecretOptions, T as BaseActionConfig, Tt as envSource, U as ResourceHooks, Ut as text, V as ResourceConfig, Vt as real, W as ResourceIdInput, Wt as uniqueIndex, X as ResourceTypeOptions, Y as ResourceRow, Z as ResourceUpdateInput, _ as ActionConfig, _t as isDatabaseHandle, a as BrickClientOptions, at as ToolAnnotations, b as ActionContext, bt as PostgresDatabaseConfig, c as BrickTransportError, ct as ToolOptions, d as InferActionInput, dt as DatabaseDefinition, et as ServiceOptions, f as InferActionOutput, ft as DatabaseHandle, g as Action, gt as defineDatabase, h as isBrickTransportError, ht as SQLiteDefinition, i as BrickClientAction, it as Tool, j as InferTableInsert, jt as secret, k as DefaultServiceContext, kt as resetSecrets, l as InferActionErrorCodes, lt as ValidationError, m as isBrickServerError, mt as PostgresDefinition, n as BrickCallOptions, nt as StandardErrorMap, o as BrickResourceClient, ot as ToolConfigWithAuthorize, p as createBrickClient, pt as EnvInput, q as ResourceOperationsConfig, r as BrickClient, rt as TelemetryOptions, s as BrickServerError, st as ToolConfigWithoutAuthorize, t as BrickActionCaller, tt as ServiceSchema, u as InferActionFailure, ut as ValidationErrorItem, v as ActionConfigWithAuthorize, vt as DatabaseAdapter, w as ArchitectureSchema, wt as SecretSource, x as ActionErrorDefinition, xt as createPostgresDatabase, y as ActionConfigWithoutAuthorize, yt as PostgresDatabase, z as Resource, zt as integer } from "./chunks/client.js";
2
+ import { Static, TSchema, TSchema as TSchema$1, Type } from "@sinclair/typebox";
2
3
  import { TypeCheck } from "@sinclair/typebox/compiler";
3
- import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
4
- import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
5
- import { Table, Table as Table$1, and, asc, desc, eq, getTableColumns, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql } from "drizzle-orm";
6
- import { Database } from "bun:sqlite";
7
- import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
8
- //#region src/db/sqlite.d.ts
9
- export interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
10
- /** Database file path or ':memory:' (default: ':memory:') */
11
- path?: string;
12
- /** Alias for path */
13
- filename?: string;
14
- /** Whether to enable WAL journal mode for file-based DBs (default: true) */
15
- wal?: boolean;
16
- /** Whether to enforce foreign key constraints (default: true) */
17
- foreignKeys?: boolean;
18
- /** Optional existing bun:sqlite Database instance */
19
- client?: Database;
20
- /** Optional Drizzle schema object for typed relational queries */
21
- schema?: TSchema;
22
- }
23
- export type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase$1<TSchema> & {
24
- $client: Database;
25
- };
26
- /**
27
- * Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
28
- * and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
29
- *
30
- * Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
31
- * other runtimes (e.g. Node) stays safe until this function is actually
32
- * called.
33
- */
34
- export declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase$1<TSchema>;
35
- //#endregion
36
- //#region src/secrets.d.ts
37
- /**
38
- * Type-safe secrets & environment variables.
39
- *
40
- * Declare each secret once at module scope instead of scattering untyped
41
- * `process.env.FOO` reads:
42
- *
43
- * const port = secret("PORT").default("3333").transform(Number).require();
44
- * const baseUrl = secret("BASE_URL").url().require();
45
- * const key = secret("STRIPE_KEY").validate((v) =>
46
- * v.startsWith("sk_") || "must start with sk_"
47
- * ).require();
48
- *
49
- * Values resolve from the environment (Bun populates `process.env` from
50
- * `.env` locally; in prod the same env source applies — a future
51
- * `SecretSource` such as AWS can slot in without touching call sites).
52
- *
53
- * Resolution order per secret: test/session override → source (`process.env`
54
- * by default) → declared `default`. `resolveSecrets()` validates every
55
- * registered secret at boot and throws listing all missing required ones.
56
- */
57
- interface SecretSource {
58
- get(name: string): string | undefined;
59
- }
60
- /** Default source: `process.env` (Bun loads `.env` into it automatically). */
61
- export declare const envSource: SecretSource;
62
- interface SecretOptions {
63
- /** Fallback when the source has no value. Secrets without a default are required. */
64
- default?: string;
65
- }
66
- /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
67
- type SecretValidator<T> = (value: T) => void | boolean | string;
68
- export declare class SecretRef<T = string> {
69
- readonly name: string;
70
- readonly options: SecretOptions;
71
- private transformFn?;
72
- private validators;
73
- constructor(name: string, options?: SecretOptions);
74
- /** True when a default was declared (i.e. the secret is optional). */
75
- get hasDefault(): boolean;
76
- /** Fallback used when the source has no value. Makes the secret optional. */
77
- default(value: string): this;
78
- /**
79
- * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
80
- * Runs before validators; a throwing transform fails resolution.
81
- */
82
- transform<U>(fn: (raw: string) => U): SecretRef<U>;
83
- /** Run a custom check on the (transformed) value at every resolution. */
84
- validate(fn: SecretValidator<T>): this;
85
- /** Shorthand validator: value must parse as a URL. String refs only. */
86
- url(this: SecretRef<string>): SecretRef<string>;
87
- private resolveRaw;
88
- private coerce;
89
- /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
90
- value(source?: SecretSource): T | undefined;
91
- /** Resolved value, or throws naming the missing/invalid secret. */
92
- require(source?: SecretSource): T;
93
- /** True when a value would resolve (override, source, or default). */
94
- isSet(source?: SecretSource): boolean;
95
- }
96
- /**
97
- * Declare a secret. Idempotent: re-declaring the same name returns the
98
- * original ref (first declaration wins) so module re-evaluation is safe.
99
- */
100
- export declare function secret(name: string, options?: SecretOptions): SecretRef<string>;
101
- /**
102
- * Validate every registered secret at boot. Throws a single error listing
103
- * all missing required secrets. Returns the resolved values.
104
- */
105
- export declare function resolveSecrets(opts?: {
106
- source?: SecretSource;
107
- }): Record<string, unknown>;
108
- /** Metadata for introspection (values never exposed — future dashboard use). */
109
- export declare function listSecrets(opts?: {
110
- source?: SecretSource;
111
- }): Array<{
112
- name: string;
113
- hasDefault: boolean;
114
- isSet: boolean;
115
- }>;
116
- /** Test/session override for one secret (`undefined` clears the override). */
117
- export declare function overrideSecret(name: string, value: string | undefined): void;
118
- /** Bulk overrides (test/session scoped). */
119
- export declare function overrideSecrets(values: Record<string, string | undefined>): void;
120
- /** Clear registry and overrides. Test-only. */
121
- export declare function resetSecrets(): void;
122
- //#endregion
123
- //#region src/db/postgres.d.ts
124
- export interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
125
- /** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
126
- url?: string;
127
- /** Connection string alias */
128
- connectionString?: string;
129
- host?: string;
130
- port?: number;
131
- user?: string;
132
- password?: string;
133
- database?: string;
134
- ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
135
- max?: number;
136
- /**
137
- * Disable prepared statements (required for transaction-mode poolers such
138
- * as Supabase's Supavisor on :6543, which cannot hold named prepared
139
- * statements across transactions).
140
- */
141
- prepare?: boolean;
142
- /** Optional Drizzle schema for relational queries */
143
- schema?: TSchema;
144
- /** Custom schema name for Encore-style isolated schemas */
145
- schemaName?: string;
146
- }
147
- export type PostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
148
- export interface DatabaseAdapter<TDb = any, TConfig = any> {
149
- createDatabase(config?: TConfig): TDb;
150
- }
151
- /**
152
- * Creates a PostgreSQL Drizzle instance using postgres-js.
153
- * Static imports (both are hard dependencies in package.json) so bundlers
154
- * (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
155
- * `sqlite.ts` since it only exists under Bun.
156
- */
157
- export declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
158
- //#endregion
159
- //#region src/db/define.d.ts
160
- export type EnvInput<T> = T | SecretRef<T>;
161
- type EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>>; };
162
- interface DefinitionOptions<TSchema extends Record<string, unknown>> {
163
- name?: string;
164
- /** Drizzle tables retained for schema tooling. Never applied at runtime. */
165
- tables?: (TSchema & Record<string, Table$1>) | readonly Table$1[];
166
- schema?: TSchema;
167
- }
168
- export type SQLiteDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
169
- engine?: "sqlite";
170
- client?: SQLiteDatabaseConfig<TSchema>["client"];
171
- url?: never;
172
- connectionString?: never;
173
- };
174
- export type PostgresDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema">> & {
175
- engine: "postgres";
176
- path?: never;
177
- filename?: never;
178
- wal?: never;
179
- foreignKeys?: never;
180
- client?: never;
181
- };
182
- export type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
183
- export interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
184
- readonly kind: "brick-database";
185
- readonly name?: string;
186
- readonly engine: "sqlite" | "postgres";
187
- readonly tables: Readonly<Record<string, Table$1>>;
188
- readonly schema: TSchema;
189
- getDb(): TDb;
190
- }
191
- export declare function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>;
192
- export declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>;
193
- export declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema>, TSchema>;
194
- //#endregion
195
- //#region src/types.d.ts
196
- export interface Logger {
197
- info: (...args: any[]) => void;
198
- warn: (...args: any[]) => void;
199
- error: (...args: any[]) => void;
200
- debug: (...args: any[]) => void;
201
- }
202
- /**
203
- * Base framework context supplied to all service resolvers and action executions.
204
- */
205
- export interface BaseContext<TDb = any> {
206
- request: Request;
207
- db: TDb;
208
- logger: Logger;
209
- traceId: string;
210
- requestId?: string;
211
- services?: Record<string, any>;
212
- metadata?: Record<string, unknown>;
213
- }
214
- /**
215
- * Default fallback service context for untyped or simple services.
216
- */
217
- export interface DefaultServiceContext {
218
- user?: any;
219
- session?: any;
220
- [key: string]: any;
221
- }
222
- /**
223
- * The combined execution context: BaseContext & TServiceContext.
224
- */
225
- export type ActionContext<TDb = any, TServiceContext = DefaultServiceContext> = BaseContext<TDb> & TServiceContext;
226
- /**
227
- * Type utility that automatically narrows ctx.user from User | null to User
228
- * in execute() when authorize() is declared on the action.
229
- */
230
- export type NarrowAuthorizedContext<TCtx> = TCtx extends {
231
- user: infer U;
232
- } ? [U] extends [null | undefined] ? TCtx : Omit<TCtx, "user"> & {
233
- user: NonNullable<U>;
234
- } : TCtx;
235
- export interface ActionErrorDefinition {
236
- status?: number;
237
- message: string;
238
- }
239
- export interface ValidationErrorItem {
240
- path: string;
241
- message: string;
242
- value?: unknown;
243
- type?: number;
244
- }
245
- export declare class ValidationError extends Error {
246
- readonly status: number;
247
- readonly errors: ValidationErrorItem[];
248
- constructor(message: string, errors?: ValidationErrorItem[], status?: number);
249
- toJSON(): {
250
- name: string;
251
- message: string;
252
- status: number;
253
- errors: ValidationErrorItem[];
254
- };
255
- }
256
- export declare class ActionExecutionError extends Error {
257
- readonly code: string;
258
- readonly status: number;
259
- readonly details?: unknown;
260
- constructor(code: string, message: string, status?: number, details?: unknown);
261
- toJSON(): {
262
- name: string;
263
- code: string;
264
- message: string;
265
- status: number;
266
- details: unknown;
267
- };
268
- }
269
- export interface StandardErrorMap {
270
- BAD_REQUEST: (overrideMessage?: string, details?: unknown) => never;
271
- UNAUTHORIZED: (overrideMessage?: string, details?: unknown) => never;
272
- FORBIDDEN: (overrideMessage?: string, details?: unknown) => never;
273
- NOT_FOUND: (overrideMessage?: string, details?: unknown) => never;
274
- CONFLICT: (overrideMessage?: string, details?: unknown) => never;
275
- INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown) => never;
276
- [key: string]: ((overrideMessage?: string, details?: unknown) => never) | undefined;
277
- }
278
- export type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: (overrideMessage?: string, details?: unknown) => never; };
279
- export interface BaseActionConfig<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
280
- name: string;
281
- description?: string;
282
- path?: string;
283
- method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
284
- input?: TInputSchema;
285
- output?: TOutputSchema;
286
- errors?: TErrors;
287
- emits?: string[];
288
- tags?: string[];
289
- }
290
- export interface ActionConfigWithAuthorize<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
291
- authorize: (params: {
292
- user?: TContext extends {
293
- user: infer U;
294
- } ? U : any;
295
- input: TInputSchema extends TSchema$1 ? Static$1<TInputSchema> : any;
296
- ctx: TContext;
297
- }) => boolean | Promise<boolean>;
298
- execute: (params: {
299
- input: TInputSchema extends TSchema$1 ? Static$1<TInputSchema> : any;
300
- ctx: NarrowAuthorizedContext<TContext>;
301
- error: ErrorBuilder<TErrors>;
302
- }) => Promise<TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any> | (TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any);
303
- }
304
- export interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
305
- authorize?: undefined;
306
- execute: (params: {
307
- input: TInputSchema extends TSchema$1 ? Static$1<TInputSchema> : any;
308
- ctx: TContext;
309
- error: ErrorBuilder<TErrors>;
310
- }) => Promise<TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any> | (TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any);
311
- }
312
- export type ActionConfig<TInputSchema extends TSchema$1 | undefined = any, TOutputSchema extends TSchema$1 | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> = ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext> | ActionConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>;
313
- export interface Action<TInputSchema extends TSchema$1 | undefined = any, TOutputSchema extends TSchema$1 | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> {
314
- (params: {
315
- input?: TInputSchema extends TSchema$1 ? Static$1<TInputSchema> : any;
316
- ctx?: Partial<TContext>;
317
- }): Promise<TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any>;
318
- name: string;
319
- serviceName?: string;
320
- config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
321
- run(input?: TInputSchema extends TSchema$1 ? Static$1<TInputSchema> : any, ctx?: Partial<TContext>): Promise<TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any>;
322
- execute(params: {
323
- input?: TInputSchema extends TSchema$1 ? Static$1<TInputSchema> : any;
324
- ctx?: Partial<TContext>;
325
- }): Promise<TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any>;
326
- executeResolved?(params: {
327
- input?: TInputSchema extends TSchema$1 ? Static$1<TInputSchema> : any;
328
- ctx: TContext;
329
- }): Promise<TOutputSchema extends TSchema$1 ? Static$1<TOutputSchema> : any>;
330
- validateInput(input: unknown): {
331
- success: true;
332
- data: any;
333
- } | {
334
- success: false;
335
- errors: ValidationErrorItem[];
336
- };
337
- validateOutput(output: unknown): {
338
- success: true;
339
- data: any;
340
- } | {
341
- success: false;
342
- errors: ValidationErrorItem[];
343
- };
344
- errorHelpers?: ErrorBuilder<TErrors>;
345
- }
346
- export interface ResourceOperationsConfig {
347
- list?: boolean | {
348
- defaultLimit?: number;
349
- maxLimit?: number;
350
- searchable?: string[];
351
- sortable?: string[];
352
- defaultSort?: string;
353
- };
354
- get?: boolean;
355
- create?: boolean;
356
- update?: boolean;
357
- delete?: boolean;
358
- }
359
- export type InferTableRow<TTable> = TTable extends {
360
- $inferSelect: infer S;
361
- } ? S : any;
362
- export type InferTableInsert<TTable> = TTable extends {
363
- $inferInsert: infer S;
364
- } ? S : any;
365
- export interface ResourceHooks<TRow = any, TInsert = any, TCtx = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
366
- beforeCreate?: (params: {
367
- data: TInsert;
368
- ctx: TCtx;
369
- error: ErrorBuilder<TErrors>;
370
- }) => Promise<void> | void;
371
- afterCreate?: (params: {
372
- data: TInsert;
373
- result: TRow;
374
- ctx: TCtx;
375
- }) => Promise<void> | void;
376
- beforeUpdate?: (params: {
377
- id: string | number;
378
- data: Partial<TInsert>;
379
- existing: TRow;
380
- ctx: TCtx;
381
- error: ErrorBuilder<TErrors>;
382
- }) => Promise<void> | void;
383
- afterUpdate?: (params: {
384
- id: string | number;
385
- data: Partial<TInsert>;
386
- result: TRow;
387
- ctx: TCtx;
388
- }) => Promise<void> | void;
389
- beforeDelete?: (params: {
390
- id: string | number;
391
- existing: TRow;
392
- ctx: TCtx;
393
- error: ErrorBuilder<TErrors>;
394
- }) => Promise<void> | void;
395
- afterDelete?: (params: {
396
- id: string | number;
397
- existing: TRow;
398
- ctx: TCtx;
399
- error: ErrorBuilder<TErrors>;
400
- }) => Promise<void> | void;
401
- }
402
- export interface ResourceConfig<TTable = any, TCtx = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
403
- name: string;
404
- table: TTable;
405
- ownerField?: string;
406
- idField?: string;
407
- idPrefix?: string;
408
- idGenerator?: () => string;
409
- pluralName?: string;
410
- operations?: ResourceOperationsConfig;
411
- hooks?: ResourceHooks<InferTableRow<TTable>, InferTableInsert<TTable>, TCtx, TErrors>;
412
- fields?: Record<string, TSchema$1>;
413
- errors?: TErrors;
414
- searchable?: string[];
415
- sortable?: string[];
416
- defaultSort?: string;
417
- /** Columns excluded from default list projection (Go pageMeta parity: content). */
418
- excludeFromList?: string[];
419
- }
420
- export interface ResourcePlan<TTable = any> {
421
- readonly resourceName: string;
422
- readonly pluralName: string;
423
- readonly table: TTable;
424
- readonly idField: string;
425
- readonly idCol: any;
426
- readonly ownerField?: string;
427
- readonly ownerCol?: any;
428
- readonly ownerColName?: string;
429
- readonly columnMap: Map<string, any>;
430
- readonly columns: Record<string, any>;
431
- readonly defaultColumns: ReadonlyArray<{
432
- key: string;
433
- default: any;
434
- }>;
435
- readonly timestampColumns: {
436
- readonly createdAtKey: string | null;
437
- readonly updatedAtKey: string | null;
438
- };
439
- readonly searchable: {
440
- readonly fields?: string[];
441
- readonly columns: any[];
442
- };
443
- readonly sortable: {
444
- readonly fields: Set<string>;
445
- readonly defaultSort: string;
446
- readonly defaultSortEntries: ReadonlyArray<{
447
- field: string;
448
- dir: "asc" | "desc";
449
- }>;
450
- readonly fallbackEntries: ReadonlyArray<{
451
- field: string;
452
- dir: "asc" | "desc";
453
- }>;
454
- readonly tiebreakCol: any;
455
- };
456
- readonly projections: {
457
- readonly defaultProjection?: Record<string, any>;
458
- };
459
- readonly routeTargets: {
460
- readonly listPath: string;
461
- readonly itemPath: string;
462
- };
463
- }
464
- export interface Resource<TTable = any, TCtx extends ActionContext = ActionContext> {
465
- readonly name: string;
466
- readonly serviceName: string;
467
- readonly table: TTable;
468
- readonly ownerField?: string;
469
- readonly idField: string;
470
- readonly pluralName: string;
471
- readonly config: ResourceConfig<TTable, TCtx>;
472
- readonly plan?: ResourcePlan<TTable>;
473
- readonly actions: {
474
- list: Action<any, any, any, TCtx>;
475
- get: Action<any, any, any, TCtx>;
476
- create: Action<any, any, any, TCtx>;
477
- update: Action<any, any, any, TCtx>;
478
- delete: Action<any, any, any, TCtx>;
479
- };
480
- list: Action<any, any, any, TCtx>;
481
- get: Action<any, any, any, TCtx>;
482
- create: Action<any, any, any, TCtx>;
483
- update: Action<any, any, any, TCtx>;
484
- delete: Action<any, any, any, TCtx>;
485
- }
486
- export interface ServiceAuthOptions {
487
- requireAuth?: boolean;
488
- allowedRoles?: string[];
489
- policy?: (ctx: ActionContext) => boolean | Promise<boolean>;
490
- }
491
- export interface RateLimitOptions {
492
- maxRequests: number;
493
- window: number | string;
494
- scope?: "ip" | "user" | "tenant";
495
- }
496
- export interface CacheOptions {
497
- driver?: "memory" | "redis";
498
- defaultTtl?: number;
499
- }
500
- export interface ResilienceOptions {
501
- timeoutMs?: number;
502
- retry?: {
503
- attempts: number;
504
- backoff: "linear" | "exponential";
505
- delayMs: number;
506
- };
507
- circuitBreaker?: {
508
- errorThresholdPercentage: number;
509
- resetTimeoutMs: number;
510
- };
511
- }
512
- export interface TelemetryOptions {
513
- traceQueries?: boolean;
514
- auditLog?: boolean;
515
- tags?: Record<string, string>;
516
- }
517
- export interface LifecycleOptions {
518
- onInit?: (ctx: {
519
- db?: any;
520
- logger?: Logger;
521
- }) => Promise<void>;
522
- onDestroy?: () => Promise<void>;
523
- }
524
- export interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
525
- database?: DatabaseHandle<TDb>;
526
- context?: (baseCtx: BaseContext<TDb>) => Promise<TServiceContext> | TServiceContext;
527
- auth?: ServiceAuthOptions;
528
- rateLimit?: RateLimitOptions;
529
- cache?: CacheOptions;
530
- resilience?: ResilienceOptions;
531
- telemetry?: TelemetryOptions;
532
- lifecycle?: LifecycleOptions;
533
- }
534
- export interface ActionSchema {
535
- name: string;
536
- serviceName?: string;
537
- description?: string;
538
- inputSchema?: unknown;
539
- outputSchema?: unknown;
540
- hasAuthorize: boolean;
541
- errors?: Record<string, ActionErrorDefinition>;
542
- emits?: string[];
543
- tags?: string[];
544
- }
545
- export interface ServiceSchema {
546
- name: string;
547
- options: Omit<ServiceOptions, "database"> & {
548
- database?: {
549
- name?: string;
550
- engine: "sqlite" | "postgres";
551
- tables: string[];
552
- };
553
- };
554
- hasDatabase: boolean;
555
- databaseConfig?: {
556
- name?: string;
557
- engine: "sqlite" | "postgres";
558
- tables: string[];
559
- };
560
- actions: ActionSchema[];
561
- resources?: {
562
- name: string;
563
- ownerField?: string;
564
- operations: string[];
565
- }[];
566
- }
567
- export interface ArchitectureSchema {
568
- version: string;
569
- services: ServiceSchema[];
570
- }
571
- export interface CompiledRoutePlan {
572
- service: Service<any, any>;
573
- action: Action<any, any, any, any>;
574
- actionName: string;
575
- serviceName: string;
576
- routePath: string;
577
- method?: string;
578
- isGetLike: boolean;
579
- hasInput: boolean;
580
- hasContextHook: boolean;
581
- contextHook?: (baseCtx: any) => Promise<any> | any;
582
- hasAuthorize: boolean;
583
- authorize?: (params: any) => boolean | Promise<boolean>;
584
- execute: (params: any) => Promise<any> | any;
585
- inputChecker?: {
586
- Check: (val: any) => boolean;
587
- Errors: (val: any) => Iterable<any>;
588
- };
589
- outputChecker?: {
590
- Check: (val: any) => boolean;
591
- Errors: (val: any) => Iterable<any>;
592
- };
593
- coercions?: Array<{
594
- key: string;
595
- isNumber: boolean;
596
- isBoolean: boolean;
597
- }>;
598
- logger: Logger;
599
- errorBuilder: any;
600
- cachedDb: any;
601
- }
602
- export interface Service<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> {
603
- readonly name: string;
604
- readonly options: ServiceOptions<TServiceContext, TDb>;
605
- readonly actions: Map<string, Action<any, any, any, any>>;
606
- readonly tables: Map<string, any>;
607
- readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext>>;
608
- readonly db?: TDb;
609
- readonly isBuilt?: boolean;
610
- build(): this;
611
- action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
612
- action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
613
- action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
614
- resource<TTable = any>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext>): Resource<TTable, BaseContext<TDb> & TServiceContext>;
615
- registerTable(table: any): this;
616
- getAction(name: string): Action<any, any, any, any> | undefined;
617
- listActions(): Action<any, any, any, any>[];
618
- getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
619
- listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
620
- getDb(): TDb | undefined;
621
- setDb(database: DatabaseHandle<TDb>): void;
622
- resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
623
- introspect(): ServiceSchema;
624
- }
625
- export interface ProxyOptions {
626
- isMonolith?: boolean;
627
- context?: Partial<ActionContext>;
628
- }
629
- //#endregion
4
+ import { Table, and, asc, desc, eq, getTableColumns, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql } from "drizzle-orm";
630
5
  //#region src/db/index.d.ts
631
- export interface DatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> extends SQLiteDatabaseConfig<TSchema>, PostgresDatabaseConfig<TSchema> {
6
+ export interface DatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> extends Omit<SQLiteDatabaseConfig<TSchema>, "client">, Omit<PostgresDatabaseConfig<TSchema>, "client"> {
7
+ client?: SQLiteDatabaseConfig<TSchema>["client"] | PostgresDatabaseConfig<TSchema>["client"];
632
8
  /** Database engine. Default: 'sqlite' */
633
9
  engine?: "sqlite" | "postgres" | "clickhouse";
634
10
  /** Optional service name associated with this database */
@@ -693,8 +69,9 @@ export declare class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>
693
69
  readonly name: string;
694
70
  readonly options: ServiceOptions<TServiceContext, TDb>;
695
71
  readonly actions: Map<string, Action<any, any, any, any>>;
72
+ readonly tools: Map<string, Tool<any, any, any, any>>;
696
73
  readonly tables: Map<string, any>;
697
- readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext>>;
74
+ readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext, {}>>;
698
75
  private database?;
699
76
  private _isBuilt;
700
77
  constructor(name: string, options?: ServiceOptions<TServiceContext, TDb>);
@@ -706,12 +83,17 @@ export declare class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>
706
83
  */
707
84
  build(): this;
708
85
  registerTable(table: any): this;
709
- resource<TTable = any>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext>): Resource<TTable, BaseContext<TDb> & TServiceContext>;
86
+ resource: Service<TDb, TServiceContext>["resource"];
710
87
  getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
711
88
  listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
712
89
  action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
713
90
  action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
714
91
  action<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
92
+ tool<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
93
+ tool<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
94
+ tool<TIn extends TSchema$1 | undefined = undefined, TOut extends TSchema$1 | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
95
+ getTool(name: string): Tool<any, any, any, any> | undefined;
96
+ listTools(): Tool<any, any, any, any>[];
715
97
  getAction(name: string): Action<any, any, any, any> | undefined;
716
98
  listActions(): Action<any, any, any, any>[];
717
99
  getDb(): TDb | undefined;
@@ -752,7 +134,7 @@ export declare function describeResourceReads(service: Service<any, any>, resour
752
134
  export declare function prepareResourceReads(service: Service<any, any>): void;
753
135
  /** Bun SQLite writes: prime common shapes; discover other shapes once and reuse them. */
754
136
  export declare function prepareResourceWrites(service: Service<any, any>): void;
755
- export declare function defineResource<TTable = any, TCtx extends ActionContext = ActionContext>(service: Service<any, any>, config: ResourceConfig<TTable, TCtx>): Resource<TTable, TCtx>;
137
+ export declare function defineResource<TTable = any, TCtx extends ActionContext = ActionContext, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(service: Service<any, any>, config: ResourceConfig<TTable, TCtx> & TOptions): Resource<TTable, TCtx, TOptions>;
756
138
  //#endregion
757
139
  //#region src/rpc.d.ts
758
140
  export declare function createServiceProxy<T extends Record<string, any>>(serviceName: string, options?: ProxyOptions): T;
@@ -790,10 +172,49 @@ interface OpenApiGeneratorOptions {
790
172
  version?: string;
791
173
  description?: string;
792
174
  prefix?: string;
793
- services?: Service[];
175
+ services?: Service<any, any>[];
794
176
  registry?: ServiceRegistry;
795
177
  }
796
178
  export declare function generateOpenApiSpec(options?: OpenApiGeneratorOptions): Record<string, any>;
797
179
  //#endregion
798
- export { type BunSQLiteDatabase, type OpenApiGeneratorOptions, type ResourceReadQueries, type SecretOptions, type SecretSource, type Static, type TSchema, Table, Type, Type as t, and, asc, blob, desc, eq, foreignKey, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, primaryKey, real, relations, sql, sqliteTable, text, uniqueIndex };
180
+ //#region src/tool.d.ts
181
+ export declare function defineTool<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>(config: ToolConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;
182
+ export declare function defineTool<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>(config: ToolConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>): Tool<TInputSchema, TOutputSchema, TErrors, TContext>;
183
+ export declare function isTool(value: unknown): value is Tool<any, any, any, any>;
184
+ //#endregion
185
+ //#region src/mcp.d.ts
186
+ interface McpToolDefinition {
187
+ name: string;
188
+ title?: string;
189
+ description: string;
190
+ inputSchema: unknown;
191
+ annotations: ToolAnnotations;
192
+ }
193
+ interface McpRegistryOptions {
194
+ services?: readonly Pick<Service<any, any>, "listTools">[];
195
+ tools?: readonly Tool<any, any, any, any>[];
196
+ }
197
+ interface McpRegistry {
198
+ listTools(): McpToolDefinition[];
199
+ callTool(name: string, args?: Record<string, unknown>, ctx?: Partial<ActionContext>): Promise<unknown>;
200
+ }
201
+ export declare class UnknownToolError extends Error {
202
+ constructor(name: string);
203
+ }
204
+ /** Collect only explicitly defined tools, without exposing ordinary actions. */
205
+ export declare function createMcpRegistry(options: McpRegistryOptions): McpRegistry;
206
+ interface McpHandlerOptions {
207
+ registry: McpRegistry;
208
+ serverInfo: {
209
+ name: string;
210
+ version: string;
211
+ title?: string;
212
+ };
213
+ /** Versions supported by this transport, newest first. */
214
+ protocolVersions?: readonly string[];
215
+ }
216
+ /** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
217
+ export declare function createMcpHandler(options: McpHandlerOptions): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>;
218
+ //#endregion
219
+ export { Action, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, ActionSchema, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, type BrickResourceClient, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, CompiledRoutePlan, DatabaseAdapter, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, EnvInput, ErrorBuilder, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, LifecycleOptions, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiGeneratorOptions, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, ProxyOptions, RateLimitOptions, ResilienceOptions, Resource, ResourceActions, ResourceConfig, ResourceCreateInput, ResourceHooks, ResourceIdInput, ResourceListInput, ResourceListResult, ResourceOperationsConfig, ResourcePlan, type ResourceReadQueries, ResourceRow, ResourceTypeOptions, ResourceUpdateInput, SQLiteDatabaseConfig, SQLiteDefinition, type SecretOptions, SecretRef, type SecretSource, Service, ServiceAuthOptions, ServiceOptions, ServiceSchema, StandardErrorMap, type Static, type TSchema, Table, TelemetryOptions, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, ValidationError, ValidationErrorItem, and, asc, blob, createBrickClient, createPostgresDatabase, createSQLiteDatabase, defineDatabase, desc, envSource, eq, foreignKey, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, like, listSecrets, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, relations, resetSecrets, resolveSecrets, secret, sql, sqliteTable, text, uniqueIndex };
799
220
  //# sourceMappingURL=index.d.ts.map