@brickkit/cli 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,12 +9,24 @@ bun add @brickkit/cli @brickkit/core
9
9
  ```
10
10
 
11
11
  ```ts
12
- import { createBrickServer } from "@brickkit/cli";
12
+ import { brick } from "@brickkit/cli";
13
13
 
14
- const app = createBrickServer({ title: "Pages API", version: "1.0.0" });
14
+ const app = brick({ title: "Pages API", version: "1.0.0" });
15
15
  app.listen(3333);
16
16
  ```
17
17
 
18
+ Build the backend directly from registered services:
19
+
20
+ ```ts
21
+ import { brick } from "@brickkit/cli";
22
+ import { pagesService, billingService } from "./services";
23
+
24
+ const app = brick({ services: [pagesService, billingService] });
25
+ ```
26
+
27
+ The typed HTTP client is available from `@brickkit/core/client`. See
28
+ `www/content/docs/(brick)/typed-client.mdx` for routing and error handling.
29
+
18
30
  The `brick` binary ships in this package for local dev and inspection:
19
31
 
20
32
  ```sh
@@ -25,6 +37,19 @@ brick info
25
37
 
26
38
  Source: <https://github.com/Chandraprakash-Darji/brick>.
27
39
 
40
+ ## Action routes
41
+
42
+ Each action exposes exactly one route: `method` defaults to POST, and `path`
43
+ defaults to `/api/{service}/{action}` (or your configured prefix). Explicit
44
+ methods are honored regardless of the action name. A custom `path` includes
45
+ its own prefix and replaces the default path. OpenAPI describes the same
46
+ method and path, including path parameters.
47
+
48
+ To expose a read action over GET, declare `method: "GET"`. Action names beginning
49
+ with `get`, `list`, `find`, or `read` no longer add a GET alias. Custom paths no
50
+ longer expose default action aliases or an additional method. Resource CRUD
51
+ routes keep their REST methods.
52
+
28
53
  ## Compiler
29
54
 
30
55
  The server compiles specialized JavaScript handlers for all resource CRUD and
@@ -40,3 +65,68 @@ bun dist/brick/server.js
40
65
 
41
66
  See [the compilation plan and artifact contract](COMPILER.md) for implemented
42
67
  stages, limitations and the next optimizations.
68
+
69
+ ## Automatic typed client with Vite
70
+
71
+ Add `brickClient` before your framework plugins. Its entry can be any module
72
+ whose default export is a `BrickApp`; construct the app without calling
73
+ `.listen()` there:
74
+
75
+ ```ts
76
+ // src/api/app.ts
77
+ import { brick } from "@brickkit/cli";
78
+ import { pagesService } from "./services";
79
+
80
+ export default brick({ prefix: "/v2", services: [pagesService] });
81
+ ```
82
+
83
+ ```ts
84
+ // vite.config.ts
85
+ import { brickClient } from "@brickkit/cli/vite";
86
+
87
+ export default defineConfig({
88
+ plugins: [
89
+ brickClient({ entry: "./src/api/app.ts" }),
90
+ // TanStack Start, React, or other framework plugins
91
+ ],
92
+ });
93
+ ```
94
+
95
+ Vite creates `_brick/contract.ts` before loading the frontend and before
96
+ production builds. The prefix and selected services come from the app. Backend
97
+ edits regenerate the file; unchanged metadata does not rewrite it. There is no
98
+ separate generation command or manually maintained action list.
99
+
100
+ ```ts
101
+ // src/client.ts
102
+ import { createBrickClient } from "@brickkit/core/client";
103
+ import { contract } from "../_brick/contract";
104
+
105
+ export const api = createBrickClient({
106
+ baseUrl: "http://localhost:8085",
107
+ contract,
108
+ });
109
+ ```
110
+
111
+ The generated file contains transport types and route metadata, with no runtime
112
+ imports or backend handlers. HTTP actions are grouped by service name; dotted
113
+ action names become nested namespaces. Resources use their names at the root
114
+ and their normal REST routes. MCP-only tools are excluded. Add `_brick/` to
115
+ `.gitignore`; customize its location with `output` in the plugin options.
116
+
117
+ For TanStack Start or another embedded server, import the app from
118
+ `virtual:brick-app` in server code and forward requests to `app.fetch(request)`.
119
+ Vite tracks the entry and its dependencies for backend hot reload. Browser
120
+ imports of this server module are rejected. Add
121
+ `/// <reference types="@brickkit/cli/vite/client" />` to your Vite environment
122
+ declarations. See `examples/pages` for a complete Start integration.
123
+
124
+ Generation evaluates the app entry, so the configuration it needs to construct
125
+ the app must be available in development and at build time. Keep startup jobs
126
+ and connection-opening initialization in request handlers or your server
127
+ bootstrap, outside the app definition module. Input/output types
128
+ come from JSON transport schemas; absent schemas produce `unknown`. Unresolved
129
+ schema references and non-JSON transport types fail generation explicitly.
130
+ This integration requires Vite 8; the normal server entry point has no Vite
131
+ runtime dependency. `generateClientContract(app)` exposes the source generator
132
+ for non-Vite tooling.
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env bun\nimport { startDevServer } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { getGlobalRegistry, generateOpenApiSpec } from \"@brickkit/core\";\n\nconst args = process.argv.slice(2);\nconst command = args[0] || \"dev\";\n\nasync function main() {\n switch (command) {\n case \"dev\":\n case \"start\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n const portArgIdx = args.indexOf(\"--port\");\n const port = portArgIdx !== -1 ? Number(args[portArgIdx + 1]) : 4000;\n\n await startDevServer({ entry, port });\n break;\n }\n\n case \"build\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n if (!entry) throw new Error(\"Usage: brick build <definitions.ts> [--outdir <directory>] [--prefix <path>] [--port <number>]\");\n const value = (flag: string) => {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n if (!args[index + 1] || args[index + 1]!.startsWith(\"--\")) throw new Error(`Missing value for ${flag}`);\n return args[index + 1];\n };\n const port = value(\"--port\");\n const result = await buildApplication({ entry, outdir: value(\"--outdir\"), prefix: value(\"--prefix\"),\n port: port === undefined ? undefined : Number(port), requestLogging: !args.includes(\"--no-request-logging\") });\n for (const warning of result.ir.diagnostics) console.warn(`[Brick compiler] ${warning}`);\n console.log(`Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`);\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n console.log(`Run: bun ${result.entry}`);\n break;\n }\n\n case \"gen\": {\n const subCommand = args[1];\n if (subCommand === \"openapi\") {\n const outIdx = args.indexOf(\"--output\");\n const outputFile = outIdx !== -1 ? args[outIdx + 1] : undefined;\n\n const spec = generateOpenApiSpec();\n const jsonOutput = JSON.stringify(spec, null, 2);\n\n if (outputFile) {\n await Bun.write(outputFile, jsonOutput);\n console.log(`✅ OpenAPI 3.1 specification written to ${outputFile}`);\n } else {\n console.log(jsonOutput);\n }\n break;\n }\n console.error(`Unknown generator: ${subCommand}. Available: openapi`);\n process.exit(1);\n break;\n }\n\n case \"info\":\n case \"services\": {\n const registry = getGlobalRegistry();\n console.log(JSON.stringify(registry.exportArchitecture(), null, 2));\n break;\n }\n\n default:\n console.log(`\n🧱 Brick-TS CLI\n\nUsage:\n brick dev [entry] [--port <number>] Start development server with live reload\n brick start [entry] Start production server\n brick build <entry> [--outdir <dir>] Compile definitions into a Bun server\n brick gen openapi [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick info Export architecture JSON schema\n`);\n process.exit(0);\n }\n}\n\nmain().catch((err) => {\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;AAKA,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,MAAM,UAAU,KAAK,MAAM;AAE3B,eAAe,OAAO;CACpB,QAAQ,SAAR;EACE,KAAK;EACL,KAAK,SAAS;GACZ,MAAM,QAAQ,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,WAAW,GAAG,IAAI,KAAK,KAAK,KAAA;GAC9D,MAAM,aAAa,KAAK,QAAQ,QAAQ;GACxC,MAAM,OAAO,eAAe,KAAK,OAAO,KAAK,aAAa,EAAE,IAAI;GAEhE,MAAM,eAAe;IAAE;IAAO;GAAK,CAAC;GACpC;EACF;EAEA,KAAK,SAAS;GACZ,MAAM,QAAQ,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,WAAW,GAAG,IAAI,KAAK,KAAK,KAAA;GAC9D,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,gGAAgG;GAC5H,MAAM,SAAS,SAAiB;IAC9B,MAAM,QAAQ,KAAK,QAAQ,IAAI;IAC/B,IAAI,UAAU,IAAI,OAAO,KAAA;IACzB,IAAI,CAAC,KAAK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C;CAClB;AACF;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env bun\nimport { startDevServer } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { getGlobalRegistry, generateOpenApiSpec } from \"@brickkit/core\";\n\nconst args = process.argv.slice(2);\nconst command = args[0] || \"dev\";\n\nasync function main() {\n switch (command) {\n case \"dev\":\n case \"start\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n const portArgIdx = args.indexOf(\"--port\");\n const port = portArgIdx !== -1 ? Number(args[portArgIdx + 1]) : 4000;\n\n await startDevServer({ entry, port });\n break;\n }\n\n case \"build\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n if (!entry)\n throw new Error(\n \"Usage: brick build <definitions.ts> [--outdir <directory>] [--prefix <path>] [--port <number>]\",\n );\n const value = (flag: string) => {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n if (!args[index + 1] || args[index + 1]!.startsWith(\"--\"))\n throw new Error(`Missing value for ${flag}`);\n return args[index + 1];\n };\n const port = value(\"--port\");\n const result = await buildApplication({\n entry,\n outdir: value(\"--outdir\"),\n prefix: value(\"--prefix\"),\n port: port === undefined ? undefined : Number(port),\n requestLogging: !args.includes(\"--no-request-logging\"),\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n console.log(`Run: bun ${result.entry}`);\n break;\n }\n\n case \"gen\": {\n const subCommand = args[1];\n if (subCommand === \"openapi\") {\n const outIdx = args.indexOf(\"--output\");\n const outputFile = outIdx !== -1 ? args[outIdx + 1] : undefined;\n\n const spec = generateOpenApiSpec();\n const jsonOutput = JSON.stringify(spec, null, 2);\n\n if (outputFile) {\n await Bun.write(outputFile, jsonOutput);\n console.log(`✅ OpenAPI 3.1 specification written to ${outputFile}`);\n } else {\n console.log(jsonOutput);\n }\n break;\n }\n console.error(`Unknown generator: ${subCommand}. Available: openapi`);\n process.exit(1);\n break;\n }\n\n case \"info\":\n case \"services\": {\n const registry = getGlobalRegistry();\n console.log(JSON.stringify(registry.exportArchitecture(), null, 2));\n break;\n }\n\n default:\n console.log(`\n🧱 Brick-TS CLI\n\nUsage:\n brick dev [entry] [--port <number>] Start development server with live reload\n brick start [entry] Start production server\n brick build <entry> [--outdir <dir>] Compile definitions into a Bun server\n brick gen openapi [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick info Export architecture JSON schema\n`);\n process.exit(0);\n }\n}\n\nmain().catch((err) => {\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;AAKA,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,MAAM,UAAU,KAAK,MAAM;AAE3B,eAAe,OAAO;CACpB,QAAQ,SAAR;EACE,KAAK;EACL,KAAK,SAAS;GACZ,MAAM,QAAQ,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,WAAW,GAAG,IAAI,KAAK,KAAK,KAAA;GAC9D,MAAM,aAAa,KAAK,QAAQ,QAAQ;GACxC,MAAM,OAAO,eAAe,KAAK,OAAO,KAAK,aAAa,EAAE,IAAI;GAEhE,MAAM,eAAe;IAAE;IAAO;GAAK,CAAC;GACpC;EACF;EAEA,KAAK,SAAS;GACZ,MAAM,QAAQ,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,WAAW,GAAG,IAAI,KAAK,KAAK,KAAA;GAC9D,IAAI,CAAC,OACH,MAAM,IAAI,MACR,gGACF;GACF,MAAM,SAAS,SAAiB;IAC9B,MAAM,QAAQ,KAAK,QAAQ,IAAI;IAC/B,IAAI,UAAU,IAAI,OAAO,KAAA;IACzB,IAAI,CAAC,KAA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;CAClB;AACF;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/dist/build.js CHANGED
@@ -235,7 +235,7 @@ function endpointPaths(defs) {
235
235
  }
236
236
  //#endregion
237
237
  //#region src/server.ts
238
- function createBrickServer(options = {}) {
238
+ function brick(options = {}) {
239
239
  const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
240
240
  const title = options.title ?? "Brick-TS API Mesh";
241
241
  const version = options.version ?? "1.0.0";
@@ -287,7 +287,7 @@ function createBrickServer(options = {}) {
287
287
  return {
288
288
  ...spec,
289
289
  paths: {
290
- ...spec.paths ?? {},
290
+ ...spec.paths,
291
291
  ...endpointPaths(endpointDefs)
292
292
  }
293
293
  };
@@ -335,6 +335,10 @@ function createBrickServer(options = {}) {
335
335
  };
336
336
  for (const def of options.endpoints ?? []) mountEndpoint(def);
337
337
  const brickApp = app;
338
+ Object.defineProperty(brickApp, "definition", { value: Object.freeze({
339
+ services: Object.freeze([...services]),
340
+ prefix
341
+ }) });
338
342
  brickApp.endpoint = (def) => {
339
343
  mountEndpoint(def);
340
344
  };
@@ -386,7 +390,7 @@ async function startDevServer(options = {}) {
386
390
  if (typeof svc.listResources === "function") for (const res of svc.listResources()) console.log(` -> Resource: /api/${res.name} (REST: GET, POST, /:id: GET, PATCH, DELETE)`);
387
391
  for (const act of svc.listActions()) console.log(` -> Action: /api/${svc.name}/${act.name}`);
388
392
  }
389
- const app = createBrickServer({
393
+ const app = brick({
390
394
  port,
391
395
  prefix: options.prefix
392
396
  });
@@ -418,11 +422,11 @@ async function buildApplication(options) {
418
422
  try {
419
423
  await Bun.write(join(staging, "routes.js"), emitCompiledApplication(compilation.ir));
420
424
  const source = `import ${JSON.stringify(entry)};
421
- import { createBrickServer } from "@brickkit/cli";
425
+ import { brick } from "@brickkit/cli";
422
426
  import { getGlobalRegistry } from "@brickkit/core";
423
427
  import { bind } from "./routes.js";
424
428
  const services = getGlobalRegistry().list();
425
- export const app = createBrickServer({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });
429
+ export const app = brick({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });
426
430
  if (import.meta.main) {
427
431
  const port = Number(process.env.PORT ?? ${port});
428
432
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid PORT");
@@ -464,6 +468,6 @@ if (import.meta.main) {
464
468
  }
465
469
  }
466
470
  //#endregion
467
- export { registerReferenceRoute as a, referencePlugin as i, startDevServer as n, scalarDocsHTML as o, createBrickServer as r, requestLoggingPlugin as s, buildApplication as t };
471
+ export { registerReferenceRoute as a, referencePlugin as i, startDevServer as n, scalarDocsHTML as o, brick as r, requestLoggingPlugin as s, buildApplication as t };
468
472
 
469
473
  //# sourceMappingURL=build.js.map
package/dist/build.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","names":["resolve"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/endpoints.ts","../src/server.ts","../src/runner.ts","../src/build.ts"],"sourcesContent":["import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved. Logging only —\n * no CORS headers are set here.\n *\n * Hooks are registered with `{ as: \"global\" }` so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in onBeforeHandle\n * because onRequest offers no `as` option and is never propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(\n opts: RequestLoggingOptions = {}\n): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({ request, set }: Pick<Context, \"request\" | \"set\">): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.onBeforeHandle({ as: \"global\" }, markStarted);\n plugin.onAfterHandle({ as: \"global\" }, logSuccess);\n plugin.onError({ as: \"global\" }, logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface ReferenceOptions {\n path?: string;\n title?: string;\n specUrl?: string;\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/** Mounts the Scalar reference route onto an existing app. */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {}\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","import type { Elysia } from \"elysia\";\nimport type { Service, DatabaseHandle } from \"@brickkit/core\";\nimport { ActionExecutionError, ValidationError } from \"@brickkit/core\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[]\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb() ?? undefined;\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[]\n): (elysiaCtx: any) => Promise<unknown> {\n return async ({ params, body, query, headers, request, set }: any) => {\n const traceId =\n headers?.[\"x-trace-id\"] ||\n `tr_${Math.random().toString(36).substring(2, 10)}`;\n const requestId =\n headers?.[\"x-request-id\"] ||\n `req_${Math.random().toString(36).substring(2, 10)}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n const tag = `endpoint:${def.method} ${def.path}`;\n const ctx: EndpointContext = {\n body,\n db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger: {\n info: (...args) => console.log(`[${tag}]`, ...args),\n warn: (...args) => console.warn(`[${tag}]`, ...args),\n error: (...args) => console.error(`[${tag}]`, ...args),\n debug: (...args) => console.debug(`[${tag}]`, ...args),\n },\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err: any) {\n if (err instanceof ValidationError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (typeof err?.status === \"number\") {\n set.status = err.status;\n return { message: err.message || \"Endpoint error\", status: err.status };\n }\n set.status = 500;\n return {\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n };\n}\n\n/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `createBrickServer`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Register a raw endpoint (outside the JSON action mesh). */\n endpoint(def: EndpointDefinition): void;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","import { Elysia } from \"elysia\";\nimport { compileBrickApplication, type CompiledApplication } from \"./compiler\";\nimport {\n type Service,\n getGlobalRegistry,\n generateOpenApiSpec,\n resolveSecrets,\n type SecretSource,\n} from \"@brickkit/core\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n registerReferenceRoute,\n type ReferenceOptions,\n} from \"./docs\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Generate specialized handlers once at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n reference?: boolean | ReferenceOptions; // default false, path \"/reference\"\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (outside the JSON action mesh), mounted at startup. */\n endpoints?: EndpointDefinition[];\n}\n\nexport { compileRoutePlan, executeCompiledRoute, createActionHandler } from \"./action-handler\";\n\nexport function createBrickServer(options: CreateServerOptions = {}): BrickApp {\n const prefix = options.prefix ?? options.compilation?.ir.prefix ?? \"/api\";\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const compiled = options.compiler !== false;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? \"/openapi.json\";\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n // Diagnostics & health\n app.get(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n app.get(\"/_brick/services\", compiled\n ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(), () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n })\n : () => getGlobalRegistry().exportArchitecture());\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false) {\n const pluginOpts = requestLogging === true ? {} : requestLogging;\n if (pluginOpts.enabled !== false) {\n app.use(requestLoggingPlugin(pluginOpts));\n }\n }\n\n // Scalar API reference (opt-in). Defaults to openApiPath for the spec URL.\n const reference = options.reference ?? false;\n if (reference !== false) {\n const refOpts = reference === true ? {} : reference;\n const settings = {\n path: refOpts.path ?? \"/reference\",\n title: refOpts.title ?? title,\n specUrl: refOpts.specUrl ?? openApiPath,\n };\n if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));\n else registerReferenceRoute(app, settings);\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n\n // Precompute plans and freeze immutable plans across all services\n for (const service of services) {\n if (typeof (service as any).build === \"function\") {\n (service as any).build();\n }\n }\n\n // Raw endpoints declared via options or app.endpoint() (declaration order).\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n // OpenAPI 3.1 & Interactive Documentation Endpoints\n if (enableDocs) {\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n // Raw endpoints show up in the spec alongside the action mesh.\n return { ...spec, paths: { ...(spec.paths ?? {}), ...endpointPaths(endpointDefs) } };\n };\n app.get(openApiPath, compiled\n ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision] as const)\n : buildSpec);\n\n if (compiled) {\n app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n } else {\n app.get(docsPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(openApiPath, title);\n });\n\n app.get(swaggerPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return swaggerDocsHTML(openApiPath, title);\n });\n }\n }\n\n // Dedicated Route Registry\n const registeredRoutes = new Set<string>();\n\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any\n ) => {\n const routeKey = `${method} ${path}`;\n if (registeredRoutes.has(routeKey)) {\n return;\n }\n registeredRoutes.add(routeKey);\n\n switch (method) {\n case \"GET\":\n app.get(path, handler);\n break;\n case \"POST\":\n app.post(path, handler);\n break;\n case \"PUT\":\n app.put(path, handler);\n break;\n case \"PATCH\":\n app.patch(path, handler);\n break;\n case \"DELETE\":\n app.delete(path, handler);\n break;\n }\n };\n\n // Raw endpoints (outside the JSON action mesh).\n const mountEndpoint = (def: EndpointDefinition) => {\n endpointDefs.push(def);\n endpointRevision++;\n mountRoute(def.method, def.path, createEndpointHandler(def, services));\n };\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n\n const compilation = options.compilation ?? compileBrickApplication({ services, prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\" });\n if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map(service => service.name))) {\n throw new Error(\"Brick compiler: server services/prefix differ from the bound compilation\");\n }\n for (const route of compilation.routes) mountRoute(route.ir.method, route.ir.path, route.handler);\n\n return brickApp;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, { headers: { \"content-type\": \"text/html; charset=utf-8\" } });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(build: () => unknown, revision: () => readonly [unknown, number]) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n","import { existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { createBrickServer } from \"./server\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n}\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const port = options.port ?? (Number(process.env.PORT) || 4000);\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (existsSync(resolvedEntry)) {\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n } else {\n console.warn(`[Brick-TS] Specified entry not found: ${resolvedEntry}`);\n }\n }\n\n const registry = getGlobalRegistry();\n const services = registry.list();\n\n console.log(`\\n🧱 Brick-TS Development Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n console.log(` • ${svc.name} (${svc.listActions().length} actions)`);\n if (typeof (svc as any).listResources === \"function\") {\n for (const res of (svc as any).listResources()) {\n console.log(` -> Resource: /api/${res.name} (REST: GET, POST, /:id: GET, PATCH, DELETE)`);\n }\n }\n for (const act of svc.listActions()) {\n console.log(` -> Action: /api/${svc.name}/${act.name}`);\n }\n }\n\n const app = createBrickServer({\n port,\n prefix: options.prefix,\n });\n\n app.listen(port);\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`);\n\n return app;\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { compileBrickApplication, emitCompiledApplication } from \"./compiler\";\n\nexport interface BuildApplicationOptions {\n /** A module that registers services, without starting a server. */\n entry: string;\n outdir?: string;\n prefix?: string;\n port?: number;\n requestLogging?: boolean;\n}\n\n/** Analyze definitions and bundle the emitted handlers with the user's callbacks. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!await Bun.file(entry).exists()) throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? \"dist/brick\");\n if (entry === join(outdir, \"server.js\") || entry === join(outdir, \"routes.js\")) throw new Error(\"Brick compiler: output would overwrite the application entry\");\n const port = options.port ?? 4000;\n if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(\"Brick compiler: port must be an integer between 0 and 65535\");\n await import(pathToFileURL(entry).href);\n const services = getGlobalRegistry().list();\n if (!services.length) throw new Error(\"Brick compiler: entry registered no services; use a definitions module\");\n const compilation = compileBrickApplication({ services, prefix: options.prefix });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(join(staging, \"routes.js\"), emitCompiledApplication(compilation.ir));\n const source = `import ${JSON.stringify(entry)};\nimport { createBrickServer } from \"@brickkit/cli\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { bind } from \"./routes.js\";\nconst services = getGlobalRegistry().list();\nexport const app = createBrickServer({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });\nif (import.meta.main) {\n const port = Number(process.env.PORT ?? ${port});\n if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(\"Invalid PORT\");\n app.listen(port);\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n const stop = async () => { await app.stop(); process.exit(0); };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n const result = await Bun.build({ entrypoints: [join(staging, \"entry.ts\")], target: \"bun\", format: \"esm\", outdir: staging, naming: \"server.js\", sourcemap: \"external\" });\n if (!result.success) throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n await Bun.write(join(staging, \"brick-ir.json\"), JSON.stringify(compilation.ir, null, 2) + \"\\n\");\n await mkdir(outdir, { recursive: true });\n for (const name of [\"routes.js\", \"brick-ir.json\", \"server.js.map\", \"server.js\"]) await rename(join(staging, name), join(outdir, name));\n return { outdir, entry: join(outdir, \"server.js\"), ir: compilation.ir };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;AAOA,SAAS,UACP,QACA,MACA,QACA,WACQ;CACR,OAAO,GAAG,OAAO,GAAG,KAAK,KAAK,OAAO,MAAM,EAAE,IAAI,UAAU;AAC7D;;;;;AAMA,SAAS,aAAa,OAAoC;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,OAAO;EACpE,MAAM,SAAkB,MAAM;EAC9B,IAAI,OAAO,WAAW,UAAU,OAAO;CACzC;AAEF;;;;;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,KAAK;;;;;;;;;EAS7C,MAAM,IAAI,MAAM,KAAK,SAAS,UAAU,GAAG,MAAM;EACjD,MAAM,SAAS,MAAM,IAAI,MAAM;GAAE,aAAa,CAAC,KAAK,SAAS,UAAU,CAAC;GAAG,QAAQ;GAAO,QAAQ;GAAO,QAAQ;GAAS,QAAQ;GAAa,WAAW;EAAW,CAAC;EACtK,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,eAAe,OAAO,MAAM,iCAAiC;EAC5F,MAAM,IAAI,MAAM,KAAK,SAAS,eAAe,GAAG,KAAK,UAAU,YAAY,IAAI,MAAM,CAAC,IAAI,IAAI;EAC9F,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;EACvC,KAAK,MAAM,QAAQ;GAAC;GAAa;GAAiB;GAAiB;EAAW,GAAG,MAAM,OAAO,KAAK,SAAS,IAAI,GAAG,KAAK,QAAQ,IAAI,CAAC;EACrI,OAAO;GAAE;GAAQ,OAAO,KAAK,QAAQ,WAAW;GAAG,IAAI,YAAY;EAAG;CACxE,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
1
+ {"version":3,"file":"build.js","names":["resolve"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/endpoints.ts","../src/server.ts","../src/runner.ts","../src/build.ts"],"sourcesContent":["import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved. Logging only —\n * no CORS headers are set here.\n *\n * Hooks are registered with `{ as: \"global\" }` so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in onBeforeHandle\n * because onRequest offers no `as` option and is never propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({\n request,\n set,\n }: Pick<Context, \"request\" | \"set\">): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n logger(\n formatLog(request.method, path, set.status ?? 200, Date.now() - start),\n );\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.onBeforeHandle({ as: \"global\" }, markStarted);\n plugin.onAfterHandle({ as: \"global\" }, logSuccess);\n plugin.onError({ as: \"global\" }, logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface ReferenceOptions {\n path?: string;\n title?: string;\n specUrl?: string;\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/** Mounts the Scalar reference route onto an existing app. */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","import type { Elysia } from \"elysia\";\nimport type { Service, DatabaseHandle } from \"@brickkit/core\";\nimport { ActionExecutionError, ValidationError } from \"@brickkit/core\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb() ?? undefined;\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n return async ({ params, body, query, headers, request, set }: any) => {\n const traceId =\n headers?.[\"x-trace-id\"] ||\n `tr_${Math.random().toString(36).substring(2, 10)}`;\n const requestId =\n headers?.[\"x-request-id\"] ||\n `req_${Math.random().toString(36).substring(2, 10)}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n const tag = `endpoint:${def.method} ${def.path}`;\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger: {\n info: (...args) => console.log(`[${tag}]`, ...args),\n warn: (...args) => console.warn(`[${tag}]`, ...args),\n error: (...args) => console.error(`[${tag}]`, ...args),\n debug: (...args) => console.debug(`[${tag}]`, ...args),\n },\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err: any) {\n if (err instanceof ValidationError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (typeof err?.status === \"number\") {\n set.status = err.status;\n return { message: err.message || \"Endpoint error\", status: err.status };\n }\n set.status = 500;\n return {\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n };\n}\n\n/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions and prefix selected when this app was constructed. */\n readonly definition: {\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n };\n /** Register a raw endpoint (outside the JSON action mesh). */\n endpoint(def: EndpointDefinition): void;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","import { Elysia } from \"elysia\";\nimport { compileBrickApplication, type CompiledApplication } from \"./compiler\";\nimport {\n type Service,\n getGlobalRegistry,\n generateOpenApiSpec,\n resolveSecrets,\n type SecretSource,\n} from \"@brickkit/core\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n registerReferenceRoute,\n type ReferenceOptions,\n} from \"./docs\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Generate specialized handlers once at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n reference?: boolean | ReferenceOptions; // default false, path \"/reference\"\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (outside the JSON action mesh), mounted at startup. */\n endpoints?: EndpointDefinition[];\n}\n\nexport {\n compileRoutePlan,\n executeCompiledRoute,\n createActionHandler,\n} from \"./action-handler\";\n\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n const prefix = options.prefix ?? options.compilation?.ir.prefix ?? \"/api\";\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const compiled = options.compiler !== false;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? \"/openapi.json\";\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n // Diagnostics & health\n app.get(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n app.get(\n \"/_brick/services\",\n compiled\n ? cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n )\n : () => getGlobalRegistry().exportArchitecture(),\n );\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false) {\n const pluginOpts = requestLogging === true ? {} : requestLogging;\n if (pluginOpts.enabled !== false) {\n app.use(requestLoggingPlugin(pluginOpts));\n }\n }\n\n // Scalar API reference (opt-in). Defaults to openApiPath for the spec URL.\n const reference = options.reference ?? false;\n if (reference !== false) {\n const refOpts = reference === true ? {} : reference;\n const settings = {\n path: refOpts.path ?? \"/reference\",\n title: refOpts.title ?? title,\n specUrl: refOpts.specUrl ?? openApiPath,\n };\n if (compiled)\n app.get(\n settings.path,\n htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)),\n );\n else registerReferenceRoute(app, settings);\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n\n // Precompute plans and freeze immutable plans across all services\n for (const service of services) {\n if (typeof (service as any).build === \"function\") {\n (service as any).build();\n }\n }\n\n // Raw endpoints declared via options or app.endpoint() (declaration order).\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n // OpenAPI 3.1 & Interactive Documentation Endpoints\n if (enableDocs) {\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n // Raw endpoints show up in the spec alongside the action mesh.\n return {\n ...spec,\n paths: { ...spec.paths, ...endpointPaths(endpointDefs) },\n };\n };\n app.get(\n openApiPath,\n compiled\n ? cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n )\n : buildSpec,\n );\n\n if (compiled) {\n app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n } else {\n app.get(docsPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(openApiPath, title);\n });\n\n app.get(swaggerPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return swaggerDocsHTML(openApiPath, title);\n });\n }\n }\n\n // Dedicated Route Registry\n const registeredRoutes = new Set<string>();\n\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any,\n ) => {\n const routeKey = `${method} ${path}`;\n if (registeredRoutes.has(routeKey)) {\n return;\n }\n registeredRoutes.add(routeKey);\n\n switch (method) {\n case \"GET\":\n app.get(path, handler);\n break;\n case \"POST\":\n app.post(path, handler);\n break;\n case \"PUT\":\n app.put(path, handler);\n break;\n case \"PATCH\":\n app.patch(path, handler);\n break;\n case \"DELETE\":\n app.delete(path, handler);\n break;\n }\n };\n\n // Raw endpoints (outside the JSON action mesh).\n const mountEndpoint = (def: EndpointDefinition) => {\n endpointDefs.push(def);\n endpointRevision++;\n mountRoute(def.method, def.path, createEndpointHandler(def, services));\n };\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n Object.defineProperty(brickApp, \"definition\", {\n value: Object.freeze({ services: Object.freeze([...services]), prefix }),\n });\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n for (const route of compilation.routes)\n mountRoute(route.ir.method, route.ir.path, route.handler);\n\n return brickApp;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n","import { existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { brick } from \"./server\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n}\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const port = options.port ?? (Number(process.env.PORT) || 4000);\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (existsSync(resolvedEntry)) {\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n } else {\n console.warn(`[Brick-TS] Specified entry not found: ${resolvedEntry}`);\n }\n }\n\n const registry = getGlobalRegistry();\n const services = registry.list();\n\n console.log(`\\n🧱 Brick-TS Development Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n console.log(` • ${svc.name} (${svc.listActions().length} actions)`);\n if (typeof (svc as any).listResources === \"function\") {\n for (const res of (svc as any).listResources()) {\n console.log(\n ` -> Resource: /api/${res.name} (REST: GET, POST, /:id: GET, PATCH, DELETE)`,\n );\n }\n }\n for (const act of svc.listActions()) {\n console.log(` -> Action: /api/${svc.name}/${act.name}`);\n }\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\n });\n\n app.listen(port);\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { compileBrickApplication, emitCompiledApplication } from \"./compiler\";\n\nexport interface BuildApplicationOptions {\n /** A module that registers services, without starting a server. */\n entry: string;\n outdir?: string;\n prefix?: string;\n port?: number;\n requestLogging?: boolean;\n}\n\n/** Analyze definitions and bundle the emitted handlers with the user's callbacks. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? \"dist/brick\");\n if (\n entry === join(outdir, \"server.js\") ||\n entry === join(outdir, \"routes.js\")\n )\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = options.port ?? 4000;\n if (!Number.isInteger(port) || port < 0 || port > 65535)\n throw new Error(\n \"Brick compiler: port must be an integer between 0 and 65535\",\n );\n await import(pathToFileURL(entry).href);\n const services = getGlobalRegistry().list();\n if (!services.length)\n throw new Error(\n \"Brick compiler: entry registered no services; use a definitions module\",\n );\n const compilation = compileBrickApplication({\n services,\n prefix: options.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const source = `import ${JSON.stringify(entry)};\nimport { brick } from \"@brickkit/cli\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { bind } from \"./routes.js\";\nconst services = getGlobalRegistry().list();\nexport const app = brick({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });\nif (import.meta.main) {\n const port = Number(process.env.PORT ?? ${port});\n if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(\"Invalid PORT\");\n app.listen(port);\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n const stop = async () => { await app.stop(); process.exit(0); };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of [\n \"routes.js\",\n \"brick-ir.json\",\n \"server.js.map\",\n \"server.js\",\n ])\n await rename(join(staging, name), join(outdir, name));\n return { outdir, entry: join(outdir, \"server.js\"), ir: compilation.ir };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;AAOA,SAAS,UACP,QACA,MACA,QACA,WACQ;CACR,OAAO,GAAG,OAAO,GAAG,KAAK,KAAK,OAAO,MAAM,EAAE,IAAI,UAAU;AAC7D;;;;;AAMA,SAAS,aAAa,OAAoC;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,OAAO;EACpE,MAAM,SAAkB,MAAM;EAC9B,IAAI,OAAO,WAAW,UAAU,OAAO;CACzC;AAEF;;;;;;;;;;;;;AAcA,SAAgB,qBAAqB,OAA8B,CAAC,GAAW;CAC7E,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,EADY,KAAK,WAAW,OAClB,OAAO;CACrB,MAAM,SAAS,KAAK,UAAU,QAAQ;CACtC,MAAM,4BAAY,IAAI,QAAwB;CAE9C,MAAM,eAAe,EAAE,cAA8C;EACnE,UAAU,IAAI,SAAS,KAAK,IAAI,CAAC;CACnC;CAEA,MAAM,cAAc,EAClB,SACA,UAC4C;EAC5C,MAAM,QAAQ,UAAU,IAAI,OAAO,KAAK,KAAK,IAAI;EACjD,MAAM,OAAO,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;EAClC,OACE,UAAU,QAAQ,QAAQ,MAAM,IAAI,UAAU,KAAK,KAAK,IAAI,IAAI,KAAK,CACvE;CACF;CAEA,MAAM,YAAY,EAChB,SACA,KACA,YACuE;EACvE,IAAI,SAAS;GACX,MAAM,QAAQ,UAAU,IAAI,OAAO,KAAK,KAAK,IAAI;GACjD,MAAM,OAAO,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;GAClC,MAAM,SAAS,aAAa,KAAK,KAAK,IA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AAO;EAAK,CAAC;CACpD;AACF"}
@@ -0,0 +1,168 @@
1
+ //#region src/client-contract.ts
2
+ /** Generate browser metadata and transport types from the app's selected services. */
3
+ function generateClientContract(app) {
4
+ const { services, prefix } = app.definition;
5
+ const contract = Object.create(null);
6
+ const types = Object.create(null);
7
+ const resourceActions = /* @__PURE__ */ new Set();
8
+ for (const service of services) addResources(service, prefix, contract, types, resourceActions);
9
+ for (const service of services) addServiceActions(service, prefix, contract, types, resourceActions);
10
+ return `// Generated by the Brick Vite plugin. Do not edit.
11
+ import type { BrickClientAction } from "@brickkit/core/client";
12
+
13
+ export type AppContract = ${namespaceType(types)};
14
+
15
+ export const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});
16
+ `;
17
+ }
18
+ function addResources(service, prefix, contract, types, resourceActions) {
19
+ for (const resource of service.listResources()) {
20
+ if (Object.hasOwn(contract, resource.name)) throw new Error(`Brick client: duplicate namespace '${resource.name}'`);
21
+ const node = Object.create(null);
22
+ const typeNode = Object.create(null);
23
+ contract[resource.name] = node;
24
+ types[resource.name] = typeNode;
25
+ const enabled = new Set(service.listActions());
26
+ for (const [operation, method, item] of [
27
+ [
28
+ "list",
29
+ "GET",
30
+ false
31
+ ],
32
+ [
33
+ "create",
34
+ "POST",
35
+ false
36
+ ],
37
+ [
38
+ "get",
39
+ "GET",
40
+ true
41
+ ],
42
+ [
43
+ "update",
44
+ "PATCH",
45
+ true
46
+ ],
47
+ [
48
+ "delete",
49
+ "DELETE",
50
+ true
51
+ ]
52
+ ]) {
53
+ const action = resource.actions[operation];
54
+ resourceActions.add(action);
55
+ if (!enabled.has(action)) continue;
56
+ const itemPath = item ? `/:${resource.idField}` : "";
57
+ const path = `${prefix}/${resource.name}${itemPath}`;
58
+ node[operation] = {
59
+ kind: "action",
60
+ name: action.name,
61
+ serviceName: service.name,
62
+ config: {
63
+ path,
64
+ method
65
+ }
66
+ };
67
+ typeNode[operation] = actionType(schemaType(action.config.input), schemaType(operation === "list" ? {
68
+ ...action.config.output,
69
+ required: [.../* @__PURE__ */ new Set([
70
+ ...action.config.output?.required ?? [],
71
+ "items",
72
+ "total",
73
+ "limit",
74
+ "offset",
75
+ "pageCount",
76
+ "hasMore",
77
+ "nextCursor"
78
+ ])]
79
+ } : action.config.output), action.config.errors);
80
+ }
81
+ }
82
+ }
83
+ function addServiceActions(service, prefix, contract, types, resourceActions) {
84
+ const namespace = contract[service.name] ?? Object.create(null);
85
+ const namespaceTypes = types[service.name] ?? Object.create(null);
86
+ contract[service.name] = namespace;
87
+ types[service.name] = namespaceTypes;
88
+ for (const action of service.listActions()) {
89
+ if (resourceActions.has(action)) continue;
90
+ const { input, output, errors, path, method } = action.config;
91
+ let inputType;
92
+ let outputType;
93
+ try {
94
+ inputType = input ? schemaType(input) : "unknown";
95
+ outputType = output ? schemaType(output) : "unknown";
96
+ } catch (error) {
97
+ throw new Error(`Brick client: cannot generate '${service.name}.${action.name}': ${error.message}`);
98
+ }
99
+ insertAction(namespace, namespaceTypes, {
100
+ kind: "action",
101
+ name: action.name,
102
+ serviceName: service.name,
103
+ config: {
104
+ path: path ?? `${prefix}/${service.name}/${action.name}`,
105
+ method: method ?? "POST"
106
+ }
107
+ }, actionType(inputType, outputType, errors));
108
+ }
109
+ }
110
+ function insertAction(node, typeNode, metadata, type) {
111
+ const segments = metadata.name.split(".");
112
+ for (const segment of segments.slice(0, -1)) {
113
+ if (Object.hasOwn(typeNode, segment) && typeof typeNode[segment] === "string") throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
114
+ node[segment] ??= Object.create(null);
115
+ typeNode[segment] ??= Object.create(null);
116
+ node = node[segment];
117
+ typeNode = typeNode[segment];
118
+ }
119
+ const leaf = segments.at(-1);
120
+ if (Object.hasOwn(node, leaf)) throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
121
+ node[leaf] = metadata;
122
+ typeNode[leaf] = type;
123
+ }
124
+ function actionType(input, output, errors) {
125
+ const codes = Object.keys(errors ?? {});
126
+ return `BrickClientAction<${input}, ${output}, ${codes.length ? `Record<${codes.map((code) => JSON.stringify(code)).join(" | ")}, { message: string; status?: number }>` : "{}"}>`;
127
+ }
128
+ function namespaceType(node) {
129
+ return `{\n${Object.entries(node).map(([key, value]) => ` ${JSON.stringify(key)}: ${typeof value === "string" ? value : namespaceType(value)};`).join("\n")}\n}`;
130
+ }
131
+ function schemaType(schema) {
132
+ if (schema === void 0) return "unknown";
133
+ if (schema === true) return "unknown";
134
+ if (schema === false || schema.not && !Object.keys(schema.not).length) return "never";
135
+ if (schema.$ref) throw new Error(`unresolved schema reference '${schema.$ref}'`);
136
+ if (Object.hasOwn(schema, "const")) return JSON.stringify(schema.const);
137
+ if (schema.enum) return schema.enum.map((value) => JSON.stringify(value)).join(" | ") || "never";
138
+ if (schema.anyOf || schema.oneOf) return `(${(schema.anyOf ?? schema.oneOf).map(schemaType).join(" | ")})`;
139
+ if (schema.allOf) return `(${schema.allOf.map(schemaType).join(" & ")})`;
140
+ switch (schema.type) {
141
+ case "string": return "string";
142
+ case "number":
143
+ case "integer": return "number";
144
+ case "boolean": return "boolean";
145
+ case "null": return "null";
146
+ case "undefined":
147
+ case "void": return "undefined";
148
+ case "array": return arraySchemaType(schema);
149
+ case "object": return objectSchemaType(schema);
150
+ case void 0: return "unknown";
151
+ default: throw new Error(`unsupported transport schema type '${schema.type}'`);
152
+ }
153
+ }
154
+ function arraySchemaType(schema) {
155
+ if (Array.isArray(schema.items)) return `[${schema.items.map(schemaType).join(", ")}]`;
156
+ return `Array<${schema.items ? schemaType(schema.items) : "unknown"}>`;
157
+ }
158
+ function objectSchemaType(schema) {
159
+ const object = `{ ${Object.entries(schema.properties ?? {}).map(([key, value]) => `${JSON.stringify(key)}${schema.required?.includes(key) ? "" : "?"}: ${schemaType(value)};`).join(" ")} }`;
160
+ const patterns = Object.values(schema.patternProperties ?? {});
161
+ if (patterns.length) return `${object} & Record<string, ${patterns.map(schemaType).join(" | ")}>`;
162
+ if (schema.additionalProperties) return `${object} & Record<string, ${schema.additionalProperties === true ? "unknown" : schemaType(schema.additionalProperties)}>`;
163
+ return object;
164
+ }
165
+ //#endregion
166
+ export { generateClientContract as t };
167
+
168
+ //# sourceMappingURL=client-contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-contract.js","names":[],"sources":["../src/client-contract.ts"],"sourcesContent":["import type { Service } from \"@brickkit/core\";\nimport type { BrickClientAction } from \"@brickkit/core/client\";\nimport type { BrickApp } from \"./endpoints\";\n\n/** Generate browser metadata and transport types from the app's selected services. */\nexport function generateClientContract(app: BrickApp): string {\n const { services, prefix } = app.definition;\n const contract: Record<string, any> = Object.create(null);\n const types: Record<string, any> = Object.create(null);\n const resourceActions = new Set<unknown>();\n for (const service of services) {\n addResources(service, prefix, contract, types, resourceActions);\n }\n for (const service of services) {\n addServiceActions(service, prefix, contract, types, resourceActions);\n }\n return `// Generated by the Brick Vite plugin. Do not edit.\nimport type { BrickClientAction } from \"@brickkit/core/client\";\n\nexport type AppContract = ${namespaceType(types)};\n\nexport const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});\n`;\n}\n\nfunction addResources(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n resourceActions: Set<unknown>,\n) {\n for (const resource of service.listResources()) {\n if (Object.hasOwn(contract, resource.name))\n throw new Error(`Brick client: duplicate namespace '${resource.name}'`);\n const node: Record<string, any> = Object.create(null);\n const typeNode: Record<string, any> = Object.create(null);\n contract[resource.name] = node;\n types[resource.name] = typeNode;\n const enabled = new Set(service.listActions());\n for (const [operation, method, item] of [\n [\"list\", \"GET\", false],\n [\"create\", \"POST\", false],\n [\"get\", \"GET\", true],\n [\"update\", \"PATCH\", true],\n [\"delete\", \"DELETE\", true],\n ] as const) {\n const action = resource.actions[operation];\n resourceActions.add(action);\n if (!enabled.has(action)) continue;\n const itemPath = item ? `/:${resource.idField}` : \"\";\n const path = `${prefix}/${resource.name}${itemPath}`;\n node[operation] = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n config: { path, method },\n };\n const inputType = schemaType(action.config.input);\n // The runtime list result always includes these metadata fields.\n const outputSchema =\n operation === \"list\"\n ? {\n ...action.config.output,\n required: [\n ...new Set([\n ...(action.config.output?.required ?? []),\n \"items\",\n \"total\",\n \"limit\",\n \"offset\",\n \"pageCount\",\n \"hasMore\",\n \"nextCursor\",\n ]),\n ],\n }\n : action.config.output;\n typeNode[operation] = actionType(\n inputType,\n schemaType(outputSchema),\n action.config.errors,\n );\n }\n }\n}\n\nfunction addServiceActions(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n resourceActions: Set<unknown>,\n) {\n const namespace: Record<string, any> =\n contract[service.name] ?? Object.create(null);\n const namespaceTypes: Record<string, any> =\n types[service.name] ?? Object.create(null);\n contract[service.name] = namespace;\n types[service.name] = namespaceTypes;\n for (const action of service.listActions()) {\n if (resourceActions.has(action)) continue;\n const { input, output, errors, path, method } = action.config;\n let inputType: string;\n let outputType: string;\n try {\n inputType = input ? schemaType(input) : \"unknown\";\n outputType = output ? schemaType(output) : \"unknown\";\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate '${service.name}.${action.name}': ${(error as Error).message}`,\n );\n }\n const metadata: BrickClientAction = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n config: {\n path: path ?? `${prefix}/${service.name}/${action.name}`,\n method: method ?? \"POST\",\n },\n };\n insertAction(\n namespace,\n namespaceTypes,\n metadata,\n actionType(inputType, outputType, errors),\n );\n }\n}\n\nfunction insertAction(\n node: Record<string, any>,\n typeNode: Record<string, any>,\n metadata: BrickClientAction,\n type: string,\n) {\n const segments = metadata.name.split(\".\");\n for (const segment of segments.slice(0, -1)) {\n if (\n Object.hasOwn(typeNode, segment) &&\n typeof typeNode[segment] === \"string\"\n ) {\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n }\n node[segment] ??= Object.create(null);\n typeNode[segment] ??= Object.create(null);\n node = node[segment];\n typeNode = typeNode[segment];\n }\n const leaf = segments.at(-1)!;\n if (Object.hasOwn(node, leaf))\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n node[leaf] = metadata;\n typeNode[leaf] = type;\n}\n\nfunction actionType(\n input: string,\n output: string,\n errors: Record<string, unknown> | undefined,\n): string {\n const codes = Object.keys(errors ?? {});\n const errorsType = codes.length\n ? `Record<${codes.map((code) => JSON.stringify(code)).join(\" | \")}, { message: string; status?: number }>`\n : \"{}\";\n return `BrickClientAction<${input}, ${output}, ${errorsType}>`;\n}\n\nfunction namespaceType(node: Record<string, any>): string {\n return `{\\n${Object.entries(node)\n .map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${typeof value === \"string\" ? value : namespaceType(value)};`,\n )\n .join(\"\\n\")}\\n}`;\n}\n\n// Emit transport types from schemas, rather than importing backend callbacks or databases.\nfunction schemaType(schema: any): string {\n if (schema === undefined) return \"unknown\";\n if (schema === true) return \"unknown\";\n if (schema === false || (schema.not && !Object.keys(schema.not).length))\n return \"never\";\n if (schema.$ref)\n throw new Error(`unresolved schema reference '${schema.$ref}'`);\n if (Object.hasOwn(schema, \"const\")) return JSON.stringify(schema.const);\n if (schema.enum)\n return (\n schema.enum.map((value: unknown) => JSON.stringify(value)).join(\" | \") ||\n \"never\"\n );\n if (schema.anyOf || schema.oneOf)\n return `(${(schema.anyOf ?? schema.oneOf).map(schemaType).join(\" | \")})`;\n if (schema.allOf) return `(${schema.allOf.map(schemaType).join(\" & \")})`;\n switch (schema.type) {\n case \"string\":\n return \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"null\":\n return \"null\";\n case \"undefined\":\n case \"void\":\n return \"undefined\";\n case \"array\":\n return arraySchemaType(schema);\n case \"object\":\n return objectSchemaType(schema);\n case undefined:\n return \"unknown\";\n default:\n throw new Error(`unsupported transport schema type '${schema.type}'`);\n }\n}\n\nfunction arraySchemaType(schema: any): string {\n if (Array.isArray(schema.items))\n return `[${schema.items.map(schemaType).join(\", \")}]`;\n const itemType = schema.items ? schemaType(schema.items) : \"unknown\";\n return `Array<${itemType}>`;\n}\n\nfunction objectSchemaType(schema: any): string {\n const properties = Object.entries(schema.properties ?? {}).map(\n ([key, value]) =>\n `${JSON.stringify(key)}${schema.required?.includes(key) ? \"\" : \"?\"}: ${schemaType(value)};`,\n );\n const object = `{ ${properties.join(\" \")} }`;\n const patterns = Object.values(schema.patternProperties ?? {});\n if (patterns.length)\n return `${object} & Record<string, ${patterns.map(schemaType).join(\" | \")}>`;\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : schemaType(schema.additionalProperties);\n return `${object} & Record<string, ${valueType}>`;\n }\n return object;\n}\n"],"mappings":";;AAKA,SAAgB,uBAAuB,KAAuB;CAC5D,MAAM,EAAE,UAAU,WAAW,IAAI;CACjC,MAAM,WAAgC,OAAO,OAAO,IAAI;CACxD,MAAM,QAA6B,OAAO,OAAO,IAAI;CACrD,MAAM,kCAAkB,IAAI,IAAa;CACzC,KAAK,MAAM,WAAW,UACpB,aAAa,SAAS,QAAQ,UAAU,OAAO,eAAe;CAEhE,KAAK,MAAM,WAAW,UACpB,kBAAkB,SAAS,QAAQ,UAAU,OAAO,eAAe;CAErE,OAAO;;;4BAGmB,cAAc,KAAK,EAAE;;kDAEC,KAAK,UAAU,KAAK,UAAU,QAAQ,CAAC,EAAE;;AAE3F;AAEA,SAAS,aACP,SACA,QACA,UACA,OACA,iBACA;CACA,KAAK,MAAM,YAAY,QAAQ,cAAc,GAAG;EAC9C,IAAI,OAAO,OAAO,UAAU,SAAS,IAAI,GACvC,MAAM,IAAI,MAAM,sCAAsC,SAAS,KAAK,EAAE;EACxE,MAAM,OAA4B,OAAO,OAAO,IAAI;EACpD,MAAM,WAAgC,OAAO,OAAO,IAAI;EACxD,SAAS,SAAS,QAAQ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AO,KAAK,GAC5B,OAAO,IAAI,OAAO,MAAM,IAAI,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE;CAErD,OAAO,SADU,OAAO,QAAQ,WAAW,OAAO,KAAK,IAAI,UAClC;AAC3B;AAEA,SAAS,iBAAiB,QAAqB;CAK7C,MAAM,SAAS,KAJI,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC,KACxD,CAAC,KAAK,WACL,GAAG,KAAK,UAAU,GAAG,IAAI,OAAO,UAAU,SAAS,GAAG,IAAI,KAAK,IAAI,IAAI,WAAW,KAAK,EAAE,EAEhE,CAAC,CAAC,KAAK,GAAG,EAAE;CACzC,MAAM,WAAW,OAAO,OAAO,OAAO,qBAAqB,CAAC,CAAC;CAC7D,IAAI,SAAS,QACX,OAAO,GAAG,OAAO,oBAAoB,SAAS,IAAI,UAAU,CAAC,CAAC,KAAK,KAAK,EAAE;CAC5E,IAAI,OAAO,sBAKT,OAAO,GAAG,OAAO,oBAHf,OAAO,yBAAyB,OAC5B,YACA,WAAW,OAAO,oBAAoB,EACG;CAEjD,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"compiler.d.ts","names":[],"sources":["../src/compiler/ir.ts","../src/compiler/runtime.ts","../src/compiler/emit.ts","../src/compiler.ts"],"mappings":";;KAEY;UACK;WACN,QAAQ;WACR;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;aAA+B;aAAsB;;;WAErD;WACA;;UAEM;WACN;WACA;WACA;WACA;WACA,iBAAiB;WACjB,gBAAgB;WAChB;;;;KCxBC,mBAAmB,2BAA2B;KAC9C,kBAAkB,SAAS,mBAAmB,gBAAgB,oBAAoB;;iBAarF,WAAW,YAAY,aAAa;iBASpC,SAAS,OAAO,YAAY,oCAAoC,gBAAgB,gBAAgB;iBAMhG,SAAS,UAAU;;;;;;;;;;;;;;;;cASf,iBAAe;;;;;;;EAGN,aAAA;EACL,OAAA;;;;;iBCzCD,mBAAmB,OAAO;;iBAoD1B,wBAAwB,IAAI,SAAS;;;UC9CpC;WAAyB,IAAI;WAAkB,SAAS;;UACxD;WAA+B,IAAI;WAAkB,iBAAiB;;;iBAcvE,wBAAwB;EAAW,UAAU;EAAqB;EAAiB;IAAqC;;iBAUxH,wBAAwB,IAAI,SAAS,UAAU,qBAAqB,oBAAoB,mBAAmB"}
1
+ {"version":3,"file":"compiler.d.ts","names":[],"sources":["../src/compiler/ir.ts","../src/compiler/runtime.ts","../src/compiler/emit.ts","../src/compiler.ts"],"mappings":";;KAOY;UACK;WACN,QAAQ;WACR;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;aACE;aACA;;;WAGF;WACA;;UAEM;WACN;WACA;WACA;WACA;WACA,iBAAiB;WACjB,gBAAgB;WAChB;;;;KC5BC,mBAAmB,2BAA2B;KAC9C,kBACV,SAAS,mBACT,gBAAgB,oBACb;;iBAaI,WAAW,YAAY,aAAa;iBAWpC,SACP,OAAO,YAAY,oCACnB,gBACA,gBACA;iBAeO,SAAS,UAAU;;;;;;;;;;;;;;;;cAaf,iBAAe;;;;;;;EAON,aAAA;EAEL,OAAA;;;;;iBCxED,mBAAmB,OAAO;;iBA0E1B,wBACd,IAAI,SACJ;;;UCzDe;WACN,IAAI;WACJ,SAAS;;UAEH;WACN,IAAI;WACJ,iBAAiB;;;iBAsBZ,wBAAwB;EACtC,UAAU;EACV;EACA;IACE;;iBAsBY,wBACd,IAAI,SACJ,UAAU,qBACV,oBAAoB,mBACnB"}
package/dist/compiler2.js CHANGED
@@ -128,6 +128,7 @@ async function executeCompiledRoute(plan, elysiaCtx) {
128
128
  const resolved = extra instanceof Promise ? await extra : extra;
129
129
  if (resolved) Object.assign(ctx, resolved);
130
130
  }
131
+ if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
131
132
  if (plan.hasInput && plan.inputChecker) {
132
133
  if (!plan.inputChecker.Check(input)) {
133
134
  const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
@@ -289,16 +290,8 @@ function analyzeApplication(services, prefix = "/api") {
289
290
  }
290
291
  }
291
292
  for (const action of service.listActions()) {
292
- const path = `${prefix}/${service.name}/${action.name}`;
293
- add(service, action, "POST", path, "action");
294
- if (/^(get|list|find|read)/.test(action.name)) add(service, action, "GET", path, "action");
295
- if (action.config.path) {
296
- if (action.config.method) add(service, action, action.config.method, action.config.path, "action");
297
- else {
298
- add(service, action, "GET", action.config.path, "action");
299
- add(service, action, "POST", action.config.path, "action");
300
- }
301
- }
293
+ const path = action.config.path ?? `${prefix}/${service.name}/${action.name}`;
294
+ add(service, action, action.config.method ?? "POST", path, "action");
302
295
  }
303
296
  }
304
297
  const reads = services.flatMap((service) => service.listResources().flatMap((resource) => {
@@ -338,6 +331,7 @@ function emitHandlerFactory(route) {
338
331
  input.push("}");
339
332
  }
340
333
  input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
334
+ if (route.inputSchema?.type === "object") input.push("input ??= {};");
341
335
  }
342
336
  const asyncStages = route.context || route.authorize;
343
337
  const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
@@ -447,7 +441,7 @@ function bindAnalyzed(ir, bindings, factories) {
447
441
  /** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
448
442
  function compileBrickApplication(options) {
449
443
  const { ir, bindings } = analyzeApplication(options.services, options.prefix);
450
- const factories = options.mode === "generic" ? ir.routes.map(() => ((plan) => (context) => executeCompiledRoute(plan, context))) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
444
+ const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
451
445
  if (options.mode !== "generic") for (const service of options.services) {
452
446
  prepareResourceReads(service);
453
447
  prepareResourceWrites(service);
@@ -1 +1 @@
1
- {"version":3,"file":"compiler2.js","names":["EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty"],"sources":["../src/action-handler.ts","../src/compiler/ir.ts","../src/compiler/emit.ts","../src/compiler/runtime.ts","../src/compiler.ts"],"sourcesContent":["import { type Service, type Action, type Logger, type CompiledRoutePlan,\n ValidationError, ActionExecutionError, getCompiledCheck, buildErrorHelpers } from \"@brickkit/core\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema ? (getCompiledCheck(inputSchema) as any) : undefined;\n const hasOutputCheck = Boolean(outputSchema);\n const outputChecker = outputSchema ? (getCompiledCheck(outputSchema) as any) : undefined;\n\n let coercions: Array<{ key: string; isNumber: boolean; isBoolean: boolean }> | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{ key: string; isNumber: boolean; isBoolean: boolean }> = [];\n for (const [key, prop] of Object.entries((inputSchema as any).properties) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = {\n info: (...args) => console.log(tag, ...args),\n warn: (...args) => console.warn(tag, ...args),\n error: (...args) => console.error(tag, ...args),\n debug: (...args) => console.debug(tag, ...args),\n };\n\n const errorBuilder = (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\nexport async function executeCompiledRoute(plan: CompiledRoutePlan, elysiaCtx: any) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\") coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n const hasP = isNonEmpty(params);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = params;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, params, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = params;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, params, body, coercedQuery);\n }\n }\n }\n\n const standardRequest = request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\"UNAUTHORIZED\", `Access denied for action '${plan.actionName}'`, 403);\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);\n }\n }\n\n return result;\n } catch (err: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n}\n\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import { type Service, type Action, describeResourceReads, type ResourceReadQueries } from \"@brickkit/core\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\" | \"resource\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly { readonly key: string; readonly type: \"number\" | \"boolean\" }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly reads: readonly ResourceReadQueries[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding { readonly service: Service<any, any>; readonly action: Action<any, any, any, any>; }\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(services: Service<any, any>[], prefix = \"/api\") {\n if (!prefix.startsWith(\"/\")) throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n service.build();\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, string>();\n const diagnostics: string[] = [];\n const add = (service: Service<any, any>, action: Action<any, any, any, any>, method: RouteMethod, path: string, kind: RouteIR[\"kind\"]) => {\n if (!path.startsWith(\"/\")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const key = `${method} ${path}`;\n const previous = registered.get(key);\n if (previous) {\n diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`);\n return;\n }\n if (typeof action.config.execute !== \"function\") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);\n registered.set(key, `${service.name}.${action.name}`);\n const readLike = method === \"GET\" || action.name.startsWith(\"get\") || action.name.endsWith(\".get\") || action.name.startsWith(\"list\") || action.name.endsWith(\".list\") || action.name.startsWith(\"find\") || action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" }[] = [];\n for (const [key, prop] of Object.entries(action.config.input?.properties ?? {}) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\") coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\") coercions.push({ key, type: \"boolean\" });\n }\n routes.push({ method, path, service: service.name, action: action.name, kind,\n input: Boolean(action.config.input), output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\", authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike ? [\"query\", \"params\", \"body\"] : [\"params\", \"body\", \"query\"], coercions,\n inputSchema: schemaSnapshot(action.config.input), outputSchema: schemaSnapshot(action.config.output) });\n bindings.push({ service, action });\n };\n for (const service of services) {\n for (const resource of service.listResources()) {\n const collection = `${prefix}/${resource.name}`;\n const item = `${collection}/:id`;\n for (const [operation, method, path] of [\n [\"list\", \"GET\", collection], [\"create\", \"POST\", collection], [\"get\", \"GET\", item],\n [\"update\", \"PATCH\", item], [\"update\", \"PUT\", item], [\"delete\", \"DELETE\", item],\n ] as const) {\n const action = resource.actions[operation];\n if (action) add(service, action, method, path, \"resource\");\n }\n }\n for (const action of service.listActions()) {\n const path = `${prefix}/${service.name}/${action.name}`;\n add(service, action, \"POST\", path, \"action\");\n if (/^(get|list|find|read)/.test(action.name)) add(service, action, \"GET\", path, \"action\");\n if (action.config.path) {\n if (action.config.method) add(service, action, action.config.method, action.config.path, \"action\");\n else {\n add(service, action, \"GET\", action.config.path, \"action\");\n add(service, action, \"POST\", action.config.path, \"action\");\n }\n }\n }\n }\n const reads = services.flatMap(service => service.listResources().flatMap(resource => {\n const queries = describeResourceReads(service, resource);\n return queries ? [queries] : [];\n }));\n const ir: BrickIR = freezeIR({ version: 1, target: \"bun-elysia\", prefix, services: [...names], routes, reads, diagnostics });\n return { ir, bindings };\n}\n","import type { BrickIR, RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input ? \"params, body, query, headers, request, set\" : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);\n else input.push(`if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`);\n }\n input.push(\"}\");\n }\n input.push(`input = mergeInput(${route.inputPrecedence.map(source => source === \"query\" ? \"coercedQuery\" : source).join(\", \")});`);\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\" : \"\";\n const validation = route.input ? `validate(inputChecker, input, ${name}, \"input\");` : \"\";\n const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : \"\";\n const output = route.output ? `validate(outputChecker, result, ${name}, \"output\");` : \"\";\n const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set); }\n};\n}`;\n}\n\n/** An ES module of real JS functions; it never stringifies application callbacks. */\nexport function emitCompiledApplication(ir: BrickIR, runtimeImport = \"@brickkit/cli/compiler\"): string {\n return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\\nconst factories = [\\n${ir.routes.map(emitHandlerFactory).join(\",\\n\")}\\n];\\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\\n`;\n}\n","import { ValidationError, ActionExecutionError, type CompiledRoutePlan } from \"@brickkit/core\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRuntime) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true;\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction validate(check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>, value: unknown, action: string, stage: \"input\" | \"output\") {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({ path: err.path, message: err.message, value: err.value }));\n throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === \"output\" ? 500 : 400);\n}\n\nfunction mapError(err: any, set: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return { name: \"InternalServerError\", message: err?.message || \"An unexpected error occurred\", status: 500 };\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES, defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36), mergeInput, validate, mapError,\n isThenable: (value: any): boolean => value != null && typeof value.then === \"function\",\n deny: (action: string): never => { throw new ActionExecutionError(\"UNAUTHORIZED\", `Access denied for action '${action}'`, 403); },\n});\n","import { type Service, prepareResourceReads, prepareResourceWrites } from \"@brickkit/core\";\nimport { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport { analyzeApplication, freezeIR, type BrickIR, type RouteIR } from \"./compiler/ir\";\nimport { emitHandlerFactory } from \"./compiler/emit\";\nimport { compilerRuntime, type CompiledHandler, type HandlerFactory } from \"./compiler/runtime\";\n\nexport { emitCompiledApplication, emitHandlerFactory } from \"./compiler/emit\";\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } from \"./compiler/runtime\";\nexport interface CompiledRoute { readonly ir: RouteIR; readonly handler: CompiledHandler; }\nexport interface CompiledApplication { readonly ir: BrickIR; readonly routes: readonly CompiledRoute[]; }\n\nfunction bindAnalyzed(ir: BrickIR, bindings: ReturnType<typeof analyzeApplication>[\"bindings\"], factories: readonly HandlerFactory[]): CompiledApplication {\n if (factories.length !== ir.routes.length) throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */\nexport function compileBrickApplication(options: { services: Service<any, any>[]; prefix?: string; mode?: \"specialized\" | \"generic\" }): CompiledApplication {\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] = options.mode === \"generic\"\n ? ir.routes.map(() => (plan => context => executeCompiledRoute(plan, context)))\n : ir.routes.map(route => new Function(`return (${emitHandlerFactory(route)});`)() as HandlerFactory);\n if (options.mode !== \"generic\") for (const service of options.services) { prepareResourceReads(service); prepareResourceWrites(service); }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\nexport function bindCompiledApplication(ir: BrickIR, services: Service<any, any>[], factories: readonly HandlerFactory[]): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\") throw new Error(\"Brick compiler: unsupported IR version or target; rebuild the application\");\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error(\"Brick compiler: application definitions differ from the compiled IR; rebuild the application\");\n for (const service of services) { prepareResourceReads(service); prepareResourceWrites(service); }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n"],"mappings":";;AAGA,IAAI,UAAU;AACd,MAAMA,mBAAiB,OAAO,OAAO,CAAC,CAAC;AACvC,MAAMC,oBAAkB,IAAI,QAAQ,kBAAkB;AAEtD,SAASC,aAAW,KAAmB;CACrC,IAAI,OAAO,MAAM,OAAO;CACxB,KAAK,MAAM,KAAK,KAAK,OAAO;CAC5B,OAAO;AACT;AAEA,SAAgB,iBACd,SACA,QACA,WACA,QACmB;CACnB,MAAM,aAAa,OAAO;CAC1B,MAAM,cAAc,QAAQ;CAC5B,MAAM,YACJ,WAAW,SACX,WAAW,WAAW,KAAK,KAC3B,WAAW,SAAS,MAAM,KAC1B,WAAW,WAAW,MAAM,KAC5B,WAAW,SAAS,OAAO,KAC3B,WAAW,WAAW,MAAM,KAC5B,WAAW,WAAW,MAAM;CAE9B,MAAM,cAAc,OAAO,QAAQ;CACnC,MAAM,eAAe,OAAO,QAAQ;CACpC,MAAM,WAAW,QAAQ,WAAW;CACpC,MAAM,eAAe,cAAe,iBAAiB,WAAW,IAAY,KAAA;CAE5E,MAAM,gBAAgB,eAAgB,iBAAiB,YAAY,IAAY,KAAA;CAE/E,IAAI;CACJ,IAAI,eAAe,OAAQ,YAAoB,eAAe,UAAU;EACtE,MAAM,OAAsE,CAAC;EAC7E,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAS,YAAoB,UAAU,GAAsB;GAC5F,MAAM,OAAO,MAAM;GACnB,IAAI,SAAS,YAAY,SAAS,WAChC,KAAK,KAAK;IAAE;IAAK,UAAU;IAAM,WAAW;GAAM,CAAC;QAC9C,IAAI,SAAS,WAClB,KAAK,KAAK;IAAE;IAAK,UAAU;IAAO,WAAW;GAAK,CAAC;EAEvD;EACA,IAAI,KAAK,SAAS,GAAG,YAAY;CACnC;CAEA,MAAM,cAAc,QAAQ,SAAS;CACrC,MAAM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D,IAAI,KAAK,UAAU,SAAS,EAAE,MAAM,KAAK,UAAU,EAAE,GAAG,MAAM,IAAI,MAAM,8FAA8F;CACtK,KAAK,MAAM,WAAW,UAAU;EAAE,qBAAqB,OAAO;EAAG,sBAAsB,OAAO;CAAG;CACjG,OAAO,aAAa,IAAI,SAAS,UAAU,SAAS;AACtD"}
1
+ {"version":3,"file":"compiler2.js","names":["EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty"],"sources":["../src/action-handler.ts","../src/compiler/ir.ts","../src/compiler/emit.ts","../src/compiler/runtime.ts","../src/compiler.ts"],"sourcesContent":["import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n getCompiledCheck,\n buildErrorHelpers,\n} from \"@brickkit/core\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n const outputChecker = outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{ key: string; isNumber: boolean; isBoolean: boolean }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{ key: string; isNumber: boolean; isBoolean: boolean }> =\n [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = {\n info: (...args) => console.log(tag, ...args),\n warn: (...args) => console.warn(tag, ...args),\n error: (...args) => console.error(tag, ...args),\n debug: (...args) => console.debug(tag, ...args),\n };\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n const hasP = isNonEmpty(params);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = params;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, params, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = params;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, params, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${plan.actionName}'`,\n 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n}\n\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import {\n type Service,\n type Action,\n describeResourceReads,\n type ResourceReadQueries,\n} from \"@brickkit/core\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\" | \"resource\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly reads: readonly ResourceReadQueries[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n service.build();\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, string>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const key = `${method} ${path}`;\n const previous = registered.get(key);\n if (previous) {\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, `${service.name}.${action.name}`);\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" }[] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\")\n coercions.push({ key, type: \"boolean\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\n bindings.push({ service, action });\n };\n for (const service of services) {\n for (const resource of service.listResources()) {\n const collection = `${prefix}/${resource.name}`;\n const item = `${collection}/:id`;\n for (const [operation, method, path] of [\n [\"list\", \"GET\", collection],\n [\"create\", \"POST\", collection],\n [\"get\", \"GET\", item],\n [\"update\", \"PATCH\", item],\n [\"update\", \"PUT\", item],\n [\"delete\", \"DELETE\", item],\n ] as const) {\n const action = resource.actions[operation];\n if (action) add(service, action, method, path, \"resource\");\n }\n }\n for (const action of service.listActions()) {\n const path =\n action.config.path ?? `${prefix}/${service.name}/${action.name}`;\n add(service, action, action.config.method ?? \"POST\", path, \"action\");\n }\n }\n const reads = services.flatMap((service) =>\n service.listResources().flatMap((resource) => {\n const queries = describeResourceReads(service, resource);\n return queries ? [queries] : [];\n }),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n reads,\n diagnostics,\n });\n return { ir, bindings };\n}\n","import type { BrickIR, RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input\n ? \"params, body, query, headers, request, set\"\n : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\")\n input.push(\n `if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`,\n );\n else\n input.push(\n `if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`,\n );\n }\n input.push(\"}\");\n }\n input.push(\n `input = mergeInput(${route.inputPrecedence.map((source) => (source === \"query\" ? \"coercedQuery\" : source)).join(\", \")});`,\n );\n if ((route.inputSchema as { type?: string } | undefined)?.type === \"object\")\n input.push(\"input ??= {};\");\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context\n ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\"\n : \"\";\n const validation = route.input\n ? `validate(inputChecker, input, ${name}, \"input\");`\n : \"\";\n const authorization = route.authorize\n ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});`\n : \"\";\n const output = route.output\n ? `validate(outputChecker, result, ${name}, \"output\");`\n : \"\";\n const execute = asyncStages\n ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;`\n : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set); }\n};\n}`;\n}\n\n/** An ES module of real JS functions; it never stringifies application callbacks. */\nexport function emitCompiledApplication(\n ir: BrickIR,\n runtimeImport = \"@brickkit/cli/compiler\",\n): string {\n return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\\nconst factories = [\\n${ir.routes.map(emitHandlerFactory).join(\",\\n\")}\\n];\\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\\n`;\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"@brickkit/core\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true;\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction mapError(err: any, set: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n deny: (action: string): never => {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${action}'`,\n 403,\n );\n },\n});\n","import {\n type Service,\n prepareResourceReads,\n prepareResourceWrites,\n} from \"@brickkit/core\";\nimport { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport { emitHandlerFactory } from \"./compiler/emit\";\nimport {\n compilerRuntime,\n type CompiledHandler,\n type HandlerFactory,\n} from \"./compiler/runtime\";\n\nexport { emitCompiledApplication, emitHandlerFactory } from \"./compiler/emit\";\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(\n compileRoutePlan(service, action, route.path, route.method),\n );\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] =\n options.mode === \"generic\"\n ? ir.routes.map(\n () => (plan) => (context) => executeCompiledRoute(plan, context),\n )\n : ir.routes.map(\n (route) =>\n new Function(\n `return (${emitHandlerFactory(route)});`,\n )() as HandlerFactory,\n );\n if (options.mode !== \"generic\")\n for (const service of options.services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n for (const service of services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n"],"mappings":";;AAWA,IAAI,UAAU;AACd,MAAMA,mBAAiB,OAAO,OAAO,CAAC,CAAC;AACvC,MAAMC,oBAAkB,IAAI,QAAQ,kBAAkB;AAEtD,SAASC,aAAW,KAAmB;CACrC,IAAI,OAAO,MAAM,OAAO;CACxB,KAAK,MAAM,KAAK,KAAK,OAAO;CAC5B,OAAO;AACT;AAEA,SAAgB,iBACd,SACA,QACA,WACA,QACmB;CACnB,MAAM,aAAa,OAAO;CAC1B,MAAM,cAAc,QAAQ;CAC5B,MAAM,YACJ,WAAW,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AG,OAAO,WACD,UAAU,YAAY,qBAAqB,MAAM,OAAO,CACjE,IACA,GAAG,OAAO,KACP,UACC,IAAI,SACF,WAAW,mBAAmB,KAAK,EAAE,GACvC,CAAC,CAAC,CACN;CACN,IAAI,QAAQ,SAAS,WACnB,KAAK,MAAM,WAAW,QAAQ,UAAU;EACtC,qBAAqB,OAAO;EAC5B,sBAAsB,OAAO;CAC/B;CACF,OAAO,aAAa,IAAI,UAAU,SAAS;AAC7C;;AAGA,SAAgB,wBACd,IACA,UACA,WACqB;CACrB,IAAI,GAAG,YAAY,KAAK,GAAG,WAAW,cACpC,MAAM,IAAI,MACR,2EACF;CACF,MAAM,WAAW,mBAAmB,UAAU,GAAG,MAAM;CACvD,IAAI,KAAK,UAAU,SAAS,EAAE,MAAM,KAAK,UAAU,EAAE,GACnD,MAAM,IAAI,MACR,8FACF;CACF,KAAK,MAAM,WAAW,UAAU;EAC9B,qBAAqB,OAAO;EAC5B,sBAAsB,OAAO;CAC/B;CACA,OAAO,aAAa,IAAI,SAAS,UAAU,SAAS;AACtD"}
package/dist/index.d.ts CHANGED
@@ -73,8 +73,13 @@ interface EndpointDefinition {
73
73
  description?: string;
74
74
  tags?: string[];
75
75
  }
76
- /** The app object returned by `createBrickServer`: Elysia plus `endpoint()`. */
76
+ /** The app object returned by `brick`: Elysia plus `endpoint()`. */
77
77
  type BrickApp = Elysia<any, any, any, any, any, any, any> & {
78
+ /** Service definitions and prefix selected when this app was constructed. */
79
+ readonly definition: {
80
+ readonly services: readonly Service<any, any>[];
81
+ readonly prefix: string;
82
+ };
78
83
  /** Register a raw endpoint (outside the JSON action mesh). */
79
84
  endpoint(def: EndpointDefinition): void;
80
85
  /** All endpoints registered via `endpoint()` (declaration order). */
@@ -106,7 +111,7 @@ interface CreateServerOptions {
106
111
  /** Raw endpoints (outside the JSON action mesh), mounted at startup. */
107
112
  endpoints?: EndpointDefinition[];
108
113
  }
109
- export declare function createBrickServer(options?: CreateServerOptions): BrickApp;
114
+ export declare function brick(options?: CreateServerOptions): BrickApp;
110
115
  //#endregion
111
116
  //#region src/runner.d.ts
112
117
  interface DevServerOptions {
@@ -132,5 +137,9 @@ export declare function buildApplication(options: BuildApplicationOptions): Prom
132
137
  ir: BrickIR;
133
138
  }>;
134
139
  //#endregion
140
+ //#region src/client-contract.d.ts
141
+ /** Generate browser metadata and transport types from the app's selected services. */
142
+ export declare function generateClientContract(app: BrickApp): string;
143
+ //#endregion
135
144
  export { type BrickApp, type BrickIR, type BuildApplicationOptions, type CompiledApplication, type CreateServerOptions, type DevServerOptions, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, type ReferenceOptions, type RequestLoggingOptions, type RouteIR, bindCompiledApplication, compileBrickApplication, emitCompiledApplication };
136
145
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["_$__endpoints0.BrickApp","_$__compiler0.BrickIR"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/endpoints.ts","../src/server.ts","../src/runner.ts","../src/build.ts"],"mappings":";;;;UAEiB;EACf;EACA,UAAU;;;;;;;;;;;;;;wBAoCI,qBACd,OAAM,wBACL;;;UCxCc;EACf;EACA;EACA;;;wBAIc,eAAe,iBAAiB;;wBAwBhC,gBAAgB,OAAM,mBAAwB;;wBAa9C,uBACd,KAAK,QACL,OAAM,mBACL;;;KC7CS;;UAGK;EACf,UAAU;EACV,UAAU;EACV,WAAW;EACX,WAAW;;;UAII;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;;EAET;IAAO;IAAiB,SAAS;;;EAEjC;EACA,QAAQ;EACR;EACA;;UAGe;EACf,QAAQ;;EAER;EACA,UAAU,KAAK,8BAA8B;;EAE7C,UAAU;;EAEV,WAAW;EACX;EACA;EACA;;;KA2HU,WAAW;;EAErB,SAAS,KAAK;;EAEd,iBAAiB;;;;UC9IF;EACf;;EAEA;;EAEA,cAAc;EACd,WAAW;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3B,sBAAsB;EACtB;IAAY,SAAS;IAAc;;;EAEnC,YAAY;;wBAKE,kBAAkB,UAAS,sBAA2B;;;UC7CrD;EACf;EACA;EACA;;wBAGoB,eAAe,UAAS,mBAAqB,QAArBA;;;UCL7B;;EAEf;EACA;EACA;EACA;EACA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;MAAvBC"}
1
+ {"version":3,"file":"index.d.ts","names":["_$__endpoints0.BrickApp","_$__compiler0.BrickIR"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/endpoints.ts","../src/server.ts","../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;;UAEiB;EACf;EACA,UAAU;;;;;;;;;;;;;;wBAoCI,qBAAqB,OAAM,wBAA6B;;;UCtCvD;EACf;EACA;EACA;;;wBAIc,eAAe,iBAAiB;;wBAwBhC,gBAAgB,OAAM,mBAAwB;;wBAa9C,uBACd,KAAK,QACL,OAAM,mBACL;;;KC7CS;;UAGK;EACf,UAAU;EACV,UAAU;EACV,WAAW;EACX,WAAW;;;UAII;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;;EAET;IAAO;IAAiB,SAAS;;;EAEjC;EACA,QAAQ;EACR;EACA;;UAGe;EACf,QAAQ;;EAER;EACA,UAAU,KAAK,8BAA8B;;EAE7C,UAAU;;EAEV,WAAW;EACX;EACA;EACA;;;KA6HU,WAAW;;WAEZ;aACE,mBAAmB;aACnB;;;EAGX,SAAS,KAAK;;EAEd,iBAAiB;;;;UCrJF;EACf;;EAEA;;EAEA,cAAc;EACd,WAAW;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3B,sBAAsB;EACtB;IAAY,SAAS;IAAc;;;EAEnC,YAAY;;wBASE,MAAM,UAAS,sBAA2B;;;UCjDzC;EACf;EACA;EACA;;wBAGoB,eAAe,UAAS,mBAAqB,QAArBA;;;UCL7B;;EAEf;EACA;EACA;EACA;EACA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;MAAvBC;;;;;wBCXhC,uBAAuB,KAAK"}
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  import { n as compileBrickApplication, r as emitCompiledApplication, t as bindCompiledApplication } from "./compiler2.js";
2
- import { a as registerReferenceRoute, i as referencePlugin, n as startDevServer, o as scalarDocsHTML, r as createBrickServer, s as requestLoggingPlugin, t as buildApplication } from "./build.js";
3
- export { bindCompiledApplication, buildApplication, compileBrickApplication, createBrickServer, emitCompiledApplication, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
2
+ import { a as registerReferenceRoute, i as referencePlugin, n as startDevServer, o as scalarDocsHTML, r as brick, s as requestLoggingPlugin, t as buildApplication } from "./build.js";
3
+ import { t as generateClientContract } from "./client-contract.js";
4
+ export { bindCompiledApplication, brick, buildApplication, compileBrickApplication, emitCompiledApplication, generateClientContract, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
package/dist/vite.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { Plugin } from "vite";
2
+ //#region src/vite.d.ts
3
+ export interface BrickClientPluginOptions {
4
+ /** Any module whose default export is a BrickApp; do not call listen() there. */
5
+ entry: string;
6
+ /** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */
7
+ output?: string;
8
+ }
9
+ /** Load a BrickApp through Vite's server module graph, including dependency HMR. */
10
+ export declare function brickClient(options: BrickClientPluginOptions): Plugin;
11
+ //#endregion
12
+ //# sourceMappingURL=vite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;iBAciB;;EAEf;;EAEA;;;wBAIc,YAAY,SAAS,2BAA2B"}
package/dist/vite.js ADDED
@@ -0,0 +1,118 @@
1
+ import { t as generateClientContract } from "./client-contract.js";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { createServer, isRunnableDevEnvironment, normalizePath } from "vite";
5
+ import { ModuleRunner } from "vite/module-runner";
6
+ //#region src/vite.ts
7
+ /** Load a BrickApp through Vite's server module graph, including dependency HMR. */
8
+ function brickClient(options) {
9
+ const virtualId = "virtual:brick-app";
10
+ const resolvedId = "\0" + virtualId;
11
+ let entry;
12
+ let output;
13
+ let config;
14
+ let buildGeneration;
15
+ let runner;
16
+ let reload = Promise.resolve();
17
+ const dependencies = /* @__PURE__ */ new Set();
18
+ async function writeContract(value) {
19
+ if (!value || typeof value.endpoint !== "function" || !value.definition) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
20
+ const source = generateClientContract(value);
21
+ if (await readFile(output, "utf8").catch((error) => {
22
+ if (error.code !== "ENOENT") throw error;
23
+ }) === source) return;
24
+ await mkdir(dirname(output), { recursive: true });
25
+ await writeFile(output, source);
26
+ }
27
+ function collectDependencies(node, seen = /* @__PURE__ */ new Set()) {
28
+ if (!node || seen.has(node)) return;
29
+ seen.add(node);
30
+ if (node.file) dependencies.add(node.file);
31
+ for (const imported of node.importedModules) collectDependencies(imported, seen);
32
+ }
33
+ return {
34
+ name: "brick:client",
35
+ enforce: "pre",
36
+ configResolved(resolved) {
37
+ config = resolved;
38
+ entry = normalizePath(resolve(config.root, options.entry));
39
+ output = normalizePath(resolve(config.root, options.output ?? "_brick/contract.ts"));
40
+ if (entry === output) throw new Error("Brick: contract output must not overwrite the app entry.");
41
+ },
42
+ async configureServer(server) {
43
+ const environment = server.environments.ssr;
44
+ if (!environment) throw new Error("Brick: client generation requires a Vite SSR environment.");
45
+ runner = new ModuleRunner({
46
+ hmr: false,
47
+ transport: { invoke: (payload) => environment.hot.handleInvoke(payload) }
48
+ });
49
+ await writeContract((await runner.import(entry)).default);
50
+ dependencies.clear();
51
+ collectDependencies(environment.moduleGraph.getModuleById(entry));
52
+ dependencies.add(entry);
53
+ },
54
+ async hotUpdate(context) {
55
+ if (this.environment.name !== "ssr" || !dependencies.has(context.file) || context.file === output) return;
56
+ if (!runner) return;
57
+ const currentRunner = runner;
58
+ reload = reload.catch(() => {}).then(async () => {
59
+ for (const module of context.modules) this.environment.moduleGraph.invalidateModule(module);
60
+ currentRunner.clearCache();
61
+ await writeContract((await currentRunner.import(entry)).default);
62
+ dependencies.clear();
63
+ collectDependencies(this.environment.moduleGraph.getModuleById(entry));
64
+ dependencies.add(entry);
65
+ });
66
+ await reload;
67
+ },
68
+ async closeBundle() {
69
+ await runner?.close();
70
+ },
71
+ async buildStart() {
72
+ if (config.command !== "build") return;
73
+ buildGeneration ??= (async () => {
74
+ const loader = await createServer({
75
+ configFile: false,
76
+ root: config.root,
77
+ mode: config.mode,
78
+ envDir: config.envDir,
79
+ base: config.base,
80
+ define: config.define,
81
+ logLevel: "silent",
82
+ resolve: { alias: config.resolve.alias },
83
+ ssr: config.ssr,
84
+ server: {
85
+ middlewareMode: true,
86
+ watch: null
87
+ }
88
+ });
89
+ try {
90
+ const environment = loader.environments.ssr;
91
+ if (!environment || !isRunnableDevEnvironment(environment)) throw new Error("Brick: missing build-time SSR loader.");
92
+ await writeContract((await environment.runner.import(entry)).default);
93
+ } finally {
94
+ await loader.close();
95
+ }
96
+ })();
97
+ await buildGeneration;
98
+ },
99
+ resolveId(id) {
100
+ if (id !== virtualId) return;
101
+ if (this.environment.config.consumer === "client") throw new Error("Brick: virtual:brick-app is server-only; never import the backend app in the browser.");
102
+ return resolvedId;
103
+ },
104
+ load(id) {
105
+ if (id !== resolvedId) return;
106
+ return `import app from ${JSON.stringify(entry)};
107
+ if (!app || typeof app.fetch !== "function" || typeof app.endpoint !== "function") {
108
+ throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
109
+ }
110
+ export default app;
111
+ `;
112
+ }
113
+ };
114
+ }
115
+ //#endregion
116
+ export { brickClient };
117
+
118
+ //# sourceMappingURL=vite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["import { resolve, dirname } from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport {\n createServer,\n isRunnableDevEnvironment,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type EnvironmentModuleNode,\n} from \"vite\";\nimport { generateClientContract } from \"./client-contract\";\nimport type { BrickApp } from \"./endpoints\";\nimport { ModuleRunner } from \"vite/module-runner\";\n\nexport interface BrickClientPluginOptions {\n /** Any module whose default export is a BrickApp; do not call listen() there. */\n entry: string;\n /** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */\n output?: string;\n}\n\n/** Load a BrickApp through Vite's server module graph, including dependency HMR. */\nexport function brickClient(options: BrickClientPluginOptions): Plugin {\n const virtualId = \"virtual:brick-app\";\n const resolvedId = \"\\0\" + virtualId;\n let entry: string;\n let output: string;\n let config: ResolvedConfig;\n let buildGeneration: Promise<void> | undefined;\n let runner: ModuleRunner | undefined;\n let reload = Promise.resolve();\n const dependencies = new Set<string>();\n\n async function writeContract(value: unknown) {\n if (\n !value ||\n typeof (value as BrickApp).endpoint !== \"function\" ||\n !(value as BrickApp).definition\n ) {\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n }\n const source = generateClientContract(value as BrickApp);\n const previous = await readFile(output, \"utf8\").catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n return undefined;\n });\n if (previous === source) return;\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, source);\n }\n\n function collectDependencies(\n node: EnvironmentModuleNode | undefined,\n seen = new Set<EnvironmentModuleNode>(),\n ) {\n if (!node || seen.has(node)) return;\n seen.add(node);\n if (node.file) dependencies.add(node.file);\n for (const imported of node.importedModules)\n collectDependencies(imported, seen);\n }\n\n return {\n name: \"brick:client\",\n enforce: \"pre\",\n configResolved(resolved) {\n config = resolved;\n entry = normalizePath(resolve(config.root, options.entry));\n output = normalizePath(\n resolve(config.root, options.output ?? \"_brick/contract.ts\"),\n );\n if (entry === output)\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n },\n async configureServer(server) {\n const environment = server.environments.ssr;\n if (!environment)\n throw new Error(\n \"Brick: client generation requires a Vite SSR environment.\",\n );\n // Frameworks such as Start own their SSR runner. Use an independent runner\n // on the same transform graph to read app metadata without changing theirs.\n runner = new ModuleRunner({\n hmr: false,\n transport: {\n invoke: (payload) => environment.hot.handleInvoke(payload),\n },\n });\n await writeContract((await runner.import(entry)).default);\n dependencies.clear();\n collectDependencies(environment.moduleGraph.getModuleById(entry));\n dependencies.add(entry);\n },\n async hotUpdate(context) {\n if (\n this.environment.name !== \"ssr\" ||\n !dependencies.has(context.file) ||\n context.file === output\n )\n return;\n if (!runner) return;\n const currentRunner = runner;\n reload = reload\n .catch(() => {})\n .then(async () => {\n for (const module of context.modules)\n this.environment.moduleGraph.invalidateModule(module);\n currentRunner.clearCache();\n await writeContract((await currentRunner.import(entry)).default);\n dependencies.clear();\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n dependencies.add(entry);\n });\n await reload;\n },\n async closeBundle() {\n await runner?.close();\n },\n async buildStart() {\n if (config.command !== \"build\") return;\n buildGeneration ??= (async () => {\n // Evaluate the server entry through Vite's TS/alias resolver before client compilation.\n // This loader has no app plugins, so it cannot recursively trigger generation.\n const loader = await createServer({\n configFile: false,\n root: config.root,\n mode: config.mode,\n envDir: config.envDir,\n base: config.base,\n define: config.define,\n logLevel: \"silent\",\n resolve: { alias: config.resolve.alias },\n ssr: config.ssr,\n server: { middlewareMode: true, watch: null },\n });\n try {\n const environment = loader.environments.ssr;\n if (!environment || !isRunnableDevEnvironment(environment))\n throw new Error(\"Brick: missing build-time SSR loader.\");\n await writeContract((await environment.runner.import(entry)).default);\n } finally {\n await loader.close();\n }\n })();\n await buildGeneration;\n },\n resolveId(id) {\n if (id !== virtualId) return;\n if (this.environment.config.consumer === \"client\") {\n throw new Error(\n \"Brick: virtual:brick-app is server-only; never import the backend app in the browser.\",\n );\n }\n return resolvedId;\n },\n load(id) {\n if (id !== resolvedId) return;\n return `import app from ${JSON.stringify(entry)};\nif (!app || typeof app.fetch !== \"function\" || typeof app.endpoint !== \"function\") {\n throw new Error(\"Brick: the entry module must default-export a BrickApp created by brick().\");\n}\nexport default app;\n`;\n },\n };\n}\n"],"mappings":";;;;;;;AAsBA,SAAgB,YAAY,SAA2C;CACrE,MAAM,YAAY;CAClB,MAAM,aAAa,OAAO;CAC1B,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS,QAAQ,QAAQ;CAC7B,MAAM,+BAAe,IAAI,IAAY;CAErC,eAAe,cAAc,OAAgB;EAC3C,IACE,CAAC,SACD,OAAQ,MAAmB,aAAa,cACxC,CAAE,MAAmB,YAErB,MAAM,IAAI,MACR,4EACF;EAEF,MAAM,SAAS,uBAAuB,KAAiB;EAKvD,IAAI,MAJmB,SAAS,QAAQ,MAAM,CAAC,CAAC,OAAO,UAAU;GAC/D,IAAI,MAAM,SAAS,UAAU,MAAM;EAErC,CAAC,MACgB,QAAQ;EACzB,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EAChD,MAAM,UAAU,QAAQ,MAAM;CAChC;CAEA,SAAS,oBACP,MACA,uBAAO,IAAI,IAA2B,GACtC;EACA,IAAI,CAAC,QAAQ,KAAK,IAAI,IAAI,GAAG;EAC7B,KAAK,IAAI,IAAI;EACb,IAAI,KAAK,MAAM,aAAa,IAAI,KAAK,IAAI;EACzC,KAAK,MAAM,YAAY,KAAK,iBAC1B,oBAAoB,UAAU,IAAI;CACtC;CAEA,OAAO;EACL,MAAM;EACN,SAAS;EACT,eAAe,UAAU;GACvB,SAAS;GACT,QAAQ,cAAc,QAAQ,OAAO,MAAM,QAAQ,KAAK,CAAC;GACzD,SAAS,cACP,QAAQ,OAAO,MAAM,QAAQ,UAAU,oBAAoB,CAC7D;GACA,IAAI,UAAU,QACZ,MAAM,IAAI,MACR,0DACF;EACJ;EACA,MAAM,gBAAgB,QAAQ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,aAAa;KACxC,IAAI,CAAC,eAAe,CAAC,yBAAyB,WAAW,GACvD,MAAM,IAAI,MAAM,uCAAuC;KACzD,MAAM,eAAe,MAAM,YAAY,OAAO,OAAO,KAAK,EAAA,CAAG,OAAO;IACtE,UAAU;KACR,MAAM,OAAO,MAAM;IACrB;GACF,EAAA,CAAG;GACH,MAAM;EACR;EACA,UAAU,IAAI;GACZ,IAAI,OAAO,WAAW;GACtB,IAAI,KAAK,YAAY,OAAO,aAAa,UACvC,MAAM,IAAI,MACR,uFACF;GAEF,OAAO;EACT;EACA,KAAK,IAAI;GACP,IAAI,OAAO,YAAY;GACvB,OAAO,mBAAmB,KAAK,UAAU,KAAK,EAAE;;;;;;EAMlD;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brickkit/cli",
3
- "version": "0.1.3",
3
+ "version": "0.2.1",
4
4
  "description": "CLI and server engine for Brick-TS",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,13 +17,21 @@
17
17
  "./compiler": {
18
18
  "import": "./dist/compiler.js",
19
19
  "types": "./dist/compiler.d.ts"
20
+ },
21
+ "./vite": {
22
+ "import": "./dist/vite.js",
23
+ "types": "./dist/vite.d.ts"
24
+ },
25
+ "./vite/client": {
26
+ "types": "./vite-client.d.ts"
20
27
  }
21
28
  },
22
29
  "publishConfig": {
23
30
  "access": "public"
24
31
  },
25
32
  "files": [
26
- "dist"
33
+ "dist",
34
+ "vite-client.d.ts"
27
35
  ],
28
36
  "repository": {
29
37
  "type": "git",
@@ -33,16 +41,31 @@
33
41
  "scripts": {
34
42
  "build": "tsdown",
35
43
  "prepublishOnly": "bun run build",
36
- "typecheck": "tsc --noEmit -p tsconfig.build.json"
44
+ "typecheck": "tsc --noEmit -p tsconfig.build.json",
45
+ "lint": "oxlint .",
46
+ "lint:fix": "oxlint --fix .",
47
+ "format": "oxfmt .",
48
+ "format:check": "oxfmt --check ."
37
49
  },
38
50
  "dependencies": {
39
- "@brickkit/core": "^0.1.3",
51
+ "@brickkit/core": "^0.2.1",
40
52
  "@sinclair/typebox": "^0.34.0",
41
53
  "elysia": "^1.2.0"
42
54
  },
43
55
  "devDependencies": {
44
56
  "@types/bun": "latest",
57
+ "oxfmt": "^0.72.0",
58
+ "oxlint": "^1.87.0",
45
59
  "tsdown": "^0.23.0",
46
- "typescript": "^5.7.0"
60
+ "typescript": "^5.7.0",
61
+ "vite": "^8.3.0"
62
+ },
63
+ "peerDependencies": {
64
+ "vite": "^8.0.0"
65
+ },
66
+ "peerDependenciesMeta": {
67
+ "vite": {
68
+ "optional": true
69
+ }
47
70
  }
48
71
  }
@@ -0,0 +1,4 @@
1
+ declare module "virtual:brick-app" {
2
+ const app: import("@brickkit/cli").BrickApp;
3
+ export default app;
4
+ }