@brickkit/core 0.7.1 → 0.7.3

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/client.js CHANGED
@@ -137,7 +137,8 @@ async function dispatch(resolved, path, target, input, callOptions) {
137
137
  const timeoutMs = callOptions?.timeoutMs ?? resolved.timeoutMs;
138
138
  let timeoutSignal;
139
139
  if (timeoutMs !== void 0) timeoutSignal = AbortSignal.timeout(timeoutMs);
140
- const signal = callOptions?.signal ?? timeoutSignal ?? resolved.signal;
140
+ const signals = [callOptions?.signal ?? resolved.signal, timeoutSignal].filter((value) => value !== void 0);
141
+ const signal = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
141
142
  let response;
142
143
  try {
143
144
  response = await resolved.fetch(url, {
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["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":";;;;;;;AA0HA,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,KAAK,QAAQ,KAAK;CACpB;AACF;;;;;AAMA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,OAAgB;CAChB;CACA;CACA;CAEA,YACE,SACA,MACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,KAAK;EACnB,KAAK,MAAM,KAAK;EAChB,KAAK,OAAO,KAAK;CACnB;AACF;AAEA,SAAgB,sBACd,KAC4B;CAC5B,OAAO,eAAe;AACxB;AAEA,SAAgB,mBAAmB,KAAuC;CACxE,OAAO,eAAe;AACxB;AAqGA,SAAS,iBAAiB,SAAyB;CACjD,MAAM,UAAU,QAAQ,QAAQ,QAAQ,EAAE;CAC1C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,gDAAgD;CAClE,OAAO;AACT;AAEA,SAAS,gBAAgB,QAAoC;CAC3D,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,cAAc,OAAO,WAAW,GAAG,IAAI,SAAS,IAAI;CAC1D,OAAO,YAAY,SAAS,IAAI,YAAY,QAAQ,QAAQ,EAAE,IAAI;AACpE;AAEA,SAAS,cAAc,O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;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/client.ts"],"sourcesContent":["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 signals = [\n callOptions?.signal ?? resolved.signal,\n timeoutSignal,\n ].filter((value): value is AbortSignal => value !== undefined);\n const signal = signals.length > 1 ? AbortSignal.any(signals) : signals[0];\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)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.js";
2
- import { B as Type, M as createMcpHandler, a as adaptEffectActionConfig, an as defineEffectResourcePlugin, c as EffectMcpRegistry, cn as EffectService, d as runEffectPromise, f as EffectBrickApp, i as EffectTool, l as createEffectMcpRegistry, ln as EffectServiceOptions, m as effectBrick, n as EffectActionConfigWithAuthorize, o as defineEffectAction, on as defineEffectServicePlugin, p as EffectServerOptions, r as EffectActionConfigWithoutAuthorize, s as defineEffectTool, sn as defineResource, t as EffectAction, u as createEffectServiceProxy, un as defineEffectService } from "./chunks/effect.js";
2
+ import { M as createMcpHandler, V as Type, a as adaptEffectActionConfig, c as EffectMcpRegistry, cn as defineResource, d as runEffectPromise, dn as defineEffectService, f as EffectBrickApp, i as EffectTool, l as createEffectMcpRegistry, ln as EffectService, m as effectBrick, n as EffectActionConfigWithAuthorize, o as defineEffectAction, on as defineEffectResourcePlugin, p as EffectServerOptions, r as EffectActionConfigWithoutAuthorize, s as defineEffectTool, sn as defineEffectServicePlugin, t as EffectAction, u as createEffectServiceProxy, un as EffectServiceOptions } from "./chunks/effect.js";
3
3
  export { EffectAction, EffectActionConfigWithAuthorize, EffectActionConfigWithoutAuthorize, type EffectBrickApp, type EffectMcpRegistry, type EffectServerOptions, type EffectService, type EffectServiceOptions, EffectTool, Type, Type as t, adaptEffectActionConfig, effectBrick as brick, effectBrick, createEffectMcpRegistry, createEffectMcpRegistry as createMcpRegistry, createEffectServiceProxy, createEffectServiceProxy as createServiceProxy, createMcpHandler, defineEffectAction as defineAction, defineEffectAction, defineDatabase, defineEffectResourcePlugin, defineEffectResourcePlugin as defineResourcePlugin, defineEffectService, defineEffectService as defineService, defineEffectServicePlugin, defineEffectServicePlugin as defineServicePlugin, defineEffectTool, defineEffectTool as defineTool, defineResource, runEffectPromise };
package/dist/effect.js CHANGED
@@ -1 +1 @@
1
- export { Kt as Type, t as adaptEffectActionConfig, u as brick, u as effectBrick, i as createEffectMcpRegistry, i as createMcpRegistry, a as createEffectServiceProxy, a as createServiceProxy, c as createMcpHandler, n as defineAction, n as defineEffectAction, J as defineDatabase, d as defineEffectResourcePlugin, d as defineResourcePlugin, p as defineEffectService, p as defineService, f as defineEffectServicePlugin, f as defineServicePlugin, r as defineEffectTool, r as defineTool, g as defineResource, Zt as runEffectPromise, Jt as t } from "./chunks/effect.js";
1
+ export { qt as Type, t as adaptEffectActionConfig, u as brick, u as effectBrick, i as createEffectMcpRegistry, i as createMcpRegistry, a as createEffectServiceProxy, a as createServiceProxy, c as createMcpHandler, n as defineAction, n as defineEffectAction, J as defineDatabase, d as defineEffectResourcePlugin, d as defineResourcePlugin, p as defineEffectService, p as defineService, f as defineEffectServicePlugin, f as defineServicePlugin, r as defineEffectTool, r as defineTool, g as defineResource, Qt as runEffectPromise, Yt as t } from "./chunks/effect.js";
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { $ as ToolConfigWithoutAuthorize, A as ErrorBuilder, At as index, B as Resource, Bt as PluginRouteScope, C as ActionSchema, Ct as secret, D as CacheOptions, Dt as blob, E as BaseContext, Et as SQLiteDatabaseConfig, F as NarrowAuthorizedContext, Ft as text, G as ServiceAuthOptions, Gt as ResourcePluginTypes, H as ResourceIdentity, Ht as ResourcePlugin, I as PreparationContribution, It as uniqueIndex, J as StandardErrorMap, Jt as defineResourcePlugin, K as ServiceOptions, Kt as ServicePlugin, L as ProxyOptions, Lt as PluginEndpointContext, M as InferTableRow, Mt as primaryKey, N as LifecycleOptions, Nt as real, O as CompiledRoutePlan, Ot as createSQLiteDatabase, P as Logger, Pt as sqliteTable, Q as ToolConfigWithAuthorize, R as RateLimitOptions, Rt as PluginRouteMethod, S as ActionExecutionError, St as resolveSecrets, T as BaseActionConfig, Tt as BunSQLiteDatabase, U as ResourceTypeOptions, Ut as ResourcePluginAPI, V as ResourceConfig, Vt as PluginRoutes, W as Service, Wt as ResourcePluginContext, X as Tool, Xt as getPluginActionRoute, Y as TelemetryOptions, Yt as defineServicePlugin, Z as ToolAnnotations, Zt as getPluginEndpoints, _ as ActionConfig, _t as envSource, a as BrickClientOptions, at as EnvInput, b as ActionContext, bt as overrideSecrets, c as InferActionErrorCodes, ct as defineDatabase, d as InferActionOutput, dt as PostgresDatabase, et as ToolOptions, f as createBrickClient, ft as PostgresDatabaseConfig, g as ActionAccessPolicy, gt as SecretSource, h as Action, ht as SecretRef, i as BrickClientAction, it as DatabaseHandle, j as InferTableInsert, jt as integer, k as DefaultServiceContext, kt as foreignKey, l as InferActionFailure, lt as isDatabaseHandle, m as isBrickTransportError, mt as SecretOptions, n as BrickCallOptions, nt as ValidationErrorItem, o as BrickServerError, ot as PostgresDefinition, p as isBrickServerError, pt as createPostgresDatabase, q as ServiceSchema, qt as ServicePluginContext, r as BrickClient, rt as DatabaseDefinition, s as BrickTransportError, st as SQLiteDefinition, t as BrickActionCaller, tt as ValidationError, u as InferActionInput, ut as DatabaseAdapter, v as ActionConfigWithAuthorize, vt as listSecrets, w as ArchitectureSchema, wt as BrickSQLiteDatabase, x as ActionErrorDefinition, xt as resetSecrets, y as ActionConfigWithoutAuthorize, yt as overrideSecret, z as ResilienceOptions, zt as PluginRouteRegistrar } from "./chunks/client.js";
2
- import { $ as ServiceImpl, $t as endpointPaths, A as McpToolDefinition, At as or, B as Type, Bt as RequestLoggingOptions, C as HandlerFactory, Ct as isNull, D as McpHandlerOptions, Dt as ne, E as toErrorResponse, Et as lte, F as isTool, Ft as ReferenceOptions, G as resetGlobalRegistry, Gt as createActionHandler, H as validateWithSchema, Ht as isBrickApp, I as OpenApiGeneratorOptions, It as referencePlugin, J as defineAction, Jt as EndpointContext, K as createServiceProxy, Kt as executeCompiledRoute, L as generateOpenApiSpec, Lt as registerReferenceRoute, M as createMcpHandler, Mt as sql, N as createMcpRegistry, Nt as syncSchema, O as McpRegistry, Ot as not, P as defineTool, Pt as emitHandlerFactory, Q as setActionAccess, Qt as createEndpointHandler, R as Static, Rt as scalarDocsHTML, S as CompiledHandler, St as isNotNull, T as ErrorEnvelope, Tt as lt, U as ServiceRegistry, Ut as requireBrickApp, V as getCompiledCheck, Vt as requestLoggingPlugin, W as getGlobalRegistry, Wt as compileRoutePlan, X as ActionAccessInfo, Xt as EndpointLogger, Y as ACTION_ACCESS_KEY, Yt as EndpointDefinition, Z as getActionAccess, Zt as EndpointMethod, _ as CompiledApplication, _t as gt, an as defineEffectResourcePlugin, at as asc, b as compileBrickApplication, bt as inArray, cn as EffectService, ct as createDatabase, dt as ensureSQLiteFts, en as resolveEndpointDb, et as defineService, f as EffectBrickApp, ft as eq, g as brick, gt as getTableName, h as CreateServerOptions, ht as getTableColumns, i as EffectTool, in as RouteMethod, it as and, j as UnknownToolError, jt as relations, k as McpRegistryOptions, kt as notInArray, ln as EffectServiceOptions, lt as desc, m as effectBrick, mt as generateSQLiteTableDdl, nn as BrickIR, nt as DatabaseConfig, o as defineEffectAction, on as defineEffectServicePlugin, ot as attachDatabase, p as EffectServerOptions, pt as generateSQLiteIndexDdl, q as buildErrorHelpers, qt as BrickApp, rn as RouteIR, rt as Table, s as defineEffectTool, sn as defineResource, st as buildFtsMatchQuery, t as EffectAction, tn as toOpenApiPath, tt as BrickDatabase, un as defineEffectService, ut as ensureResourceIndexes, v as CompiledRoute, vt as gte, w as compilerRuntime, wt as like, x as loadCompiledBrickApp, xt as is, y as bindCompiledApplication, yt as ilike, z as TSchema, zt as swaggerDocsHTML } from "./chunks/effect.js";
3
- export { ACTION_ACCESS_KEY, 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, BrickDatabase, type BrickIR, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CreateServerOptions, DatabaseAdapter, DatabaseConfig, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type EffectAction, type EffectBrickApp, type EffectServerOptions, type EffectService, type EffectServiceOptions, type EffectTool, 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, ServiceImpl, ServiceOptions, type ServicePlugin, type ServicePluginContext, ServiceRegistry, ServiceSchema, StandardErrorMap, type Static, type TSchema, Table, TelemetryOptions, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, UnknownToolError, ValidationError, ValidationErrorItem, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineEffectAction, defineEffectResourcePlugin, defineEffectService, defineEffectServicePlugin, defineEffectTool, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, effectBrick, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
2
+ import { $ as setActionAccess, $t as createEndpointHandler, A as McpToolDefinition, At as notInArray, B as TSchema, Bt as swaggerDocsHTML, C as HandlerFactory, Ct as isNotNull, D as McpHandlerOptions, Dt as lte, E as toErrorResponse, Et as lt, F as isTool, Ft as emitHandlerFactory, G as getGlobalRegistry, Gt as compileRoutePlan, H as getCompiledCheck, Ht as requestLoggingPlugin, I as OpenApiGeneratorOptions, It as ReferenceOptions, J as buildErrorHelpers, Jt as BrickApp, K as resetGlobalRegistry, Kt as createActionHandler, L as generateOpenApiSpec, Lt as referencePlugin, M as createMcpHandler, Mt as relations, N as createMcpRegistry, Nt as sql, O as McpRegistry, Ot as ne, P as defineTool, Pt as syncSchema, Q as getActionAccess, Qt as EndpointMethod, R as hoistAnchoredSchemas, Rt as registerReferenceRoute, S as CompiledHandler, St as is, T as ErrorEnvelope, Tt as like, U as validateWithSchema, Ut as isBrickApp, V as Type, Vt as RequestLoggingOptions, W as ServiceRegistry, Wt as requireBrickApp, X as ACTION_ACCESS_KEY, Xt as EndpointDefinition, Y as defineAction, Yt as EndpointContext, Z as ActionAccessInfo, Zt as EndpointLogger, _ as CompiledApplication, _t as getTableName, an as RouteMethod, at as and, b as compileBrickApplication, bt as ilike, cn as defineResource, ct as buildFtsMatchQuery, dn as defineEffectService, dt as ensureResourceIndexes, en as endpointPaths, et as ServiceImpl, f as EffectBrickApp, ft as ensureSQLiteFts, g as brick, gt as getTableColumns, h as CreateServerOptions, ht as generateSQLiteTableDdl, i as EffectTool, in as RouteIR, it as Table, j as UnknownToolError, jt as or, k as McpRegistryOptions, kt as not, ln as EffectService, lt as createDatabase, m as effectBrick, mt as generateSQLiteIndexDdl, nn as toOpenApiPath, nt as BrickDatabase, o as defineEffectAction, on as defineEffectResourcePlugin, ot as asc, p as EffectServerOptions, pt as eq, q as createServiceProxy, qt as executeCompiledRoute, rn as BrickIR, rt as DatabaseConfig, s as defineEffectTool, sn as defineEffectServicePlugin, st as attachDatabase, t as EffectAction, tn as resolveEndpointDb, tt as defineService, un as EffectServiceOptions, ut as desc, v as CompiledRoute, vt as gt, w as compilerRuntime, wt as isNull, x as loadCompiledBrickApp, xt as inArray, y as bindCompiledApplication, yt as gte, z as Static, zt as scalarDocsHTML } from "./chunks/effect.js";
3
+ export { ACTION_ACCESS_KEY, 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, BrickDatabase, type BrickIR, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CreateServerOptions, DatabaseAdapter, DatabaseConfig, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type EffectAction, type EffectBrickApp, type EffectServerOptions, type EffectService, type EffectServiceOptions, type EffectTool, 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, ServiceImpl, ServiceOptions, type ServicePlugin, type ServicePluginContext, ServiceRegistry, ServiceSchema, StandardErrorMap, type Static, type TSchema, Table, TelemetryOptions, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, UnknownToolError, ValidationError, ValidationErrorItem, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineEffectAction, defineEffectResourcePlugin, defineEffectService, defineEffectServicePlugin, defineEffectTool, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, effectBrick, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hoistAnchoredSchemas, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as foreignKey, $t as getGlobalRegistry, A as getTableName, At as setActionAccess, B as lte, Bt as defineResourcePlugin, C as desc, Ct as overrideSecrets, D as generateSQLiteIndexDdl, Dt as generateOpenApiSpec, E as eq, Et as secret, F as is, Ft as requireBrickApp, G as relations, Gt as defineAction, H as not, Ht as getPluginActionRoute, I as isNotNull, It as compileRoutePlan, J as defineDatabase, Jt as t, K as sql, Kt as Type, L as isNull, Lt as createActionHandler, M as gte, Mt as compileBrickApplication, N as ilike, Nt as loadCompiledBrickApp, O as generateSQLiteTableDdl, Ot as ACTION_ACCESS_KEY, P as inArray, Pt as isBrickApp, Q as createSQLiteDatabase, Qt as ServiceRegistry, R as like, Rt as executeCompiledRoute, S as createDatabase, St as overrideSecret, T as ensureSQLiteFts, Tt as resolveSecrets, U as notInArray, Ut as getPluginEndpoints, V as ne, Vt as defineServicePlugin, W as or, Wt as buildErrorHelpers, X as createPostgresDatabase, Xt as toErrorResponse, Y as isDatabaseHandle, Yt as validateWithSchema, Z as blob, _ as Table, _t as swaggerDocsHTML, at as text, b as attachDatabase, bt as envSource, c as createMcpHandler, ct as isTool, d as defineEffectResourcePlugin, dt as endpointPaths, en as resetGlobalRegistry, et as index, f as defineEffectServicePlugin, ft as resolveEndpointDb, g as defineResource, gt as scalarDocsHTML, h as defineService, ht as registerReferenceRoute, it as sqliteTable, j as gt, jt as bindCompiledApplication, k as getTableColumns, kt as getActionAccess, l as createMcpRegistry, lt as brick, m as ServiceImpl, mt as referencePlugin, n as defineEffectAction, nt as primaryKey, o as createServiceProxy, ot as uniqueIndex, p as defineEffectService, pt as toOpenApiPath, q as syncSchema, qt as getCompiledCheck, r as defineEffectTool, rt as real, s as UnknownToolError, st as defineTool, tt as integer, u as effectBrick, ut as createEndpointHandler, v as and, vt as requestLoggingPlugin, w as ensureResourceIndexes, wt as resetSecrets, x as buildFtsMatchQuery, xt as listSecrets, y as asc, yt as SecretRef, z as lt, zt as compilerRuntime } from "./chunks/effect.js";
1
+ import { $ as foreignKey, $t as ServiceRegistry, A as getTableName, At as getActionAccess, B as lte, Bt as compilerRuntime, C as desc, Ct as overrideSecrets, D as generateSQLiteIndexDdl, Dt as generateOpenApiSpec, E as eq, Et as secret, F as is, Ft as isBrickApp, G as relations, Gt as buildErrorHelpers, H as not, Ht as defineServicePlugin, I as isNotNull, It as requireBrickApp, J as defineDatabase, Jt as getCompiledCheck, K as sql, Kt as defineAction, L as isNull, Lt as compileRoutePlan, M as gte, Mt as bindCompiledApplication, N as ilike, Nt as compileBrickApplication, O as generateSQLiteTableDdl, Ot as hoistAnchoredSchemas, P as inArray, Pt as loadCompiledBrickApp, Q as createSQLiteDatabase, R as like, Rt as createActionHandler, S as createDatabase, St as overrideSecret, T as ensureSQLiteFts, Tt as resolveSecrets, U as notInArray, Ut as getPluginActionRoute, V as ne, Vt as defineResourcePlugin, W as or, Wt as getPluginEndpoints, X as createPostgresDatabase, Xt as validateWithSchema, Y as isDatabaseHandle, Yt as t, Z as blob, Zt as toErrorResponse, _ as Table, _t as swaggerDocsHTML, at as text, b as attachDatabase, bt as envSource, c as createMcpHandler, ct as isTool, d as defineEffectResourcePlugin, dt as endpointPaths, en as getGlobalRegistry, et as index, f as defineEffectServicePlugin, ft as resolveEndpointDb, g as defineResource, gt as scalarDocsHTML, h as defineService, ht as registerReferenceRoute, it as sqliteTable, j as gt, jt as setActionAccess, k as getTableColumns, kt as ACTION_ACCESS_KEY, l as createMcpRegistry, lt as brick, m as ServiceImpl, mt as referencePlugin, n as defineEffectAction, nt as primaryKey, o as createServiceProxy, ot as uniqueIndex, p as defineEffectService, pt as toOpenApiPath, q as syncSchema, qt as Type, r as defineEffectTool, rt as real, s as UnknownToolError, st as defineTool, tn as resetGlobalRegistry, tt as integer, u as effectBrick, ut as createEndpointHandler, v as and, vt as requestLoggingPlugin, w as ensureResourceIndexes, wt as resetSecrets, x as buildFtsMatchQuery, xt as listSecrets, y as asc, yt as SecretRef, z as lt, zt as executeCompiledRoute } from "./chunks/effect.js";
2
2
  import { n as ValidationError, t as ActionExecutionError } from "./chunks/types.js";
3
3
  import { BrickServerError, BrickTransportError, createBrickClient, isBrickServerError, isBrickTransportError } from "./client.js";
4
4
  //#region src/compiler/emit.ts
@@ -55,6 +55,6 @@ ${execute}
55
55
  }`;
56
56
  }
57
57
  //#endregion
58
- export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineEffectAction, defineEffectResourcePlugin, defineEffectService, defineEffectServicePlugin, defineEffectTool, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, effectBrick, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
58
+ export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineEffectAction, defineEffectResourcePlugin, defineEffectService, defineEffectServicePlugin, defineEffectTool, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, effectBrick, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hoistAnchoredSchemas, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, uniqueIndex, validateWithSchema };
59
59
 
60
60
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,44 @@
1
+ import { a as BrickClientOptions, d as InferActionOutput, h as Action, i as BrickClientAction, n as BrickCallOptions, t as BrickActionCaller, u as InferActionInput } from "./chunks/client.js";
2
+ import { DataTag, QueryFunctionContext } from "@tanstack/query-core";
3
+ //#region src/tanstack-query.d.ts
4
+ type ActionKey = readonly ["brick", string, string, readonly string[], {
5
+ method: string | null;
6
+ path: string | null;
7
+ serviceName: string | null;
8
+ name: string | null;
9
+ }, ...unknown[]];
10
+ type InputOptions<A> = undefined extends InferActionInput<A> ? {
11
+ input?: InferActionInput<A>;
12
+ request?: BrickCallOptions;
13
+ } : {
14
+ input: InferActionInput<A>;
15
+ request?: BrickCallOptions;
16
+ };
17
+ type InputArgs<A> = undefined extends InferActionInput<A> ? [options?: InputOptions<A>] : [options: InputOptions<A>];
18
+ export type BrickQueryAction<A> = BrickActionCaller<A> & {
19
+ /** Omit options for an action-wide invalidation key. */
20
+ queryKey: {
21
+ (): ActionKey;
22
+ (options: {
23
+ input: InferActionInput<A>;
24
+ }): DataTag<ActionKey, InferActionOutput<A>>;
25
+ };
26
+ queryOptions: (...args: InputArgs<A>) => {
27
+ queryKey: DataTag<ActionKey, InferActionOutput<A>>;
28
+ queryFn: (context: QueryFunctionContext<ActionKey>) => Promise<InferActionOutput<A>>;
29
+ };
30
+ mutationOptions: (options?: {
31
+ request?: BrickCallOptions;
32
+ }) => {
33
+ mutationKey: ActionKey;
34
+ mutationFn: (input: InferActionInput<A>) => Promise<InferActionOutput<A>>;
35
+ };
36
+ };
37
+ export type BrickQueryClient<T> = T extends BrickClientAction<infer _I, infer _O, infer _E> | Action<infer _AI, infer _AO, infer _AC, infer _AE> | ((...args: never[]) => unknown) ? BrickQueryAction<T> : { [K in keyof T]: BrickQueryClient<T[K]>; };
38
+ /** Query helpers share the ordinary Brick HTTP client, including custom routes. */
39
+ export declare function createBrickQueryClient<T extends Record<string, unknown>>(options: BrickClientOptions & {
40
+ contract: T;
41
+ }): BrickQueryClient<T>;
42
+ //#endregion
43
+ export {};
44
+ //# sourceMappingURL=tanstack-query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tanstack-query.d.ts","names":[],"sources":["../src/tanstack-query.ts"],"mappings":";;;KAYK;EAMD;EACA;EACA;EACA;;KAIC,aAAa,uBACE,iBAAiB;EAC7B,QAAQ,iBAAiB;EAAI,UAAU;;EACvC,OAAO,iBAAiB;EAAI,UAAU;;KACzC,UAAU,uBACK,iBAAiB,MAC9B,UAAU,aAAa,OACvB,SAAS,aAAa;YAEjB,iBAAiB,KAAK,kBAAkB;;EAElD;QACM;KACH;MACC,OAAO,iBAAiB;QACtB,QAAQ,WAAW,kBAAkB;;EAE3C,kBAAkB,MAAM,UAAU;IAChC,UAAU,QAAQ,WAAW,kBAAkB;IAC/C,UACE,SAAS,qBAAqB,eAC3B,QAAQ,kBAAkB;;EAEjC,kBAAkB;IAAY,UAAU;;IACtC,aAAa;IACb,aAAa,OAAO,iBAAiB,OAAO,QAAQ,kBAAkB;;;YAI9D,iBAAiB,KAAK,UAC9B,wBAAwB,UAAU,UAAU,MAC5C,aAAa,WAAW,WAAW,WAAW,YACzC,6BACL,iBAAiB,QACd,WAAW,IAAI,iBAAiB,EAAE;;wBAGzB,uBAAuB,UAAU,yBAC/C,SAAS;EAAuB,UAAU;IACzC,iBAAiB"}
@@ -0,0 +1,64 @@
1
+ import { createBrickClient } from "./client.js";
2
+ //#region src/tanstack-query.ts
3
+ /** Query helpers share the ordinary Brick HTTP client, including custom routes. */
4
+ function createBrickQueryClient(options) {
5
+ const client = createBrickClient(options);
6
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
7
+ const prefix = options.prefix ?? "/api";
8
+ function stringProperty(value, property) {
9
+ const result = Reflect.get(Object(value), property);
10
+ return typeof result === "string" ? result : null;
11
+ }
12
+ function namespace(node, path, metadata) {
13
+ const config = Reflect.get(Object(metadata), "config");
14
+ const identity = {
15
+ method: stringProperty(config, "method"),
16
+ path: stringProperty(config, "path"),
17
+ serviceName: stringProperty(metadata, "serviceName"),
18
+ name: stringProperty(metadata, "name")
19
+ };
20
+ const key = (args) => args === void 0 ? [
21
+ "brick",
22
+ baseUrl,
23
+ prefix,
24
+ path,
25
+ identity
26
+ ] : [
27
+ "brick",
28
+ baseUrl,
29
+ prefix,
30
+ path,
31
+ identity,
32
+ args.input
33
+ ];
34
+ const call = (input, request) => {
35
+ if (typeof node !== "function") throw new Error("Brick: select an action before calling Query helpers.");
36
+ return node(input, request);
37
+ };
38
+ return new Proxy(call, { get(_target, prop) {
39
+ if (prop === "then" || prop === "catch" || prop === "finally") return void 0;
40
+ if (prop === "queryKey") return key;
41
+ if (prop === "queryOptions") return (args) => ({
42
+ queryKey: key({ input: args?.input }),
43
+ queryFn: ({ signal }) => {
44
+ const signals = [signal, args?.request?.signal ?? options.signal].filter((value) => value !== void 0);
45
+ return call(args?.input, {
46
+ ...args?.request,
47
+ signal: AbortSignal.any(signals)
48
+ });
49
+ }
50
+ });
51
+ if (prop === "mutationOptions") return (args) => ({
52
+ mutationKey: key(),
53
+ mutationFn: (input) => call(input, args?.request)
54
+ });
55
+ if (typeof prop !== "string") return void 0;
56
+ return namespace(Reflect.get(Object(node), prop), [...path, prop], Reflect.get(Object(metadata), prop));
57
+ } });
58
+ }
59
+ return namespace(client, [], options.contract);
60
+ }
61
+ //#endregion
62
+ export { createBrickQueryClient };
63
+
64
+ //# sourceMappingURL=tanstack-query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tanstack-query.js","names":[],"sources":["../src/tanstack-query.ts"],"sourcesContent":["import type { DataTag, QueryFunctionContext } from \"@tanstack/query-core\";\nimport {\n createBrickClient,\n type BrickActionCaller,\n type BrickCallOptions,\n type BrickClientAction,\n type BrickClientOptions,\n type InferActionInput,\n type InferActionOutput,\n} from \"./client\";\nimport type { Action } from \"./types\";\n\ntype ActionKey = readonly [\n \"brick\",\n string,\n string,\n readonly string[],\n {\n method: string | null;\n path: string | null;\n serviceName: string | null;\n name: string | null;\n },\n ...unknown[],\n];\ntype InputOptions<A> =\n undefined extends InferActionInput<A>\n ? { input?: InferActionInput<A>; request?: BrickCallOptions }\n : { input: InferActionInput<A>; request?: BrickCallOptions };\ntype InputArgs<A> =\n undefined extends InferActionInput<A>\n ? [options?: InputOptions<A>]\n : [options: InputOptions<A>];\n\nexport type BrickQueryAction<A> = BrickActionCaller<A> & {\n /** Omit options for an action-wide invalidation key. */\n queryKey: {\n (): ActionKey;\n (options: {\n input: InferActionInput<A>;\n }): DataTag<ActionKey, InferActionOutput<A>>;\n };\n queryOptions: (...args: InputArgs<A>) => {\n queryKey: DataTag<ActionKey, InferActionOutput<A>>;\n queryFn: (\n context: QueryFunctionContext<ActionKey>,\n ) => Promise<InferActionOutput<A>>;\n };\n mutationOptions: (options?: { request?: BrickCallOptions }) => {\n mutationKey: ActionKey;\n mutationFn: (input: InferActionInput<A>) => Promise<InferActionOutput<A>>;\n };\n};\n\nexport type BrickQueryClient<T> = T extends\n | BrickClientAction<infer _I, infer _O, infer _E>\n | Action<infer _AI, infer _AO, infer _AC, infer _AE>\n | ((...args: never[]) => unknown)\n ? BrickQueryAction<T>\n : { [K in keyof T]: BrickQueryClient<T[K]> };\n\n/** Query helpers share the ordinary Brick HTTP client, including custom routes. */\nexport function createBrickQueryClient<T extends Record<string, unknown>>(\n options: BrickClientOptions & { contract: T },\n): BrickQueryClient<T> {\n const client = createBrickClient(options);\n const baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n const prefix = options.prefix ?? \"/api\";\n function stringProperty(value: unknown, property: string): string | null {\n const result: unknown = Reflect.get(Object(value), property);\n return typeof result === \"string\" ? result : null;\n }\n function namespace(\n node: unknown,\n path: string[],\n metadata: unknown,\n ): unknown {\n const config: unknown = Reflect.get(Object(metadata), \"config\");\n const identity = {\n method: stringProperty(config, \"method\"),\n path: stringProperty(config, \"path\"),\n serviceName: stringProperty(metadata, \"serviceName\"),\n name: stringProperty(metadata, \"name\"),\n };\n const key = (args?: { input: unknown }): ActionKey =>\n args === undefined\n ? [\"brick\", baseUrl, prefix, path, identity]\n : [\"brick\", baseUrl, prefix, path, identity, args.input];\n const call = (\n input: unknown,\n request?: BrickCallOptions,\n ): Promise<unknown> => {\n if (typeof node !== \"function\")\n throw new Error(\n \"Brick: select an action before calling Query helpers.\",\n );\n return node(input, request);\n };\n return new Proxy(call, {\n get(_target, prop) {\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\")\n return undefined;\n if (prop === \"queryKey\") return key;\n if (prop === \"queryOptions\")\n return (args?: { input?: unknown; request?: BrickCallOptions }) => ({\n queryKey: key({ input: args?.input }),\n queryFn: ({ signal }: QueryFunctionContext<ActionKey>) => {\n const signals = [\n signal,\n args?.request?.signal ?? options.signal,\n ].filter((value): value is AbortSignal => value !== undefined);\n return call(args?.input, {\n ...args?.request,\n signal: AbortSignal.any(signals),\n });\n },\n });\n if (prop === \"mutationOptions\")\n return (args?: { request?: BrickCallOptions }) => ({\n mutationKey: key(),\n mutationFn: (input: unknown) => call(input, args?.request),\n });\n if (typeof prop !== \"string\") return undefined;\n return namespace(\n Reflect.get(Object(node), prop),\n [...path, prop],\n Reflect.get(Object(metadata), prop),\n );\n },\n });\n }\n // The proxy maps contract leaves to callable helpers; no backend values are loaded.\n return namespace(client, [], options.contract) as BrickQueryClient<T>;\n}\n"],"mappings":";;;AA8DA,SAAgB,uBACd,SACqB;CACrB,MAAM,SAAS,kBAAkB,OAAO;CACxC,MAAM,UAAU,QAAQ,QAAQ,QAAQ,QAAQ,EAAE;CAClD,MAAM,SAAS,QAAQ,UAAU;CACjC,SAAS,eAAe,OAAgB,UAAiC;EACvE,MAAM,SAAkB,QAAQ,IAAI,OAAO,KAAK,GAAG,QAAQ;EAC3D,OAAO,OAAO,WAAW,WAAW,SAAS;CAC/C;CACA,SAAS,UACP,MACA,MACA,UACS;EACT,MAAM,SAAkB,QAAQ,IAAI,OAAO,QAAQ,GA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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brickkit/core",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Core engine primitives for the Brick-TS framework",
5
5
  "keywords": [
6
6
  "typescript",
@@ -36,6 +36,10 @@
36
36
  "./effect": {
37
37
  "import": "./dist/effect.js",
38
38
  "types": "./dist/effect.d.ts"
39
+ },
40
+ "./tanstack-query": {
41
+ "import": "./dist/tanstack-query.js",
42
+ "types": "./dist/tanstack-query.d.ts"
39
43
  }
40
44
  },
41
45
  "publishConfig": {
@@ -70,6 +74,15 @@
70
74
  "tsdown": "^0.23.1",
71
75
  "typescript": "^5.7.0",
72
76
  "oxfmt": "^0.73.0",
73
- "oxlint": "^1.88.0"
77
+ "oxlint": "^1.88.0",
78
+ "@tanstack/query-core": "^5.104.2"
79
+ },
80
+ "peerDependencies": {
81
+ "@tanstack/query-core": "^5.0.0"
82
+ },
83
+ "peerDependenciesMeta": {
84
+ "@tanstack/query-core": {
85
+ "optional": true
86
+ }
74
87
  }
75
88
  }