@brickkit/cli 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -2
- package/dist/bin.js.map +1 -1
- package/dist/build.js +6 -6
- package/dist/build.js.map +1 -1
- package/dist/compiler.d.ts.map +1 -1
- package/dist/compiler2.js +3 -1
- package/dist/compiler2.js.map +1 -1
- package/dist/index.d.ts +39 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +87 -2
- package/dist/index.js.map +1 -0
- package/package.json +10 -4
package/README.md
CHANGED
|
@@ -9,12 +9,33 @@ bun add @brickkit/cli @brickkit/core
|
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
```ts
|
|
12
|
-
import {
|
|
12
|
+
import { brick } from "@brickkit/cli";
|
|
13
13
|
|
|
14
|
-
const app =
|
|
14
|
+
const app = brick({ title: "Pages API", version: "1.0.0" });
|
|
15
15
|
app.listen(3333);
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
+
Prefer a single source of truth? Define the client contract once and derive
|
|
19
|
+
the server from it — no separate `services` list:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { brickFromContract } from "@brickkit/cli";
|
|
23
|
+
import { defineAppContract } from "@brickkit/core/client";
|
|
24
|
+
|
|
25
|
+
export const contract = defineAppContract({
|
|
26
|
+
page: pagesResource,
|
|
27
|
+
billing: { charge: chargeAction },
|
|
28
|
+
});
|
|
29
|
+
export type AppServer = typeof contract;
|
|
30
|
+
|
|
31
|
+
const app = brickFromContract(contract);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Frontends then call it fully typed via `createBrickClient<AppServer>()`
|
|
35
|
+
(`@brickkit/core/client`, type-only import). See
|
|
36
|
+
`www/content/docs/(brick)/typed-client.mdx` for routing, error handling, and
|
|
37
|
+
options.
|
|
38
|
+
|
|
18
39
|
The `brick` binary ships in this package for local dev and inspection:
|
|
19
40
|
|
|
20
41
|
```sh
|
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)
|
|
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,QAA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C,IAAI,YAAY;KACd,MAAM,IAAI,MAAM,YAAY,UAAU;KACtC,QAAQ,IAAI,0CAA0C,YAAY;IACpE,OACE,QAAQ,IAAI,UAAU;IAExB;GACF;GACA,QAAQ,MAAM,sBAAsB,WAAW,qBAAqB;GACpE,QAAQ,KAAK,CAAC;GACd;EACF;EAEA,KAAK;EACL,KAAK,YAAY;GACf,MAAM,WAAW,kBAAkB;GACnC,QAAQ,IAAI,KAAK,UAAU,SAAS,mBAAmB,GAAG,MAAM,CAAC,CAAC;GAClE;EACF;EAEA;GACE,QAAQ,IAAI;;;;;;;;;CASjB;GACK,QAAQ,KAAK,CAAC;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
|
|
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
|
};
|
|
@@ -386,7 +386,7 @@ async function startDevServer(options = {}) {
|
|
|
386
386
|
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
387
|
for (const act of svc.listActions()) console.log(` -> Action: /api/${svc.name}/${act.name}`);
|
|
388
388
|
}
|
|
389
|
-
const app =
|
|
389
|
+
const app = brick({
|
|
390
390
|
port,
|
|
391
391
|
prefix: options.prefix
|
|
392
392
|
});
|
|
@@ -418,11 +418,11 @@ async function buildApplication(options) {
|
|
|
418
418
|
try {
|
|
419
419
|
await Bun.write(join(staging, "routes.js"), emitCompiledApplication(compilation.ir));
|
|
420
420
|
const source = `import ${JSON.stringify(entry)};
|
|
421
|
-
import {
|
|
421
|
+
import { brick } from "@brickkit/cli";
|
|
422
422
|
import { getGlobalRegistry } from "@brickkit/core";
|
|
423
423
|
import { bind } from "./routes.js";
|
|
424
424
|
const services = getGlobalRegistry().list();
|
|
425
|
-
export const app =
|
|
425
|
+
export const app = brick({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });
|
|
426
426
|
if (import.meta.main) {
|
|
427
427
|
const port = Number(process.env.PORT ?? ${port});
|
|
428
428
|
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid PORT");
|
|
@@ -464,6 +464,6 @@ if (import.meta.main) {
|
|
|
464
464
|
}
|
|
465
465
|
}
|
|
466
466
|
//#endregion
|
|
467
|
-
export { registerReferenceRoute as a, referencePlugin as i, startDevServer as n, scalarDocsHTML as o,
|
|
467
|
+
export { registerReferenceRoute as a, referencePlugin as i, startDevServer as n, scalarDocsHTML as o, brick as r, requestLoggingPlugin as s, buildApplication as t };
|
|
468
468
|
|
|
469
469
|
//# 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, \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,cAAc,wBAAwB;EAAE;EAAU,QAAQ,QAAQ;CAAO,CAAC;CAChF,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CAChD,MAAM,UAAU,MAAM,QAAQ,KAAK,QAAQ,MAAM,GAAG,eAAe,CAAC;CACpE,IAAI;EACF,MAAM,IAAI,MAAM,KAAK,SAAS,WAAW,GAAG,wBAAwB,YAAY,EAAE,CAAC;EACnF,MAAM,SAAS,UAAU,KAAK,UAAU,KAAK,EAAE;;;;;gGAK6C,QAAQ,kBAAkB,KAAK;;4CAEnF,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 /** 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 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,K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Q,WAAW;GAAG,IAAI,YAAY;EAAG;CACxE,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
package/dist/compiler.d.ts.map
CHANGED
|
@@ -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":";;
|
|
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) => ({
|
|
@@ -338,6 +339,7 @@ function emitHandlerFactory(route) {
|
|
|
338
339
|
input.push("}");
|
|
339
340
|
}
|
|
340
341
|
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
|
|
342
|
+
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
341
343
|
}
|
|
342
344
|
const asyncStages = route.context || route.authorize;
|
|
343
345
|
const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
|
|
@@ -447,7 +449,7 @@ function bindAnalyzed(ir, bindings, factories) {
|
|
|
447
449
|
/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
|
|
448
450
|
function compileBrickApplication(options) {
|
|
449
451
|
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
450
|
-
const factories = options.mode === "generic" ? ir.routes.map(() => (
|
|
452
|
+
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
|
|
451
453
|
if (options.mode !== "generic") for (const service of options.services) {
|
|
452
454
|
prepareResourceReads(service);
|
|
453
455
|
prepareResourceWrites(service);
|
package/dist/compiler2.js.map
CHANGED
|
@@ -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,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TY_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 = `${prefix}/${service.name}/${action.name}`;\n add(service, action, \"POST\", path, \"action\");\n if (/^(get|list|find|read)/.test(action.name))\n add(service, action, \"GET\", path, \"action\");\n if (action.config.path) {\n if (action.config.method)\n add(\n service,\n action,\n action.config.method,\n action.config.path,\n \"action\",\n );\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) =>\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,SACX,WAAW,WAAW,KAAK,KAC3B,WAAW,SAAS,MAAM,KAC1B,WAAW,WAAW,MAAM,K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AAO;EAAE,IAAI,SAAS,EAAE;EAAG,QAAQ,OAAO,OAAO,MAAM;CAAE,CAAC;AAC1E;;AAGA,SAAgB,wBAAwB,SAIhB;CACtB,MAAM,EAAE,IAAI,aAAa,mBAAmB,QAAQ,UAAU,QAAQ,MAAM;CAC5E,MAAM,YACJ,QAAQ,SAAS,YACb,GAAG,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,7 +73,7 @@ interface EndpointDefinition {
|
|
|
73
73
|
description?: string;
|
|
74
74
|
tags?: string[];
|
|
75
75
|
}
|
|
76
|
-
/** The app object returned by `
|
|
76
|
+
/** The app object returned by `brick`: Elysia plus `endpoint()`. */
|
|
77
77
|
type BrickApp = Elysia<any, any, any, any, any, any, any> & {
|
|
78
78
|
/** Register a raw endpoint (outside the JSON action mesh). */
|
|
79
79
|
endpoint(def: EndpointDefinition): void;
|
|
@@ -106,7 +106,43 @@ interface CreateServerOptions {
|
|
|
106
106
|
/** Raw endpoints (outside the JSON action mesh), mounted at startup. */
|
|
107
107
|
endpoints?: EndpointDefinition[];
|
|
108
108
|
}
|
|
109
|
-
export declare function
|
|
109
|
+
export declare function brick(options?: CreateServerOptions): BrickApp;
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/contract.d.ts
|
|
112
|
+
/**
|
|
113
|
+
* Options for {@link brickFromContract}: everything `brick()` accepts except
|
|
114
|
+
* `services`, which is derived from the contract itself.
|
|
115
|
+
*/
|
|
116
|
+
type BrickFromContractOptions = Omit<CreateServerOptions, "services">;
|
|
117
|
+
/**
|
|
118
|
+
* Contract-first server: builds the `brick()` app from the same contract
|
|
119
|
+
* object that types the frontend client, so services are declared once.
|
|
120
|
+
*
|
|
121
|
+
* ```ts
|
|
122
|
+
* // server.ts (backend, single source of truth)
|
|
123
|
+
* export const contract = defineAppContract({
|
|
124
|
+
* page: { list: listPages, create: createPage },
|
|
125
|
+
* billing: { charge: chargeAction },
|
|
126
|
+
* });
|
|
127
|
+
* export type AppServer = typeof contract;
|
|
128
|
+
*
|
|
129
|
+
* export const app = brickFromContract(contract, { port: 4000 });
|
|
130
|
+
* ```
|
|
131
|
+
*
|
|
132
|
+
* ```ts
|
|
133
|
+
* // frontend (type-only import, erased at build)
|
|
134
|
+
* import type { AppServer } from "./server";
|
|
135
|
+
* const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
|
|
136
|
+
* ```
|
|
137
|
+
*
|
|
138
|
+
* Services are resolved through the global registry by each action's
|
|
139
|
+
* `serviceName`, so every definition in the contract must be bound to a service
|
|
140
|
+
* (via `service.action(...)` or `service.tool(...)`). Only HTTP actions
|
|
141
|
+
* registered on that service produce routes. An
|
|
142
|
+
* error names the offending action when it is unbound or its service was
|
|
143
|
+
* never registered.
|
|
144
|
+
*/
|
|
145
|
+
export declare function brickFromContract<TContract extends Record<string, any>>(contract: TContract, options?: BrickFromContractOptions): BrickApp;
|
|
110
146
|
//#endregion
|
|
111
147
|
//#region src/runner.d.ts
|
|
112
148
|
interface DevServerOptions {
|
|
@@ -132,5 +168,5 @@ export declare function buildApplication(options: BuildApplicationOptions): Prom
|
|
|
132
168
|
ir: BrickIR;
|
|
133
169
|
}>;
|
|
134
170
|
//#endregion
|
|
135
|
-
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 };
|
|
171
|
+
export { type BrickApp, type BrickFromContractOptions, 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
172
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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,
|
|
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/contract.ts","../src/runner.ts","../src/build.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;;EAErB,SAAS,KAAK;;EAEd,iBAAiB;;;;UChJF;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;;;;;;;KCzC9C,2BAA2B,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAqF5B,kBAAkB,kBAAkB,qBAClD,UAAU,WACV,UAAS,2BACR;;;UChGc;EACf;EACA;EACA;;wBAGoB,eAAe,UAAS,mBAAqB,QAArBA;;;UCL7B;;EAEf;EACA;EACA;EACA;EACA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;MAAvBC"}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,88 @@
|
|
|
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
|
|
3
|
-
|
|
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 { getGlobalRegistry } from "@brickkit/core";
|
|
4
|
+
//#region src/contract.ts
|
|
5
|
+
function isAction(value) {
|
|
6
|
+
return typeof value === "function" && !!value.config && typeof value.config.execute === "function";
|
|
7
|
+
}
|
|
8
|
+
function isService(value) {
|
|
9
|
+
return !!value && typeof value === "object" && typeof value.listActions === "function" && value.actions instanceof Map;
|
|
10
|
+
}
|
|
11
|
+
function isResource(value) {
|
|
12
|
+
return !!value && typeof value === "object" && !isService(value) && !!value.actions && typeof value.actions === "object";
|
|
13
|
+
}
|
|
14
|
+
function isPlainObject(value) {
|
|
15
|
+
if (!value || typeof value !== "object") return false;
|
|
16
|
+
const proto = Object.getPrototypeOf(value);
|
|
17
|
+
return proto === Object.prototype || proto === null;
|
|
18
|
+
}
|
|
19
|
+
/** Collects definitions to resolve services; each service registers its own HTTP actions. */
|
|
20
|
+
function collectActions(node, out) {
|
|
21
|
+
if (isAction(node)) {
|
|
22
|
+
out.push(node);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (isService(node)) {
|
|
26
|
+
out.push(...node.listActions(), ...node.listTools?.() ?? []);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (isResource(node)) {
|
|
30
|
+
out.push(...Object.values(node.actions));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (isPlainObject(node)) for (const value of Object.values(node)) collectActions(value, out);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Contract-first server: builds the `brick()` app from the same contract
|
|
37
|
+
* object that types the frontend client, so services are declared once.
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* // server.ts (backend, single source of truth)
|
|
41
|
+
* export const contract = defineAppContract({
|
|
42
|
+
* page: { list: listPages, create: createPage },
|
|
43
|
+
* billing: { charge: chargeAction },
|
|
44
|
+
* });
|
|
45
|
+
* export type AppServer = typeof contract;
|
|
46
|
+
*
|
|
47
|
+
* export const app = brickFromContract(contract, { port: 4000 });
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* ```ts
|
|
51
|
+
* // frontend (type-only import, erased at build)
|
|
52
|
+
* import type { AppServer } from "./server";
|
|
53
|
+
* const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* Services are resolved through the global registry by each action's
|
|
57
|
+
* `serviceName`, so every definition in the contract must be bound to a service
|
|
58
|
+
* (via `service.action(...)` or `service.tool(...)`). Only HTTP actions
|
|
59
|
+
* registered on that service produce routes. An
|
|
60
|
+
* error names the offending action when it is unbound or its service was
|
|
61
|
+
* never registered.
|
|
62
|
+
*/
|
|
63
|
+
function brickFromContract(contract, options = {}) {
|
|
64
|
+
if (!contract || typeof contract !== "object") throw new Error("[Brick-TS] brickFromContract: `contract` must be an object of actions, resources, or services.");
|
|
65
|
+
const actions = [];
|
|
66
|
+
collectActions(contract, actions);
|
|
67
|
+
if (actions.length === 0) throw new Error("[Brick-TS] brickFromContract: contract contains no actions.");
|
|
68
|
+
const unbound = actions.filter((action) => !action.serviceName);
|
|
69
|
+
if (unbound.length > 0) throw new Error(`[Brick-TS] brickFromContract: actions not bound to a service (define them via service.action(...)): ${unbound.map((action) => `'${action.name}'`).join(", ")}.`);
|
|
70
|
+
const services = [];
|
|
71
|
+
const seen = /* @__PURE__ */ new Set();
|
|
72
|
+
for (const action of actions) {
|
|
73
|
+
const name = action.serviceName;
|
|
74
|
+
if (seen.has(name)) continue;
|
|
75
|
+
seen.add(name);
|
|
76
|
+
const service = getGlobalRegistry().get(name);
|
|
77
|
+
if (!service) throw new Error(`[Brick-TS] brickFromContract: service '${name}' (used by action '${action.name}') is not registered.`);
|
|
78
|
+
services.push(service);
|
|
79
|
+
}
|
|
80
|
+
return brick({
|
|
81
|
+
...options,
|
|
82
|
+
services
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
export { bindCompiledApplication, brick, brickFromContract, buildApplication, compileBrickApplication, emitCompiledApplication, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/contract.ts"],"sourcesContent":["import {\n getGlobalRegistry,\n type Action,\n type Resource,\n type Service,\n} from \"@brickkit/core\";\nimport { brick, type CreateServerOptions } from \"./server\";\nimport type { BrickApp } from \"./endpoints\";\n\n/**\n * Options for {@link brickFromContract}: everything `brick()` accepts except\n * `services`, which is derived from the contract itself.\n */\nexport type BrickFromContractOptions = Omit<CreateServerOptions, \"services\">;\n\nfunction isAction(value: unknown): value is Action<any, any, any, any> {\n return (\n typeof value === \"function\" &&\n !!(value as any).config &&\n typeof (value as any).config.execute === \"function\"\n );\n}\n\nfunction isService(value: unknown): value is Service<any, any> {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as any).listActions === \"function\" &&\n (value as any).actions instanceof Map\n );\n}\n\nfunction isResource(value: unknown): value is Resource<any, any> {\n return (\n !!value &&\n typeof value === \"object\" &&\n !isService(value) &&\n !!(value as any).actions &&\n typeof (value as any).actions === \"object\"\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/** Collects definitions to resolve services; each service registers its own HTTP actions. */\nfunction collectActions(\n node: unknown,\n out: Action<any, any, any, any>[],\n): void {\n if (isAction(node)) {\n out.push(node);\n return;\n }\n if (isService(node)) {\n out.push(...node.listActions(), ...(node.listTools?.() ?? []));\n return;\n }\n if (isResource(node)) {\n out.push(...Object.values(node.actions));\n return;\n }\n if (isPlainObject(node)) {\n for (const value of Object.values(node)) collectActions(value, out);\n }\n}\n\n/**\n * Contract-first server: builds the `brick()` app from the same contract\n * object that types the frontend client, so services are declared once.\n *\n * ```ts\n * // server.ts (backend, single source of truth)\n * export const contract = defineAppContract({\n * page: { list: listPages, create: createPage },\n * billing: { charge: chargeAction },\n * });\n * export type AppServer = typeof contract;\n *\n * export const app = brickFromContract(contract, { port: 4000 });\n * ```\n *\n * ```ts\n * // frontend (type-only import, erased at build)\n * import type { AppServer } from \"./server\";\n * const api = createBrickClient<AppServer>({ baseUrl: \"http://localhost:4000\" });\n * ```\n *\n * Services are resolved through the global registry by each action's\n * `serviceName`, so every definition in the contract must be bound to a service\n * (via `service.action(...)` or `service.tool(...)`). Only HTTP actions\n * registered on that service produce routes. An\n * error names the offending action when it is unbound or its service was\n * never registered.\n */\nexport function brickFromContract<TContract extends Record<string, any>>(\n contract: TContract,\n options: BrickFromContractOptions = {},\n): BrickApp {\n if (!contract || typeof contract !== \"object\") {\n throw new Error(\n \"[Brick-TS] brickFromContract: `contract` must be an object of actions, resources, or services.\",\n );\n }\n\n const actions: Action<any, any, any, any>[] = [];\n collectActions(contract, actions);\n if (actions.length === 0) {\n throw new Error(\n \"[Brick-TS] brickFromContract: contract contains no actions.\",\n );\n }\n\n const unbound = actions.filter((action) => !action.serviceName);\n if (unbound.length > 0) {\n throw new Error(\n `[Brick-TS] brickFromContract: actions not bound to a service (define them via service.action(...)): ${unbound.map((action) => `'${action.name}'`).join(\", \")}.`,\n );\n }\n\n const services: Service<any, any>[] = [];\n const seen = new Set<string>();\n for (const action of actions) {\n const name = action.serviceName!;\n if (seen.has(name)) continue;\n seen.add(name);\n const service = getGlobalRegistry().get(name);\n if (!service) {\n throw new Error(\n `[Brick-TS] brickFromContract: service '${name}' (used by action '${action.name}') is not registered.`,\n );\n }\n services.push(service);\n }\n\n return brick({ ...options, services });\n}\n"],"mappings":";;;;AAeA,SAAS,SAAS,OAAqD;CACrE,OACE,OAAO,UAAU,cACjB,CAAC,CAAE,MAAc,UACjB,OAAQ,MAAc,OAAO,YAAY;AAE7C;AAEA,SAAS,UAAU,OAA4C;CAC7D,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YACjB,OAAQ,MAAc,gBAAgB,cACrC,MAAc,mBAAmB;AAEtC;AAEA,SAAS,WAAW,OAA6C;CAC/D,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YACjB,CAAC,UAAU,KAAK,KAChB,CAAC,CAAE,MAAc,WACjB,OAAQ,MAA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EAC5C,IAAI,CAAC,SACH,MAAM,IAAI,MACR,0CAA0C,KAAK,qBAAqB,OAAO,KAAK,sBAClF;EAEF,SAAS,KAAK,OAAO;CACvB;CAEA,OAAO,MAAM;EAAE,GAAG;EAAS;CAAS,CAAC;AACvC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@brickkit/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "CLI and server engine for Brick-TS",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -33,16 +33,22 @@
|
|
|
33
33
|
"scripts": {
|
|
34
34
|
"build": "tsdown",
|
|
35
35
|
"prepublishOnly": "bun run build",
|
|
36
|
-
"typecheck": "tsc --noEmit -p tsconfig.build.json"
|
|
36
|
+
"typecheck": "tsc --noEmit -p tsconfig.build.json",
|
|
37
|
+
"lint": "oxlint .",
|
|
38
|
+
"lint:fix": "oxlint --fix .",
|
|
39
|
+
"format": "oxfmt .",
|
|
40
|
+
"format:check": "oxfmt --check ."
|
|
37
41
|
},
|
|
38
42
|
"dependencies": {
|
|
39
|
-
"@brickkit/core": "^0.
|
|
43
|
+
"@brickkit/core": "^0.2.0",
|
|
40
44
|
"@sinclair/typebox": "^0.34.0",
|
|
41
45
|
"elysia": "^1.2.0"
|
|
42
46
|
},
|
|
43
47
|
"devDependencies": {
|
|
44
48
|
"@types/bun": "latest",
|
|
45
49
|
"tsdown": "^0.23.0",
|
|
46
|
-
"typescript": "^5.7.0"
|
|
50
|
+
"typescript": "^5.7.0",
|
|
51
|
+
"oxfmt": "^0.72.0",
|
|
52
|
+
"oxlint": "^1.87.0"
|
|
47
53
|
}
|
|
48
54
|
}
|