@brickkit/core 0.4.0 → 0.4.2
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/chunks/client.d.ts +18 -12
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js +5 -3
- package/dist/chunks/client.js.map +1 -1
- package/dist/index.d.ts +22 -18
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +169 -186
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/chunks/client.d.ts
CHANGED
|
@@ -313,6 +313,8 @@ interface BaseContext<TDb = any> {
|
|
|
313
313
|
logger: Logger;
|
|
314
314
|
traceId: string;
|
|
315
315
|
requestId?: string;
|
|
316
|
+
caller?: string;
|
|
317
|
+
tenantId?: string;
|
|
316
318
|
services?: Record<string, any>;
|
|
317
319
|
metadata?: Record<string, unknown>;
|
|
318
320
|
}
|
|
@@ -348,11 +350,13 @@ interface ValidationErrorItem {
|
|
|
348
350
|
type?: number;
|
|
349
351
|
}
|
|
350
352
|
declare class ValidationError extends Error {
|
|
353
|
+
readonly code = "VALIDATION_FAILED";
|
|
351
354
|
readonly status: number;
|
|
352
355
|
readonly errors: ValidationErrorItem[];
|
|
353
356
|
constructor(message: string, errors?: ValidationErrorItem[], status?: number);
|
|
354
357
|
toJSON(): {
|
|
355
358
|
name: string;
|
|
359
|
+
code: string;
|
|
356
360
|
message: string;
|
|
357
361
|
status: number;
|
|
358
362
|
errors: ValidationErrorItem[];
|
|
@@ -362,7 +366,7 @@ declare class ActionExecutionError extends Error {
|
|
|
362
366
|
readonly code: string;
|
|
363
367
|
readonly status: number;
|
|
364
368
|
readonly details?: unknown;
|
|
365
|
-
constructor(code: string, message: string, status?: number, details?: unknown);
|
|
369
|
+
constructor(code: string, message: string, status?: number, details?: unknown, options?: ErrorOptions);
|
|
366
370
|
toJSON(): {
|
|
367
371
|
name: string;
|
|
368
372
|
code: string;
|
|
@@ -372,15 +376,15 @@ declare class ActionExecutionError extends Error {
|
|
|
372
376
|
};
|
|
373
377
|
}
|
|
374
378
|
interface StandardErrorMap {
|
|
375
|
-
BAD_REQUEST: (overrideMessage?: string, details?: unknown) => never;
|
|
376
|
-
UNAUTHORIZED: (overrideMessage?: string, details?: unknown) => never;
|
|
377
|
-
FORBIDDEN: (overrideMessage?: string, details?: unknown) => never;
|
|
378
|
-
NOT_FOUND: (overrideMessage?: string, details?: unknown) => never;
|
|
379
|
-
CONFLICT: (overrideMessage?: string, details?: unknown) => never;
|
|
380
|
-
INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown) => never;
|
|
381
|
-
[key: string]: ((overrideMessage?: string, details?: unknown) => never) | undefined;
|
|
382
|
-
}
|
|
383
|
-
type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: (overrideMessage?: string, details?: unknown) => never; };
|
|
379
|
+
BAD_REQUEST: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
380
|
+
UNAUTHORIZED: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
381
|
+
FORBIDDEN: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
382
|
+
NOT_FOUND: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
383
|
+
CONFLICT: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
384
|
+
INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
385
|
+
[key: string]: ((overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never) | undefined;
|
|
386
|
+
}
|
|
387
|
+
type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never; };
|
|
384
388
|
interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
|
|
385
389
|
name: string;
|
|
386
390
|
description?: string;
|
|
@@ -566,7 +570,9 @@ interface LifecycleOptions {
|
|
|
566
570
|
}
|
|
567
571
|
interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
|
|
568
572
|
database?: DatabaseHandle<TDb>;
|
|
569
|
-
context?: (baseCtx: BaseContext<TDb>
|
|
573
|
+
context?: (baseCtx: BaseContext<TDb> & {
|
|
574
|
+
user?: unknown;
|
|
575
|
+
}) => Promise<TServiceContext> | TServiceContext;
|
|
570
576
|
auth?: ServiceAuthOptions;
|
|
571
577
|
rateLimit?: RateLimitOptions;
|
|
572
578
|
cache?: CacheOptions;
|
|
@@ -868,7 +874,7 @@ type InferActionErrorCodes<A> = A extends BrickClientAction<any, any, infer E> ?
|
|
|
868
874
|
* (Standard framework codes are always possible alongside declared ones.)
|
|
869
875
|
*/
|
|
870
876
|
type InferActionFailure<A> = ActionExecutionError & {
|
|
871
|
-
code: InferActionErrorCodes<A> | "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "INTERNAL_SERVER_ERROR" | "
|
|
877
|
+
code: InferActionErrorCodes<A> | "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "INTERNAL_SERVER_ERROR" | "VALIDATION_FAILED";
|
|
872
878
|
};
|
|
873
879
|
/**
|
|
874
880
|
* Typed caller for one action. Required inputs stay required; actions whose
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","names":["BunSQLiteDatabase","_$__plugin0.ResourcePluginAPI","BunSQLiteDatabase"],"sources":["../../src/plugin.ts","../../src/db/sqlite.ts","../../src/secrets.ts","../../src/db/postgres.ts","../../src/db/define.ts","../../src/types.ts","../../src/client.ts"],"mappings":";;;;;;;;KAcY;KACA;KACA,aAAa,UAAU,mBAAmB,4BAElD,SAAS;EAAyB;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,OACA,KAAK;EAAkB,MAAM,YAAY;IAC3C;UAEa;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;;cAGW,wBAAwB;WAC1B;WACA,QAAQ;EAGf,YAAA,iBACA,SAAQ,uBACR;EAQF
|
|
1
|
+
{"version":3,"file":"client.d.ts","names":["BunSQLiteDatabase","_$__plugin0.ResourcePluginAPI","BunSQLiteDatabase"],"sources":["../../src/plugin.ts","../../src/db/sqlite.ts","../../src/secrets.ts","../../src/db/postgres.ts","../../src/db/define.ts","../../src/types.ts","../../src/client.ts"],"mappings":";;;;;;;;KAcY;KACA;KACA,aAAa,UAAU,mBAAmB,4BAElD,SAAS;EAAyB;EAAe,QAAQ;;KAExD,UAAU,KACb,UAAU,cAAc,SAAS,KAAK,YAAY,KAAK;UAExC,sBACf,UAAU,gBAAgB;EAE1B,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;EACT;IAAO;IAAiB,SAAS;;EACjC,KAAK;;UAGU,qBACf,UAAU,gBAAgB,eAC1B,UAAU,mBAAmB;EAE7B,OACE,UAAU,iCACV,UAAU,iCACV,UAAU,eAAe,yBAAyB,eAEhD,wBAGF,QAAQ,0BAA0B,GAAG,GAAG,GAAG;IACzC;IACA,QAAQ;IACR,QAAQ;MAET,OAAO,GAAG,GAAG,GAAG;EACnB,OACE,UAAU,iCACV,UAAU,iCACV,UAAU,eAAe,yBAAyB,eAEhD,wBAGF,QAAQ,6BAA6B,GAAG,GAAG,GAAG;IAC5C;IACA,QAAQ;IACR,QAAQ;MAET,OAAO,GAAG,GAAG,GAAG;EACnB,SAAS;IACP;IACA;IACA,QAAQ;IACR,QAAQ;IACR,UAAU,SAAS,sBAAsB,iBAAiB;IAC1D;IACA;IACA;;;UAIa,qBACf,UAAU,oBAAoB;EAE9B,SAAS;EACT,QAAQ,qBAAqB,UAAU;;UAExB,sBACf,UAAU,oBAAoB,mBAC9B,UAAU,0BAA0B,cAAc,UAAU;EAE5D,SAAS;EACT,UAAU;EACV,Q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ACA,6BACA,kBAAkB,KAClB,eAAc,uBACZ,kBAAkB,KAClB,sBACK,WAAW,IAAI,YAAY,EAAE,SAChC;;;;;;iBAiSQ,kBAAkB,aAAa,qBAC7C,SAAS;EAAuB,UAAU;IACzC,YAAY;iBACC,kBAAkB,aAAa,qBAC7C,SAAS,qBACR,YAAY"}
|
package/dist/chunks/client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
//#region src/types.ts
|
|
2
2
|
var ValidationError = class extends Error {
|
|
3
|
+
code = "VALIDATION_FAILED";
|
|
3
4
|
status;
|
|
4
5
|
errors;
|
|
5
6
|
constructor(message, errors = [], status = 400) {
|
|
@@ -11,6 +12,7 @@ var ValidationError = class extends Error {
|
|
|
11
12
|
toJSON() {
|
|
12
13
|
return {
|
|
13
14
|
name: this.name,
|
|
15
|
+
code: this.code,
|
|
14
16
|
message: this.message,
|
|
15
17
|
status: this.status,
|
|
16
18
|
errors: this.errors
|
|
@@ -21,8 +23,8 @@ var ActionExecutionError = class extends Error {
|
|
|
21
23
|
code;
|
|
22
24
|
status;
|
|
23
25
|
details;
|
|
24
|
-
constructor(code, message, status = 400, details) {
|
|
25
|
-
super(message);
|
|
26
|
+
constructor(code, message, status = 400, details, options) {
|
|
27
|
+
super(message, options);
|
|
26
28
|
this.name = "ActionExecutionError";
|
|
27
29
|
this.code = code;
|
|
28
30
|
this.status = status;
|
|
@@ -148,8 +150,8 @@ function planRequest(path, target, input, baseUrl, prefix) {
|
|
|
148
150
|
function toActionError(status, body, url) {
|
|
149
151
|
if (body !== null && typeof body === "object") {
|
|
150
152
|
const record = body;
|
|
151
|
-
if (typeof record.code === "string") return new ActionExecutionError(record.code, typeof record.message === "string" ? record.message : record.code, typeof record.status === "number" ? record.status : status, record.details ?? void 0);
|
|
152
153
|
if (record.name === "ValidationError") return new ValidationError(typeof record.message === "string" ? record.message : "Validation failed", Array.isArray(record.errors) ? record.errors : [], typeof record.status === "number" ? record.status : status);
|
|
154
|
+
if (typeof record.code === "string") return new ActionExecutionError(record.code, typeof record.message === "string" ? record.message : record.code, typeof record.status === "number" ? record.status : status, record.details ?? void 0);
|
|
153
155
|
}
|
|
154
156
|
if (status >= 500) return new BrickServerError(`Unexpected server error (status ${status}) for ${url}.`, {
|
|
155
157
|
status,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/types.ts","../../src/client.ts"],"sourcesContent":["import type { ServicePlugin, ResourcePlugin } from \"./plugin\";\nimport type { TSchema, Static } from \"@sinclair/typebox\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type { DatabaseHandle } from \"./db/define\";\n\nexport interface Logger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/**\n * Base framework context supplied to all service resolvers and action executions.\n */\nexport interface BaseContext<TDb = any> {\n request: Request;\n db: TDb;\n logger: Logger;\n traceId: string;\n requestId?: string;\n services?: Record<string, any>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Default fallback service context for untyped or simple services.\n */\nexport interface DefaultServiceContext {\n user?: any;\n session?: any;\n [key: string]: any;\n}\n\n/**\n * The combined execution context: BaseContext & TServiceContext.\n */\nexport type ActionContext<\n TDb = any,\n TServiceContext = DefaultServiceContext,\n> = BaseContext<TDb> & TServiceContext;\n\n/**\n * Type utility that automatically narrows ctx.user from User | null to User\n * in execute() when authorize() is declared on the action.\n */\nexport type NarrowAuthorizedContext<TCtx> = TCtx extends { user: infer U }\n ? [U] extends [null | undefined]\n ? TCtx\n : Omit<TCtx, \"user\"> & { user: NonNullable<U> }\n : TCtx;\n\nexport interface ActionErrorDefinition {\n status?: number;\n message: string;\n}\n\nexport interface ValidationErrorItem {\n path: string;\n message: string;\n value?: unknown;\n type?: number;\n}\n\nexport class ValidationError extends Error {\n readonly status: number;\n readonly errors: ValidationErrorItem[];\n\n constructor(\n message: string,\n errors: ValidationErrorItem[] = [],\n status = 400,\n ) {\n super(message);\n this.name = \"ValidationError\";\n this.status = status;\n this.errors = errors;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n errors: this.errors,\n };\n }\n}\n\nexport class ActionExecutionError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status = 400, details?: unknown) {\n super(message);\n this.name = \"ActionExecutionError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n details: this.details,\n };\n }\n}\n\nexport interface StandardErrorMap {\n BAD_REQUEST: (overrideMessage?: string, details?: unknown) => never;\n UNAUTHORIZED: (overrideMessage?: string, details?: unknown) => never;\n FORBIDDEN: (overrideMessage?: string, details?: unknown) => never;\n NOT_FOUND: (overrideMessage?: string, details?: unknown) => never;\n CONFLICT: (overrideMessage?: string, details?: unknown) => never;\n INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown) => never;\n [key: string]:\n | ((overrideMessage?: string, details?: unknown) => never)\n | undefined;\n}\n\nexport type ErrorBuilder<\n TErrors extends Record<string, ActionErrorDefinition>,\n> = StandardErrorMap & {\n [K in keyof TErrors]: (overrideMessage?: string, details?: unknown) => never;\n};\n\nexport interface BaseActionConfig<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n> {\n name: string;\n description?: string;\n /** Effective HTTP path, including the prefix; replaces the default action path. */\n path?: string;\n /** Single HTTP method exposed for this action (default POST). */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n input?: TInputSchema;\n output?: TOutputSchema;\n errors?: TErrors;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ActionConfigWithAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize: (params: {\n user?: TContext extends { user: infer U } ? U : any;\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }) => boolean | Promise<boolean>;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: NarrowAuthorizedContext<TContext>;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport interface ActionConfigWithoutAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize?: undefined;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport type ActionConfig<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> =\n | ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>\n | ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >;\n\nexport interface Action<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> {\n (params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n\n name: string;\n serviceName?: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;\n /**\n * Optional runtime-only output schema. When present, `validateOutput` and\n * HTTP output checking validate against it instead of `config.output`,\n * while `config.output` remains the published contract (client types,\n * OpenAPI). Lets projected/subset responses validate at runtime without\n * leaking optionality into the generated contract.\n */\n outputValidationSchema?: TSchema;\n run(\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any,\n ctx?: Partial<TContext>,\n ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n execute(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n executeResolved?(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n validateInput(\n input: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n validateOutput(\n output: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n errorHelpers?: ErrorBuilder<TErrors>;\n}\n\n/** MCP tool metadata, kept with the executable definition. */\nexport interface ToolAnnotations {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\nexport interface ToolOptions {\n title?: string;\n annotations?: ToolAnnotations;\n /** Also register HTTP routes and OpenAPI. Defaults to false. */\n http?: boolean;\n}\nexport type ToolConfigWithAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;\nexport type ToolConfigWithoutAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;\nexport interface Tool<\n I extends TSchema | undefined = any,\n O extends TSchema | undefined = any,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> extends Action<I, O, E, C> {\n readonly kind: \"tool\";\n config:\n | ToolConfigWithAuthorize<I, O, E, C>\n | ToolConfigWithoutAuthorize<I, O, E, C>;\n}\n\n/** A resource declares identity and a table; plugins supply behavior. */\nexport interface ResourceConfig<TTable = any, _TCtx = any> {\n name: string;\n table: TTable;\n id?: import(\"drizzle-orm\").Column;\n}\n\nexport type InferTableRow<TTable> = TTable extends { $inferSelect: infer S }\n ? S\n : any;\nexport type InferTableInsert<TTable> = TTable extends { $inferInsert: infer S }\n ? S\n : any;\nexport type ResourceTypeOptions = Pick<ResourceConfig, \"name\" | \"id\">;\n\ntype PrimaryColumn<T> = T extends { _: { columns: infer C } }\n ? {\n [K in keyof C]: C[K] extends { _: { isPrimaryKey: true } } ? C[K] : never;\n }[keyof C]\n : import(\"drizzle-orm\").Column;\nexport type ResourceIdentity<T, O> = O & {\n id: O extends { id: infer I extends import(\"drizzle-orm\").Column }\n ? I\n : PrimaryColumn<T>;\n};\n\n/** Generic preparation declarations consumed by the application compiler. */\nexport interface PreparationContribution {\n readonly name: string;\n describe(): unknown;\n prepare(): void;\n}\n\nexport interface Resource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n TOptions = {},\n> {\n use<\n P extends ResourcePlugin<\n Service<TCtx[\"db\"], Omit<TCtx, keyof BaseContext>>,\n this,\n any\n >,\n >(\n plugin: P,\n ): this & import(\"./plugin\").ResourcePluginAPI<P, TTable, TCtx, this>;\n readonly name: string;\n readonly serviceName: string;\n readonly table: TTable;\n readonly id: TOptions extends {\n id: infer I extends import(\"drizzle-orm\").Column;\n }\n ? I\n : import(\"drizzle-orm\").Column;\n readonly idField: string;\n readonly config: ResourceConfig<TTable, TCtx> & TOptions;\n}\n\nexport interface ServiceAuthOptions {\n requireAuth?: boolean;\n allowedRoles?: string[];\n policy?: (ctx: ActionContext) => boolean | Promise<boolean>;\n}\n\nexport interface RateLimitOptions {\n maxRequests: number;\n window: number | string;\n scope?: \"ip\" | \"user\" | \"tenant\";\n}\n\nexport interface CacheOptions {\n driver?: \"memory\" | \"redis\";\n defaultTtl?: number;\n}\n\nexport interface ResilienceOptions {\n timeoutMs?: number;\n retry?: {\n attempts: number;\n backoff: \"linear\" | \"exponential\";\n delayMs: number;\n };\n circuitBreaker?: {\n errorThresholdPercentage: number;\n resetTimeoutMs: number;\n };\n}\n\nexport interface TelemetryOptions {\n traceQueries?: boolean;\n auditLog?: boolean;\n tags?: Record<string, string>;\n}\n\nexport interface LifecycleOptions {\n onInit?: (ctx: { db?: any; logger?: Logger }) => Promise<void>;\n onDestroy?: () => Promise<void>;\n}\n\nexport interface ServiceOptions<\n TServiceContext extends Record<string, any> = Record<string, any>,\n TDb = any,\n> {\n database?: DatabaseHandle<TDb>;\n context?: (\n baseCtx: BaseContext<TDb>,\n ) => Promise<TServiceContext> | TServiceContext;\n auth?: ServiceAuthOptions;\n rateLimit?: RateLimitOptions;\n cache?: CacheOptions;\n resilience?: ResilienceOptions;\n telemetry?: TelemetryOptions;\n lifecycle?: LifecycleOptions;\n}\n\nexport type ActionAccessPolicy = \"public\" | \"authorized\" | \"scoped\";\n\nexport interface ActionSchema {\n name: string;\n /** Present only when this action has a registered HTTP route. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path?: string;\n serviceName?: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n hasAuthorize: boolean;\n hasScope?: boolean;\n accessPolicy?: ActionAccessPolicy;\n errors?: Record<string, ActionErrorDefinition>;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ServiceSchema {\n name: string;\n options: Omit<ServiceOptions, \"database\">;\n hasDatabase: boolean;\n databaseConfig?: {\n name?: string;\n engine: \"sqlite\" | \"postgres\";\n tables: string[];\n };\n actions: ActionSchema[];\n resources?: { name: string }[];\n}\n\nexport interface ArchitectureSchema {\n version: string;\n services: ServiceSchema[];\n}\n\nexport interface CompiledRoutePlan {\n service: Service<any, any>;\n action: Action<any, any, any, any>;\n actionName: string;\n serviceName: string;\n routePath: string;\n method?: string;\n isGetLike: boolean;\n hasInput: boolean;\n hasContextHook: boolean;\n contextHook?: (baseCtx: any) => Promise<any> | any;\n hasAuthorize: boolean;\n authorize?: (params: any) => boolean | Promise<boolean>;\n execute: (params: any) => Promise<any> | any;\n inputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n outputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n coercions?: Array<{ key: string; isNumber: boolean; isBoolean: boolean }>;\n logger: Logger;\n errorBuilder: any;\n cachedDb: any;\n}\n\nexport interface Service<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n readonly actions: Map<string, Action<any, any, any, any>>;\n readonly tools: Map<string, Tool<any, any, any, any>>;\n readonly tables: Map<string, any>;\n readonly resources: Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >;\n readonly db?: TDb;\n readonly isBuilt?: boolean;\n\n use<A>(plugin: ServicePlugin<this, A>): A;\n\n build(): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n resource<\n TTable = any,\n const TOptions extends ResourceTypeOptions = ResourceTypeOptions,\n >(\n config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> &\n TOptions &\n Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>,\n ): Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n >;\n\n readonly preparations: Map<string, PreparationContribution>;\n contributePreparation(contribution: PreparationContribution): void;\n listPreparations(): PreparationContribution[];\n prepareContributions(): void;\n registerTable(table: any): this;\n getAction(name: string): Action<any, any, any, any> | undefined;\n listActions(): Action<any, any, any, any>[];\n getTool(name: string): Tool<any, any, any, any> | undefined;\n listTools(): Tool<any, any, any, any>[];\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];\n getDb(): TDb | undefined;\n setDb(database: DatabaseHandle<TDb>): void;\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n ): Promise<BaseContext<TDb> & TServiceContext>;\n introspect(): ServiceSchema;\n}\n\nexport interface ProxyOptions {\n isMonolith?: boolean;\n context?: Partial<ActionContext>;\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport type { Action, ActionErrorDefinition } from \"./types\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\n\n/**\n * Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.\n *\n * The frontend imports only the contract *type* — never a backend implementation:\n *\n * ```ts\n * import { createBrickClient } from \"@brickkit/core/client\";\n * import type { AppServer } from \"./server\"; // `import type`: erased at build\n *\n * const api = createBrickClient<AppServer>({ baseUrl: \"http://localhost:4000\" });\n * const pages = await api.page.list({ limit: 10, sort: \"-createdAt\" });\n * const created = await api.page.create({ title: \"Hello\", content: \"World\" });\n * ```\n *\n * Build the contract from individually-typed actions (each `defineAction` call\n * preserves its input/output/error literal types):\n *\n * ```ts\n * // server.ts (backend)\n * export const listPages = pagesService.action({ name: \"page.list\", ... });\n * export const createPage = pagesService.action({ name: \"page.create\", ... });\n * export const contract = { page: { list: listPages, create: createPage } };\n * export type AppServer = typeof contract;\n * ```\n *\n * ## Result / error convention\n *\n * The client uses a throw-based convention that mirrors local `action.execute`\n * semantics, because TypeScript promises cannot encode thrown exception types:\n *\n * - Success → the promise resolves with the action output.\n * - Declared domain failures (your `errors: { SLUG_EXISTS: ... }`) and framework\n * guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected with\n * {@link ActionExecutionError} carrying the declared `code`, `status`,\n * `message`, and `details`. Narrow with `instanceof` and read `err.code`.\n * - Input/output validation failures → rejected with {@link ValidationError},\n * exactly as local execution throws.\n * - Network failures, unparsable bodies, and non-OK responses outside the\n * declared contract → {@link BrickTransportError} (4xx) or\n * {@link BrickServerError} (5xx).\n * - Cancellation via `AbortSignal` → the native `AbortError` propagates\n * unwrapped so `err.name === \"AbortError\"` keeps working.\n *\n * ## URL mapping\n *\n * A client path is a namespace walk ending in an action call. The leaf segment\n * decides the route, matching the server compiler (`packages/cli/src/compiler`):\n *\n * | Client call | HTTP request |\n * |---|---|\n * Generated browser contracts carry each action's HTTP method and path,\n * including plugin routes and consumer overrides. Without runtime metadata,\n * callers use `POST /api/<service>/<action>` with dotted action names.\n * GET/DELETE input is serialized as a query string; other methods send JSON.\n\n */\n\nexport interface BrickClientOptions {\n /** Server origin, e.g. `\"http://localhost:4000\"`. No trailing slash required. */\n baseUrl: string;\n /**\n * Route prefix the server was mounted with (default `\"/api\"`).\n * Must match the `prefix` passed to `brick({ prefix })`.\n */\n prefix?: string;\n /**\n * Default headers sent with every call (e.g. an `Authorization` bearer).\n * A thunk is re-evaluated per call, so rotated tokens stay fresh.\n */\n headers?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n /** `fetch` implementation. Defaults to `globalThis.fetch`. */\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n /** Default signal applied to every call (per-call `signal` wins). */\n signal?: AbortSignal;\n /** Default per-call timeout in milliseconds (per-call `timeoutMs` wins). */\n timeoutMs?: number;\n /**\n * Browser-safe route metadata generated by the Brick Vite plugin.\n * Required for custom methods/paths and plugin routes. Without a contract,\n * calls use POST and service/action names inferred from namespace keys.\n */\n contract?: Record<string, any>;\n}\n\n/** Browser-safe action metadata generated by the Brick Vite plugin. */\nexport interface BrickClientAction<\n TInput = unknown,\n TOutput = unknown,\n TErrors = {},\n> {\n kind: \"action\";\n name: string;\n serviceName: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n config: { path: string; method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" };\n /** Type information only; never emitted at runtime. */\n readonly __types?: { input: TInput; output: TOutput; errors: TErrors };\n}\n\nexport interface BrickCallOptions {\n /** Extra headers merged over the client defaults for this call only. */\n headers?: Record<string, string>;\n /** Abort signal for this call only. Never wrapped: aborts reject with `AbortError`. */\n signal?: AbortSignal;\n /** Per-call timeout in milliseconds. Implemented with `AbortSignal.timeout`. */\n timeoutMs?: number;\n}\n\n/**\n * The request never received a meaningful server answer: DNS / connection\n * failure, a malformed body, or a 4xx response outside the declared contract\n * (no `code` and no `ValidationError` shape).\n */\nexport class BrickTransportError extends Error {\n readonly kind = \"transport\" as const;\n readonly status?: number;\n readonly url: string;\n readonly body?: unknown;\n override readonly cause?: unknown;\n\n constructor(\n message: string,\n opts: { status?: number; url: string; body?: unknown; cause?: unknown },\n ) {\n super(message);\n this.name = \"BrickTransportError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n this.cause = opts.cause;\n }\n}\n\n/**\n * The server answered 5xx without a declared `code` / `ValidationError` shape,\n * i.e. an unexpected failure rather than a modelled domain error.\n */\nexport class BrickServerError extends Error {\n readonly kind = \"server\" as const;\n readonly status: number;\n readonly url: string;\n readonly body: unknown;\n\n constructor(\n message: string,\n opts: { status: number; url: string; body: unknown },\n ) {\n super(message);\n this.name = \"BrickServerError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n }\n}\n\nexport function isBrickTransportError(\n err: unknown,\n): err is BrickTransportError {\n return err instanceof BrickTransportError;\n}\n\nexport function isBrickServerError(err: unknown): err is BrickServerError {\n return err instanceof BrickServerError;\n}\n\n/** Static input type from the schema, with a fallback for structural actions. */\nexport type InferActionInput<A> =\n A extends BrickClientAction<infer I, any, any>\n ? I\n : A extends {\n config: { input?: infer S extends TSchema };\n }\n ? Static<S>\n : A extends {\n execute(params: { input?: infer I; ctx?: any }): any;\n }\n ? I\n : A extends { run(input?: infer I, ctx?: any): any }\n ? I\n : A extends (params: { input?: infer I; ctx?: any }) => any\n ? I\n : unknown;\n\n/** Resolved output type of an action. */\nexport type InferActionOutput<A> =\n A extends BrickClientAction<any, infer O, any>\n ? O\n : A extends (...args: any[]) => Promise<infer O>\n ? O\n : A extends { execute(params: any): Promise<infer O> }\n ? O\n : unknown;\n\n/** Union of error `code`s declared in an action's `errors` map. */\nexport type InferActionErrorCodes<A> =\n A extends BrickClientAction<any, any, infer E>\n ? Extract<keyof E, string>\n : A extends {\n config: { errors?: infer E };\n }\n ? E extends Record<string, ActionErrorDefinition>\n ? Extract<keyof E, string>\n : never\n : never;\n\n/**\n * The declared failure shape of an action for `catch` narrowing:\n * ```ts\n * try { await api.page.create(input); }\n * catch (err) {\n * if (err instanceof ActionExecutionError) {\n * const code: InferActionErrorCodes<typeof createPage> | \"UNAUTHORIZED\" | ... = err.code;\n * }\n * }\n * ```\n * (Standard framework codes are always possible alongside declared ones.)\n */\nexport type InferActionFailure<A> = ActionExecutionError & {\n code:\n | InferActionErrorCodes<A>\n | \"BAD_REQUEST\"\n | \"UNAUTHORIZED\"\n | \"FORBIDDEN\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"INTERNAL_SERVER_ERROR\"\n | \"VALIDATION_ERROR\";\n};\n\n/**\n * Typed caller for one action. Required inputs stay required; actions whose\n * input includes `undefined` (no schema / all-optional) can be called bare.\n */\nexport type BrickActionCaller<A> =\n undefined extends InferActionInput<A>\n ? (\n input?: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>\n : (\n input: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>;\n\n/** Recursively maps action leaves and their namespaces to browser callers. */\nexport type BrickClient<T> = T extends\n | BrickClientAction<any, any, any>\n | Action<any, any, any, any>\n ? BrickActionCaller<T>\n : T extends (...args: any[]) => any\n ? BrickActionCaller<T>\n : T extends object\n ? { [K in keyof T]: BrickClient<T[K]> }\n : T;\n\ninterface ResolvedClientOptions {\n baseUrl: string;\n prefix: string;\n headers?: BrickClientOptions[\"headers\"];\n fetch: NonNullable<BrickClientOptions[\"fetch\"]>;\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/+$/, \"\");\n if (!trimmed)\n throw new Error(\"[Brick-TS client] `baseUrl` must not be empty.\");\n return trimmed;\n}\n\nfunction normalizePrefix(prefix: string | undefined): string {\n if (!prefix) return \"/api\";\n const withLeading = prefix.startsWith(\"/\") ? prefix : `/${prefix}`;\n return withLeading.length > 1 ? withLeading.replace(/\\/+$/, \"\") : withLeading;\n}\n\nfunction toQueryString(input: unknown): string {\n if (input == null || typeof input !== \"object\") return \"\";\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item === undefined || item === null) continue;\n params.append(\n key,\n typeof item === \"object\" ? JSON.stringify(item) : String(item),\n );\n }\n } else if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n } else {\n params.append(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\ninterface PlannedRequest {\n method: string;\n url: string;\n body: unknown;\n hasBody: boolean;\n}\n\nfunction isActionValue(value: unknown): value is {\n serviceName?: unknown;\n name?: unknown;\n config: Action<any, any, any, any>[\"config\"];\n} & Function {\n return (\n typeof value === \"function\" &&\n !!(value as any).config &&\n typeof (value as any).config.execute === \"function\"\n );\n}\n\nfunction isClientAction(value: unknown): value is BrickClientAction {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as BrickClientAction).kind === \"action\"\n );\n}\n\nfunction planRequest(\n path: string[],\n /** Runtime contract value at `path`, when the `contract` option is set. */\n target: unknown,\n input: unknown,\n baseUrl: string,\n prefix: string,\n): PlannedRequest {\n if (path.length === 0) {\n throw new Error(\n \"[Brick-TS client] No action selected: call a leaf such as `api.page.list(input)`.\",\n );\n }\n const actionTarget =\n isActionValue(target) || isClientAction(target) ? target : undefined;\n const actionConfig = actionTarget?.config;\n if (path.length < 2) {\n throw new Error(\n `[Brick-TS client] Cannot address '${path.join(\".\")}': custom actions need a service segment, e.g. \\`api.${path[0]}.<action>(input)\\`.`,\n );\n }\n // Exact mode: the runtime contract reveals the bound service/action names,\n // so contract keys can differ from backend names.\n const service =\n typeof actionTarget?.serviceName === \"string\" && actionTarget.serviceName\n ? actionTarget.serviceName\n : path[0]!;\n const action =\n typeof actionTarget?.name === \"string\" && actionTarget.name\n ? actionTarget.name\n : path.slice(1).join(\".\");\n const method = actionConfig?.method ?? \"POST\";\n const configuredPath = actionConfig?.path;\n let actionPath =\n configuredPath ??\n `${prefix}/${encodeURIComponent(service)}/${action.split(\".\").map(encodeURIComponent).join(\".\")}`;\n let remaining = input;\n if (configuredPath !== undefined) {\n if (!configuredPath.startsWith(\"/\")) {\n throw new Error(\"[Brick-TS client] Action paths must start with '/'.\");\n }\n const source = { ...((input ?? {}) as Record<string, unknown>) };\n const record = { ...source };\n actionPath = actionPath.replace(/:([^/]+)/g, (_match, key: string) => {\n const value = Object.hasOwn(source, key) ? source[key] : undefined;\n if (value === undefined || value === null || value === \"\") {\n throw new Error(`[Brick-TS client] Missing path parameter '${key}'.`);\n }\n delete record[key];\n return encodeURIComponent(String(value));\n });\n remaining = input === undefined ? undefined : record;\n }\n const queryOnly = method === \"GET\" || method === \"DELETE\";\n return {\n method,\n url: `${baseUrl}${actionPath}${queryOnly ? toQueryString(remaining) : \"\"}`,\n body: queryOnly ? undefined : remaining,\n hasBody: !queryOnly && remaining !== undefined,\n };\n}\n\nfunction toActionError(status: number, body: unknown, url: string): Error {\n if (body !== null && typeof body === \"object\") {\n const record = body as Record<string, unknown>;\n if (typeof record.code === \"string\") {\n return new ActionExecutionError(\n record.code,\n typeof record.message === \"string\" ? record.message : record.code,\n typeof record.status === \"number\" ? record.status : status,\n (record.details ?? undefined) as unknown,\n );\n }\n if (record.name === \"ValidationError\") {\n return new ValidationError(\n typeof record.message === \"string\"\n ? record.message\n : \"Validation failed\",\n Array.isArray(record.errors) ? (record.errors as any) : [],\n typeof record.status === \"number\" ? record.status : status,\n );\n }\n }\n if (status >= 500) {\n return new BrickServerError(\n `Unexpected server error (status ${status}) for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n }\n return new BrickTransportError(\n `Request failed with status ${status} for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n}\n\nasync function dispatch(\n resolved: ResolvedClientOptions,\n path: string[],\n target: unknown,\n input: unknown,\n callOptions: BrickCallOptions | undefined,\n): Promise<unknown> {\n const { method, url, body, hasBody } = planRequest(\n path,\n target,\n input,\n resolved.baseUrl,\n resolved.prefix,\n );\n\n const staticHeaders =\n typeof resolved.headers === \"function\"\n ? await resolved.headers()\n : (resolved.headers ?? {});\n const headers: Record<string, string> = {\n accept: \"application/json\",\n ...staticHeaders,\n ...callOptions?.headers,\n };\n let payload: string | undefined;\n if (hasBody) {\n headers[\"content-type\"] = \"application/json\";\n payload = JSON.stringify(body ?? null);\n }\n\n const timeoutMs = callOptions?.timeoutMs ?? resolved.timeoutMs;\n let timeoutSignal: AbortSignal | undefined;\n if (timeoutMs !== undefined) timeoutSignal = AbortSignal.timeout(timeoutMs);\n const signal = callOptions?.signal ?? timeoutSignal ?? resolved.signal;\n\n let response: Response;\n try {\n response = await resolved.fetch(url, {\n method,\n headers,\n body: payload,\n signal,\n });\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") throw err;\n throw new BrickTransportError(\n `Network request failed for ${url}: ${err instanceof Error ? err.message : String(err)}`,\n { url, cause: err },\n );\n }\n\n let parsed: unknown;\n const text = await response.text();\n if (response.headers.get(\"content-type\")?.includes(\"text/plain\")) {\n parsed = text;\n } else if (text) {\n try {\n parsed = JSON.parse(text);\n } catch (err) {\n if (!response.headers.has(\"content-type\")) {\n parsed = text;\n } else {\n throw new BrickTransportError(`Unparsable response body for ${url}.`, {\n status: response.status,\n url,\n cause: err,\n });\n }\n }\n }\n\n if (response.ok) return parsed;\n throw toActionError(response.status, parsed, url);\n}\n\nfunction childNode(node: unknown, prop: string): unknown {\n if (\n node != null &&\n (typeof node === \"object\" || typeof node === \"function\")\n ) {\n return (node as Record<string, unknown>)[prop];\n }\n return undefined;\n}\n\nfunction createNamespace(\n resolved: ResolvedClientOptions,\n path: string[],\n node: unknown,\n): any {\n const callable = async (input?: unknown, options?: BrickCallOptions) =>\n dispatch(resolved, path, node, input, options);\n return new Proxy(callable, {\n get(target, prop, receiver) {\n if (typeof prop !== \"string\") return Reflect.get(target, prop, receiver);\n // Never masquerade as a thenable: awaiting a namespace must not dispatch.\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\")\n return undefined;\n return createNamespace(resolved, [...path, prop], childNode(node, prop));\n },\n apply(_target, _thisArg, args: unknown[]) {\n const [input, options] = args as [unknown, BrickCallOptions | undefined];\n return dispatch(resolved, path, node, input, options);\n },\n });\n}\n\n/**\n * Create an Eden/tRPC-style typed client for the application contract `TApp`.\n * `TApp` is a type-only parameter: `import type { AppServer }` keeps backend\n * implementations out of the frontend bundle.\n */\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions & { contract: TApp },\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp> {\n if (!options?.baseUrl)\n throw new Error(\n '[Brick-TS client] `baseUrl` is required, e.g. `{ baseUrl: \"http://localhost:4000\" }`.',\n );\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\n \"[Brick-TS client] No `fetch` implementation available: pass `fetch` explicitly.\",\n );\n }\n const resolved: ResolvedClientOptions = {\n baseUrl: normalizeBaseUrl(options.baseUrl),\n prefix: normalizePrefix(options.prefix),\n headers: options.headers,\n fetch: fetchImpl,\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n return createNamespace(resolved, [], options.contract) as BrickClient<TApp>;\n}\n"],"mappings":";AAgEA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CAEA,YACE,SACA,SAAgC,CAAC,GACjC,SAAS,KACT;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;CAEA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,SAAS,KAAK;GACd,QAAQ,KAAK;GACb,QAAQ,KAAK;EACf;CACF;AACF;AAEA,IAAa,uBAAb,cAA0C,MAAM;CAC9C;CACA;CACA;CAEA,YAAY,MAAc,SAAiB,SAAS,KAAK,SAAmB;EAC1E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,UAAU;CACjB;CAEA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,SAAS,KAAK;GACd,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB;CACF;AACF;;;;;;;;ACWA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAgB;CAChB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,OAAO,SAAS,YAAY,OAAO,SAAS,aAE7C,OAAQ,KAAiC;AAG7C;AAEA,SAAS,gBACP,UACA,MACA,MACK;CACL,MAAM,WAAW,OAAO,OAAiB,YACvC,SAAS,UAAU,MAAM,MAAM,OAAO,OAAO;CAC/C,OAAO,IAAI,MAAM,UAAU;EACzB,IAAI,QAAQ,MAAM,UAAU;GAC1B,IAAI,OAAO,SAAS,UAAU,OAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;GAEvE,IAAI,SAAS,UAAU,SAAS,WAAW,SAAS,WAClD,OAAO,KAAA;GACT,OAAO,gBAAgB,UAAU,CAAC,GAAG,MAAM,IAAI,GAAG,UAAU,MAAM,IAAI,CAAC;EACzE;EACA,MAAM,SAAS,UAAU,MAAiB;GACxC,MAAM,CAAC,OAAO,WAAW;GACzB,OAAO,SAAS,UAAU,MAAM,MAAM,OAAO,OAAO;EACtD;CACF,CAAC;AACH;AAaA,SAAgB,kBACd,SACmB;CACnB,IAAI,CAAC,SAAS,SACZ,MAAM,IAAI,MACR,yFACF;CACF,MAAM,YAAY,QAAQ,SAAS,WAAW;CAC9C,IAAI,OAAO,cAAc,YACvB,MAAM,IAAI,MACR,iFACF;CAUF,OAAO,gBAAgB;EAPrB,SAAS,iBAAiB,QAAQ,OAAO;EACzC,QAAQ,gBAAgB,QAAQ,MAAM;EACtC,SAAS,QAAQ;EACjB,OAAO;EACP,QAAQ,QAAQ;EAChB,WAAW,QAAQ;CAES,GAAG,CAAC,GAAG,QAAQ,QAAQ;AACvD"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/types.ts","../../src/client.ts"],"sourcesContent":["import type { ServicePlugin, ResourcePlugin } from \"./plugin\";\nimport type { TSchema, Static } from \"@sinclair/typebox\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type { DatabaseHandle } from \"./db/define\";\n\nexport interface Logger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/**\n * Base framework context supplied to all service resolvers and action executions.\n */\nexport interface BaseContext<TDb = any> {\n request: Request;\n db: TDb;\n logger: Logger;\n traceId: string;\n requestId?: string;\n caller?: string;\n tenantId?: string;\n services?: Record<string, any>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Default fallback service context for untyped or simple services.\n */\nexport interface DefaultServiceContext {\n user?: any;\n session?: any;\n [key: string]: any;\n}\n\n/**\n * The combined execution context: BaseContext & TServiceContext.\n */\nexport type ActionContext<\n TDb = any,\n TServiceContext = DefaultServiceContext,\n> = BaseContext<TDb> & TServiceContext;\n\n/**\n * Type utility that automatically narrows ctx.user from User | null to User\n * in execute() when authorize() is declared on the action.\n */\nexport type NarrowAuthorizedContext<TCtx> = TCtx extends { user: infer U }\n ? [U] extends [null | undefined]\n ? TCtx\n : Omit<TCtx, \"user\"> & { user: NonNullable<U> }\n : TCtx;\n\nexport interface ActionErrorDefinition {\n status?: number;\n message: string;\n}\n\nexport interface ValidationErrorItem {\n path: string;\n message: string;\n value?: unknown;\n type?: number;\n}\n\nexport class ValidationError extends Error {\n readonly code = \"VALIDATION_FAILED\";\n readonly status: number;\n readonly errors: ValidationErrorItem[];\n\n constructor(\n message: string,\n errors: ValidationErrorItem[] = [],\n status = 400,\n ) {\n super(message);\n this.name = \"ValidationError\";\n this.status = status;\n this.errors = errors;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n errors: this.errors,\n };\n }\n}\n\nexport class ActionExecutionError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(\n code: string,\n message: string,\n status = 400,\n details?: unknown,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"ActionExecutionError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n details: this.details,\n };\n }\n}\n\nexport interface StandardErrorMap {\n BAD_REQUEST: (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never;\n UNAUTHORIZED: (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never;\n FORBIDDEN: (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never;\n NOT_FOUND: (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never;\n CONFLICT: (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never;\n INTERNAL_SERVER_ERROR: (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never;\n [key: string]:\n | ((\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never)\n | undefined;\n}\n\nexport type ErrorBuilder<\n TErrors extends Record<string, ActionErrorDefinition>,\n> = StandardErrorMap & {\n [K in keyof TErrors]: (\n overrideMessage?: string,\n details?: unknown,\n options?: ErrorOptions,\n ) => never;\n};\n\nexport interface BaseActionConfig<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n> {\n name: string;\n description?: string;\n /** Effective HTTP path, including the prefix; replaces the default action path. */\n path?: string;\n /** Single HTTP method exposed for this action (default POST). */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n input?: TInputSchema;\n output?: TOutputSchema;\n errors?: TErrors;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ActionConfigWithAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize: (params: {\n user?: TContext extends { user: infer U } ? U : any;\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }) => boolean | Promise<boolean>;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: NarrowAuthorizedContext<TContext>;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport interface ActionConfigWithoutAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize?: undefined;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport type ActionConfig<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> =\n | ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>\n | ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >;\n\nexport interface Action<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> {\n (params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n\n name: string;\n serviceName?: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;\n /**\n * Optional runtime-only output schema. When present, `validateOutput` and\n * HTTP output checking validate against it instead of `config.output`,\n * while `config.output` remains the published contract (client types,\n * OpenAPI). Lets projected/subset responses validate at runtime without\n * leaking optionality into the generated contract.\n */\n outputValidationSchema?: TSchema;\n run(\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any,\n ctx?: Partial<TContext>,\n ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n execute(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n executeResolved?(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n validateInput(\n input: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n validateOutput(\n output: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n errorHelpers?: ErrorBuilder<TErrors>;\n}\n\n/** MCP tool metadata, kept with the executable definition. */\nexport interface ToolAnnotations {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\nexport interface ToolOptions {\n title?: string;\n annotations?: ToolAnnotations;\n /** Also register HTTP routes and OpenAPI. Defaults to false. */\n http?: boolean;\n}\nexport type ToolConfigWithAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;\nexport type ToolConfigWithoutAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;\nexport interface Tool<\n I extends TSchema | undefined = any,\n O extends TSchema | undefined = any,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> extends Action<I, O, E, C> {\n readonly kind: \"tool\";\n config:\n | ToolConfigWithAuthorize<I, O, E, C>\n | ToolConfigWithoutAuthorize<I, O, E, C>;\n}\n\n/** A resource declares identity and a table; plugins supply behavior. */\nexport interface ResourceConfig<TTable = any, _TCtx = any> {\n name: string;\n table: TTable;\n id?: import(\"drizzle-orm\").Column;\n}\n\nexport type InferTableRow<TTable> = TTable extends { $inferSelect: infer S }\n ? S\n : any;\nexport type InferTableInsert<TTable> = TTable extends { $inferInsert: infer S }\n ? S\n : any;\nexport type ResourceTypeOptions = Pick<ResourceConfig, \"name\" | \"id\">;\n\ntype PrimaryColumn<T> = T extends { _: { columns: infer C } }\n ? {\n [K in keyof C]: C[K] extends { _: { isPrimaryKey: true } } ? C[K] : never;\n }[keyof C]\n : import(\"drizzle-orm\").Column;\nexport type ResourceIdentity<T, O> = O & {\n id: O extends { id: infer I extends import(\"drizzle-orm\").Column }\n ? I\n : PrimaryColumn<T>;\n};\n\n/** Generic preparation declarations consumed by the application compiler. */\nexport interface PreparationContribution {\n readonly name: string;\n describe(): unknown;\n prepare(): void;\n}\n\nexport interface Resource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n TOptions = {},\n> {\n use<\n P extends ResourcePlugin<\n Service<TCtx[\"db\"], Omit<TCtx, keyof BaseContext>>,\n this,\n any\n >,\n >(\n plugin: P,\n ): this & import(\"./plugin\").ResourcePluginAPI<P, TTable, TCtx, this>;\n readonly name: string;\n readonly serviceName: string;\n readonly table: TTable;\n readonly id: TOptions extends {\n id: infer I extends import(\"drizzle-orm\").Column;\n }\n ? I\n : import(\"drizzle-orm\").Column;\n readonly idField: string;\n readonly config: ResourceConfig<TTable, TCtx> & TOptions;\n}\n\nexport interface ServiceAuthOptions {\n requireAuth?: boolean;\n allowedRoles?: string[];\n policy?: (ctx: ActionContext) => boolean | Promise<boolean>;\n}\n\nexport interface RateLimitOptions {\n maxRequests: number;\n window: number | string;\n scope?: \"ip\" | \"user\" | \"tenant\";\n}\n\nexport interface CacheOptions {\n driver?: \"memory\" | \"redis\";\n defaultTtl?: number;\n}\n\nexport interface ResilienceOptions {\n timeoutMs?: number;\n retry?: {\n attempts: number;\n backoff: \"linear\" | \"exponential\";\n delayMs: number;\n };\n circuitBreaker?: {\n errorThresholdPercentage: number;\n resetTimeoutMs: number;\n };\n}\n\nexport interface TelemetryOptions {\n traceQueries?: boolean;\n auditLog?: boolean;\n tags?: Record<string, string>;\n}\n\nexport interface LifecycleOptions {\n onInit?: (ctx: { db?: any; logger?: Logger }) => Promise<void>;\n onDestroy?: () => Promise<void>;\n}\n\nexport interface ServiceOptions<\n TServiceContext extends Record<string, any> = Record<string, any>,\n TDb = any,\n> {\n database?: DatabaseHandle<TDb>;\n context?: (\n baseCtx: BaseContext<TDb> & { user?: unknown },\n ) => Promise<TServiceContext> | TServiceContext;\n auth?: ServiceAuthOptions;\n rateLimit?: RateLimitOptions;\n cache?: CacheOptions;\n resilience?: ResilienceOptions;\n telemetry?: TelemetryOptions;\n lifecycle?: LifecycleOptions;\n}\n\nexport type ActionAccessPolicy = \"public\" | \"authorized\" | \"scoped\";\n\nexport interface ActionSchema {\n name: string;\n /** Present only when this action has a registered HTTP route. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path?: string;\n serviceName?: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n hasAuthorize: boolean;\n hasScope?: boolean;\n accessPolicy?: ActionAccessPolicy;\n errors?: Record<string, ActionErrorDefinition>;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ServiceSchema {\n name: string;\n options: Omit<ServiceOptions, \"database\">;\n hasDatabase: boolean;\n databaseConfig?: {\n name?: string;\n engine: \"sqlite\" | \"postgres\";\n tables: string[];\n };\n actions: ActionSchema[];\n resources?: { name: string }[];\n}\n\nexport interface ArchitectureSchema {\n version: string;\n services: ServiceSchema[];\n}\n\nexport interface CompiledRoutePlan {\n service: Service<any, any>;\n action: Action<any, any, any, any>;\n actionName: string;\n serviceName: string;\n routePath: string;\n method?: string;\n isGetLike: boolean;\n hasInput: boolean;\n hasContextHook: boolean;\n contextHook?: (baseCtx: any) => Promise<any> | any;\n hasAuthorize: boolean;\n authorize?: (params: any) => boolean | Promise<boolean>;\n execute: (params: any) => Promise<any> | any;\n inputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n outputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n coercions?: Array<{ key: string; isNumber: boolean; isBoolean: boolean }>;\n logger: Logger;\n errorBuilder: any;\n cachedDb: any;\n}\n\nexport interface Service<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n readonly actions: Map<string, Action<any, any, any, any>>;\n readonly tools: Map<string, Tool<any, any, any, any>>;\n readonly tables: Map<string, any>;\n readonly resources: Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >;\n readonly db?: TDb;\n readonly isBuilt?: boolean;\n\n use<A>(plugin: ServicePlugin<this, A>): A;\n\n build(): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n resource<\n TTable = any,\n const TOptions extends ResourceTypeOptions = ResourceTypeOptions,\n >(\n config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> &\n TOptions &\n Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>,\n ): Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n >;\n\n readonly preparations: Map<string, PreparationContribution>;\n contributePreparation(contribution: PreparationContribution): void;\n listPreparations(): PreparationContribution[];\n prepareContributions(): void;\n registerTable(table: any): this;\n getAction(name: string): Action<any, any, any, any> | undefined;\n listActions(): Action<any, any, any, any>[];\n getTool(name: string): Tool<any, any, any, any> | undefined;\n listTools(): Tool<any, any, any, any>[];\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];\n getDb(): TDb | undefined;\n setDb(database: DatabaseHandle<TDb>): void;\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n ): Promise<BaseContext<TDb> & TServiceContext>;\n introspect(): ServiceSchema;\n}\n\nexport interface ProxyOptions {\n isMonolith?: boolean;\n context?: Partial<ActionContext>;\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport type { Action, ActionErrorDefinition } from \"./types\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\n\n/**\n * Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.\n *\n * The frontend imports only the contract *type* — never a backend implementation:\n *\n * ```ts\n * import { createBrickClient } from \"@brickkit/core/client\";\n * import type { AppServer } from \"./server\"; // `import type`: erased at build\n *\n * const api = createBrickClient<AppServer>({ baseUrl: \"http://localhost:4000\" });\n * const pages = await api.page.list({ limit: 10, sort: \"-createdAt\" });\n * const created = await api.page.create({ title: \"Hello\", content: \"World\" });\n * ```\n *\n * Build the contract from individually-typed actions (each `defineAction` call\n * preserves its input/output/error literal types):\n *\n * ```ts\n * // server.ts (backend)\n * export const listPages = pagesService.action({ name: \"page.list\", ... });\n * export const createPage = pagesService.action({ name: \"page.create\", ... });\n * export const contract = { page: { list: listPages, create: createPage } };\n * export type AppServer = typeof contract;\n * ```\n *\n * ## Result / error convention\n *\n * The client uses a throw-based convention that mirrors local `action.execute`\n * semantics, because TypeScript promises cannot encode thrown exception types:\n *\n * - Success → the promise resolves with the action output.\n * - Declared domain failures (your `errors: { SLUG_EXISTS: ... }`) and framework\n * guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected with\n * {@link ActionExecutionError} carrying the declared `code`, `status`,\n * `message`, and `details`. Narrow with `instanceof` and read `err.code`.\n * - Input/output validation failures → rejected with {@link ValidationError},\n * exactly as local execution throws.\n * - Network failures, unparsable bodies, and non-OK responses outside the\n * declared contract → {@link BrickTransportError} (4xx) or\n * {@link BrickServerError} (5xx).\n * - Cancellation via `AbortSignal` → the native `AbortError` propagates\n * unwrapped so `err.name === \"AbortError\"` keeps working.\n *\n * ## URL mapping\n *\n * A client path is a namespace walk ending in an action call. The leaf segment\n * decides the route, matching the server compiler (`packages/cli/src/compiler`):\n *\n * | Client call | HTTP request |\n * |---|---|\n * Generated browser contracts carry each action's HTTP method and path,\n * including plugin routes and consumer overrides. Without runtime metadata,\n * callers use `POST /api/<service>/<action>` with dotted action names.\n * GET/DELETE input is serialized as a query string; other methods send JSON.\n\n */\n\nexport interface BrickClientOptions {\n /** Server origin, e.g. `\"http://localhost:4000\"`. No trailing slash required. */\n baseUrl: string;\n /**\n * Route prefix the server was mounted with (default `\"/api\"`).\n * Must match the `prefix` passed to `brick({ prefix })`.\n */\n prefix?: string;\n /**\n * Default headers sent with every call (e.g. an `Authorization` bearer).\n * A thunk is re-evaluated per call, so rotated tokens stay fresh.\n */\n headers?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n /** `fetch` implementation. Defaults to `globalThis.fetch`. */\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n /** Default signal applied to every call (per-call `signal` wins). */\n signal?: AbortSignal;\n /** Default per-call timeout in milliseconds (per-call `timeoutMs` wins). */\n timeoutMs?: number;\n /**\n * Browser-safe route metadata generated by the Brick Vite plugin.\n * Required for custom methods/paths and plugin routes. Without a contract,\n * calls use POST and service/action names inferred from namespace keys.\n */\n contract?: Record<string, any>;\n}\n\n/** Browser-safe action metadata generated by the Brick Vite plugin. */\nexport interface BrickClientAction<\n TInput = unknown,\n TOutput = unknown,\n TErrors = {},\n> {\n kind: \"action\";\n name: string;\n serviceName: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n config: { path: string; method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" };\n /** Type information only; never emitted at runtime. */\n readonly __types?: { input: TInput; output: TOutput; errors: TErrors };\n}\n\nexport interface BrickCallOptions {\n /** Extra headers merged over the client defaults for this call only. */\n headers?: Record<string, string>;\n /** Abort signal for this call only. Never wrapped: aborts reject with `AbortError`. */\n signal?: AbortSignal;\n /** Per-call timeout in milliseconds. Implemented with `AbortSignal.timeout`. */\n timeoutMs?: number;\n}\n\n/**\n * The request never received a meaningful server answer: DNS / connection\n * failure, a malformed body, or a 4xx response outside the declared contract\n * (no `code` and no `ValidationError` shape).\n */\nexport class BrickTransportError extends Error {\n readonly kind = \"transport\" as const;\n readonly status?: number;\n readonly url: string;\n readonly body?: unknown;\n override readonly cause?: unknown;\n\n constructor(\n message: string,\n opts: { status?: number; url: string; body?: unknown; cause?: unknown },\n ) {\n super(message);\n this.name = \"BrickTransportError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n this.cause = opts.cause;\n }\n}\n\n/**\n * The server answered 5xx without a declared `code` / `ValidationError` shape,\n * i.e. an unexpected failure rather than a modelled domain error.\n */\nexport class BrickServerError extends Error {\n readonly kind = \"server\" as const;\n readonly status: number;\n readonly url: string;\n readonly body: unknown;\n\n constructor(\n message: string,\n opts: { status: number; url: string; body: unknown },\n ) {\n super(message);\n this.name = \"BrickServerError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n }\n}\n\nexport function isBrickTransportError(\n err: unknown,\n): err is BrickTransportError {\n return err instanceof BrickTransportError;\n}\n\nexport function isBrickServerError(err: unknown): err is BrickServerError {\n return err instanceof BrickServerError;\n}\n\n/** Static input type from the schema, with a fallback for structural actions. */\nexport type InferActionInput<A> =\n A extends BrickClientAction<infer I, any, any>\n ? I\n : A extends {\n config: { input?: infer S extends TSchema };\n }\n ? Static<S>\n : A extends {\n execute(params: { input?: infer I; ctx?: any }): any;\n }\n ? I\n : A extends { run(input?: infer I, ctx?: any): any }\n ? I\n : A extends (params: { input?: infer I; ctx?: any }) => any\n ? I\n : unknown;\n\n/** Resolved output type of an action. */\nexport type InferActionOutput<A> =\n A extends BrickClientAction<any, infer O, any>\n ? O\n : A extends (...args: any[]) => Promise<infer O>\n ? O\n : A extends { execute(params: any): Promise<infer O> }\n ? O\n : unknown;\n\n/** Union of error `code`s declared in an action's `errors` map. */\nexport type InferActionErrorCodes<A> =\n A extends BrickClientAction<any, any, infer E>\n ? Extract<keyof E, string>\n : A extends {\n config: { errors?: infer E };\n }\n ? E extends Record<string, ActionErrorDefinition>\n ? Extract<keyof E, string>\n : never\n : never;\n\n/**\n * The declared failure shape of an action for `catch` narrowing:\n * ```ts\n * try { await api.page.create(input); }\n * catch (err) {\n * if (err instanceof ActionExecutionError) {\n * const code: InferActionErrorCodes<typeof createPage> | \"UNAUTHORIZED\" | ... = err.code;\n * }\n * }\n * ```\n * (Standard framework codes are always possible alongside declared ones.)\n */\nexport type InferActionFailure<A> = ActionExecutionError & {\n code:\n | InferActionErrorCodes<A>\n | \"BAD_REQUEST\"\n | \"UNAUTHORIZED\"\n | \"FORBIDDEN\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"INTERNAL_SERVER_ERROR\"\n | \"VALIDATION_FAILED\";\n};\n\n/**\n * Typed caller for one action. Required inputs stay required; actions whose\n * input includes `undefined` (no schema / all-optional) can be called bare.\n */\nexport type BrickActionCaller<A> =\n undefined extends InferActionInput<A>\n ? (\n input?: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>\n : (\n input: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>;\n\n/** Recursively maps action leaves and their namespaces to browser callers. */\nexport type BrickClient<T> = T extends\n | BrickClientAction<any, any, any>\n | Action<any, any, any, any>\n ? BrickActionCaller<T>\n : T extends (...args: any[]) => any\n ? BrickActionCaller<T>\n : T extends object\n ? { [K in keyof T]: BrickClient<T[K]> }\n : T;\n\ninterface ResolvedClientOptions {\n baseUrl: string;\n prefix: string;\n headers?: BrickClientOptions[\"headers\"];\n fetch: NonNullable<BrickClientOptions[\"fetch\"]>;\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/+$/, \"\");\n if (!trimmed)\n throw new Error(\"[Brick-TS client] `baseUrl` must not be empty.\");\n return trimmed;\n}\n\nfunction normalizePrefix(prefix: string | undefined): string {\n if (!prefix) return \"/api\";\n const withLeading = prefix.startsWith(\"/\") ? prefix : `/${prefix}`;\n return withLeading.length > 1 ? withLeading.replace(/\\/+$/, \"\") : withLeading;\n}\n\nfunction toQueryString(input: unknown): string {\n if (input == null || typeof input !== \"object\") return \"\";\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item === undefined || item === null) continue;\n params.append(\n key,\n typeof item === \"object\" ? JSON.stringify(item) : String(item),\n );\n }\n } else if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n } else {\n params.append(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\ninterface PlannedRequest {\n method: string;\n url: string;\n body: unknown;\n hasBody: boolean;\n}\n\nfunction isActionValue(value: unknown): value is {\n serviceName?: unknown;\n name?: unknown;\n config: Action<any, any, any, any>[\"config\"];\n} & Function {\n return (\n typeof value === \"function\" &&\n !!(value as any).config &&\n typeof (value as any).config.execute === \"function\"\n );\n}\n\nfunction isClientAction(value: unknown): value is BrickClientAction {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as BrickClientAction).kind === \"action\"\n );\n}\n\nfunction planRequest(\n path: string[],\n /** Runtime contract value at `path`, when the `contract` option is set. */\n target: unknown,\n input: unknown,\n baseUrl: string,\n prefix: string,\n): PlannedRequest {\n if (path.length === 0) {\n throw new Error(\n \"[Brick-TS client] No action selected: call a leaf such as `api.page.list(input)`.\",\n );\n }\n const actionTarget =\n isActionValue(target) || isClientAction(target) ? target : undefined;\n const actionConfig = actionTarget?.config;\n if (path.length < 2) {\n throw new Error(\n `[Brick-TS client] Cannot address '${path.join(\".\")}': custom actions need a service segment, e.g. \\`api.${path[0]}.<action>(input)\\`.`,\n );\n }\n // Exact mode: the runtime contract reveals the bound service/action names,\n // so contract keys can differ from backend names.\n const service =\n typeof actionTarget?.serviceName === \"string\" && actionTarget.serviceName\n ? actionTarget.serviceName\n : path[0]!;\n const action =\n typeof actionTarget?.name === \"string\" && actionTarget.name\n ? actionTarget.name\n : path.slice(1).join(\".\");\n const method = actionConfig?.method ?? \"POST\";\n const configuredPath = actionConfig?.path;\n let actionPath =\n configuredPath ??\n `${prefix}/${encodeURIComponent(service)}/${action.split(\".\").map(encodeURIComponent).join(\".\")}`;\n let remaining = input;\n if (configuredPath !== undefined) {\n if (!configuredPath.startsWith(\"/\")) {\n throw new Error(\"[Brick-TS client] Action paths must start with '/'.\");\n }\n const source = { ...((input ?? {}) as Record<string, unknown>) };\n const record = { ...source };\n actionPath = actionPath.replace(/:([^/]+)/g, (_match, key: string) => {\n const value = Object.hasOwn(source, key) ? source[key] : undefined;\n if (value === undefined || value === null || value === \"\") {\n throw new Error(`[Brick-TS client] Missing path parameter '${key}'.`);\n }\n delete record[key];\n return encodeURIComponent(String(value));\n });\n remaining = input === undefined ? undefined : record;\n }\n const queryOnly = method === \"GET\" || method === \"DELETE\";\n return {\n method,\n url: `${baseUrl}${actionPath}${queryOnly ? toQueryString(remaining) : \"\"}`,\n body: queryOnly ? undefined : remaining,\n hasBody: !queryOnly && remaining !== undefined,\n };\n}\n\nfunction toActionError(status: number, body: unknown, url: string): Error {\n if (body !== null && typeof body === \"object\") {\n const record = body as Record<string, unknown>;\n if (record.name === \"ValidationError\") {\n return new ValidationError(\n typeof record.message === \"string\"\n ? record.message\n : \"Validation failed\",\n Array.isArray(record.errors) ? (record.errors as any) : [],\n typeof record.status === \"number\" ? record.status : status,\n );\n }\n if (typeof record.code === \"string\") {\n return new ActionExecutionError(\n record.code,\n typeof record.message === \"string\" ? record.message : record.code,\n typeof record.status === \"number\" ? record.status : status,\n (record.details ?? undefined) as unknown,\n );\n }\n }\n if (status >= 500) {\n return new BrickServerError(\n `Unexpected server error (status ${status}) for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n }\n return new BrickTransportError(\n `Request failed with status ${status} for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n}\n\nasync function dispatch(\n resolved: ResolvedClientOptions,\n path: string[],\n target: unknown,\n input: unknown,\n callOptions: BrickCallOptions | undefined,\n): Promise<unknown> {\n const { method, url, body, hasBody } = planRequest(\n path,\n target,\n input,\n resolved.baseUrl,\n resolved.prefix,\n );\n\n const staticHeaders =\n typeof resolved.headers === \"function\"\n ? await resolved.headers()\n : (resolved.headers ?? {});\n const headers: Record<string, string> = {\n accept: \"application/json\",\n ...staticHeaders,\n ...callOptions?.headers,\n };\n let payload: string | undefined;\n if (hasBody) {\n headers[\"content-type\"] = \"application/json\";\n payload = JSON.stringify(body ?? null);\n }\n\n const timeoutMs = callOptions?.timeoutMs ?? resolved.timeoutMs;\n let timeoutSignal: AbortSignal | undefined;\n if (timeoutMs !== undefined) timeoutSignal = AbortSignal.timeout(timeoutMs);\n const signal = callOptions?.signal ?? timeoutSignal ?? resolved.signal;\n\n let response: Response;\n try {\n response = await resolved.fetch(url, {\n method,\n headers,\n body: payload,\n signal,\n });\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") throw err;\n throw new BrickTransportError(\n `Network request failed for ${url}: ${err instanceof Error ? err.message : String(err)}`,\n { url, cause: err },\n );\n }\n\n let parsed: unknown;\n const text = await response.text();\n if (response.headers.get(\"content-type\")?.includes(\"text/plain\")) {\n parsed = text;\n } else if (text) {\n try {\n parsed = JSON.parse(text);\n } catch (err) {\n if (!response.headers.has(\"content-type\")) {\n parsed = text;\n } else {\n throw new BrickTransportError(`Unparsable response body for ${url}.`, {\n status: response.status,\n url,\n cause: err,\n });\n }\n }\n }\n\n if (response.ok) return parsed;\n throw toActionError(response.status, parsed, url);\n}\n\nfunction childNode(node: unknown, prop: string): unknown {\n if (\n node != null &&\n (typeof node === \"object\" || typeof node === \"function\")\n ) {\n return (node as Record<string, unknown>)[prop];\n }\n return undefined;\n}\n\nfunction createNamespace(\n resolved: ResolvedClientOptions,\n path: string[],\n node: unknown,\n): any {\n const callable = async (input?: unknown, options?: BrickCallOptions) =>\n dispatch(resolved, path, node, input, options);\n return new Proxy(callable, {\n get(target, prop, receiver) {\n if (typeof prop !== \"string\") return Reflect.get(target, prop, receiver);\n // Never masquerade as a thenable: awaiting a namespace must not dispatch.\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\")\n return undefined;\n return createNamespace(resolved, [...path, prop], childNode(node, prop));\n },\n apply(_target, _thisArg, args: unknown[]) {\n const [input, options] = args as [unknown, BrickCallOptions | undefined];\n return dispatch(resolved, path, node, input, options);\n },\n });\n}\n\n/**\n * Create an Eden/tRPC-style typed client for the application contract `TApp`.\n * `TApp` is a type-only parameter: `import type { AppServer }` keeps backend\n * implementations out of the frontend bundle.\n */\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions & { contract: TApp },\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp> {\n if (!options?.baseUrl)\n throw new Error(\n '[Brick-TS client] `baseUrl` is required, e.g. `{ baseUrl: \"http://localhost:4000\" }`.',\n );\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\n \"[Brick-TS client] No `fetch` implementation available: pass `fetch` explicitly.\",\n );\n }\n const resolved: ResolvedClientOptions = {\n baseUrl: normalizeBaseUrl(options.baseUrl),\n prefix: normalizePrefix(options.prefix),\n headers: options.headers,\n fetch: fetchImpl,\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n return createNamespace(resolved, [], options.contract) as BrickClient<TApp>;\n}\n"],"mappings":";AAkEA,IAAa,kBAAb,cAAqC,MAAM;CACzC,OAAgB;CAChB;CACA;CAEA,YACE,SACA,SAAgC,CAAC,GACjC,SAAS,KACT;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;CAEA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,SAAS,KAAK;GACd,QAAQ,KAAK;GACb,QAAQ,KAAK;EACf;CACF;AACF;AAEA,IAAa,uBAAb,cAA0C,MAAM;CAC9C;CACA;CACA;CAEA,YACE,MACA,SACA,SAAS,KACT,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,UAAU;CACjB;CAEA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,SAAS,KAAK;GACd,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB;CACF;AACF;;;;;;;;ACCA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAgB;CAChB;CACA;CACA;CACA;CAEA,YACE,SACA,MACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,KAAK;EACnB,KAAK,MAAM,KAAK;EAChB,KAAK,OAAO,KAAK;EACjB,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AAM,OAAO,OAAO;CAC/C,OAAO,IAAI,MAAM,UAAU;EACzB,IAAI,QAAQ,MAAM,UAAU;GAC1B,IAAI,OAAO,SAAS,UAAU,OAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;GAEvE,IAAI,SAAS,UAAU,SAAS,WAAW,SAAS,WAClD,OAAO,KAAA;GACT,OAAO,gBAAgB,UAAU,CAAC,GAAG,MAAM,IAAI,GAAG,UAAU,MAAM,IAAI,CAAC;EACzE;EACA,MAAM,SAAS,UAAU,MAAiB;GACxC,MAAM,CAAC,OAAO,WAAW;GACzB,OAAO,SAAS,UAAU,MAAM,MAAM,OAAO,OAAO;EACtD;CACF,CAAC;AACH;AAaA,SAAgB,kBACd,SACmB;CACnB,IAAI,CAAC,SAAS,SACZ,MAAM,IAAI,MACR,yFACF;CACF,MAAM,YAAY,QAAQ,SAAS,WAAW;CAC9C,IAAI,OAAO,cAAc,YACvB,MAAM,IAAI,MACR,iFACF;CAUF,OAAO,gBAAgB;EAPrB,SAAS,iBAAiB,QAAQ,OAAO;EACzC,QAAQ,gBAAgB,QAAQ,MAAM;EACtC,SAAS,QAAQ;EACjB,OAAO;EACP,QAAQ,QAAQ;EAChB,WAAW,QAAQ;CAES,GAAG,CAAC,GAAG,QAAQ,QAAQ;AACvD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -107,22 +107,10 @@ type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRunti
|
|
|
107
107
|
declare function mergeInput(first: any, second: any, third: any): any;
|
|
108
108
|
declare function checkDepth(value: unknown, action: string): void;
|
|
109
109
|
declare function validate(check: NonNullable<CompiledRoutePlan["inputChecker"]>, value: unknown, action: string, stage: "input" | "output"): void;
|
|
110
|
-
declare function mapError(err:
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
status: number;
|
|
115
|
-
details: unknown;
|
|
116
|
-
} | {
|
|
117
|
-
name: string;
|
|
118
|
-
message: string;
|
|
119
|
-
status: number;
|
|
120
|
-
errors: ValidationErrorItem[];
|
|
121
|
-
} | {
|
|
122
|
-
name: string;
|
|
123
|
-
message: any;
|
|
124
|
-
status: number;
|
|
125
|
-
};
|
|
110
|
+
declare function mapError(err: unknown, set: any, options: {
|
|
111
|
+
logger: Logger;
|
|
112
|
+
requestId: string;
|
|
113
|
+
}): ErrorEnvelope;
|
|
126
114
|
export declare const compilerRuntime: Readonly<{
|
|
127
115
|
emptyServices: Readonly<{}>;
|
|
128
116
|
defaultRequest: Request;
|
|
@@ -132,7 +120,7 @@ export declare const compilerRuntime: Readonly<{
|
|
|
132
120
|
validate: typeof validate;
|
|
133
121
|
mapError: typeof mapError;
|
|
134
122
|
isThenable: (value: any) => boolean;
|
|
135
|
-
deny: (action: string) => never;
|
|
123
|
+
deny: (action: string, user: unknown) => never;
|
|
136
124
|
}>;
|
|
137
125
|
//#endregion
|
|
138
126
|
//#region src/compiler.d.ts
|
|
@@ -457,5 +445,21 @@ interface McpHandlerOptions {
|
|
|
457
445
|
/** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
|
|
458
446
|
export declare function createMcpHandler(options: McpHandlerOptions): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>;
|
|
459
447
|
//#endregion
|
|
460
|
-
|
|
448
|
+
//#region src/error-response.d.ts
|
|
449
|
+
interface ErrorEnvelope {
|
|
450
|
+
name: string;
|
|
451
|
+
code: string;
|
|
452
|
+
message: string;
|
|
453
|
+
status: number;
|
|
454
|
+
requestId: string;
|
|
455
|
+
details?: unknown;
|
|
456
|
+
errors?: ValidationError["errors"];
|
|
457
|
+
}
|
|
458
|
+
type ErrorContext = {
|
|
459
|
+
logger: Pick<Logger, "error">;
|
|
460
|
+
requestId: string;
|
|
461
|
+
};
|
|
462
|
+
export declare function toErrorResponse(err: unknown, context: ErrorContext): ErrorEnvelope;
|
|
463
|
+
//#endregion
|
|
464
|
+
export { Action, type ActionAccessInfo, ActionAccessPolicy, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, ActionSchema, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickApp, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, type BrickIR, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CreateServerOptions, DatabaseAdapter, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, EnvInput, ErrorBuilder, type ErrorEnvelope, type HandlerFactory, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, LifecycleOptions, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiGeneratorOptions, type PluginEndpointContext, type PluginRouteMethod, type PluginRouteRegistrar, type PluginRouteScope, type PluginRoutes, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, PreparationContribution, ProxyOptions, RateLimitOptions, type ReferenceOptions, type RequestLoggingOptions, ResilienceOptions, Resource, ResourceConfig, ResourceIdentity, type ResourcePlugin, type ResourcePluginAPI, type ResourcePluginContext, type ResourcePluginTypes, ResourceTypeOptions, type RouteIR, type RouteMethod, SQLiteDatabaseConfig, SQLiteDefinition, type SecretOptions, SecretRef, type SecretSource, Service, ServiceAuthOptions, ServiceOptions, type ServicePlugin, type ServicePluginContext, 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, defineResourcePlugin, defineServicePlugin, desc, envSource, eq, foreignKey, getPluginActionRoute, getPluginEndpoints, 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 };
|
|
461
465
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["_$__0.
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["_$__0.ErrorEnvelope","_$__endpoints0.BrickApp","TSchema","TSchema","TSchema"],"sources":["../src/compiler/ir.ts","../src/endpoints.ts","../src/compiler/runtime.ts","../src/compiler.ts","../src/request-logger.ts","../src/docs.ts","../src/action-handler.ts","../src/server.ts","../src/app-entry.ts","../src/compiler/emit.ts","../src/db/index.ts","../src/service.ts","../src/access.ts","../src/action.ts","../src/resource.ts","../src/rpc.ts","../src/registry.ts","../src/typebox.ts","../src/openapi.ts","../src/tool.ts","../src/mcp.ts","../src/error-response.ts"],"mappings":";;;;;;KAGY;UACK;WACN,QAAQ;WACR;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;aACE;aACA;;;WAGF;WACA;;UAEM;WACN;WACA;WACA;WACA;WACA,iBAAiB;WACjB;IACP;IACA;IACA;;WAEO;;;;KC3BC;;UAGK;EACf,UAAU;EACV,UAAU;EACV,WAAW;EACX,WAAW;;;UAII;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;;EAET;IAAO;IAAiB,SAAS;;;EAEjC;EACA,QAAQ;EACR;EACA;;UAGe;EACf,QAAQ;;EAER;EACA,UAAU,KAAK,8BAA8B;;EAE7C,UAAU;;EAEV,WAAW;EACX;EACA;EACA;;;wBAIc,kBACd,SAAS,wCACT,UAAU;;wBAiBI,sBACd,KAAK,oBACL,UAAU,uBACR,mBAAmB;;wBAwEP,cAAc;;wBAUd,cAAc,MAAM,uBAAuB;;KAuB/C,WA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