@brickkit/cli 0.3.0-beta.1 → 0.3.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build.js +37 -13
- package/dist/build.js.map +1 -1
- package/dist/client-contract.js +12 -78
- package/dist/client-contract.js.map +1 -1
- package/dist/compiler.d.ts +7 -3
- package/dist/compiler.d.ts.map +1 -1
- package/dist/compiler2.js +48 -62
- package/dist/compiler2.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/build.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as emitCompiledApplication, i as loadBrickApp, n as compileBrickApplication } from "./compiler2.js";
|
|
2
2
|
import { Elysia } from "elysia";
|
|
3
|
-
import { ActionExecutionError, ValidationError, generateOpenApiSpec, getGlobalRegistry, resolveSecrets } from "@brickkit/core";
|
|
3
|
+
import { ActionExecutionError, ValidationError, generateOpenApiSpec, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, resolveSecrets } from "@brickkit/core";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
5
5
|
import { existsSync } from "fs";
|
|
6
6
|
import { resolve as resolve$1 } from "path";
|
|
@@ -284,12 +284,14 @@ function brick(options = {}) {
|
|
|
284
284
|
prefix,
|
|
285
285
|
services
|
|
286
286
|
});
|
|
287
|
+
const paths = { ...spec.paths };
|
|
288
|
+
for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
|
|
289
|
+
...paths[path],
|
|
290
|
+
...operations
|
|
291
|
+
};
|
|
287
292
|
return {
|
|
288
293
|
...spec,
|
|
289
|
-
paths
|
|
290
|
-
...spec.paths,
|
|
291
|
-
...endpointPaths(endpointDefs)
|
|
292
|
-
}
|
|
294
|
+
paths
|
|
293
295
|
};
|
|
294
296
|
};
|
|
295
297
|
app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
|
|
@@ -307,10 +309,22 @@ function brick(options = {}) {
|
|
|
307
309
|
});
|
|
308
310
|
}
|
|
309
311
|
}
|
|
310
|
-
const registeredRoutes = /* @__PURE__ */ new
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
312
|
+
const registeredRoutes = /* @__PURE__ */ new Map();
|
|
313
|
+
const routeKey = (method, path) => `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
314
|
+
registeredRoutes.set(routeKey("GET", "/_health"), false);
|
|
315
|
+
registeredRoutes.set(routeKey("GET", "/_brick/services"), false);
|
|
316
|
+
if (enableDocs) for (const path of [
|
|
317
|
+
openApiPath,
|
|
318
|
+
docsPath,
|
|
319
|
+
swaggerPath
|
|
320
|
+
]) registeredRoutes.set(routeKey("GET", path), false);
|
|
321
|
+
if (reference !== false) registeredRoutes.set(routeKey("GET", reference === true ? "/reference" : reference.path ?? "/reference"), false);
|
|
322
|
+
const mountRoute = (method, path, handler, plugin = false) => {
|
|
323
|
+
const key = routeKey(method, path);
|
|
324
|
+
if (registeredRoutes.has(key)) {
|
|
325
|
+
if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
314
328
|
switch (method) {
|
|
315
329
|
case "GET":
|
|
316
330
|
app.get(path, handler);
|
|
@@ -326,13 +340,14 @@ function brick(options = {}) {
|
|
|
326
340
|
break;
|
|
327
341
|
case "DELETE": app.delete(path, handler);
|
|
328
342
|
}
|
|
329
|
-
registeredRoutes.
|
|
343
|
+
registeredRoutes.set(key, plugin);
|
|
330
344
|
};
|
|
331
|
-
const mountEndpoint = (def) => {
|
|
332
|
-
mountRoute(def.method, def.path, createEndpointHandler(def, services));
|
|
345
|
+
const mountEndpoint = (def, plugin = false) => {
|
|
346
|
+
mountRoute(def.method, def.path, createEndpointHandler(def, services), plugin);
|
|
333
347
|
endpointDefs.push(def);
|
|
334
348
|
endpointRevision++;
|
|
335
349
|
};
|
|
350
|
+
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
336
351
|
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
337
352
|
const brickApp = app;
|
|
338
353
|
Object.defineProperty(brickApp, "definition", { value: Object.freeze({
|
|
@@ -349,9 +364,18 @@ function brick(options = {}) {
|
|
|
349
364
|
mode: options.compiler === false ? "generic" : "specialized"
|
|
350
365
|
});
|
|
351
366
|
if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
|
|
352
|
-
for (const route of compilation.routes)
|
|
367
|
+
for (const route of compilation.routes) {
|
|
368
|
+
const action = services.find((candidate) => candidate.name === route.ir.service).listActions().find((candidate) => candidate.name === route.ir.action);
|
|
369
|
+
mountRoute(route.ir.method, route.ir.path, (context) => {
|
|
370
|
+
const result = route.handler(context);
|
|
371
|
+
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
372
|
+
}, getPluginActionRoute(action, prefix) !== void 0);
|
|
373
|
+
}
|
|
353
374
|
return brickApp;
|
|
354
375
|
}
|
|
376
|
+
function jsonActionResult(value) {
|
|
377
|
+
return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
|
|
378
|
+
}
|
|
355
379
|
function htmlResponse(html) {
|
|
356
380
|
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
357
381
|
}
|
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 the \"global\" scope 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 beforeHandle\n * because request hooks are not 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.beforeHandle(\"global\", markStarted);\n plugin.afterHandle(\"global\", logSuccess);\n plugin.error(\"global\", logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface ReferenceOptions {\n path?: string;\n title?: string;\n specUrl?: string;\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/** Mounts the Scalar reference route onto an existing app. */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","import type { Elysia } from \"elysia\";\nimport type { Service, DatabaseHandle } from \"@brickkit/core\";\nimport { ActionExecutionError, ValidationError } from \"@brickkit/core\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb() ?? undefined;\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n return async ({ params, body, query, headers, request, set }: any) => {\n const traceId =\n headers?.[\"x-trace-id\"] ||\n `tr_${Math.random().toString(36).substring(2, 10)}`;\n const requestId =\n headers?.[\"x-request-id\"] ||\n `req_${Math.random().toString(36).substring(2, 10)}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n const tag = `endpoint:${def.method} ${def.path}`;\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger: {\n info: (...args) => console.log(`[${tag}]`, ...args),\n warn: (...args) => console.warn(`[${tag}]`, ...args),\n error: (...args) => console.error(`[${tag}]`, ...args),\n debug: (...args) => console.debug(`[${tag}]`, ...args),\n },\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err: any) {\n if (err instanceof ValidationError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (typeof err?.status === \"number\") {\n set.status = err.status;\n return { message: err.message || \"Endpoint error\", status: err.status };\n }\n set.status = 500;\n return {\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n };\n}\n\n/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions and prefix selected when this app was constructed. */\n readonly definition: {\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n };\n /** Register a raw endpoint (outside the JSON action mesh). */\n endpoint(def: EndpointDefinition): void;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","import { Elysia } from \"elysia\";\nimport { compileBrickApplication, type CompiledApplication } from \"./compiler\";\nimport {\n type Service,\n getGlobalRegistry,\n generateOpenApiSpec,\n resolveSecrets,\n type SecretSource,\n} from \"@brickkit/core\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n registerReferenceRoute,\n type ReferenceOptions,\n} from \"./docs\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Generate specialized handlers once at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n reference?: boolean | ReferenceOptions; // default false, path \"/reference\"\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (outside the JSON action mesh), mounted at startup. */\n endpoints?: EndpointDefinition[];\n}\n\nexport {\n compileRoutePlan,\n executeCompiledRoute,\n createActionHandler,\n} from \"./action-handler\";\n\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n const prefix = options.prefix ?? options.compilation?.ir.prefix ?? \"/api\";\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const compiled = options.compiler !== false;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? \"/openapi.json\";\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n // Diagnostics & health\n app.get(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n app.get(\n \"/_brick/services\",\n compiled\n ? cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n )\n : () => getGlobalRegistry().exportArchitecture(),\n );\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false) {\n const pluginOpts = requestLogging === true ? {} : requestLogging;\n if (pluginOpts.enabled !== false) {\n app.use(requestLoggingPlugin(pluginOpts));\n }\n }\n\n // Scalar API reference (opt-in). Defaults to openApiPath for the spec URL.\n const reference = options.reference ?? false;\n if (reference !== false) {\n const refOpts = reference === true ? {} : reference;\n const settings = {\n path: refOpts.path ?? \"/reference\",\n title: refOpts.title ?? title,\n specUrl: refOpts.specUrl ?? openApiPath,\n };\n if (compiled)\n app.get(\n settings.path,\n htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)),\n );\n else registerReferenceRoute(app, settings);\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n\n // Precompute plans and freeze immutable plans across all services\n for (const service of services) {\n if (typeof (service as any).build === \"function\") {\n (service as any).build();\n }\n }\n\n // Raw endpoints declared via options or app.endpoint() (declaration order).\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n // OpenAPI 3.1 & Interactive Documentation Endpoints\n if (enableDocs) {\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n // Raw endpoints show up in the spec alongside the action mesh.\n return {\n ...spec,\n paths: { ...spec.paths, ...endpointPaths(endpointDefs) },\n };\n };\n app.get(\n openApiPath,\n compiled\n ? cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n )\n : buildSpec,\n );\n\n if (compiled) {\n app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n } else {\n app.get(docsPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(openApiPath, title);\n });\n\n app.get(swaggerPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return swaggerDocsHTML(openApiPath, title);\n });\n }\n }\n\n // Dedicated Route Registry\n const registeredRoutes = new Set<string>();\n\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any,\n ) => {\n const routeKey = `${method} ${path}`;\n if (registeredRoutes.has(routeKey)) {\n return;\n }\n 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 registeredRoutes.add(routeKey);\n };\n\n // Raw endpoints (outside the JSON action mesh).\n const mountEndpoint = (def: EndpointDefinition) => {\n mountRoute(def.method, def.path, createEndpointHandler(def, services));\n endpointDefs.push(def);\n endpointRevision++;\n };\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n Object.defineProperty(brickApp, \"definition\", {\n value: Object.freeze({ services: Object.freeze([...services]), prefix }),\n });\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n for (const route of compilation.routes)\n mountRoute(route.ir.method, route.ir.path, route.handler);\n\n return brickApp;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n","import { existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { brick } from \"./server\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n}\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const port = options.port ?? (Number(process.env.PORT) || 4000);\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (existsSync(resolvedEntry)) {\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n } else {\n console.warn(`[Brick-TS] Specified entry not found: ${resolvedEntry}`);\n }\n }\n\n const registry = getGlobalRegistry();\n const services = registry.list();\n\n console.log(`\\n🧱 Brick-TS Development Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n console.log(` • ${svc.name} (${svc.listActions().length} actions)`);\n if (typeof (svc as any).listResources === \"function\") {\n for (const res of (svc as any).listResources()) {\n console.log(\n ` -> Resource: /api/${res.name} (REST: GET, POST, /:id: GET, PATCH, DELETE)`,\n );\n }\n }\n for (const act of svc.listActions()) {\n console.log(` -> Action: /api/${svc.name}/${act.name}`);\n }\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\n });\n\n app.listen(port);\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication, emitCompiledApplication } from \"./compiler\";\nimport { aot } from \"elysia/plugin/aot/bun\";\nimport { loadBrickApp } from \"./app-entry\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n}\n\n/** Bundle an exported BrickApp with generated handlers and its original configuration. */\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 const app = await loadBrickApp(entry);\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.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 { loadCompiledBrickApp } from \"@brickkit/cli/compiler\";\nimport { ir, bind } from \"./routes.js\";\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), ir, bind);\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 plugins:\n options.aot === false\n ? []\n : [aot(join(staging, \"entry.ts\"), { target: \"bun\", strip: true })],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of [\n \"routes.js\",\n \"brick-ir.json\",\n \"server.js.map\",\n \"server.js\",\n ])\n await rename(join(staging, name), join(outdir, name));\n return { outdir, entry: join(outdir, \"server.js\"), ir: compilation.ir };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;AAOA,SAAS,UACP,QACA,MACA,QACA,WACQ;CACR,OAAO,GAAG,OAAO,GAAG,KAAK,KAAK,OAAO,MAAM,EAAE,IAAI,UAAU;AAC7D;;;;;AAMA,SAAS,aAAa,OAAoC;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,OAAO;EACpE,MAAM,SAAkB,MAAM;EAC9B,IAAI,OAAO,WAAW,UAAU,OAAO;CACzC;AAEF;;;;;;;;;;;;;AAcA,SAAgB,qBAAqB,OAA8B,CAAC,GAAW;CAC7E,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,EADY,KAAK,WAAW,OAClB,OAAO;CACrB,MAAM,SAAS,KAAK,UAAU,QAAQ;CACtC,MAAM,4BAAY,IAAI,QAAwB;CAE9C,MAAM,eAAe,EAAE,cAA8C;EACnE,UAAU,IAAI,SAAS,KAAK,IAAI,CAAC;CACnC;CAEA,MAAM,cAAc,EAClB,SACA,UAC4C;EAC5C,MAAM,QAAQ,UAAU,IAAI,OAAO,KAAK,KAAK,IAAI;EACjD,MAAM,OAAO,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;EAClC,OACE,UAAU,QAAQ,QAAQ,MAAM,IAAI,UAAU,KAAK,KAAK,IAAI,IAAI,KAAK,CACvE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EACF,GACE,MAAM,OAAO,KAAK,SAAS,IAAI,GAAG,KAAK,QAAQ,IAAI,CAAC;EACtD,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 the \"global\" scope 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 beforeHandle\n * because request hooks are not 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.beforeHandle(\"global\", markStarted);\n plugin.afterHandle(\"global\", logSuccess);\n plugin.error(\"global\", logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface ReferenceOptions {\n path?: string;\n title?: string;\n specUrl?: string;\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/** Mounts the Scalar reference route onto an existing app. */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","import type { Elysia } from \"elysia\";\nimport type { Service, DatabaseHandle } from \"@brickkit/core\";\nimport { ActionExecutionError, ValidationError } from \"@brickkit/core\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb() ?? undefined;\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n return async ({ params, body, query, headers, request, set }: any) => {\n const traceId =\n headers?.[\"x-trace-id\"] ||\n `tr_${Math.random().toString(36).substring(2, 10)}`;\n const requestId =\n headers?.[\"x-request-id\"] ||\n `req_${Math.random().toString(36).substring(2, 10)}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n const tag = `endpoint:${def.method} ${def.path}`;\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger: {\n info: (...args) => console.log(`[${tag}]`, ...args),\n warn: (...args) => console.warn(`[${tag}]`, ...args),\n error: (...args) => console.error(`[${tag}]`, ...args),\n debug: (...args) => console.debug(`[${tag}]`, ...args),\n },\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err: any) {\n if (err instanceof ValidationError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (typeof err?.status === \"number\") {\n set.status = err.status;\n return { message: err.message || \"Endpoint error\", status: err.status };\n }\n set.status = 500;\n return {\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n };\n}\n\n/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Service definitions and prefix selected when this app was constructed. */\n readonly definition: {\n readonly services: readonly Service<any, any>[];\n readonly prefix: string;\n };\n /** Register a raw endpoint (outside the JSON action mesh). */\n endpoint(def: EndpointDefinition): void;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","import { Elysia } from \"elysia\";\nimport { compileBrickApplication, type CompiledApplication } from \"./compiler\";\nimport {\n type Service,\n getGlobalRegistry,\n getPluginActionRoute,\n getPluginEndpoints,\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 const paths = { ...spec.paths };\n for (const [path, operations] of Object.entries(\n endpointPaths(endpointDefs),\n ))\n paths[path] = { ...paths[path], ...operations };\n return { ...spec, paths };\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 Map<string, boolean>();\n const routeKey = (method: string, path: string) =>\n `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n registeredRoutes.set(routeKey(\"GET\", \"/_health\"), false);\n registeredRoutes.set(routeKey(\"GET\", \"/_brick/services\"), false);\n if (enableDocs) {\n for (const path of [openApiPath, docsPath, swaggerPath])\n registeredRoutes.set(routeKey(\"GET\", path), false);\n }\n if (reference !== false)\n registeredRoutes.set(\n routeKey(\n \"GET\",\n reference === true ? \"/reference\" : (reference.path ?? \"/reference\"),\n ),\n false,\n );\n\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any,\n plugin = false,\n ) => {\n const key = routeKey(method, path);\n if (registeredRoutes.has(key)) {\n if (plugin || registeredRoutes.get(key))\n throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);\n return;\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 registeredRoutes.set(key, plugin);\n };\n\n // Raw endpoints (outside the JSON action mesh).\n const mountEndpoint = (def: EndpointDefinition, plugin = false) => {\n mountRoute(\n def.method,\n def.path,\n createEndpointHandler(def, services),\n plugin,\n );\n endpointDefs.push(def);\n endpointRevision++;\n };\n\n for (const service of services) {\n for (const def of getPluginEndpoints(service, prefix))\n mountEndpoint(def, true);\n }\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n Object.defineProperty(brickApp, \"definition\", {\n value: Object.freeze({ services: Object.freeze([...services]), prefix }),\n });\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n for (const route of compilation.routes) {\n const service = services.find(\n (candidate) => candidate.name === route.ir.service,\n )!;\n const action = service\n .listActions()\n .find((candidate) => candidate.name === route.ir.action)!;\n mountRoute(\n route.ir.method,\n route.ir.path,\n (context: any) => {\n const result = route.handler(context);\n return result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ? Promise.resolve(result).then(jsonActionResult)\n : jsonActionResult(result);\n },\n getPluginActionRoute(action, prefix) !== undefined,\n );\n }\n\n return brickApp;\n}\n\nfunction jsonActionResult(value: unknown): unknown {\n return value === null\n ? new Response(\"null\", { headers: { \"content-type\": \"application/json\" } })\n : value;\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 { compileBrickApplication, emitCompiledApplication } from \"./compiler\";\nimport { aot } from \"elysia/plugin/aot/bun\";\nimport { loadBrickApp } from \"./app-entry\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n}\n\n/** Bundle an exported BrickApp with generated handlers and its original configuration. */\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 const app = await loadBrickApp(entry);\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.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 { loadCompiledBrickApp } from \"@brickkit/cli/compiler\";\nimport { ir, bind } from \"./routes.js\";\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), ir, bind);\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 plugins:\n options.aot === false\n ? []\n : [aot(join(staging, \"entry.ts\"), { target: \"bun\", strip: true })],\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,CAA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AAC;EACvC,KAAK,MAAM,QAAQ;GACjB;GACA;GACA;GACA;EACF,GACE,MAAM,OAAO,KAAK,SAAS,IAAI,GAAG,KAAK,QAAQ,IAAI,CAAC;EACtD,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"}
|
package/dist/client-contract.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getPluginActionRoute } from "@brickkit/core";
|
|
1
2
|
import { createHash } from "node:crypto";
|
|
2
3
|
//#region src/client-contract.ts
|
|
3
4
|
/** Generate browser metadata and transport types from the app's selected services. */
|
|
@@ -5,10 +6,8 @@ function generateClientContract(app) {
|
|
|
5
6
|
const { services, prefix } = app.definition;
|
|
6
7
|
const contract = Object.create(null);
|
|
7
8
|
const types = Object.create(null);
|
|
8
|
-
const resourceActions = /* @__PURE__ */ new Set();
|
|
9
9
|
const schemas = new SchemaTypes();
|
|
10
|
-
for (const service of services)
|
|
11
|
-
for (const service of services) addServiceActions(service, prefix, contract, types, resourceActions, schemas);
|
|
10
|
+
for (const service of services) addServiceActions(service, prefix, contract, types, schemas);
|
|
12
11
|
return `// Generated by the Brick Vite plugin. Do not edit.
|
|
13
12
|
import type { BrickClientAction } from "@brickkit/core/client";
|
|
14
13
|
|
|
@@ -17,80 +16,14 @@ ${schemas.renderContract(namespaceType(types))}
|
|
|
17
16
|
export const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});
|
|
18
17
|
`;
|
|
19
18
|
}
|
|
20
|
-
function
|
|
21
|
-
for (const resource of service.listResources()) {
|
|
22
|
-
if (Object.hasOwn(contract, resource.name)) throw new Error(`Brick client: duplicate namespace '${resource.name}'`);
|
|
23
|
-
const node = Object.create(null);
|
|
24
|
-
const typeNode = Object.create(null);
|
|
25
|
-
contract[resource.name] = node;
|
|
26
|
-
types[resource.name] = typeNode;
|
|
27
|
-
const enabled = new Set(service.listActions());
|
|
28
|
-
for (const [operation, method, item] of [
|
|
29
|
-
[
|
|
30
|
-
"list",
|
|
31
|
-
"GET",
|
|
32
|
-
false
|
|
33
|
-
],
|
|
34
|
-
[
|
|
35
|
-
"create",
|
|
36
|
-
"POST",
|
|
37
|
-
false
|
|
38
|
-
],
|
|
39
|
-
[
|
|
40
|
-
"get",
|
|
41
|
-
"GET",
|
|
42
|
-
true
|
|
43
|
-
],
|
|
44
|
-
[
|
|
45
|
-
"update",
|
|
46
|
-
"PATCH",
|
|
47
|
-
true
|
|
48
|
-
],
|
|
49
|
-
[
|
|
50
|
-
"delete",
|
|
51
|
-
"DELETE",
|
|
52
|
-
true
|
|
53
|
-
]
|
|
54
|
-
]) {
|
|
55
|
-
const action = resource.actions[operation];
|
|
56
|
-
resourceActions.add(action);
|
|
57
|
-
if (!enabled.has(action)) continue;
|
|
58
|
-
const itemPath = item ? `/:${resource.idField}` : "";
|
|
59
|
-
const path = `${prefix}/${resource.name}${itemPath}`;
|
|
60
|
-
node[operation] = {
|
|
61
|
-
kind: "action",
|
|
62
|
-
name: action.name,
|
|
63
|
-
serviceName: service.name,
|
|
64
|
-
config: {
|
|
65
|
-
path,
|
|
66
|
-
method
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
const inputType = schemas.generate(action.config.input);
|
|
70
|
-
const outputSchema = operation === "list" ? {
|
|
71
|
-
...action.config.output,
|
|
72
|
-
required: [.../* @__PURE__ */ new Set([
|
|
73
|
-
...action.config.output?.required ?? [],
|
|
74
|
-
"items",
|
|
75
|
-
"total",
|
|
76
|
-
"limit",
|
|
77
|
-
"offset",
|
|
78
|
-
"pageCount",
|
|
79
|
-
"hasMore",
|
|
80
|
-
"nextCursor"
|
|
81
|
-
])]
|
|
82
|
-
} : action.config.output;
|
|
83
|
-
typeNode[operation] = actionType(inputType, schemas.generate(outputSchema), action.config.errors);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
function addServiceActions(service, prefix, contract, types, resourceActions, schemas) {
|
|
19
|
+
function addServiceActions(service, prefix, contract, types, schemas) {
|
|
88
20
|
const namespace = contract[service.name] ?? Object.create(null);
|
|
89
21
|
const namespaceTypes = types[service.name] ?? Object.create(null);
|
|
90
22
|
contract[service.name] = namespace;
|
|
91
23
|
types[service.name] = namespaceTypes;
|
|
92
24
|
for (const action of service.listActions()) {
|
|
93
|
-
|
|
25
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
26
|
+
if (pluginRoute === false) continue;
|
|
94
27
|
const { input, output, errors, path, method } = action.config;
|
|
95
28
|
let inputType;
|
|
96
29
|
let outputType;
|
|
@@ -100,19 +33,20 @@ function addServiceActions(service, prefix, contract, types, resourceActions, sc
|
|
|
100
33
|
} catch (error) {
|
|
101
34
|
throw new Error(`Brick client: cannot generate '${service.name}.${action.name}': ${error.message}`);
|
|
102
35
|
}
|
|
103
|
-
|
|
36
|
+
const metadata = {
|
|
104
37
|
kind: "action",
|
|
105
38
|
name: action.name,
|
|
106
39
|
serviceName: service.name,
|
|
107
40
|
config: {
|
|
108
|
-
path: path ?? `${prefix}/${service.name}/${action.name}`,
|
|
109
|
-
method: method ?? "POST"
|
|
41
|
+
path: pluginRoute?.path ?? path ?? `${prefix}/${service.name}/${action.name}`,
|
|
42
|
+
method: pluginRoute?.method ?? method ?? "POST"
|
|
110
43
|
}
|
|
111
|
-
}
|
|
44
|
+
};
|
|
45
|
+
insertAction(pluginRoute?.clientPath ? contract : namespace, pluginRoute?.clientPath ? types : namespaceTypes, metadata, actionType(inputType, outputType, errors), pluginRoute?.clientPath);
|
|
112
46
|
}
|
|
113
47
|
}
|
|
114
|
-
function insertAction(node, typeNode, metadata, type) {
|
|
115
|
-
const segments = metadata.name.split(".");
|
|
48
|
+
function insertAction(node, typeNode, metadata, type, clientPath) {
|
|
49
|
+
const segments = clientPath ?? metadata.name.split(".");
|
|
116
50
|
for (const segment of segments.slice(0, -1)) {
|
|
117
51
|
if (Object.hasOwn(typeNode, segment) && typeof typeNode[segment] === "string") throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
|
|
118
52
|
node[segment] ??= Object.create(null);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-contract.js","names":[],"sources":["../src/client-contract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Service } from \"@brickkit/core\";\nimport type { BrickClientAction } from \"@brickkit/core/client\";\nimport type { BrickApp } from \"./endpoints\";\n\n/** Generate browser metadata and transport types from the app's selected services. */\nexport function generateClientContract(app: BrickApp): string {\n const { services, prefix } = app.definition;\n const contract: Record<string, any> = Object.create(null);\n const types: Record<string, any> = Object.create(null);\n const resourceActions = new Set<unknown>();\n const schemas = new SchemaTypes();\n for (const service of services) {\n addResources(service, prefix, contract, types, resourceActions, schemas);\n }\n for (const service of services) {\n addServiceActions(\n service,\n prefix,\n contract,\n types,\n resourceActions,\n schemas,\n );\n }\n return `// Generated by the Brick Vite plugin. Do not edit.\nimport type { BrickClientAction } from \"@brickkit/core/client\";\n\n${schemas.renderContract(namespaceType(types))}\n\nexport const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});\n`;\n}\n\nfunction addResources(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n resourceActions: Set<unknown>,\n schemas: SchemaTypes,\n) {\n for (const resource of service.listResources()) {\n if (Object.hasOwn(contract, resource.name))\n throw new Error(`Brick client: duplicate namespace '${resource.name}'`);\n const node: Record<string, any> = Object.create(null);\n const typeNode: Record<string, any> = Object.create(null);\n contract[resource.name] = node;\n types[resource.name] = typeNode;\n const enabled = new Set(service.listActions());\n for (const [operation, method, item] of [\n [\"list\", \"GET\", false],\n [\"create\", \"POST\", false],\n [\"get\", \"GET\", true],\n [\"update\", \"PATCH\", true],\n [\"delete\", \"DELETE\", true],\n ] as const) {\n const action = resource.actions[operation];\n resourceActions.add(action);\n if (!enabled.has(action)) continue;\n const itemPath = item ? `/:${resource.idField}` : \"\";\n const path = `${prefix}/${resource.name}${itemPath}`;\n node[operation] = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n config: { path, method },\n };\n const inputType = schemas.generate(action.config.input);\n // The runtime list result always includes these metadata fields.\n const outputSchema =\n operation === \"list\"\n ? {\n ...action.config.output,\n required: [\n ...new Set([\n ...(action.config.output?.required ?? []),\n \"items\",\n \"total\",\n \"limit\",\n \"offset\",\n \"pageCount\",\n \"hasMore\",\n \"nextCursor\",\n ]),\n ],\n }\n : action.config.output;\n typeNode[operation] = actionType(\n inputType,\n schemas.generate(outputSchema),\n action.config.errors,\n );\n }\n }\n}\n\nfunction addServiceActions(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n resourceActions: Set<unknown>,\n schemas: SchemaTypes,\n) {\n const namespace: Record<string, any> =\n contract[service.name] ?? Object.create(null);\n const namespaceTypes: Record<string, any> =\n types[service.name] ?? Object.create(null);\n contract[service.name] = namespace;\n types[service.name] = namespaceTypes;\n for (const action of service.listActions()) {\n if (resourceActions.has(action)) continue;\n const { input, output, errors, path, method } = action.config;\n let inputType: string;\n let outputType: string;\n try {\n inputType = input ? schemas.generate(input) : \"unknown\";\n outputType = output ? schemas.generate(output) : \"unknown\";\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate '${service.name}.${action.name}': ${(error as Error).message}`,\n );\n }\n const metadata: BrickClientAction = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n config: {\n path: path ?? `${prefix}/${service.name}/${action.name}`,\n method: method ?? \"POST\",\n },\n };\n insertAction(\n namespace,\n namespaceTypes,\n metadata,\n actionType(inputType, outputType, errors),\n );\n }\n}\n\nfunction insertAction(\n node: Record<string, any>,\n typeNode: Record<string, any>,\n metadata: BrickClientAction,\n type: string,\n) {\n const segments = metadata.name.split(\".\");\n for (const segment of segments.slice(0, -1)) {\n if (\n Object.hasOwn(typeNode, segment) &&\n typeof typeNode[segment] === \"string\"\n ) {\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n }\n node[segment] ??= Object.create(null);\n typeNode[segment] ??= Object.create(null);\n node = node[segment];\n typeNode = typeNode[segment];\n }\n const leaf = segments.at(-1)!;\n if (Object.hasOwn(node, leaf))\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n node[leaf] = metadata;\n typeNode[leaf] = type;\n}\n\nfunction actionType(\n input: string,\n output: string,\n errors: Record<string, unknown> | undefined,\n): string {\n const codes = Object.keys(errors ?? {});\n const errorsType = codes.length\n ? `Record<${codes.map((code) => JSON.stringify(code)).join(\" | \")}, { message: string; status?: number }>`\n : \"{}\";\n return `BrickClientAction<${input}, ${output}, ${errorsType}>`;\n}\n\nfunction namespaceType(node: Record<string, any>): string {\n return `{\\n${Object.entries(node)\n .map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${typeof value === \"string\" ? value : namespaceType(value)};`,\n )\n .join(\"\\n\")}\\n}`;\n}\n\n// Emit transport types from schemas, rather than importing backend callbacks or databases.\nclass SchemaTypes {\n private readonly aliases = new Map<string, string>();\n private readonly names = new Set([\n \"AppContract\",\n \"BrickClientAction\",\n \"contract\",\n ]);\n\n // Internal tokens cannot occur in JSON-escaped property names or literals.\n private readonly fragments: { body: string; size: number; hash: string }[] =\n [];\n private readonly fragmentIds = new Map<string, number>();\n\n private fragment(body: string): string {\n let id = this.fragmentIds.get(body);\n if (id === undefined) {\n id = this.fragments.length;\n const size =\n body.replace(/\\0(\\d+)\\0/g, \"\").length +\n [...body.matchAll(/\\0(\\d+)\\0/g)].reduce(\n (total, match) => total + this.fragments[Number(match[1])]!.size,\n 0,\n );\n const shape = body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => this.fragments[Number(child)]!.hash,\n );\n const hash = createHash(\"sha256\").update(shape).digest(\"hex\");\n this.fragments.push({ body, size, hash });\n this.fragmentIds.set(body, id);\n }\n return `\\0${id}\\0`;\n }\n\n renderContract(contract: string): string {\n const uses = this.fragments.map(() => 0);\n const count = (body: string, multiplier: number) => {\n for (const match of body.matchAll(/\\0(\\d+)\\0/g))\n uses[Number(match[1])]! += multiplier;\n };\n count(contract, 1);\n for (const body of this.aliases.values()) count(body, 1);\n const shared = new Map<number, string>();\n // Parents are interned after their children. Once a parent is shared, its\n // children occur only once in its declaration, avoiding overlapping savings.\n for (let id = this.fragments.length - 1; id >= 0; id--) {\n const { body, size, hash } = this.fragments[id]!;\n const nameBase = `BrickSchema_${hash.slice(0, 12)}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) name = `${nameBase}_${suffix++}`;\n const declarationCost = `export type ${name} = ;\\n\\n`.length;\n if (\n uses[id]! > 1 &&\n (uses[id]! - 1) * size > uses[id]! * name.length + declarationCost\n ) {\n this.names.add(name);\n shared.set(id, name);\n }\n count(body, shared.has(id) ? 1 : uses[id]!);\n }\n const rendered: string[] = [];\n const declarations: string[] = [];\n for (let id = 0; id < this.fragments.length; id++) {\n const body = this.fragments[id]!.body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => rendered[Number(child)]!,\n );\n const name = shared.get(id);\n // Child aliases can make a parent too small to justify sharing it.\n if (\n name &&\n (uses[id]! - 1) * body.length >\n uses[id]! * name.length + `export type ${name} = ;\\n\\n`.length\n ) {\n declarations.push(`export type ${name} = ${body};\\n\\n`);\n rendered.push(name);\n } else rendered.push(body);\n }\n const render = (body: string) =>\n body.replace(/\\0(\\d+)\\0/g, (_, id) => rendered[Number(id)]!);\n return (\n declarations.join(\"\") +\n [...this.aliases]\n .map(([name, type]) => `export type ${name} = ${render(type)};\\n\\n`)\n .join(\"\") +\n `export type AppContract = ${render(contract)};`\n );\n }\n\n generate(root: any): string {\n // IDs belong to this schema document. Separate actions may reuse the same ID.\n const ids = new Map<string, any>();\n const references: { ref: string; base: any }[] = [];\n const resources = new Map<unknown, any>();\n const active = new Set<unknown>();\n const visit = (schema: any, base: any) => {\n if (!schema || typeof schema !== \"object\" || active.has(schema)) return;\n const currentBase =\n typeof schema.$id === \"string\" && schema.$id ? schema : base;\n if (!resources.has(schema)) resources.set(schema, currentBase);\n if (typeof schema.$ref === \"string\")\n references.push({ ref: schema.$ref, base: currentBase });\n active.add(schema);\n try {\n if (typeof schema.$id === \"string\" && schema.$id)\n ids.set(schema.$id, schema);\n for (const key of [\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n ]) {\n for (const child of Object.values(schema[key] ?? {}))\n visit(child, currentBase);\n }\n for (const key of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"]) {\n for (const child of schema[key] ?? []) visit(child, currentBase);\n }\n for (const key of [\"items\", \"additionalProperties\", \"not\"]) {\n if (Array.isArray(schema[key]))\n schema[key].forEach((child: any) => visit(child, currentBase));\n else visit(schema[key], currentBase);\n }\n } finally {\n active.delete(schema);\n }\n };\n visit(root, root);\n\n const resolve = (reference: string, base: any): any => {\n const hashIndex = reference.indexOf(\"#\");\n const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);\n const fragment =\n hashIndex === -1 ? undefined : reference.slice(hashIndex + 1);\n let target = id ? ids.get(id) : base;\n if (fragment) {\n if (!fragment.startsWith(\"/\")) return undefined;\n try {\n for (const part of decodeURIComponent(fragment).slice(1).split(\"/\")) {\n const key = part.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (!target || !Object.hasOwn(target, key)) return undefined;\n target = target[key];\n }\n } catch {\n return undefined;\n }\n }\n return typeof target === \"boolean\" ||\n (target && typeof target === \"object\")\n ? target\n : undefined;\n };\n const targets = new Set(\n references\n .map(({ ref, base }) => resolve(ref, base))\n .filter((value) => value !== undefined),\n );\n const names = new Map<any, string>();\n const emit = (schema: any, inline = false, base: any = root): string => {\n const body = emitInline(schema, inline, base);\n // References already have document-scoped aliases; scalars stay inline.\n if (\n schema &&\n !schema.$ref &&\n !Object.hasOwn(schema, \"const\") &&\n (schema.anyOf ||\n schema.oneOf ||\n schema.allOf ||\n schema.enum?.length > 1 ||\n schema.type === \"array\" ||\n schema.type === \"object\")\n )\n return this.fragment(body);\n return body;\n };\n const emitInline = (schema: any, inline: boolean, base: any): string => {\n if (schema === undefined || schema === true) return \"unknown\";\n if (schema === false || (schema.not && !Object.keys(schema.not).length))\n return \"never\";\n const currentBase =\n schema &&\n typeof schema === \"object\" &&\n typeof schema.$id === \"string\" &&\n schema.$id\n ? schema\n : base;\n if (!inline && targets.has(schema)) {\n const existing = names.get(schema);\n if (existing) return existing;\n // Titles provide readable names; generated TypeBox IDs remain usable fallbacks.\n const hint = schema.title ?? schema.$id ?? \"Schema\";\n let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, \"_\");\n if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;\n nameBase = `Brick${nameBase}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) {\n name = `${nameBase}_${suffix}`;\n suffix += 1;\n }\n this.names.add(name);\n names.set(schema, name);\n // names is reserved before the body is rendered, so recursive refs terminate.\n this.aliases.set(name, emit(schema, true, currentBase));\n return name;\n }\n if (schema.$ref) {\n const target = resolve(schema.$ref, currentBase);\n if (target === undefined)\n throw new Error(`unresolved schema reference '${schema.$ref}'`);\n const targetBase =\n target && typeof target === \"object\"\n ? (resources.get(target) ?? root)\n : currentBase;\n return emit(target, false, targetBase);\n }\n if (Object.hasOwn(schema, \"const\")) return JSON.stringify(schema.const);\n if (schema.enum)\n return (\n schema.enum\n .map((value: unknown) => JSON.stringify(value))\n .join(\" | \") || \"never\"\n );\n if (schema.anyOf || schema.oneOf)\n return `(${(schema.anyOf ?? schema.oneOf).map((child: any) => emit(child, false, currentBase)).join(\" | \")})`;\n if (schema.allOf)\n return `(${schema.allOf.map((child: any) => emit(child, false, currentBase)).join(\" & \")})`;\n switch (schema.type) {\n case \"string\":\n return \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"null\":\n return \"null\";\n case \"undefined\":\n case \"void\":\n return \"undefined\";\n case \"array\":\n if (Array.isArray(schema.items))\n return `[${schema.items.map((child: any) => emit(child, false, currentBase)).join(\", \")}]`;\n return `Array<${emit(schema.items, false, currentBase)}>`;\n case \"object\": {\n const entries = Object.entries(schema.properties ?? {});\n const properties = entries.map(\n ([key, value]) =>\n `${JSON.stringify(key)}${schema.required?.includes(key) ? \"\" : \"?\"}: ${emit(value, false, currentBase)};`,\n );\n // additionalProperties applies to keys matched by neither properties\n // nor patternProperties, so union it instead of discarding it.\n const indexParts = Object.values(schema.patternProperties ?? {}).map(\n (child) => emit(child, false, currentBase),\n );\n if (schema.additionalProperties) {\n indexParts.push(\n emit(schema.additionalProperties, false, currentBase),\n );\n }\n let indexType: string | undefined;\n if (indexParts.length) {\n // TS index signatures must also cover declared keys, so widen\n // with their types; otherwise the intersection below rejects\n // valid values. Over-approximating is safe: the server validates.\n for (const [, value] of entries) {\n const propType = emit(value, false, currentBase);\n if (!indexParts.includes(propType)) indexParts.push(propType);\n }\n indexType = indexParts.join(\" | \");\n }\n const object = `{ ${properties.join(\" \")} }`;\n if (indexType) {\n const index = `{ [key: string]: ${indexType} }`;\n return properties.length ? `${object} & ${index}` : index;\n }\n return object;\n }\n case undefined:\n return \"unknown\";\n default:\n throw new Error(`unsupported transport schema type '${schema.type}'`);\n }\n };\n return emit(root);\n }\n}\n"],"mappings":";;;AAMA,SAAgB,uBAAuB,KAAuB;CAC5D,MAAM,EAAE,UAAU,WAAW,IAAI;CACjC,MAAM,WAAgC,OAAO,OAAO,IAAI;CACxD,MAAM,QAA6B,OAAO,OAAO,IAAI;CACrD,MAAM,kCAAkB,IAAI,IAAa;CACzC,MAAM,UAAU,IAAI,YAAY;CAChC,KAAK,MAAM,WAAW,UACpB,aAAa,SAAS,QAAQ,UAAU,OAAO,iBAAiB,OAAO;CAEzE,KAAK,MAAM,WAAW,UACpB,kBACE,SACA,QACA,UACA,OACA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,CAAC,CAAC,CAAC,CAAC,KAC9D,UAAU,KAAK,OAAO,OAAO,WAAW,CAC3C;KACA,IAAI,OAAO,sBACT,WAAW,KACT,KAAK,OAAO,sBAAsB,OAAO,WAAW,CACtD;KAEF,IAAI;KACJ,IAAI,WAAW,QAAQ;MAIrB,KAAK,MAAM,GAAG,UAAU,SAAS;OAC/B,MAAM,WAAW,KAAK,OAAO,OAAO,WAAW;OAC/C,IAAI,CAAC,WAAW,SAAS,QAAQ,GAAG,WAAW,KAAK,QAAQ;MAC9D;MACA,YAAY,WAAW,KAAK,KAAK;KACnC;KACA,MAAM,SAAS,KAAK,WAAW,KAAK,GAAG,EAAE;KACzC,IAAI,WAAW;MACb,MAAM,QAAQ,oBAAoB,UAAU;MAC5C,OAAO,WAAW,SAAS,GAAG,OAAO,KAAK,UAAU;KACtD;KACA,OAAO;IACT;IACA,KAAK,KAAA,GACH,OAAO;IACT,SACE,MAAM,IAAI,MAAM,sCAAsC,OAAO,KAAK,EAAE;GACxE;EACF;EACA,OAAO,KAAK,IAAI;CAClB;AACF"}
|
|
1
|
+
{"version":3,"file":"client-contract.js","names":[],"sources":["../src/client-contract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { getPluginActionRoute, type Service } from \"@brickkit/core\";\nimport type { BrickClientAction } from \"@brickkit/core/client\";\nimport type { BrickApp } from \"./endpoints\";\n\n/** Generate browser metadata and transport types from the app's selected services. */\nexport function generateClientContract(app: BrickApp): string {\n const { services, prefix } = app.definition;\n const contract: Record<string, any> = Object.create(null);\n const types: Record<string, any> = Object.create(null);\n const schemas = new SchemaTypes();\n for (const service of services) {\n addServiceActions(service, prefix, contract, types, schemas);\n }\n return `// Generated by the Brick Vite plugin. Do not edit.\nimport type { BrickClientAction } from \"@brickkit/core/client\";\n\n${schemas.renderContract(namespaceType(types))}\n\nexport const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});\n`;\n}\n\nfunction addServiceActions(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n schemas: SchemaTypes,\n) {\n const namespace: Record<string, any> =\n contract[service.name] ?? Object.create(null);\n const namespaceTypes: Record<string, any> =\n types[service.name] ?? Object.create(null);\n contract[service.name] = namespace;\n types[service.name] = namespaceTypes;\n for (const action of service.listActions()) {\n const pluginRoute = getPluginActionRoute(action, prefix);\n if (pluginRoute === false) continue;\n const { input, output, errors, path, method } = action.config;\n let inputType: string;\n let outputType: string;\n try {\n inputType = input ? schemas.generate(input) : \"unknown\";\n outputType = output ? schemas.generate(output) : \"unknown\";\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate '${service.name}.${action.name}': ${(error as Error).message}`,\n );\n }\n const metadata: BrickClientAction = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n config: {\n path:\n pluginRoute?.path ??\n path ??\n `${prefix}/${service.name}/${action.name}`,\n method: pluginRoute?.method ?? method ?? \"POST\",\n },\n };\n insertAction(\n pluginRoute?.clientPath ? contract : namespace,\n pluginRoute?.clientPath ? types : namespaceTypes,\n metadata,\n actionType(inputType, outputType, errors),\n pluginRoute?.clientPath,\n );\n }\n}\n\nfunction insertAction(\n node: Record<string, any>,\n typeNode: Record<string, any>,\n metadata: BrickClientAction,\n type: string,\n clientPath?: readonly string[],\n) {\n const segments = clientPath ?? metadata.name.split(\".\");\n for (const segment of segments.slice(0, -1)) {\n if (\n Object.hasOwn(typeNode, segment) &&\n typeof typeNode[segment] === \"string\"\n ) {\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n }\n node[segment] ??= Object.create(null);\n typeNode[segment] ??= Object.create(null);\n node = node[segment];\n typeNode = typeNode[segment];\n }\n const leaf = segments.at(-1)!;\n if (Object.hasOwn(node, leaf))\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n node[leaf] = metadata;\n typeNode[leaf] = type;\n}\n\nfunction actionType(\n input: string,\n output: string,\n errors: Record<string, unknown> | undefined,\n): string {\n const codes = Object.keys(errors ?? {});\n const errorsType = codes.length\n ? `Record<${codes.map((code) => JSON.stringify(code)).join(\" | \")}, { message: string; status?: number }>`\n : \"{}\";\n return `BrickClientAction<${input}, ${output}, ${errorsType}>`;\n}\n\nfunction namespaceType(node: Record<string, any>): string {\n return `{\\n${Object.entries(node)\n .map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${typeof value === \"string\" ? value : namespaceType(value)};`,\n )\n .join(\"\\n\")}\\n}`;\n}\n\n// Emit transport types from schemas, rather than importing backend callbacks or databases.\nclass SchemaTypes {\n private readonly aliases = new Map<string, string>();\n private readonly names = new Set([\n \"AppContract\",\n \"BrickClientAction\",\n \"contract\",\n ]);\n\n // Internal tokens cannot occur in JSON-escaped property names or literals.\n private readonly fragments: { body: string; size: number; hash: string }[] =\n [];\n private readonly fragmentIds = new Map<string, number>();\n\n private fragment(body: string): string {\n let id = this.fragmentIds.get(body);\n if (id === undefined) {\n id = this.fragments.length;\n const size =\n body.replace(/\\0(\\d+)\\0/g, \"\").length +\n [...body.matchAll(/\\0(\\d+)\\0/g)].reduce(\n (total, match) => total + this.fragments[Number(match[1])]!.size,\n 0,\n );\n const shape = body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => this.fragments[Number(child)]!.hash,\n );\n const hash = createHash(\"sha256\").update(shape).digest(\"hex\");\n this.fragments.push({ body, size, hash });\n this.fragmentIds.set(body, id);\n }\n return `\\0${id}\\0`;\n }\n\n renderContract(contract: string): string {\n const uses = this.fragments.map(() => 0);\n const count = (body: string, multiplier: number) => {\n for (const match of body.matchAll(/\\0(\\d+)\\0/g))\n uses[Number(match[1])]! += multiplier;\n };\n count(contract, 1);\n for (const body of this.aliases.values()) count(body, 1);\n const shared = new Map<number, string>();\n // Parents are interned after their children. Once a parent is shared, its\n // children occur only once in its declaration, avoiding overlapping savings.\n for (let id = this.fragments.length - 1; id >= 0; id--) {\n const { body, size, hash } = this.fragments[id]!;\n const nameBase = `BrickSchema_${hash.slice(0, 12)}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) name = `${nameBase}_${suffix++}`;\n const declarationCost = `export type ${name} = ;\\n\\n`.length;\n if (\n uses[id]! > 1 &&\n (uses[id]! - 1) * size > uses[id]! * name.length + declarationCost\n ) {\n this.names.add(name);\n shared.set(id, name);\n }\n count(body, shared.has(id) ? 1 : uses[id]!);\n }\n const rendered: string[] = [];\n const declarations: string[] = [];\n for (let id = 0; id < this.fragments.length; id++) {\n const body = this.fragments[id]!.body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => rendered[Number(child)]!,\n );\n const name = shared.get(id);\n // Child aliases can make a parent too small to justify sharing it.\n if (\n name &&\n (uses[id]! - 1) * body.length >\n uses[id]! * name.length + `export type ${name} = ;\\n\\n`.length\n ) {\n declarations.push(`export type ${name} = ${body};\\n\\n`);\n rendered.push(name);\n } else rendered.push(body);\n }\n const render = (body: string) =>\n body.replace(/\\0(\\d+)\\0/g, (_, id) => rendered[Number(id)]!);\n return (\n declarations.join(\"\") +\n [...this.aliases]\n .map(([name, type]) => `export type ${name} = ${render(type)};\\n\\n`)\n .join(\"\") +\n `export type AppContract = ${render(contract)};`\n );\n }\n\n generate(root: any): string {\n // IDs belong to this schema document. Separate actions may reuse the same ID.\n const ids = new Map<string, any>();\n const references: { ref: string; base: any }[] = [];\n const resources = new Map<unknown, any>();\n const active = new Set<unknown>();\n const visit = (schema: any, base: any) => {\n if (!schema || typeof schema !== \"object\" || active.has(schema)) return;\n const currentBase =\n typeof schema.$id === \"string\" && schema.$id ? schema : base;\n if (!resources.has(schema)) resources.set(schema, currentBase);\n if (typeof schema.$ref === \"string\")\n references.push({ ref: schema.$ref, base: currentBase });\n active.add(schema);\n try {\n if (typeof schema.$id === \"string\" && schema.$id)\n ids.set(schema.$id, schema);\n for (const key of [\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n ]) {\n for (const child of Object.values(schema[key] ?? {}))\n visit(child, currentBase);\n }\n for (const key of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"]) {\n for (const child of schema[key] ?? []) visit(child, currentBase);\n }\n for (const key of [\"items\", \"additionalProperties\", \"not\"]) {\n if (Array.isArray(schema[key]))\n schema[key].forEach((child: any) => visit(child, currentBase));\n else visit(schema[key], currentBase);\n }\n } finally {\n active.delete(schema);\n }\n };\n visit(root, root);\n\n const resolve = (reference: string, base: any): any => {\n const hashIndex = reference.indexOf(\"#\");\n const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);\n const fragment =\n hashIndex === -1 ? undefined : reference.slice(hashIndex + 1);\n let target = id ? ids.get(id) : base;\n if (fragment) {\n if (!fragment.startsWith(\"/\")) return undefined;\n try {\n for (const part of decodeURIComponent(fragment).slice(1).split(\"/\")) {\n const key = part.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (!target || !Object.hasOwn(target, key)) return undefined;\n target = target[key];\n }\n } catch {\n return undefined;\n }\n }\n return typeof target === \"boolean\" ||\n (target && typeof target === \"object\")\n ? target\n : undefined;\n };\n const targets = new Set(\n references\n .map(({ ref, base }) => resolve(ref, base))\n .filter((value) => value !== undefined),\n );\n const names = new Map<any, string>();\n const emit = (schema: any, inline = false, base: any = root): string => {\n const body = emitInline(schema, inline, base);\n // References already have document-scoped aliases; scalars stay inline.\n if (\n schema &&\n !schema.$ref &&\n !Object.hasOwn(schema, \"const\") &&\n (schema.anyOf ||\n schema.oneOf ||\n schema.allOf ||\n schema.enum?.length > 1 ||\n schema.type === \"array\" ||\n schema.type === \"object\")\n )\n return this.fragment(body);\n return body;\n };\n const emitInline = (schema: any, inline: boolean, base: any): string => {\n if (schema === undefined || schema === true) return \"unknown\";\n if (schema === false || (schema.not && !Object.keys(schema.not).length))\n return \"never\";\n const currentBase =\n schema &&\n typeof schema === \"object\" &&\n typeof schema.$id === \"string\" &&\n schema.$id\n ? schema\n : base;\n if (!inline && targets.has(schema)) {\n const existing = names.get(schema);\n if (existing) return existing;\n // Titles provide readable names; generated TypeBox IDs remain usable fallbacks.\n const hint = schema.title ?? schema.$id ?? \"Schema\";\n let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, \"_\");\n if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;\n nameBase = `Brick${nameBase}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) {\n name = `${nameBase}_${suffix}`;\n suffix += 1;\n }\n this.names.add(name);\n names.set(schema, name);\n // names is reserved before the body is rendered, so recursive refs terminate.\n this.aliases.set(name, emit(schema, true, currentBase));\n return name;\n }\n if (schema.$ref) {\n const target = resolve(schema.$ref, currentBase);\n if (target === undefined)\n throw new Error(`unresolved schema reference '${schema.$ref}'`);\n const targetBase =\n target && typeof target === \"object\"\n ? (resources.get(target) ?? root)\n : currentBase;\n return emit(target, false, targetBase);\n }\n if (Object.hasOwn(schema, \"const\")) return JSON.stringify(schema.const);\n if (schema.enum)\n return (\n schema.enum\n .map((value: unknown) => JSON.stringify(value))\n .join(\" | \") || \"never\"\n );\n if (schema.anyOf || schema.oneOf)\n return `(${(schema.anyOf ?? schema.oneOf).map((child: any) => emit(child, false, currentBase)).join(\" | \")})`;\n if (schema.allOf)\n return `(${schema.allOf.map((child: any) => emit(child, false, currentBase)).join(\" & \")})`;\n switch (schema.type) {\n case \"string\":\n return \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"null\":\n return \"null\";\n case \"undefined\":\n case \"void\":\n return \"undefined\";\n case \"array\":\n if (Array.isArray(schema.items))\n return `[${schema.items.map((child: any) => emit(child, false, currentBase)).join(\", \")}]`;\n return `Array<${emit(schema.items, false, currentBase)}>`;\n case \"object\": {\n const entries = Object.entries(schema.properties ?? {});\n const properties = entries.map(\n ([key, value]) =>\n `${JSON.stringify(key)}${schema.required?.includes(key) ? \"\" : \"?\"}: ${emit(value, false, currentBase)};`,\n );\n // additionalProperties applies to keys matched by neither properties\n // nor patternProperties, so union it instead of discarding it.\n const indexParts = Object.values(schema.patternProperties ?? {}).map(\n (child) => emit(child, false, currentBase),\n );\n if (schema.additionalProperties) {\n indexParts.push(\n emit(schema.additionalProperties, false, currentBase),\n );\n }\n let indexType: string | undefined;\n if (indexParts.length) {\n // TS index signatures must also cover declared keys, so widen\n // with their types; otherwise the intersection below rejects\n // valid values. Over-approximating is safe: the server validates.\n for (const [, value] of entries) {\n const propType = emit(value, false, currentBase);\n if (!indexParts.includes(propType)) indexParts.push(propType);\n }\n indexType = indexParts.join(\" | \");\n }\n const object = `{ ${properties.join(\" \")} }`;\n if (indexType) {\n const index = `{ [key: string]: ${indexType} }`;\n return properties.length ? `${object} & ${index}` : index;\n }\n return object;\n }\n case undefined:\n return \"unknown\";\n default:\n throw new Error(`unsupported transport schema type '${schema.type}'`);\n }\n };\n return emit(root);\n }\n}\n"],"mappings":";;;;AAMA,SAAgB,uBAAuB,KAAuB;CAC5D,MAAM,EAAE,UAAU,WAAW,IAAI;CACjC,MAAM,WAAgC,OAAO,OAAO,IAAI;CACxD,MAAM,QAA6B,OAAO,OAAO,IAAI;CACrD,MAAM,UAAU,IAAI,YAAY;CAChC,KAAK,MAAM,WAAW,UACpB,kBAAkB,SAAS,QAAQ,UAAU,OAAO,OAAO;CAE7D,OAAO;;;EAGP,QAAQ,eAAe,cAAc,KAAK,CAAC,EAAE;;kDAEG,KAAK,UAAU,KAAK,UAAU,QAAQ,CAAC,EAAE;;AAE3F;AAEA,SAAS,kBACP,SACA,QACA,UACA,OACA,SACA;CACA,MAAM,YACJ,SAAS,QAAQ,SAAS,OAAO,OAAO,IAAI;CAC9C,MAAM,iBACJ,MAAM,QAAQ,SAAS,OAAO,OAAO,IAAI;CAC3C,SAAS,QAAQ,QAAQ;CACzB,MAAM,QAAQ,QAAQ;CACtB,KAAK,MAAM,UAAU,QAAQ,YAAY,GAAG;EAC1C,MAAM,cAAc,qBAAqB,QAAQ,MAAM;EACvD,IAAI,gBAAgB,OAAO;EAC3B,M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KAAK,QAAQ;MAC9D;MACA,YAAY,WAAW,KAAK,KAAK;KACnC;KACA,MAAM,SAAS,KAAK,WAAW,KAAK,GAAG,EAAE;KACzC,IAAI,WAAW;MACb,MAAM,QAAQ,oBAAoB,UAAU;MAC5C,OAAO,WAAW,SAAS,GAAG,OAAO,KAAK,UAAU;KACtD;KACA,OAAO;IACT;IACA,KAAK,KAAA,GACH,OAAO;IACT,SACE,MAAM,IAAI,MAAM,sCAAsC,OAAO,KAAK,EAAE;GACxE;EACF;EACA,OAAO,KAAK,IAAI;CAClB;AACF"}
|
package/dist/compiler.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Elysia } from "elysia";
|
|
2
|
-
import { CompiledRoutePlan, DatabaseHandle,
|
|
2
|
+
import { CompiledRoutePlan, DatabaseHandle, Service } from "@brickkit/core";
|
|
3
3
|
//#region src/endpoints.d.ts
|
|
4
4
|
type EndpointMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
5
5
|
/** Logger subset handed to endpoint handlers (mirrors action context loggers). */
|
|
@@ -60,7 +60,7 @@ interface RouteIR {
|
|
|
60
60
|
readonly path: string;
|
|
61
61
|
readonly service: string;
|
|
62
62
|
readonly action: string;
|
|
63
|
-
readonly kind: "action"
|
|
63
|
+
readonly kind: "action";
|
|
64
64
|
readonly input: boolean;
|
|
65
65
|
readonly output: boolean;
|
|
66
66
|
readonly context: boolean;
|
|
@@ -80,7 +80,11 @@ interface BrickIR {
|
|
|
80
80
|
readonly prefix: string;
|
|
81
81
|
readonly services: readonly string[];
|
|
82
82
|
readonly routes: readonly RouteIR[];
|
|
83
|
-
readonly
|
|
83
|
+
readonly preparations: readonly {
|
|
84
|
+
service: string;
|
|
85
|
+
name: string;
|
|
86
|
+
metadata: unknown;
|
|
87
|
+
}[];
|
|
84
88
|
readonly diagnostics: readonly string[];
|
|
85
89
|
}
|
|
86
90
|
//#endregion
|
package/dist/compiler.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compiler.d.ts","names":["_$__endpoints0.BrickApp"],"sources":["../src/endpoints.ts","../src/compiler/ir.ts","../src/compiler/runtime.ts","../src/compiler/emit.ts","../src/compiler.ts"],"mappings":";;;KAIY;;UAGK;EACf,UAAU;EACV,UAAU;EACV,WAAW;EACX,WAAW;;;UAII;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;;EAET;IAAO;IAAiB,SAAS;;;EAEjC;EACA,QAAQ;EACR;EACA;;UAGe;EACf,QAAQ;;EAER;EACA,UAAU,KAAK,8BAA8B;;EAE7C,UAAU;;EAEV,WAAW;EACX;EACA;EACA;;;KA6HU,WAAW;;WAEZ;aACE,mBAAmB;aACnB;;;EAGX,SAAS,KAAK;;EAEd,iBAAiB;;;;
|
|
1
|
+
{"version":3,"file":"compiler.d.ts","names":["_$__endpoints0.BrickApp"],"sources":["../src/endpoints.ts","../src/compiler/ir.ts","../src/compiler/runtime.ts","../src/compiler/emit.ts","../src/compiler.ts"],"mappings":";;;KAIY;;UAGK;EACf,UAAU;EACV,UAAU;EACV,WAAW;EACX,WAAW;;;UAII;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;;EAET;IAAO;IAAiB,SAAS;;;EAEjC;EACA,QAAQ;EACR;EACA;;UAGe;EACf,QAAQ;;EAER;EACA,UAAU,KAAK,8BAA8B;;EAE7C,UAAU;;EAEV,WAAW;EACX;EACA;EACA;;;KA6HU,WAAW;;WAEZ;aACE,mBAAmB;aACnB;;;EAGX,SAAS,KAAK;;EAEd,iBAAiB;;;;KCzKP;UACK;WACN,QAAQ;WACR;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;aACE;aACA;;;WAGF;WACA;;UAEM;WACN;WACA;WACA;WACA;WACA,iBAAiB;WACjB;IACP;IACA;IACA;;WAEO;;;;KC/BC,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;;;KC/DG,qBAAqB,UAAU,wBAAwB;;iBAWtC,qBACpB,YAAY;EAAU;IACtB,IAAI,SACJ,MAAM,oBAAiB,QAAjBA;UAqBS;WACN,IAAI;WACJ,SAAS;;UAEH;WACN,IAAI;WACJ,iBAAiB;;;iBAsBZ,wBAAwB;EACtC,UAAU;EACV;EACA;IACE;;iBAyBY,wBACd,IAAI,SACJ,UAAU,qBACV,oBAAoB,mBACnB"}
|
package/dist/compiler2.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ActionExecutionError, ValidationError, buildErrorHelpers,
|
|
1
|
+
import { ActionExecutionError, ValidationError, buildErrorHelpers, getCompiledCheck, getPluginActionRoute } from "@brickkit/core";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import { pathToFileURL } from "node:url";
|
|
4
4
|
//#region src/action-handler.ts
|
|
@@ -10,6 +10,26 @@ function isNonEmpty$1(obj) {
|
|
|
10
10
|
for (const _ in obj) return true;
|
|
11
11
|
return false;
|
|
12
12
|
}
|
|
13
|
+
const MAX_INPUT_DEPTH = 128;
|
|
14
|
+
function inputTooDeep(value) {
|
|
15
|
+
if (!value || typeof value !== "object") return false;
|
|
16
|
+
const stack = [{
|
|
17
|
+
node: value,
|
|
18
|
+
depth: 0
|
|
19
|
+
}];
|
|
20
|
+
while (stack.length > 0) {
|
|
21
|
+
const { node, depth } = stack.pop();
|
|
22
|
+
if (depth > MAX_INPUT_DEPTH) return true;
|
|
23
|
+
if (node && typeof node === "object") {
|
|
24
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
25
|
+
for (const child of children) if (child && typeof child === "object") stack.push({
|
|
26
|
+
node: child,
|
|
27
|
+
depth: depth + 1
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
13
33
|
function compileRoutePlan(service, action, routePath, method) {
|
|
14
34
|
const actionName = action.name;
|
|
15
35
|
const serviceName = service.name;
|
|
@@ -18,7 +38,8 @@ function compileRoutePlan(service, action, routePath, method) {
|
|
|
18
38
|
const outputSchema = action.config?.output;
|
|
19
39
|
const hasInput = Boolean(inputSchema);
|
|
20
40
|
const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
|
|
21
|
-
const
|
|
41
|
+
const runtimeOutputSchema = action.outputValidationSchema ?? outputSchema;
|
|
42
|
+
const outputChecker = runtimeOutputSchema ? getCompiledCheck(runtimeOutputSchema) : void 0;
|
|
22
43
|
let coercions;
|
|
23
44
|
if (inputSchema && typeof inputSchema.properties === "object") {
|
|
24
45
|
const list = [];
|
|
@@ -132,6 +153,10 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
132
153
|
}
|
|
133
154
|
if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
|
|
134
155
|
if (plan.hasInput && plan.inputChecker) {
|
|
156
|
+
if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
|
|
157
|
+
path: "",
|
|
158
|
+
message: "Input exceeds maximum nesting depth"
|
|
159
|
+
}]);
|
|
135
160
|
if (!plan.inputChecker.Check(input)) {
|
|
136
161
|
const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
|
|
137
162
|
path: err.path,
|
|
@@ -205,14 +230,19 @@ function analyzeApplication(services, prefix = "/api") {
|
|
|
205
230
|
const diagnostics = [];
|
|
206
231
|
const add = (service, action, method, path, kind) => {
|
|
207
232
|
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
208
|
-
const
|
|
233
|
+
const plugin = getPluginActionRoute(action, prefix) !== void 0;
|
|
234
|
+
const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
209
235
|
const previous = registered.get(key);
|
|
210
236
|
if (previous) {
|
|
211
|
-
|
|
237
|
+
if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
238
|
+
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
|
|
212
239
|
return;
|
|
213
240
|
}
|
|
214
241
|
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
215
|
-
registered.set(key,
|
|
242
|
+
registered.set(key, {
|
|
243
|
+
name: `${service.name}.${action.name}`,
|
|
244
|
+
plugin
|
|
245
|
+
});
|
|
216
246
|
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");
|
|
217
247
|
const coercions = [];
|
|
218
248
|
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
@@ -251,55 +281,17 @@ function analyzeApplication(services, prefix = "/api") {
|
|
|
251
281
|
action
|
|
252
282
|
});
|
|
253
283
|
};
|
|
254
|
-
for (const service of services) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
[
|
|
260
|
-
"list",
|
|
261
|
-
"GET",
|
|
262
|
-
collection
|
|
263
|
-
],
|
|
264
|
-
[
|
|
265
|
-
"create",
|
|
266
|
-
"POST",
|
|
267
|
-
collection
|
|
268
|
-
],
|
|
269
|
-
[
|
|
270
|
-
"get",
|
|
271
|
-
"GET",
|
|
272
|
-
item
|
|
273
|
-
],
|
|
274
|
-
[
|
|
275
|
-
"update",
|
|
276
|
-
"PATCH",
|
|
277
|
-
item
|
|
278
|
-
],
|
|
279
|
-
[
|
|
280
|
-
"update",
|
|
281
|
-
"PUT",
|
|
282
|
-
item
|
|
283
|
-
],
|
|
284
|
-
[
|
|
285
|
-
"delete",
|
|
286
|
-
"DELETE",
|
|
287
|
-
item
|
|
288
|
-
]
|
|
289
|
-
]) {
|
|
290
|
-
const action = resource.actions[operation];
|
|
291
|
-
if (action) add(service, action, method, path, "resource");
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
for (const action of service.listActions()) {
|
|
295
|
-
const path = action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
296
|
-
add(service, action, action.config.method ?? "POST", path, "action");
|
|
297
|
-
}
|
|
284
|
+
for (const service of services) for (const action of service.listActions()) {
|
|
285
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
286
|
+
if (pluginRoute === false) continue;
|
|
287
|
+
const path = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
288
|
+
add(service, action, pluginRoute?.method ?? action.config.method ?? "POST", path, "action");
|
|
298
289
|
}
|
|
299
|
-
const
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
290
|
+
const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
|
|
291
|
+
service: service.name,
|
|
292
|
+
name: contribution.name,
|
|
293
|
+
metadata: schemaSnapshot(contribution.describe?.())
|
|
294
|
+
})));
|
|
303
295
|
return {
|
|
304
296
|
ir: freezeIR({
|
|
305
297
|
version: 1,
|
|
@@ -307,7 +299,7 @@ function analyzeApplication(services, prefix = "/api") {
|
|
|
307
299
|
prefix,
|
|
308
300
|
services: [...names],
|
|
309
301
|
routes,
|
|
310
|
-
|
|
302
|
+
preparations,
|
|
311
303
|
diagnostics
|
|
312
304
|
}),
|
|
313
305
|
bindings
|
|
@@ -477,10 +469,7 @@ function compileBrickApplication(options) {
|
|
|
477
469
|
if (bind && options.mode !== "generic") return bind(options.services);
|
|
478
470
|
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
479
471
|
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
|
|
480
|
-
if (options.mode !== "generic") for (const service of options.services)
|
|
481
|
-
prepareResourceReads(service);
|
|
482
|
-
prepareResourceWrites(service);
|
|
483
|
-
}
|
|
472
|
+
if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
|
|
484
473
|
return bindAnalyzed(ir, bindings, factories);
|
|
485
474
|
}
|
|
486
475
|
/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
|
|
@@ -488,10 +477,7 @@ function bindCompiledApplication(ir, services, factories) {
|
|
|
488
477
|
if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
|
|
489
478
|
const analyzed = analyzeApplication(services, ir.prefix);
|
|
490
479
|
if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
|
|
491
|
-
for (const service of services)
|
|
492
|
-
prepareResourceReads(service);
|
|
493
|
-
prepareResourceWrites(service);
|
|
494
|
-
}
|
|
480
|
+
for (const service of services) service.prepareContributions();
|
|
495
481
|
return bindAnalyzed(ir, analyzed.bindings, factories);
|
|
496
482
|
}
|
|
497
483
|
//#endregion
|
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/app-entry.ts","../src/compiler.ts"],"sourcesContent":["import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n getCompiledCheck,\n buildErrorHelpers,\n} from \"@brickkit/core\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n const outputChecker = outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{ key: string; isNumber: boolean; isBoolean: boolean }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{ key: string; isNumber: boolean; isBoolean: boolean }> =\n [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = {\n info: (...args) => console.log(tag, ...args),\n warn: (...args) => console.warn(tag, ...args),\n error: (...args) => console.error(tag, ...args),\n debug: (...args) => console.debug(tag, ...args),\n };\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n const hasP = isNonEmpty(params);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = params;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, params, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = params;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, params, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${plan.actionName}'`,\n 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n}\n\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import {\n type Service,\n type Action,\n describeResourceReads,\n type ResourceReadQueries,\n} from \"@brickkit/core\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\" | \"resource\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly reads: readonly ResourceReadQueries[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n service.build();\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, string>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const key = `${method} ${path}`;\n const previous = registered.get(key);\n if (previous) {\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, `${service.name}.${action.name}`);\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" }[] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\")\n coercions.push({ key, type: \"boolean\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\n bindings.push({ service, action });\n };\n for (const service of services) {\n for (const resource of service.listResources()) {\n const collection = `${prefix}/${resource.name}`;\n const item = `${collection}/:id`;\n for (const [operation, method, path] of [\n [\"list\", \"GET\", collection],\n [\"create\", \"POST\", collection],\n [\"get\", \"GET\", item],\n [\"update\", \"PATCH\", item],\n [\"update\", \"PUT\", item],\n [\"delete\", \"DELETE\", item],\n ] as const) {\n const action = resource.actions[operation];\n if (action) add(service, action, method, path, \"resource\");\n }\n }\n for (const action of service.listActions()) {\n const path =\n action.config.path ?? `${prefix}/${service.name}/${action.name}`;\n add(service, action, action.config.method ?? \"POST\", path, \"action\");\n }\n }\n const reads = services.flatMap((service) =>\n service.listResources().flatMap((resource) => {\n const queries = describeResourceReads(service, resource);\n return queries ? [queries] : [];\n }),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n reads,\n diagnostics,\n });\n return { ir, bindings };\n}\n","import type { BrickIR, RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input\n ? \"params, body, query, headers, request, set\"\n : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\")\n input.push(\n `if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`,\n );\n else\n input.push(\n `if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`,\n );\n }\n input.push(\"}\");\n }\n input.push(\n `input = mergeInput(${route.inputPrecedence.map((source) => (source === \"query\" ? \"coercedQuery\" : source)).join(\", \")});`,\n );\n if ((route.inputSchema as { type?: string } | undefined)?.type === \"object\")\n input.push(\"input ??= {};\");\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context\n ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\"\n : \"\";\n const validation = route.input\n ? `validate(inputChecker, input, ${name}, \"input\");`\n : \"\";\n const authorization = route.authorize\n ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});`\n : \"\";\n const output = route.output\n ? `validate(outputChecker, result, ${name}, \"output\");`\n : \"\";\n const execute = asyncStages\n ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;`\n : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set); }\n};\n}`;\n}\n\n/** An ES module of real JS functions; it never stringifies application callbacks. */\nexport function emitCompiledApplication(\n ir: BrickIR,\n runtimeImport = \"@brickkit/cli/compiler\",\n): string {\n return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\\nconst factories = [\\n${ir.routes.map(emitHandlerFactory).join(\",\\n\")}\\n];\\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\\n`;\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"@brickkit/core\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true;\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction mapError(err: any, set: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n deny: (action: string): never => {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${action}'`,\n 403,\n );\n },\n});\n","import { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { BrickApp } from \"./endpoints\";\n\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n\nexport async function loadBrickApp(entry: string): Promise<BrickApp> {\n const module = await import(pathToFileURL(resolve(entry)).href);\n return requireBrickApp(module.default);\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\";\nimport { requireBrickApp } from \"./app-entry\";\n\ntype ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;\nconst buildBindings = new Map<string, ApplicationBinder>();\n\nfunction applicationKey(\n services: readonly Service<any, any>[],\n prefix = \"/api\",\n) {\n return JSON.stringify([prefix, services.map((service) => service.name)]);\n}\n\n/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n ir: BrickIR,\n bind: ApplicationBinder,\n) {\n const key = JSON.stringify([ir.prefix, ir.services]);\n if (buildBindings.has(key))\n throw new Error(\"Brick compiler: overlapping compiled app imports\");\n buildBindings.set(key, bind);\n try {\n const app = requireBrickApp((await load()).default);\n if (applicationKey(app.definition.services, app.definition.prefix) !== key)\n throw new Error(\n \"Brick compiler: app services/prefix changed; rebuild the application\",\n );\n return app;\n } finally {\n buildBindings.delete(key);\n }\n}\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 bind = buildBindings.get(\n applicationKey(options.services, options.prefix),\n );\n if (bind && options.mode !== \"generic\") return bind(options.services);\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,KAC5B,WAAW,SAAS,OAAO,KAC3B,WAAW,WAAW,MAAM,KAC5B,WAAW,WAAW,MAAM;CAE9B,MAAM,cAAc,OAAO,QAAQ;CACnC,MAAM,eAAe,OAAO,QAAQ;CACpC,MAAM,WAAW,QAAQ,WAAW;CACpC,MAAM,eAAe,cAChB,iBAAiB,WAAW,IAC7B,KAAA;CACJ,MAAM,gBAAgB,eACjB,iBAAiB,YAAY,IAC9B,KAAA;CAEJ,IAAI;CAGJ,IAAI,eAAe,OAAQ,YAAoB,eAAe,UAAU;EACtE,MAAM,OACJ,CAAC;EACH,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAC9B,YAAoB,UACvB,GAAsB;GACpB,MAAM,OAAO,MAAM;GACnB,IAAI,SAAS,YAAY,SAAS,WAChC,KAAK,KAAK;IAAE;IAAK,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K,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"}
|
|
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/app-entry.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\n// Generic pre-validation nesting cap for parsed HTTP input. Compiled input\n// validators recurse, so unbounded nesting (e.g. a 20k-deep filter object)\n// would throw RangeError (HTTP 500) instead of failing validation with a\n// 400. The walk is iterative and far above legitimate depths (a max-depth\n// CRUD filter is ~45 levels of JSON).\nconst MAX_INPUT_DEPTH = 128;\nfunction inputTooDeep(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const stack: { node: unknown; depth: number }[] = [{ node: value, depth: 0 }];\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (depth > MAX_INPUT_DEPTH) return true;\n if (node && typeof node === \"object\") {\n const children = Array.isArray(node) ? node : Object.values(node);\n for (const child of children)\n if (child && typeof child === \"object\")\n stack.push({ node: child, depth: depth + 1 });\n }\n }\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 // Prefer a runtime-only output schema when the action provides one (CRUD\n // subset projections validate loosely at runtime while `config.output`\n // stays strict for contracts/OpenAPI).\n const runtimeOutputSchema =\n (action as { outputValidationSchema?: typeof outputSchema })\n .outputValidationSchema ?? outputSchema;\n const outputChecker = runtimeOutputSchema\n ? (getCompiledCheck(runtimeOutputSchema) 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 (inputTooDeep(input)) {\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n [{ path: \"\", message: \"Input exceeds maximum nesting depth\" }],\n );\n }\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 getPluginActionRoute,\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\";\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 preparations: readonly {\n service: string;\n name: string;\n metadata: unknown;\n }[];\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, { name: string; plugin: boolean }>();\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 plugin = getPluginActionRoute(action, prefix) !== undefined;\n const key = `${method} ${path.replace(/:[^/]+/g, \":param\")}`;\n const previous = registered.get(key);\n if (previous) {\n if (plugin || previous.plugin)\n throw new Error(\n `Brick compiler: duplicate plugin route '${method} ${path}'`,\n );\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (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, { name: `${service.name}.${action.name}`, plugin });\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 action of service.listActions()) {\n const pluginRoute = getPluginActionRoute(action, prefix);\n if (pluginRoute === false) continue;\n const path =\n pluginRoute?.path ??\n action.config.path ??\n `${prefix}/${service.name}/${action.name}`;\n add(\n service,\n action,\n pluginRoute?.method ?? action.config.method ?? \"POST\",\n path,\n \"action\",\n );\n }\n }\n const preparations = services.flatMap((service) =>\n service.listPreparations().map((contribution) => ({\n service: service.name,\n name: contribution.name,\n metadata: schemaSnapshot(contribution.describe?.()),\n })),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n preparations,\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 { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { BrickApp } from \"./endpoints\";\n\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n\nexport async function loadBrickApp(entry: string): Promise<BrickApp> {\n const module = await import(pathToFileURL(resolve(entry)).href);\n return requireBrickApp(module.default);\n}\n","import { type Service } 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\";\nimport { requireBrickApp } from \"./app-entry\";\n\ntype ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;\nconst buildBindings = new Map<string, ApplicationBinder>();\n\nfunction applicationKey(\n services: readonly Service<any, any>[],\n prefix = \"/api\",\n) {\n return JSON.stringify([prefix, services.map((service) => service.name)]);\n}\n\n/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n ir: BrickIR,\n bind: ApplicationBinder,\n) {\n const key = JSON.stringify([ir.prefix, ir.services]);\n if (buildBindings.has(key))\n throw new Error(\"Brick compiler: overlapping compiled app imports\");\n buildBindings.set(key, bind);\n try {\n const app = requireBrickApp((await load()).default);\n if (applicationKey(app.definition.services, app.definition.prefix) !== key)\n throw new Error(\n \"Brick compiler: app services/prefix changed; rebuild the application\",\n );\n return app;\n } finally {\n buildBindings.delete(key);\n }\n}\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 bind = buildBindings.get(\n applicationKey(options.services, options.prefix),\n );\n if (bind && options.mode !== \"generic\") return bind(options.services);\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 service.prepareContributions();\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 service.prepareContributions();\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;AAOA,MAAM,kBAAkB;AACxB,SAAS,aAAa,OAAyB;CAC7C,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,QAA4C,CAAC;EAAE,MAAM;EAAO,OAAO;CAAE,CAAC;CAC5E,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,EAAE,MAAM,UAAU,MAAM,IAAI;EAClC,IAAI,QAAQ,iBAAiB,OAAO;EACpC,IAAI,QAAQ,OAAO,SAAS,UAAU;GACpC,MAAM,WAAW,MAAM,QAAQ,IAAI,IAAI,OAAO,OAAO,OAAO,IAAI;GAChE,KAAK,MAAM,SAAS,UAClB,IAAI,SAAS,OAAO,UAAU,UAC5B,MAAM,KAAK;IAAE,MAAM;IAAO,OAAO,QAAQ;GAAE,CAAC;EAClD;CACF;CACA,OAAO;AACT;AAEA,SAAgB,iBACd,SACA,QACA,WACA,QACmB;CACnB,MAAM,aAAa,OAAO;CAC1B,MAAM,cAAc,QAAQ;CAC5B,MAAM,YACJ,WAAW,SACX,WAAW,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,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,UAC5B,QAAQ,qBAAqB;CAEjC,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,UACpB,QAAQ,qBAAqB;CAE/B,OAAO,aAAa,IAAI,SAAS,UAAU,SAAS;AACtD"}
|
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/server.ts","../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;;UAEiB;EACf;EACA,UAAU;;;;;;;;;;;;;;wBAoCI,qBAAqB,OAAM,wBAA6B;;;UCtCvD;EACf;EACA;EACA;;;wBAIc,eAAe,iBAAiB;;wBAwBhC,gBAAgB,OAAM,mBAAwB;;wBAa9C,uBACd,KAAK,QACL,OAAM,mBACL;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["_$__endpoints0.BrickApp","_$__compiler0.BrickIR"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/server.ts","../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;;UAEiB;EACf;EACA,UAAU;;;;;;;;;;;;;;wBAoCI,qBAAqB,OAAM,wBAA6B;;;UCtCvD;EACf;EACA;EACA;;;wBAIc,eAAe,iBAAiB;;wBAwBhC,gBAAgB,OAAM,mBAAwB;;wBAa9C,uBACd,KAAK,QACL,OAAM,mBACL;;;UCrBc;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;;;UCnDzC;EACf;EACA;EACA;;wBAGoB,eAAe,UAAS,mBAAqB,QAArBA;;;UCL7B;;EAEf;EACA;EACA;;EAEA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;MAAvBC;;;;;wBCVhC,uBAAuB,KAAK"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@brickkit/cli",
|
|
3
|
-
"version": "0.3.0-beta.
|
|
3
|
+
"version": "0.3.0-beta.2",
|
|
4
4
|
"description": "CLI and server engine for Brick-TS",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"format:check": "oxfmt --check ."
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@brickkit/core": "^0.3.0-beta.
|
|
52
|
+
"@brickkit/core": "^0.3.0-beta.2",
|
|
53
53
|
"@sinclair/typebox": "^0.34.0",
|
|
54
54
|
"elysia": "2.0.0-beta.29"
|
|
55
55
|
},
|