@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/README.md +70 -0
- package/dist/chunks/client.d.ts +950 -0
- package/dist/chunks/client.d.ts.map +1 -0
- package/dist/chunks/client.js +311 -0
- package/dist/chunks/client.js.map +1 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +2 -0
- package/dist/index.d.ts +55 -634
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +206 -95
- package/dist/index.js.map +1 -1
- package/package.json +13 -3
|
@@ -0,0 +1,950 @@
|
|
|
1
|
+
import { Static, TSchema, TUnsafe } from "@sinclair/typebox";
|
|
2
|
+
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
3
|
+
import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
|
|
4
|
+
import { Sql } from "postgres";
|
|
5
|
+
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
6
|
+
import { Table } from "drizzle-orm";
|
|
7
|
+
import { Database } from "bun:sqlite";
|
|
8
|
+
//#region src/db/sqlite.d.ts
|
|
9
|
+
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
|
+
type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<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
|
+
declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase<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
|
+
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
|
+
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
|
+
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
|
+
declare function resolveSecrets(opts?: {
|
|
106
|
+
source?: SecretSource;
|
|
107
|
+
}): Record<string, unknown>;
|
|
108
|
+
/** Metadata for introspection (values never exposed — future dashboard use). */
|
|
109
|
+
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
|
+
declare function overrideSecret(name: string, value: string | undefined): void;
|
|
118
|
+
/** Bulk overrides (test/session scoped). */
|
|
119
|
+
declare function overrideSecrets(values: Record<string, string | undefined>): void;
|
|
120
|
+
/** Clear registry and overrides. Test-only. */
|
|
121
|
+
declare function resetSecrets(): void;
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/db/postgres.d.ts
|
|
124
|
+
interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
|
|
125
|
+
/** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
|
|
126
|
+
client?: Sql;
|
|
127
|
+
/** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
|
|
128
|
+
url?: string;
|
|
129
|
+
/** Connection string alias */
|
|
130
|
+
connectionString?: string;
|
|
131
|
+
host?: string;
|
|
132
|
+
port?: number;
|
|
133
|
+
user?: string;
|
|
134
|
+
password?: string;
|
|
135
|
+
database?: string;
|
|
136
|
+
ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
|
|
137
|
+
max?: number;
|
|
138
|
+
/**
|
|
139
|
+
* Disable prepared statements (required for transaction-mode poolers such
|
|
140
|
+
* as Supabase's Supavisor on :6543, which cannot hold named prepared
|
|
141
|
+
* statements across transactions).
|
|
142
|
+
*/
|
|
143
|
+
prepare?: boolean;
|
|
144
|
+
/** Optional Drizzle schema for relational queries */
|
|
145
|
+
schema?: TSchema;
|
|
146
|
+
/** Custom schema name for Encore-style isolated schemas */
|
|
147
|
+
schemaName?: string;
|
|
148
|
+
}
|
|
149
|
+
type PostgresDatabase<_TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
|
|
150
|
+
interface DatabaseAdapter<TDb = any, TConfig = any> {
|
|
151
|
+
createDatabase(config?: TConfig): TDb;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Creates a PostgreSQL Drizzle instance using postgres-js.
|
|
155
|
+
* Static imports (both are hard dependencies in package.json) so bundlers
|
|
156
|
+
* (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
|
|
157
|
+
* `sqlite.ts` since it only exists under Bun.
|
|
158
|
+
*/
|
|
159
|
+
declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
|
|
160
|
+
//#endregion
|
|
161
|
+
//#region src/db/define.d.ts
|
|
162
|
+
type EnvInput<T> = T | SecretRef<T>;
|
|
163
|
+
type EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>>; };
|
|
164
|
+
interface DefinitionOptions<TSchema extends Record<string, unknown>> {
|
|
165
|
+
name?: string;
|
|
166
|
+
/** Drizzle tables retained for schema tooling. Never applied at runtime. */
|
|
167
|
+
tables?: (TSchema & Record<string, Table>) | readonly Table[];
|
|
168
|
+
schema?: TSchema;
|
|
169
|
+
}
|
|
170
|
+
type SQLiteDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
|
|
171
|
+
engine?: "sqlite";
|
|
172
|
+
client?: SQLiteDatabaseConfig<TSchema>["client"];
|
|
173
|
+
url?: never;
|
|
174
|
+
connectionString?: never;
|
|
175
|
+
};
|
|
176
|
+
type PostgresDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
|
|
177
|
+
engine: "postgres";
|
|
178
|
+
path?: never;
|
|
179
|
+
filename?: never;
|
|
180
|
+
wal?: never;
|
|
181
|
+
foreignKeys?: never;
|
|
182
|
+
client?: PostgresDatabaseConfig<TSchema>["client"];
|
|
183
|
+
};
|
|
184
|
+
type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
|
|
185
|
+
interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
|
|
186
|
+
readonly kind: "brick-database";
|
|
187
|
+
readonly name?: string;
|
|
188
|
+
readonly engine: "sqlite" | "postgres";
|
|
189
|
+
readonly tables: Readonly<Record<string, Table>>;
|
|
190
|
+
readonly schema: TSchema;
|
|
191
|
+
getDb(): TDb;
|
|
192
|
+
}
|
|
193
|
+
declare function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>;
|
|
194
|
+
declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
|
|
195
|
+
declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
|
|
196
|
+
$client: Sql;
|
|
197
|
+
}, TSchema>;
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region src/types.d.ts
|
|
200
|
+
interface Logger {
|
|
201
|
+
info: (...args: any[]) => void;
|
|
202
|
+
warn: (...args: any[]) => void;
|
|
203
|
+
error: (...args: any[]) => void;
|
|
204
|
+
debug: (...args: any[]) => void;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Base framework context supplied to all service resolvers and action executions.
|
|
208
|
+
*/
|
|
209
|
+
interface BaseContext<TDb = any> {
|
|
210
|
+
request: Request;
|
|
211
|
+
db: TDb;
|
|
212
|
+
logger: Logger;
|
|
213
|
+
traceId: string;
|
|
214
|
+
requestId?: string;
|
|
215
|
+
services?: Record<string, any>;
|
|
216
|
+
metadata?: Record<string, unknown>;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Default fallback service context for untyped or simple services.
|
|
220
|
+
*/
|
|
221
|
+
interface DefaultServiceContext {
|
|
222
|
+
user?: any;
|
|
223
|
+
session?: any;
|
|
224
|
+
[key: string]: any;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The combined execution context: BaseContext & TServiceContext.
|
|
228
|
+
*/
|
|
229
|
+
type ActionContext<TDb = any, TServiceContext = DefaultServiceContext> = BaseContext<TDb> & TServiceContext;
|
|
230
|
+
/**
|
|
231
|
+
* Type utility that automatically narrows ctx.user from User | null to User
|
|
232
|
+
* in execute() when authorize() is declared on the action.
|
|
233
|
+
*/
|
|
234
|
+
type NarrowAuthorizedContext<TCtx> = TCtx extends {
|
|
235
|
+
user: infer U;
|
|
236
|
+
} ? [U] extends [null | undefined] ? TCtx : Omit<TCtx, "user"> & {
|
|
237
|
+
user: NonNullable<U>;
|
|
238
|
+
} : TCtx;
|
|
239
|
+
interface ActionErrorDefinition {
|
|
240
|
+
status?: number;
|
|
241
|
+
message: string;
|
|
242
|
+
}
|
|
243
|
+
interface ValidationErrorItem {
|
|
244
|
+
path: string;
|
|
245
|
+
message: string;
|
|
246
|
+
value?: unknown;
|
|
247
|
+
type?: number;
|
|
248
|
+
}
|
|
249
|
+
declare class ValidationError extends Error {
|
|
250
|
+
readonly status: number;
|
|
251
|
+
readonly errors: ValidationErrorItem[];
|
|
252
|
+
constructor(message: string, errors?: ValidationErrorItem[], status?: number);
|
|
253
|
+
toJSON(): {
|
|
254
|
+
name: string;
|
|
255
|
+
message: string;
|
|
256
|
+
status: number;
|
|
257
|
+
errors: ValidationErrorItem[];
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
declare class ActionExecutionError extends Error {
|
|
261
|
+
readonly code: string;
|
|
262
|
+
readonly status: number;
|
|
263
|
+
readonly details?: unknown;
|
|
264
|
+
constructor(code: string, message: string, status?: number, details?: unknown);
|
|
265
|
+
toJSON(): {
|
|
266
|
+
name: string;
|
|
267
|
+
code: string;
|
|
268
|
+
message: string;
|
|
269
|
+
status: number;
|
|
270
|
+
details: unknown;
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
interface StandardErrorMap {
|
|
274
|
+
BAD_REQUEST: (overrideMessage?: string, details?: unknown) => never;
|
|
275
|
+
UNAUTHORIZED: (overrideMessage?: string, details?: unknown) => never;
|
|
276
|
+
FORBIDDEN: (overrideMessage?: string, details?: unknown) => never;
|
|
277
|
+
NOT_FOUND: (overrideMessage?: string, details?: unknown) => never;
|
|
278
|
+
CONFLICT: (overrideMessage?: string, details?: unknown) => never;
|
|
279
|
+
INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown) => never;
|
|
280
|
+
[key: string]: ((overrideMessage?: string, details?: unknown) => never) | undefined;
|
|
281
|
+
}
|
|
282
|
+
type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: (overrideMessage?: string, details?: unknown) => never; };
|
|
283
|
+
interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
|
|
284
|
+
name: string;
|
|
285
|
+
description?: string;
|
|
286
|
+
/** Effective HTTP path, including the prefix; replaces the default action path. */
|
|
287
|
+
path?: string;
|
|
288
|
+
/** Single HTTP method exposed for this action (default POST). */
|
|
289
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
290
|
+
input?: TInputSchema;
|
|
291
|
+
output?: TOutputSchema;
|
|
292
|
+
errors?: TErrors;
|
|
293
|
+
emits?: string[];
|
|
294
|
+
tags?: string[];
|
|
295
|
+
}
|
|
296
|
+
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> {
|
|
297
|
+
authorize: (params: {
|
|
298
|
+
user?: TContext extends {
|
|
299
|
+
user: infer U;
|
|
300
|
+
} ? U : any;
|
|
301
|
+
input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
302
|
+
ctx: TContext;
|
|
303
|
+
}) => boolean | Promise<boolean>;
|
|
304
|
+
execute: (params: {
|
|
305
|
+
input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
306
|
+
ctx: NarrowAuthorizedContext<TContext>;
|
|
307
|
+
error: ErrorBuilder<TErrors>;
|
|
308
|
+
}) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
|
|
309
|
+
}
|
|
310
|
+
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> {
|
|
311
|
+
authorize?: undefined;
|
|
312
|
+
execute: (params: {
|
|
313
|
+
input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
314
|
+
ctx: TContext;
|
|
315
|
+
error: ErrorBuilder<TErrors>;
|
|
316
|
+
}) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
|
|
317
|
+
}
|
|
318
|
+
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>;
|
|
319
|
+
interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> {
|
|
320
|
+
(params: {
|
|
321
|
+
input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
322
|
+
ctx?: Partial<TContext>;
|
|
323
|
+
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
324
|
+
name: string;
|
|
325
|
+
serviceName?: string;
|
|
326
|
+
config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
|
|
327
|
+
run(input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
328
|
+
execute(params: {
|
|
329
|
+
input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
330
|
+
ctx?: Partial<TContext>;
|
|
331
|
+
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
332
|
+
executeResolved?(params: {
|
|
333
|
+
input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
334
|
+
ctx: TContext;
|
|
335
|
+
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
336
|
+
validateInput(input: unknown): {
|
|
337
|
+
success: true;
|
|
338
|
+
data: any;
|
|
339
|
+
} | {
|
|
340
|
+
success: false;
|
|
341
|
+
errors: ValidationErrorItem[];
|
|
342
|
+
};
|
|
343
|
+
validateOutput(output: unknown): {
|
|
344
|
+
success: true;
|
|
345
|
+
data: any;
|
|
346
|
+
} | {
|
|
347
|
+
success: false;
|
|
348
|
+
errors: ValidationErrorItem[];
|
|
349
|
+
};
|
|
350
|
+
errorHelpers?: ErrorBuilder<TErrors>;
|
|
351
|
+
}
|
|
352
|
+
/** MCP tool metadata, kept with the executable definition. */
|
|
353
|
+
interface ToolAnnotations {
|
|
354
|
+
title?: string;
|
|
355
|
+
readOnlyHint?: boolean;
|
|
356
|
+
destructiveHint?: boolean;
|
|
357
|
+
idempotentHint?: boolean;
|
|
358
|
+
openWorldHint?: boolean;
|
|
359
|
+
}
|
|
360
|
+
interface ToolOptions {
|
|
361
|
+
title?: string;
|
|
362
|
+
annotations?: ToolAnnotations;
|
|
363
|
+
/** Also register HTTP routes and OpenAPI. Defaults to false. */
|
|
364
|
+
http?: boolean;
|
|
365
|
+
}
|
|
366
|
+
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;
|
|
367
|
+
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;
|
|
368
|
+
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> {
|
|
369
|
+
readonly kind: "tool";
|
|
370
|
+
config: ToolConfigWithAuthorize<I, O, E, C> | ToolConfigWithoutAuthorize<I, O, E, C>;
|
|
371
|
+
}
|
|
372
|
+
interface ResourceOperationsConfig {
|
|
373
|
+
list?: boolean | {
|
|
374
|
+
defaultLimit?: number;
|
|
375
|
+
maxLimit?: number;
|
|
376
|
+
searchable?: string[];
|
|
377
|
+
sortable?: string[];
|
|
378
|
+
defaultSort?: string;
|
|
379
|
+
};
|
|
380
|
+
get?: boolean;
|
|
381
|
+
create?: boolean;
|
|
382
|
+
update?: boolean;
|
|
383
|
+
delete?: boolean;
|
|
384
|
+
}
|
|
385
|
+
type InferTableRow<TTable> = TTable extends {
|
|
386
|
+
$inferSelect: infer S;
|
|
387
|
+
} ? S : any;
|
|
388
|
+
type InferTableInsert<TTable> = TTable extends {
|
|
389
|
+
$inferInsert: infer S;
|
|
390
|
+
} ? S : any;
|
|
391
|
+
interface ResourceHooks<TRow = any, TInsert = any, TCtx = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
|
|
392
|
+
beforeCreate?: (params: {
|
|
393
|
+
data: TInsert;
|
|
394
|
+
ctx: TCtx;
|
|
395
|
+
error: ErrorBuilder<TErrors>;
|
|
396
|
+
}) => Promise<void> | void;
|
|
397
|
+
afterCreate?: (params: {
|
|
398
|
+
data: TInsert;
|
|
399
|
+
result: TRow;
|
|
400
|
+
ctx: TCtx;
|
|
401
|
+
}) => Promise<void> | void;
|
|
402
|
+
beforeUpdate?: (params: {
|
|
403
|
+
id: string | number;
|
|
404
|
+
data: Partial<TInsert>;
|
|
405
|
+
existing: TRow;
|
|
406
|
+
ctx: TCtx;
|
|
407
|
+
error: ErrorBuilder<TErrors>;
|
|
408
|
+
}) => Promise<void> | void;
|
|
409
|
+
afterUpdate?: (params: {
|
|
410
|
+
id: string | number;
|
|
411
|
+
data: Partial<TInsert>;
|
|
412
|
+
result: TRow;
|
|
413
|
+
ctx: TCtx;
|
|
414
|
+
}) => Promise<void> | void;
|
|
415
|
+
beforeDelete?: (params: {
|
|
416
|
+
id: string | number;
|
|
417
|
+
existing: TRow;
|
|
418
|
+
ctx: TCtx;
|
|
419
|
+
error: ErrorBuilder<TErrors>;
|
|
420
|
+
}) => Promise<void> | void;
|
|
421
|
+
afterDelete?: (params: {
|
|
422
|
+
id: string | number;
|
|
423
|
+
existing: TRow;
|
|
424
|
+
ctx: TCtx;
|
|
425
|
+
error: ErrorBuilder<TErrors>;
|
|
426
|
+
}) => Promise<void> | void;
|
|
427
|
+
}
|
|
428
|
+
interface ResourceConfig<TTable = any, TCtx = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
|
|
429
|
+
name: string;
|
|
430
|
+
table: TTable;
|
|
431
|
+
ownerField?: string;
|
|
432
|
+
idField?: string;
|
|
433
|
+
idPrefix?: string;
|
|
434
|
+
idGenerator?: () => string;
|
|
435
|
+
pluralName?: string;
|
|
436
|
+
operations?: ResourceOperationsConfig;
|
|
437
|
+
hooks?: ResourceHooks<InferTableRow<TTable>, InferTableInsert<TTable>, TCtx, TErrors>;
|
|
438
|
+
fields?: Record<string, TSchema>;
|
|
439
|
+
errors?: TErrors;
|
|
440
|
+
searchable?: string[];
|
|
441
|
+
sortable?: string[];
|
|
442
|
+
defaultSort?: string;
|
|
443
|
+
/** Columns excluded from default list projection (Go pageMeta parity: content). */
|
|
444
|
+
excludeFromList?: string[];
|
|
445
|
+
}
|
|
446
|
+
interface ResourcePlan<TTable = any> {
|
|
447
|
+
readonly resourceName: string;
|
|
448
|
+
readonly pluralName: string;
|
|
449
|
+
readonly table: TTable;
|
|
450
|
+
readonly idField: string;
|
|
451
|
+
readonly idCol: any;
|
|
452
|
+
readonly ownerField?: string;
|
|
453
|
+
readonly ownerCol?: any;
|
|
454
|
+
readonly ownerColName?: string;
|
|
455
|
+
readonly columnMap: Map<string, any>;
|
|
456
|
+
readonly columns: Record<string, any>;
|
|
457
|
+
readonly defaultColumns: ReadonlyArray<{
|
|
458
|
+
key: string;
|
|
459
|
+
default: any;
|
|
460
|
+
}>;
|
|
461
|
+
readonly timestampColumns: {
|
|
462
|
+
readonly createdAtKey: string | null;
|
|
463
|
+
readonly updatedAtKey: string | null;
|
|
464
|
+
};
|
|
465
|
+
readonly searchable: {
|
|
466
|
+
readonly fields?: string[];
|
|
467
|
+
readonly columns: any[];
|
|
468
|
+
};
|
|
469
|
+
readonly sortable: {
|
|
470
|
+
readonly fields: Set<string>;
|
|
471
|
+
readonly defaultSort: string;
|
|
472
|
+
readonly defaultSortEntries: ReadonlyArray<{
|
|
473
|
+
field: string;
|
|
474
|
+
dir: "asc" | "desc";
|
|
475
|
+
}>;
|
|
476
|
+
readonly fallbackEntries: ReadonlyArray<{
|
|
477
|
+
field: string;
|
|
478
|
+
dir: "asc" | "desc";
|
|
479
|
+
}>;
|
|
480
|
+
readonly tiebreakCol: any;
|
|
481
|
+
};
|
|
482
|
+
readonly projections: {
|
|
483
|
+
readonly defaultProjection?: Record<string, any>;
|
|
484
|
+
};
|
|
485
|
+
readonly routeTargets: {
|
|
486
|
+
readonly listPath: string;
|
|
487
|
+
readonly itemPath: string;
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
/** Options whose literals affect the generated CRUD types. */
|
|
491
|
+
type ResourceTypeOptions = Pick<ResourceConfig, "name" | "idField" | "ownerField" | "fields" | "errors" | "pluralName">;
|
|
492
|
+
type TableColumns<T> = T extends {
|
|
493
|
+
_: {
|
|
494
|
+
columns: infer C;
|
|
495
|
+
};
|
|
496
|
+
} ? C : {};
|
|
497
|
+
type ColumnName<C> = C extends {
|
|
498
|
+
_: {
|
|
499
|
+
name: infer N extends string;
|
|
500
|
+
};
|
|
501
|
+
} ? N : never;
|
|
502
|
+
type FieldKeys<T, F> = { [K in keyof TableColumns<T>]: K extends F ? K : ColumnName<TableColumns<T>[K]> extends F ? K : never; }[keyof TableColumns<T>];
|
|
503
|
+
type PrimaryKeys<T> = { [K in keyof TableColumns<T>]: TableColumns<T>[K] extends {
|
|
504
|
+
_: {
|
|
505
|
+
isPrimaryKey: true;
|
|
506
|
+
};
|
|
507
|
+
} ? K : never; }[keyof TableColumns<T>];
|
|
508
|
+
type IdField<O> = O extends {
|
|
509
|
+
idField: infer K extends string;
|
|
510
|
+
} ? K : "id";
|
|
511
|
+
type OwnerField<O> = O extends {
|
|
512
|
+
ownerField: infer K extends string;
|
|
513
|
+
} ? K : never;
|
|
514
|
+
type TimestampKeys<T> = FieldKeys<T, "created_at" | "updated_at"> | Extract<keyof TableColumns<T>, "createdAt" | "updatedAt">;
|
|
515
|
+
type GeneratedKeys<T, O> = PrimaryKeys<T> | FieldKeys<T, IdField<O> | OwnerField<O>> | TimestampKeys<T>;
|
|
516
|
+
type FieldSchema<T, O, K> = O extends {
|
|
517
|
+
fields: infer F;
|
|
518
|
+
} ? K extends keyof F ? F[K] : K extends keyof TableColumns<T> ? ColumnName<TableColumns<T>[K]> extends keyof F ? F[ColumnName<TableColumns<T>[K]>] : never : never : never;
|
|
519
|
+
type FieldValue<T, O, K, V> = [FieldSchema<T, O, K>] extends [never] ? V : FieldSchema<T, O, K> extends TSchema ? Static<FieldSchema<T, O, K>> : V;
|
|
520
|
+
/** The same editable columns as the runtime create schema, retaining defaults. */
|
|
521
|
+
type ResourceCreateInput<T, O = {}> = { [K in keyof Omit<InferTableInsert<T>, GeneratedKeys<T, O>>]: FieldValue<T, O, K, Exclude<InferTableInsert<T>[K & keyof InferTableInsert<T>], null>>; };
|
|
522
|
+
type ResourceIdInput<O = {}> = { [K in IdField<O>]: string; };
|
|
523
|
+
type ResourceUpdateInput<T, O = {}> = ResourceIdInput<O> & Partial<ResourceCreateInput<T, O>>;
|
|
524
|
+
type ResourceRow<T, O = {}> = { [K in keyof InferTableRow<T>]: FieldValue<T, O, K, InferTableRow<T>[K]> | Extract<InferTableRow<T>[K], null>; };
|
|
525
|
+
type ResourceListInput<T, O = {}> = Partial<{ [K in keyof Omit<ResourceRow<T, O>, TimestampKeys<T>>]: Exclude<ResourceRow<T, O>[K & keyof ResourceRow<T, O>], null>; }> & {
|
|
526
|
+
limit?: number;
|
|
527
|
+
offset?: number;
|
|
528
|
+
page?: number;
|
|
529
|
+
sort?: string;
|
|
530
|
+
search?: string;
|
|
531
|
+
select?: string | string[];
|
|
532
|
+
cursor?: string;
|
|
533
|
+
};
|
|
534
|
+
/** List rows may be projected by select or excludeFromList. */
|
|
535
|
+
type ResourceListResult<T, O = {}> = {
|
|
536
|
+
items: Partial<ResourceRow<T, O>>[];
|
|
537
|
+
total: number;
|
|
538
|
+
limit: number;
|
|
539
|
+
offset: number;
|
|
540
|
+
page?: number;
|
|
541
|
+
pageCount: number;
|
|
542
|
+
hasMore: boolean;
|
|
543
|
+
nextCursor: string | null;
|
|
544
|
+
};
|
|
545
|
+
type ResourceErrors<O> = O extends {
|
|
546
|
+
errors: infer E extends Record<string, ActionErrorDefinition>;
|
|
547
|
+
} ? E : {};
|
|
548
|
+
type ResourceActions<T, C extends ActionContext, O = {}> = 0 extends 1 & T ? {
|
|
549
|
+
list: Action<any, any, any, C>;
|
|
550
|
+
get: Action<any, any, any, C>;
|
|
551
|
+
create: Action<any, any, any, C>;
|
|
552
|
+
update: Action<any, any, any, C>;
|
|
553
|
+
delete: Action<any, any, any, C>;
|
|
554
|
+
} : {
|
|
555
|
+
list: Action<TUnsafe<ResourceListInput<T, O> | undefined>, TUnsafe<ResourceListResult<T, O>>, ResourceErrors<O>, C>;
|
|
556
|
+
get: Action<TUnsafe<ResourceIdInput<O>>, TUnsafe<ResourceRow<T, O>>, ResourceErrors<O> & Record<"NOT_FOUND" | "FORBIDDEN", ActionErrorDefinition>, C>;
|
|
557
|
+
create: Action<TUnsafe<ResourceCreateInput<T, O>>, TUnsafe<ResourceRow<T, O>>, ResourceErrors<O> & Record<"CONFLICT", ActionErrorDefinition>, C>;
|
|
558
|
+
update: Action<TUnsafe<ResourceUpdateInput<T, O>>, TUnsafe<ResourceRow<T, O>>, ResourceErrors<O> & Record<"NOT_FOUND" | "FORBIDDEN", ActionErrorDefinition>, C>;
|
|
559
|
+
delete: Action<TUnsafe<ResourceIdInput<O>>, TUnsafe<{
|
|
560
|
+
success: boolean;
|
|
561
|
+
id: string | number;
|
|
562
|
+
}>, ResourceErrors<O> & Record<"NOT_FOUND" | "FORBIDDEN", ActionErrorDefinition>, C>;
|
|
563
|
+
};
|
|
564
|
+
interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}> {
|
|
565
|
+
readonly name: string;
|
|
566
|
+
readonly serviceName: string;
|
|
567
|
+
readonly table: TTable;
|
|
568
|
+
readonly ownerField?: string;
|
|
569
|
+
readonly idField: string;
|
|
570
|
+
readonly pluralName: string;
|
|
571
|
+
readonly config: ResourceConfig<TTable, TCtx>;
|
|
572
|
+
readonly plan?: ResourcePlan<TTable>;
|
|
573
|
+
readonly actions: ResourceActions<TTable, TCtx, TOptions>;
|
|
574
|
+
list: ResourceActions<TTable, TCtx, TOptions>["list"];
|
|
575
|
+
get: ResourceActions<TTable, TCtx, TOptions>["get"];
|
|
576
|
+
create: ResourceActions<TTable, TCtx, TOptions>["create"];
|
|
577
|
+
update: ResourceActions<TTable, TCtx, TOptions>["update"];
|
|
578
|
+
delete: ResourceActions<TTable, TCtx, TOptions>["delete"];
|
|
579
|
+
}
|
|
580
|
+
interface ServiceAuthOptions {
|
|
581
|
+
requireAuth?: boolean;
|
|
582
|
+
allowedRoles?: string[];
|
|
583
|
+
policy?: (ctx: ActionContext) => boolean | Promise<boolean>;
|
|
584
|
+
}
|
|
585
|
+
interface RateLimitOptions {
|
|
586
|
+
maxRequests: number;
|
|
587
|
+
window: number | string;
|
|
588
|
+
scope?: "ip" | "user" | "tenant";
|
|
589
|
+
}
|
|
590
|
+
interface CacheOptions {
|
|
591
|
+
driver?: "memory" | "redis";
|
|
592
|
+
defaultTtl?: number;
|
|
593
|
+
}
|
|
594
|
+
interface ResilienceOptions {
|
|
595
|
+
timeoutMs?: number;
|
|
596
|
+
retry?: {
|
|
597
|
+
attempts: number;
|
|
598
|
+
backoff: "linear" | "exponential";
|
|
599
|
+
delayMs: number;
|
|
600
|
+
};
|
|
601
|
+
circuitBreaker?: {
|
|
602
|
+
errorThresholdPercentage: number;
|
|
603
|
+
resetTimeoutMs: number;
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
interface TelemetryOptions {
|
|
607
|
+
traceQueries?: boolean;
|
|
608
|
+
auditLog?: boolean;
|
|
609
|
+
tags?: Record<string, string>;
|
|
610
|
+
}
|
|
611
|
+
interface LifecycleOptions {
|
|
612
|
+
onInit?: (ctx: {
|
|
613
|
+
db?: any;
|
|
614
|
+
logger?: Logger;
|
|
615
|
+
}) => Promise<void>;
|
|
616
|
+
onDestroy?: () => Promise<void>;
|
|
617
|
+
}
|
|
618
|
+
interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
|
|
619
|
+
database?: DatabaseHandle<TDb>;
|
|
620
|
+
context?: (baseCtx: BaseContext<TDb>) => Promise<TServiceContext> | TServiceContext;
|
|
621
|
+
auth?: ServiceAuthOptions;
|
|
622
|
+
rateLimit?: RateLimitOptions;
|
|
623
|
+
cache?: CacheOptions;
|
|
624
|
+
resilience?: ResilienceOptions;
|
|
625
|
+
telemetry?: TelemetryOptions;
|
|
626
|
+
lifecycle?: LifecycleOptions;
|
|
627
|
+
}
|
|
628
|
+
interface ActionSchema {
|
|
629
|
+
name: string;
|
|
630
|
+
serviceName?: string;
|
|
631
|
+
description?: string;
|
|
632
|
+
inputSchema?: unknown;
|
|
633
|
+
outputSchema?: unknown;
|
|
634
|
+
hasAuthorize: boolean;
|
|
635
|
+
errors?: Record<string, ActionErrorDefinition>;
|
|
636
|
+
emits?: string[];
|
|
637
|
+
tags?: string[];
|
|
638
|
+
}
|
|
639
|
+
interface ServiceSchema {
|
|
640
|
+
name: string;
|
|
641
|
+
options: Omit<ServiceOptions, "database"> & {
|
|
642
|
+
database?: {
|
|
643
|
+
name?: string;
|
|
644
|
+
engine: "sqlite" | "postgres";
|
|
645
|
+
tables: string[];
|
|
646
|
+
};
|
|
647
|
+
};
|
|
648
|
+
hasDatabase: boolean;
|
|
649
|
+
databaseConfig?: {
|
|
650
|
+
name?: string;
|
|
651
|
+
engine: "sqlite" | "postgres";
|
|
652
|
+
tables: string[];
|
|
653
|
+
};
|
|
654
|
+
actions: ActionSchema[];
|
|
655
|
+
resources?: {
|
|
656
|
+
name: string;
|
|
657
|
+
ownerField?: string;
|
|
658
|
+
operations: string[];
|
|
659
|
+
}[];
|
|
660
|
+
}
|
|
661
|
+
interface ArchitectureSchema {
|
|
662
|
+
version: string;
|
|
663
|
+
services: ServiceSchema[];
|
|
664
|
+
}
|
|
665
|
+
interface CompiledRoutePlan {
|
|
666
|
+
service: Service<any, any>;
|
|
667
|
+
action: Action<any, any, any, any>;
|
|
668
|
+
actionName: string;
|
|
669
|
+
serviceName: string;
|
|
670
|
+
routePath: string;
|
|
671
|
+
method?: string;
|
|
672
|
+
isGetLike: boolean;
|
|
673
|
+
hasInput: boolean;
|
|
674
|
+
hasContextHook: boolean;
|
|
675
|
+
contextHook?: (baseCtx: any) => Promise<any> | any;
|
|
676
|
+
hasAuthorize: boolean;
|
|
677
|
+
authorize?: (params: any) => boolean | Promise<boolean>;
|
|
678
|
+
execute: (params: any) => Promise<any> | any;
|
|
679
|
+
inputChecker?: {
|
|
680
|
+
Check: (val: any) => boolean;
|
|
681
|
+
Errors: (val: any) => Iterable<any>;
|
|
682
|
+
};
|
|
683
|
+
outputChecker?: {
|
|
684
|
+
Check: (val: any) => boolean;
|
|
685
|
+
Errors: (val: any) => Iterable<any>;
|
|
686
|
+
};
|
|
687
|
+
coercions?: Array<{
|
|
688
|
+
key: string;
|
|
689
|
+
isNumber: boolean;
|
|
690
|
+
isBoolean: boolean;
|
|
691
|
+
}>;
|
|
692
|
+
logger: Logger;
|
|
693
|
+
errorBuilder: any;
|
|
694
|
+
cachedDb: any;
|
|
695
|
+
}
|
|
696
|
+
interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> {
|
|
697
|
+
readonly name: string;
|
|
698
|
+
readonly options: ServiceOptions<TServiceContext, TDb>;
|
|
699
|
+
readonly actions: Map<string, Action<any, any, any, any>>;
|
|
700
|
+
readonly tools: Map<string, Tool<any, any, any, any>>;
|
|
701
|
+
readonly tables: Map<string, any>;
|
|
702
|
+
readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext>>;
|
|
703
|
+
readonly db?: TDb;
|
|
704
|
+
readonly isBuilt?: boolean;
|
|
705
|
+
build(): this;
|
|
706
|
+
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;
|
|
707
|
+
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>;
|
|
708
|
+
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>;
|
|
709
|
+
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;
|
|
710
|
+
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>;
|
|
711
|
+
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>;
|
|
712
|
+
resource<TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions): Resource<TTable, BaseContext<TDb> & TServiceContext, TOptions>;
|
|
713
|
+
registerTable(table: any): this;
|
|
714
|
+
getAction(name: string): Action<any, any, any, any> | undefined;
|
|
715
|
+
listActions(): Action<any, any, any, any>[];
|
|
716
|
+
getTool(name: string): Tool<any, any, any, any> | undefined;
|
|
717
|
+
listTools(): Tool<any, any, any, any>[];
|
|
718
|
+
getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
|
|
719
|
+
listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
|
|
720
|
+
getDb(): TDb | undefined;
|
|
721
|
+
setDb(database: DatabaseHandle<TDb>): void;
|
|
722
|
+
resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
|
|
723
|
+
introspect(): ServiceSchema;
|
|
724
|
+
}
|
|
725
|
+
interface ProxyOptions {
|
|
726
|
+
isMonolith?: boolean;
|
|
727
|
+
context?: Partial<ActionContext>;
|
|
728
|
+
}
|
|
729
|
+
//#endregion
|
|
730
|
+
//#region src/client.d.ts
|
|
731
|
+
/**
|
|
732
|
+
* Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.
|
|
733
|
+
*
|
|
734
|
+
* The frontend imports only the contract *type* — never a backend implementation:
|
|
735
|
+
*
|
|
736
|
+
* ```ts
|
|
737
|
+
* import { createBrickClient } from "@brickkit/core/client";
|
|
738
|
+
* import type { AppServer } from "./server"; // `import type`: erased at build
|
|
739
|
+
*
|
|
740
|
+
* const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
|
|
741
|
+
* const pages = await api.page.list({ limit: 10, sort: "-createdAt" });
|
|
742
|
+
* const created = await api.page.create({ title: "Hello", content: "World" });
|
|
743
|
+
* ```
|
|
744
|
+
*
|
|
745
|
+
* Build the contract from individually-typed actions (each `defineAction` call
|
|
746
|
+
* preserves its input/output/error literal types):
|
|
747
|
+
*
|
|
748
|
+
* ```ts
|
|
749
|
+
* // server.ts (backend)
|
|
750
|
+
* export const listPages = pagesService.action({ name: "page.list", ... });
|
|
751
|
+
* export const createPage = pagesService.action({ name: "page.create", ... });
|
|
752
|
+
* export const contract = { page: { list: listPages, create: createPage } };
|
|
753
|
+
* export type AppServer = typeof contract;
|
|
754
|
+
* ```
|
|
755
|
+
*
|
|
756
|
+
* ## Result / error convention
|
|
757
|
+
*
|
|
758
|
+
* The client uses a throw-based convention that mirrors local `action.execute`
|
|
759
|
+
* semantics, because TypeScript promises cannot encode thrown exception types:
|
|
760
|
+
*
|
|
761
|
+
* - Success → the promise resolves with the action output.
|
|
762
|
+
* - Declared domain failures (your `errors: { SLUG_EXISTS: ... }`) and framework
|
|
763
|
+
* guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected with
|
|
764
|
+
* {@link ActionExecutionError} carrying the declared `code`, `status`,
|
|
765
|
+
* `message`, and `details`. Narrow with `instanceof` and read `err.code`.
|
|
766
|
+
* - Input/output validation failures → rejected with {@link ValidationError},
|
|
767
|
+
* exactly as local execution throws.
|
|
768
|
+
* - Network failures, unparsable bodies, and non-OK responses outside the
|
|
769
|
+
* declared contract → {@link BrickTransportError} (4xx) or
|
|
770
|
+
* {@link BrickServerError} (5xx).
|
|
771
|
+
* - Cancellation via `AbortSignal` → the native `AbortError` propagates
|
|
772
|
+
* unwrapped so `err.name === "AbortError"` keeps working.
|
|
773
|
+
*
|
|
774
|
+
* ## URL mapping
|
|
775
|
+
*
|
|
776
|
+
* A client path is a namespace walk ending in an action call. The leaf segment
|
|
777
|
+
* decides the route, matching the server compiler (`packages/cli/src/compiler`):
|
|
778
|
+
*
|
|
779
|
+
* | Client call | HTTP request |
|
|
780
|
+
* |---|---|
|
|
781
|
+
* | `api.page.list(input)` | `GET /api/page?...` (query) |
|
|
782
|
+
* | `api.page.create(input)` | `POST /api/page` (JSON body) |
|
|
783
|
+
* | `api.page.get({ id })` | `GET /api/page/:id` (+ remaining input as query) |
|
|
784
|
+
* | `api.page.update({ id, ...rest })` | `PATCH /api/page/:id` (JSON body of `rest`) |
|
|
785
|
+
* | `api.page.delete({ id })` | `DELETE /api/page/:id` |
|
|
786
|
+
* | `api.billing.charge(input)` | `POST /api/billing/charge` (JSON body) |
|
|
787
|
+
*
|
|
788
|
+
* The last rule covers every custom action: `api.<service>.<action>` (deeper
|
|
789
|
+
* namespaces join the tail with `.` to rebuild dotted action names such as
|
|
790
|
+
* `page.render`). By default the leading segment must equal the backend
|
|
791
|
+
* service name and the segment above a resource operation must equal the
|
|
792
|
+
* resource name. Pass the runtime contract (`contract` option) to drop that
|
|
793
|
+
* constraint: routing then uses each action's bound `serviceName` and each
|
|
794
|
+
* resource's `name`, so contract keys become purely organizational.
|
|
795
|
+
* `GET`-style input is serialized as a query string; `POST`/`PATCH` input goes in the JSON body.
|
|
796
|
+
*/
|
|
797
|
+
interface BrickClientOptions {
|
|
798
|
+
/** Server origin, e.g. `"http://localhost:4000"`. No trailing slash required. */
|
|
799
|
+
baseUrl: string;
|
|
800
|
+
/**
|
|
801
|
+
* Route prefix the server was mounted with (default `"/api"`).
|
|
802
|
+
* Must match the `prefix` passed to `brick({ prefix })`.
|
|
803
|
+
*/
|
|
804
|
+
prefix?: string;
|
|
805
|
+
/**
|
|
806
|
+
* Default headers sent with every call (e.g. an `Authorization` bearer).
|
|
807
|
+
* A thunk is re-evaluated per call, so rotated tokens stay fresh.
|
|
808
|
+
*/
|
|
809
|
+
headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
|
|
810
|
+
/** `fetch` implementation. Defaults to `globalThis.fetch`. */
|
|
811
|
+
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
812
|
+
/** Default signal applied to every call (per-call `signal` wins). */
|
|
813
|
+
signal?: AbortSignal;
|
|
814
|
+
/** Default per-call timeout in milliseconds (per-call `timeoutMs` wins). */
|
|
815
|
+
timeoutMs?: number;
|
|
816
|
+
/**
|
|
817
|
+
* Runtime action/resource metadata or a generated browser-safe contract.
|
|
818
|
+
* When provided, routes resolve from bound metadata — each action's
|
|
819
|
+
* `serviceName`/`name` and each resource's `name` — so contract keys can be
|
|
820
|
+
* named freely. Omit it for pure type-only usage (`import type`), in which
|
|
821
|
+
* case contract keys must match service/resource names.
|
|
822
|
+
*/
|
|
823
|
+
contract?: Record<string, any>;
|
|
824
|
+
}
|
|
825
|
+
/** Browser-safe action metadata generated by the Brick Vite plugin. */
|
|
826
|
+
interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
|
|
827
|
+
kind: "action";
|
|
828
|
+
name: string;
|
|
829
|
+
serviceName: string;
|
|
830
|
+
config: {
|
|
831
|
+
path: string;
|
|
832
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
833
|
+
};
|
|
834
|
+
/** Type information only; never emitted at runtime. */
|
|
835
|
+
readonly __types?: {
|
|
836
|
+
input: TInput;
|
|
837
|
+
output: TOutput;
|
|
838
|
+
errors: TErrors;
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
interface BrickCallOptions {
|
|
842
|
+
/** Extra headers merged over the client defaults for this call only. */
|
|
843
|
+
headers?: Record<string, string>;
|
|
844
|
+
/** Abort signal for this call only. Never wrapped: aborts reject with `AbortError`. */
|
|
845
|
+
signal?: AbortSignal;
|
|
846
|
+
/** Per-call timeout in milliseconds. Implemented with `AbortSignal.timeout`. */
|
|
847
|
+
timeoutMs?: number;
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* The request never received a meaningful server answer: DNS / connection
|
|
851
|
+
* failure, a malformed body, or a 4xx response outside the declared contract
|
|
852
|
+
* (no `code` and no `ValidationError` shape).
|
|
853
|
+
*/
|
|
854
|
+
declare class BrickTransportError extends Error {
|
|
855
|
+
readonly kind: "transport";
|
|
856
|
+
readonly status?: number;
|
|
857
|
+
readonly url: string;
|
|
858
|
+
readonly body?: unknown;
|
|
859
|
+
readonly cause?: unknown;
|
|
860
|
+
constructor(message: string, opts: {
|
|
861
|
+
status?: number;
|
|
862
|
+
url: string;
|
|
863
|
+
body?: unknown;
|
|
864
|
+
cause?: unknown;
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* The server answered 5xx without a declared `code` / `ValidationError` shape,
|
|
869
|
+
* i.e. an unexpected failure rather than a modelled domain error.
|
|
870
|
+
*/
|
|
871
|
+
declare class BrickServerError extends Error {
|
|
872
|
+
readonly kind: "server";
|
|
873
|
+
readonly status: number;
|
|
874
|
+
readonly url: string;
|
|
875
|
+
readonly body: unknown;
|
|
876
|
+
constructor(message: string, opts: {
|
|
877
|
+
status: number;
|
|
878
|
+
url: string;
|
|
879
|
+
body: unknown;
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
declare function isBrickTransportError(err: unknown): err is BrickTransportError;
|
|
883
|
+
declare function isBrickServerError(err: unknown): err is BrickServerError;
|
|
884
|
+
/** Static input type from the schema, with a fallback for structural actions. */
|
|
885
|
+
type InferActionInput<A> = A extends BrickClientAction<infer I, any, any> ? I : A extends {
|
|
886
|
+
config: {
|
|
887
|
+
input?: infer S extends TSchema;
|
|
888
|
+
};
|
|
889
|
+
} ? Static<S> : A extends {
|
|
890
|
+
execute(params: {
|
|
891
|
+
input?: infer I;
|
|
892
|
+
ctx?: any;
|
|
893
|
+
}): any;
|
|
894
|
+
} ? I : A extends {
|
|
895
|
+
run(input?: infer I, ctx?: any): any;
|
|
896
|
+
} ? I : A extends ((params: {
|
|
897
|
+
input?: infer I;
|
|
898
|
+
ctx?: any;
|
|
899
|
+
}) => any) ? I : unknown;
|
|
900
|
+
/** Resolved output type of an action. */
|
|
901
|
+
type InferActionOutput<A> = A extends BrickClientAction<any, infer O, any> ? O : A extends ((...args: any[]) => Promise<infer O>) ? O : A extends {
|
|
902
|
+
execute(params: any): Promise<infer O>;
|
|
903
|
+
} ? O : unknown;
|
|
904
|
+
/** Union of error `code`s declared in an action's `errors` map. */
|
|
905
|
+
type InferActionErrorCodes<A> = A extends BrickClientAction<any, any, infer E> ? Extract<keyof E, string> : A extends {
|
|
906
|
+
config: {
|
|
907
|
+
errors?: infer E;
|
|
908
|
+
};
|
|
909
|
+
} ? E extends Record<string, ActionErrorDefinition> ? Extract<keyof E, string> : never : never;
|
|
910
|
+
/**
|
|
911
|
+
* The declared failure shape of an action for `catch` narrowing:
|
|
912
|
+
* ```ts
|
|
913
|
+
* try { await api.page.create(input); }
|
|
914
|
+
* catch (err) {
|
|
915
|
+
* if (err instanceof ActionExecutionError) {
|
|
916
|
+
* const code: InferActionErrorCodes<typeof createPage> | "UNAUTHORIZED" | ... = err.code;
|
|
917
|
+
* }
|
|
918
|
+
* }
|
|
919
|
+
* ```
|
|
920
|
+
* (Standard framework codes are always possible alongside declared ones.)
|
|
921
|
+
*/
|
|
922
|
+
type InferActionFailure<A> = ActionExecutionError & {
|
|
923
|
+
code: InferActionErrorCodes<A> | "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "INTERNAL_SERVER_ERROR" | "VALIDATION_ERROR";
|
|
924
|
+
};
|
|
925
|
+
/**
|
|
926
|
+
* Typed caller for one action. Required inputs stay required; actions whose
|
|
927
|
+
* input includes `undefined` (no schema / all-optional) can be called bare.
|
|
928
|
+
*/
|
|
929
|
+
type BrickActionCaller<A> = undefined extends InferActionInput<A> ? (input?: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>> : (input: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>>;
|
|
930
|
+
/** Typed client for a {@link Resource}: its five CRUD operations. */
|
|
931
|
+
type BrickResourceClient<R> = { [K in keyof R as K extends "list" | "get" | "create" | "update" | "delete" ? K : never]: R[K] extends Action<any, any, any, any> ? BrickActionCaller<R[K]> : never; };
|
|
932
|
+
/**
|
|
933
|
+
* Recursively maps an application contract to its typed client. Leaves that
|
|
934
|
+
* are actions (or action-like functions) become callers; resources become
|
|
935
|
+
* `{ list, get, create, update, delete }`; plain namespace objects recurse.
|
|
936
|
+
* Anything else passes through untouched.
|
|
937
|
+
*/
|
|
938
|
+
type BrickClient<T> = T extends BrickClientAction<any, any, any> | Action<any, any, any, any> ? BrickActionCaller<T> : T extends Resource<any, any> ? BrickResourceClient<T> : T extends ((...args: any[]) => any) ? BrickActionCaller<T> : T extends object ? { [K in keyof T]: BrickClient<T[K]>; } : T;
|
|
939
|
+
/**
|
|
940
|
+
* Create an Eden/tRPC-style typed client for the application contract `TApp`.
|
|
941
|
+
* `TApp` is a type-only parameter: `import type { AppServer }` keeps backend
|
|
942
|
+
* implementations out of the frontend bundle.
|
|
943
|
+
*/
|
|
944
|
+
declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions & {
|
|
945
|
+
contract: TApp;
|
|
946
|
+
}): BrickClient<TApp>;
|
|
947
|
+
declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
|
|
948
|
+
//#endregion
|
|
949
|
+
export { ServiceAuthOptions as $, ErrorBuilder as A, resolveSecrets as At, ResourceActions as B, primaryKey as Bt, ActionSchema as C, SecretRef as Ct, CacheOptions as D, overrideSecret as Dt, BaseContext as E, listSecrets as Et, NarrowAuthorizedContext as F, blob as Ft, ResourceListInput as G, ResourceCreateInput as H, sqliteTable as Ht, ProxyOptions as I, createSQLiteDatabase as It, ResourcePlan as J, ResourceListResult as K, RateLimitOptions as L, foreignKey as Lt, InferTableRow as M, BrickSQLiteDatabase as Mt, LifecycleOptions as N, BunSQLiteDatabase$1 as Nt, CompiledRoutePlan as O, overrideSecrets as Ot, Logger as P, SQLiteDatabaseConfig as Pt, Service as Q, ResilienceOptions as R, index as Rt, ActionExecutionError as S, SecretOptions as St, BaseActionConfig as T, envSource as Tt, ResourceHooks as U, text as Ut, ResourceConfig as V, real as Vt, ResourceIdInput as W, uniqueIndex as Wt, ResourceTypeOptions as X, ResourceRow as Y, ResourceUpdateInput as Z, ActionConfig as _, isDatabaseHandle as _t, BrickClientOptions as a, ToolAnnotations as at, ActionContext as b, PostgresDatabaseConfig as bt, BrickTransportError as c, ToolOptions as ct, InferActionInput as d, DatabaseDefinition as dt, ServiceOptions as et, InferActionOutput as f, DatabaseHandle as ft, Action as g, defineDatabase as gt, isBrickTransportError as h, SQLiteDefinition as ht, BrickClientAction as i, Tool as it, InferTableInsert as j, secret as jt, DefaultServiceContext as k, resetSecrets as kt, InferActionErrorCodes as l, ValidationError as lt, isBrickServerError as m, PostgresDefinition as mt, BrickCallOptions as n, StandardErrorMap as nt, BrickResourceClient as o, ToolConfigWithAuthorize as ot, createBrickClient as p, EnvInput as pt, ResourceOperationsConfig as q, BrickClient as r, TelemetryOptions as rt, BrickServerError as s, ToolConfigWithoutAuthorize as st, BrickActionCaller as t, ServiceSchema as tt, InferActionFailure as u, ValidationErrorItem as ut, ActionConfigWithAuthorize as v, DatabaseAdapter as vt, ArchitectureSchema as w, SecretSource as wt, ActionErrorDefinition as x, createPostgresDatabase as xt, ActionConfigWithoutAuthorize as y, PostgresDatabase as yt, Resource as z, integer as zt };
|
|
950
|
+
//# sourceMappingURL=client.d.ts.map
|