@brickkit/core 0.3.0-beta.5 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -27
- package/dist/chunks/client.d.ts +23 -8
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js.map +1 -1
- package/dist/client.js +1 -2
- package/dist/index.d.ts +68 -39
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +484 -275
- package/dist/index.js.map +1 -1
- package/package.json +20 -7
package/README.md
CHANGED
|
@@ -1,8 +1,44 @@
|
|
|
1
1
|
# @brickkit/core
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Services, actions, resources, and databases for the Brick-TS framework. You define typed services with TypeBox schemas, mount them with `brick()`, and get an Elysia HTTP server with OpenAPI output and a typed client.
|
|
4
|
+
|
|
5
|
+
You need Bun 1.2 or later. Bun-only APIs are lazy-loaded, so the package imports cleanly under strict Node ESM too.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
bun add @brickkit/core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Define a service
|
|
12
|
+
|
|
13
|
+
Create a service, register an action on it, and serve it. Each action exposes one route: `POST /api/{service}/{action}` by default.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { brick, defineAction, defineService } from "@brickkit/core";
|
|
17
|
+
|
|
18
|
+
const healthService = defineService("system");
|
|
19
|
+
const ping = defineAction({
|
|
20
|
+
name: "ping",
|
|
21
|
+
execute: async () => ({ status: "ok" }),
|
|
22
|
+
});
|
|
23
|
+
healthService.action(ping);
|
|
24
|
+
|
|
25
|
+
const app = brick({ services: [healthService] });
|
|
26
|
+
app.listen(4000);
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Set `method: "GET"` on the action config to serve reads over GET, or `path` to replace the default route. Add `input` and `output` TypeBox schemas to validate at the boundary. Add `authorize` to require a user; without it the action is public. To call an action in process with the same pipeline, use `action.run(input, ctx)` or `service.getAction("ping")`.
|
|
30
|
+
|
|
31
|
+
`brick()` also accepts `prefix`, `title`, and `version`. `generateOpenApiSpec({ services, prefix })` returns the OpenAPI 3.1 document without starting a server.
|
|
32
|
+
|
|
33
|
+
## Exports
|
|
34
|
+
|
|
35
|
+
| Path | What it holds |
|
|
36
|
+
| ----------------------- | --------------------------------------------------------------- |
|
|
37
|
+
| `@brickkit/core` | `brick`, `defineService`, `defineAction`, `defineDatabase`, MCP |
|
|
38
|
+
| `@brickkit/core/client` | `createBrickClient`, the Eden-style typed browser client |
|
|
39
|
+
| `@brickkit/core/pg` | Postgres Drizzle table helpers such as `pgTable` |
|
|
40
|
+
|
|
41
|
+
Databases use Drizzle tables through `defineDatabase({ engine, tables, url })` with `"sqlite"` or `"postgres"` engines. Database setup is documented in `DATABASES.md`.
|
|
6
42
|
|
|
7
43
|
```sh
|
|
8
44
|
bun add @brickkit/core drizzle-orm postgres
|
|
@@ -24,16 +60,11 @@ export const db = defineDatabase({
|
|
|
24
60
|
});
|
|
25
61
|
```
|
|
26
62
|
|
|
27
|
-
Bun-only APIs are lazy-loaded, so the package imports cleanly under
|
|
28
|
-
strict Node ESM too. Source: <https://github.com/Chandraprakash-Darji/brick>.
|
|
29
|
-
|
|
30
63
|
## Typed client
|
|
31
64
|
|
|
32
|
-
`@brickkit/core/client` (also re-exported from the package root) offers an
|
|
33
|
-
Eden-style HTTP client inferred from your contract type — no OpenAPI codegen:
|
|
65
|
+
`@brickkit/core/client` (also re-exported from the package root) offers an Eden-style HTTP client inferred from your contract type — no OpenAPI codegen:
|
|
34
66
|
|
|
35
|
-
With the Brick Vite plugin configured for your default-exported app, Vite
|
|
36
|
-
creates `_brick/contract.ts` automatically:
|
|
67
|
+
With the Brick Vite plugin configured for your default-exported app, Vite creates `_brick/contract.ts` automatically:
|
|
37
68
|
|
|
38
69
|
```ts
|
|
39
70
|
import { createBrickClient } from "@brickkit/core/client";
|
|
@@ -43,11 +74,7 @@ const api = createBrickClient({ baseUrl: "http://localhost:4000", contract });
|
|
|
43
74
|
const pages = await api.page.list({ limit: 10 });
|
|
44
75
|
```
|
|
45
76
|
|
|
46
|
-
The generated contract contains browser-safe route metadata and inferred
|
|
47
|
-
input/output/error types. It honors custom action paths and methods, encodes
|
|
48
|
-
path parameters, and removes them from the remaining payload. No backend
|
|
49
|
-
handlers are bundled. See the CLI README and
|
|
50
|
-
`www/content/docs/(brick)/typed-client.mdx` for Vite setup and error handling.
|
|
77
|
+
The generated contract contains browser-safe route metadata and inferred input/output/error types. It honors custom action paths and methods, encodes path parameters, and removes them from the remaining payload. No backend handlers are bundled. See the CLI README and `www/content/docs/(brick)/typed-client.mdx` for Vite setup and error handling.
|
|
51
78
|
|
|
52
79
|
## MCP tools
|
|
53
80
|
|
|
@@ -84,15 +111,8 @@ const handleMcp = createMcpHandler({
|
|
|
84
111
|
// return handleMcp(request, { user: { id: verifiedSubject } });
|
|
85
112
|
```
|
|
86
113
|
|
|
87
|
-
Tools use action validation, authorization, and service context. They are stored
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
The registry accepts `services` and/or an explicit `tools` array, rejects duplicate
|
|
94
|
-
names, and reads annotations directly from definitions. The handler is a
|
|
95
|
-
stateless POST JSON-RPC helper for initialize, ping, tools/list, and tools/call;
|
|
96
|
-
notifications receive an empty 202 response. Authentication and mounting remain
|
|
97
|
-
in your app. Its default protocol version is `2025-06-18`, following the
|
|
98
|
-
[MCP tools specification](https://modelcontextprotocol.io/specification/2025-06-18/server/tools).
|
|
114
|
+
Tools use action validation, authorization, and service context. They are stored separately from HTTP actions and stay out of routes and OpenAPI by default, including when their service is passed to `brick()`. Add `http: true` to a tool definition, or register it with `crm.action(whoami)`, to expose it over HTTP as well.
|
|
115
|
+
|
|
116
|
+
The registry accepts `services` and/or an explicit `tools` array, rejects duplicate names, and reads annotations directly from definitions. The handler is a stateless POST JSON-RPC helper for initialize, ping, tools/list, and tools/call; notifications receive an empty 202 response. Authentication and mounting remain in your app. Its default protocol version is `2025-06-18`, following the [MCP tools specification](https://modelcontextprotocol.io/specification/2025-06-18/server/tools).
|
|
117
|
+
|
|
118
|
+
Source: <https://github.com/Chandraprakash-Darji/brick>.
|
package/dist/chunks/client.d.ts
CHANGED
|
@@ -93,6 +93,8 @@ declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix
|
|
|
93
93
|
path: string;
|
|
94
94
|
method: PluginRouteMethod;
|
|
95
95
|
clientPath: string[] | undefined;
|
|
96
|
+
plugin: string;
|
|
97
|
+
resource: string | undefined;
|
|
96
98
|
} | undefined;
|
|
97
99
|
declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
|
|
98
100
|
path: string;
|
|
@@ -422,6 +424,10 @@ interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema e
|
|
|
422
424
|
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
423
425
|
name: string;
|
|
424
426
|
serviceName?: string;
|
|
427
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
428
|
+
plugin?: string;
|
|
429
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
430
|
+
resource?: string;
|
|
425
431
|
config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
|
|
426
432
|
/**
|
|
427
433
|
* Optional runtime-only output schema. When present, `validateOutput` and
|
|
@@ -568,26 +574,30 @@ interface ServiceOptions<TServiceContext extends Record<string, any> = Record<st
|
|
|
568
574
|
telemetry?: TelemetryOptions;
|
|
569
575
|
lifecycle?: LifecycleOptions;
|
|
570
576
|
}
|
|
577
|
+
type ActionAccessPolicy = "public" | "authorized" | "scoped";
|
|
571
578
|
interface ActionSchema {
|
|
572
579
|
name: string;
|
|
580
|
+
/** Present only when this action has a registered HTTP route. */
|
|
581
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
582
|
+
path?: string;
|
|
573
583
|
serviceName?: string;
|
|
584
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
585
|
+
plugin?: string;
|
|
586
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
587
|
+
resource?: string;
|
|
574
588
|
description?: string;
|
|
575
589
|
inputSchema?: unknown;
|
|
576
590
|
outputSchema?: unknown;
|
|
577
591
|
hasAuthorize: boolean;
|
|
592
|
+
hasScope?: boolean;
|
|
593
|
+
accessPolicy?: ActionAccessPolicy;
|
|
578
594
|
errors?: Record<string, ActionErrorDefinition>;
|
|
579
595
|
emits?: string[];
|
|
580
596
|
tags?: string[];
|
|
581
597
|
}
|
|
582
598
|
interface ServiceSchema {
|
|
583
599
|
name: string;
|
|
584
|
-
options: Omit<ServiceOptions, "database"
|
|
585
|
-
database?: {
|
|
586
|
-
name?: string;
|
|
587
|
-
engine: "sqlite" | "postgres";
|
|
588
|
-
tables: string[];
|
|
589
|
-
};
|
|
590
|
-
};
|
|
600
|
+
options: Omit<ServiceOptions, "database">;
|
|
591
601
|
hasDatabase: boolean;
|
|
592
602
|
databaseConfig?: {
|
|
593
603
|
name?: string;
|
|
@@ -728,6 +738,7 @@ interface ProxyOptions {
|
|
|
728
738
|
* including plugin routes and consumer overrides. Without runtime metadata,
|
|
729
739
|
* callers use `POST /api/<service>/<action>` with dotted action names.
|
|
730
740
|
* GET/DELETE input is serialized as a query string; other methods send JSON.
|
|
741
|
+
|
|
731
742
|
*/
|
|
732
743
|
interface BrickClientOptions {
|
|
733
744
|
/** Server origin, e.g. `"http://localhost:4000"`. No trailing slash required. */
|
|
@@ -760,6 +771,10 @@ interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
|
|
|
760
771
|
kind: "action";
|
|
761
772
|
name: string;
|
|
762
773
|
serviceName: string;
|
|
774
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
775
|
+
plugin?: string;
|
|
776
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
777
|
+
resource?: string;
|
|
763
778
|
config: {
|
|
764
779
|
path: string;
|
|
765
780
|
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
@@ -872,5 +887,5 @@ declare function createBrickClient<TApp extends Record<string, any>>(options: Br
|
|
|
872
887
|
}): BrickClient<TApp>;
|
|
873
888
|
declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
|
|
874
889
|
//#endregion
|
|
875
|
-
export {
|
|
890
|
+
export { ToolConfigWithoutAuthorize as $, ErrorBuilder as A, index as At, Resource as B, PluginRouteScope as Bt, ActionSchema as C, secret as Ct, CacheOptions as D, blob as Dt, BaseContext as E, SQLiteDatabaseConfig as Et, NarrowAuthorizedContext as F, text as Ft, ServiceAuthOptions as G, ResourcePluginTypes as Gt, ResourceIdentity as H, ResourcePlugin as Ht, PreparationContribution as I, uniqueIndex as It, StandardErrorMap as J, defineResourcePlugin as Jt, ServiceOptions as K, ServicePlugin as Kt, ProxyOptions as L, PluginEndpointContext as Lt, InferTableRow as M, primaryKey as Mt, LifecycleOptions as N, real as Nt, CompiledRoutePlan as O, createSQLiteDatabase as Ot, Logger as P, sqliteTable as Pt, ToolConfigWithAuthorize as Q, RateLimitOptions as R, PluginRouteMethod as Rt, ActionExecutionError as S, resolveSecrets as St, BaseActionConfig as T, BunSQLiteDatabase$1 as Tt, ResourceTypeOptions as U, ResourcePluginAPI as Ut, ResourceConfig as V, PluginRoutes as Vt, Service as W, ResourcePluginContext as Wt, Tool as X, getPluginActionRoute as Xt, TelemetryOptions as Y, defineServicePlugin as Yt, ToolAnnotations as Z, getPluginEndpoints as Zt, ActionConfig as _, envSource as _t, BrickClientOptions as a, EnvInput as at, ActionContext as b, overrideSecrets as bt, InferActionErrorCodes as c, defineDatabase as ct, InferActionOutput as d, PostgresDatabase as dt, ToolOptions as et, createBrickClient as f, PostgresDatabaseConfig as ft, ActionAccessPolicy as g, SecretSource as gt, Action as h, SecretRef as ht, BrickClientAction as i, DatabaseHandle as it, InferTableInsert as j, integer as jt, DefaultServiceContext as k, foreignKey as kt, InferActionFailure as l, isDatabaseHandle as lt, isBrickTransportError as m, SecretOptions as mt, BrickCallOptions as n, ValidationErrorItem as nt, BrickServerError as o, PostgresDefinition as ot, isBrickServerError as p, createPostgresDatabase as pt, ServiceSchema as q, ServicePluginContext as qt, BrickClient as r, DatabaseDefinition as rt, BrickTransportError as s, SQLiteDefinition as st, BrickActionCaller as t, ValidationError as tt, InferActionInput as u, DatabaseAdapter as ut, ActionConfigWithAuthorize as v, listSecrets as vt, ArchitectureSchema as w, BrickSQLiteDatabase as wt, ActionErrorDefinition as x, resetSecrets as xt, ActionConfigWithoutAuthorize as y, overrideSecret as yt, ResilienceOptions as z, PluginRouteRegistrar as zt };
|
|
876
891
|
//# sourceMappingURL=client.d.ts.map
|
|
@@ -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;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,QAAQ,qBAAqB,UAAU;;;UAIxB;WACN;WACA;WACA;WACA;;KAEC,kBAAkB,GAAG,GAAG,GAAG,eAAe;WAC3C,aAAa,UAAU;KAE7B;WACU,OAAO;WACP,SAAS;WACT,UAAU;YAErB,UAAU,+BAA+B,KACvC;
|
|
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,G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sBAAsB,KAChC,UAAU,kCAAkC,KACxC,cAAc,aACd;EACI;IAAU,eAAe;;IAE3B,UAAU,eAAe,yBACvB,cAAc;;;;;;;;;;;;;KAgBZ,mBAAmB,KAAK;EAClC,MACI,sBAAsB;;;;;;KAchB,kBAAkB,uBACV,iBAAiB,MAE7B,QAAQ,iBAAiB,IACzB,UAAU,qBACP,QAAQ,kBAAkB,OAE7B,OAAO,iBAAiB,IACxB,UAAU,qBACP,QAAQ,kBAAkB;;KAGzB,YAAY,KAAK,UACzB,mCACA,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"}
|
|
@@ -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 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 interface ActionSchema {\n name: string;\n serviceName?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n hasAuthorize: boolean;\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 database?: {\n name?: string;\n engine: \"sqlite\" | \"postgres\";\n tables: string[];\n };\n };\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 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;;;;;;;;ACOA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAgB;CAChB;CACA;CACA;CACA;CAEA,YACE,SACA,MACA;EACA,MAAM,OAAO;EACb,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C;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 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 createN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M,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/client.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { BrickServerError, BrickTransportError, createBrickClient, isBrickServerError, isBrickTransportError };
|
|
1
|
+
export { t as BrickServerError, n as BrickTransportError, r as createBrickClient, i as isBrickServerError, a as isBrickTransportError } from "./chunks/client.js";
|