@brickkit/cli 0.3.0-beta.0 ā 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/README.md +6 -5
- package/dist/bin.js +6 -8
- package/dist/bin.js.map +1 -1
- package/dist/build.js +50 -31
- 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 +67 -4
- package/dist/compiler.d.ts.map +1 -1
- package/dist/compiler.js +2 -2
- package/dist/compiler2.d.ts +2 -2
- package/dist/compiler2.js +84 -63
- package/dist/compiler2.js.map +1 -1
- package/dist/index.d.ts +4 -59
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/vite.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,19 +57,20 @@ The server compiles specialized JavaScript handlers for all resource CRUD and
|
|
|
57
57
|
custom actions at startup, pre-renders documentation, and caches OpenAPI and
|
|
58
58
|
architecture JSON with definition/endpoint invalidation. Health retains live
|
|
59
59
|
uptime and timestamps. Build a
|
|
60
|
-
|
|
60
|
+
module whose default export is a `BrickApp` into a runnable Bun server with:
|
|
61
61
|
|
|
62
62
|
```sh
|
|
63
|
-
brick build src/
|
|
63
|
+
brick build src/app.ts --outdir dist/brick
|
|
64
64
|
bun dist/brick/server.js
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
-
|
|
68
|
-
|
|
67
|
+
Use the same app entry as `brick gen client`. The build preserves its selected
|
|
68
|
+
services, prefix, docs settings, endpoints, and Elysia hooks. Keep `.listen()`
|
|
69
|
+
in a separate server bootstrap.
|
|
69
70
|
|
|
70
71
|
This beta branch pins Elysia `2.0.0-beta.29`. `brick build` also precompiles
|
|
71
72
|
Elysia's HTTP handlers with its Bun AOT plugin and removes the runtime HTTP
|
|
72
|
-
compiler. Use `brick build src/
|
|
73
|
+
compiler. Use `brick build src/app.ts --no-aot` for a regular bundle.
|
|
73
74
|
Development and direct `brick()` calls still use runtime HTTP compilation;
|
|
74
75
|
both modes share the same services and Brick handlers.
|
|
75
76
|
|
package/dist/bin.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
+
import { i as loadBrickApp } from "./compiler2.js";
|
|
2
3
|
import { n as startDevServer, t as buildApplication } from "./build.js";
|
|
3
4
|
import { t as generateClientContract } from "./client-contract.js";
|
|
4
5
|
import { generateOpenApiSpec, getGlobalRegistry } from "@brickkit/core";
|
|
5
|
-
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
6
6
|
import { dirname, join, resolve } from "node:path";
|
|
7
|
-
import {
|
|
7
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
8
8
|
import { randomUUID } from "node:crypto";
|
|
9
9
|
//#region src/client-contract-file.ts
|
|
10
10
|
/** Generate a client contract without loading Vite or starting a server. */
|
|
@@ -12,8 +12,7 @@ async function writeClientContract(entryPath, outputPath) {
|
|
|
12
12
|
const entry = resolve(entryPath);
|
|
13
13
|
const output = resolve(outputPath ?? "_brick/contract.ts");
|
|
14
14
|
if (entry === output) throw new Error("Brick: contract output must not overwrite the app entry.");
|
|
15
|
-
const
|
|
16
|
-
if (!app || typeof app.endpoint !== "function" || !app.definition) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
15
|
+
const app = await loadBrickApp(entry);
|
|
17
16
|
const source = generateClientContract(app);
|
|
18
17
|
if (await readFile(output, "utf8").catch((error) => {
|
|
19
18
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -48,7 +47,8 @@ async function main() {
|
|
|
48
47
|
}
|
|
49
48
|
case "build": {
|
|
50
49
|
const entry = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
|
|
51
|
-
if (!entry) throw new Error("Usage: brick build <
|
|
50
|
+
if (!entry) throw new Error("Usage: brick build <app.ts> [--outdir <directory>] [--port <number>] [--no-aot]");
|
|
51
|
+
if (args.includes("--prefix") || args.includes("--no-request-logging")) throw new Error("Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.");
|
|
52
52
|
const value = (flag) => {
|
|
53
53
|
const index = args.indexOf(flag);
|
|
54
54
|
if (index === -1) return void 0;
|
|
@@ -59,9 +59,7 @@ async function main() {
|
|
|
59
59
|
const result = await buildApplication({
|
|
60
60
|
entry,
|
|
61
61
|
outdir: value("--outdir"),
|
|
62
|
-
prefix: value("--prefix"),
|
|
63
62
|
port: port === void 0 ? void 0 : Number(port),
|
|
64
|
-
requestLogging: !args.includes("--no-request-logging"),
|
|
65
63
|
aot: !args.includes("--no-aot")
|
|
66
64
|
});
|
|
67
65
|
for (const warning of result.ir.diagnostics) console.warn(`[Brick compiler] ${warning}`);
|
|
@@ -108,7 +106,7 @@ async function main() {
|
|
|
108
106
|
Usage:
|
|
109
107
|
brick dev [entry] [--port <number>] Start development server with live reload
|
|
110
108
|
brick start [entry] Start production server
|
|
111
|
-
brick build <
|
|
109
|
+
brick build <app.ts> [--outdir <dir>] [--no-aot] Compile a default-exported BrickApp into a Bun server
|
|
112
110
|
brick gen openapi [--output <file>] Generate OpenAPI 3.1 JSON specification
|
|
113
111
|
brick gen client <entry> [--output <file>] Generate a typed browser client contract
|
|
114
112
|
brick info Export architecture JSON schema
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","names":[],"sources":["../src/client-contract-file.ts","../src/bin.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {
|
|
1
|
+
{"version":3,"file":"bin.js","names":[],"sources":["../src/client-contract-file.ts","../src/bin.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { generateClientContract } from \"./client-contract\";\nimport { loadBrickApp } from \"./app-entry\";\n\n/** Generate a client contract without loading Vite or starting a server. */\nexport async function writeClientContract(\n entryPath: string,\n outputPath?: string,\n) {\n const entry = resolve(entryPath);\n const output = resolve(outputPath ?? \"_brick/contract.ts\");\n if (entry === output)\n throw new Error(\"Brick: contract output must not overwrite the app entry.\");\n const app = await loadBrickApp(entry);\n const source = generateClientContract(app);\n const previous = await readFile(output, \"utf8\").catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n return undefined;\n });\n if (previous !== source) {\n await mkdir(dirname(output), { recursive: true });\n const temporary = join(\n dirname(output),\n `.brick-contract-${randomUUID()}.tmp`,\n );\n try {\n await writeFile(temporary, source, { flag: \"wx\" });\n await rename(temporary, output);\n } finally {\n await rm(temporary, { force: true });\n }\n }\n return output;\n}\n","#!/usr/bin/env bun\nimport { startDevServer } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { getGlobalRegistry, generateOpenApiSpec } from \"@brickkit/core\";\n\nconst args = process.argv.slice(2);\nconst command = args[0] || \"dev\";\n\nasync function main() {\n switch (command) {\n case \"dev\":\n case \"start\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n const portArgIdx = args.indexOf(\"--port\");\n const port = portArgIdx !== -1 ? Number(args[portArgIdx + 1]) : 4000;\n\n await startDevServer({ entry, port });\n break;\n }\n\n case \"build\": {\n const entry = args[1] && !args[1].startsWith(\"-\") ? args[1] : undefined;\n if (!entry)\n throw new Error(\n \"Usage: brick build <app.ts> [--outdir <directory>] [--port <number>] [--no-aot]\",\n );\n if (args.includes(\"--prefix\") || args.includes(\"--no-request-logging\"))\n throw new Error(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n const value = (flag: string) => {\n const index = args.indexOf(flag);\n if (index === -1) return undefined;\n if (!args[index + 1] || args[index + 1]!.startsWith(\"--\"))\n throw new Error(`Missing value for ${flag}`);\n return args[index + 1];\n };\n const port = value(\"--port\");\n const result = await buildApplication({\n entry,\n outdir: value(\"--outdir\"),\n port: port === undefined ? undefined : Number(port),\n aot: !args.includes(\"--no-aot\"),\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n console.log(`Run: bun ${result.entry}`);\n break;\n }\n\n case \"gen\": {\n const subCommand = args[1];\n if (subCommand === \"client\") {\n const entry = args[2];\n if (!entry || entry.startsWith(\"-\"))\n throw new Error(\"Usage: brick gen client <entry> [--output <file>]\");\n if (\n args.length > 3 &&\n (args[3] !== \"--output\" ||\n !args[4] ||\n args[4].startsWith(\"-\") ||\n args.length > 5)\n )\n throw new Error(\"Usage: brick gen client <entry> [--output <file>]\");\n const output = await writeClientContract(entry, args[4]);\n console.log(`Client contract written to ${output}`);\n break;\n }\n if (subCommand === \"openapi\") {\n const outIdx = args.indexOf(\"--output\");\n const outputFile = outIdx !== -1 ? args[outIdx + 1] : undefined;\n\n const spec = generateOpenApiSpec();\n const jsonOutput = JSON.stringify(spec, null, 2);\n\n if (outputFile) {\n await Bun.write(outputFile, jsonOutput);\n console.log(`ā
OpenAPI 3.1 specification written to ${outputFile}`);\n } else {\n console.log(jsonOutput);\n }\n break;\n }\n console.error(\n `Unknown generator: ${subCommand}. Available: openapi, client`,\n );\n process.exit(1);\n break;\n }\n\n case \"info\":\n case \"services\": {\n const registry = getGlobalRegistry();\n console.log(JSON.stringify(registry.exportArchitecture(), null, 2));\n break;\n }\n\n default:\n console.log(`\nš§± Brick-TS CLI\n\nUsage:\n brick dev [entry] [--port <number>] Start development server with live reload\n brick start [entry] Start production server\n brick build <app.ts> [--outdir <dir>] [--no-aot] Compile a default-exported BrickApp into a Bun server\n brick gen openapi [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick gen client <entry> [--output <file>] Generate a typed browser client contract\n brick info Export architecture JSON schema\n`);\n process.exit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;GACF;GACA,IAAI,eAAe,WAAW;IAC5B,MAAM,SAAS,KAAK,QAAQ,UAAU;IACtC,MAAM,aAAa,WAAW,KAAK,KAAK,SAAS,KAAK,KAAA;IAEtD,MAAM,OAAO,oBAAoB;IACjC,MAAM,aAAa,KAAK,UAAU,MAAM,MAAM,CAAC;IAE/C,IAAI,YAAY;KACd,MAAM,IAAI,MAAM,YAAY,UAAU;KACtC,QAAQ,IAAI,0CAA0C,YAAY;IACpE,OACE,QAAQ,IAAI,UAAU;IAExB;GACF;GACA,QAAQ,MACN,sBAAsB,WAAW,6BACnC;GACA,QAAQ,KAAK,CAAC;GACd;EACF;EAEA,KAAK;EACL,KAAK,YAAY;GACf,MAAM,WAAW,kBAAkB;GACnC,QAAQ,IAAI,KAAK,UAAU,SAAS,mBAAmB,GAAG,MAAM,CAAC,CAAC;GAClE;EACF;EAEA;GACE,QAAQ,IAAI;;;;;;;;;;CAUjB;GACK,QAAQ,KAAK,CAAC;CAClB;AACF;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
package/dist/build.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
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
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
5
|
import { existsSync } from "fs";
|
|
5
|
-
import { resolve } from "path";
|
|
6
|
+
import { resolve as resolve$1 } from "path";
|
|
6
7
|
import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
|
|
7
|
-
import { dirname, join, resolve as resolve$1 } from "node:path";
|
|
8
|
-
import { pathToFileURL } from "node:url";
|
|
9
8
|
import { aot } from "elysia/plugin/aot/bun";
|
|
10
9
|
//#region src/request-logger.ts
|
|
11
10
|
function formatLog(method, path, status, elapsedMs) {
|
|
@@ -285,12 +284,14 @@ function brick(options = {}) {
|
|
|
285
284
|
prefix,
|
|
286
285
|
services
|
|
287
286
|
});
|
|
287
|
+
const paths = { ...spec.paths };
|
|
288
|
+
for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
|
|
289
|
+
...paths[path],
|
|
290
|
+
...operations
|
|
291
|
+
};
|
|
288
292
|
return {
|
|
289
293
|
...spec,
|
|
290
|
-
paths
|
|
291
|
-
...spec.paths,
|
|
292
|
-
...endpointPaths(endpointDefs)
|
|
293
|
-
}
|
|
294
|
+
paths
|
|
294
295
|
};
|
|
295
296
|
};
|
|
296
297
|
app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
|
|
@@ -308,10 +309,22 @@ function brick(options = {}) {
|
|
|
308
309
|
});
|
|
309
310
|
}
|
|
310
311
|
}
|
|
311
|
-
const registeredRoutes = /* @__PURE__ */ new
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
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
|
+
}
|
|
315
328
|
switch (method) {
|
|
316
329
|
case "GET":
|
|
317
330
|
app.get(path, handler);
|
|
@@ -327,13 +340,14 @@ function brick(options = {}) {
|
|
|
327
340
|
break;
|
|
328
341
|
case "DELETE": app.delete(path, handler);
|
|
329
342
|
}
|
|
330
|
-
registeredRoutes.
|
|
343
|
+
registeredRoutes.set(key, plugin);
|
|
331
344
|
};
|
|
332
|
-
const mountEndpoint = (def) => {
|
|
333
|
-
mountRoute(def.method, def.path, createEndpointHandler(def, services));
|
|
345
|
+
const mountEndpoint = (def, plugin = false) => {
|
|
346
|
+
mountRoute(def.method, def.path, createEndpointHandler(def, services), plugin);
|
|
334
347
|
endpointDefs.push(def);
|
|
335
348
|
endpointRevision++;
|
|
336
349
|
};
|
|
350
|
+
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
337
351
|
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
338
352
|
const brickApp = app;
|
|
339
353
|
Object.defineProperty(brickApp, "definition", { value: Object.freeze({
|
|
@@ -350,9 +364,18 @@ function brick(options = {}) {
|
|
|
350
364
|
mode: options.compiler === false ? "generic" : "specialized"
|
|
351
365
|
});
|
|
352
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");
|
|
353
|
-
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
|
+
}
|
|
354
374
|
return brickApp;
|
|
355
375
|
}
|
|
376
|
+
function jsonActionResult(value) {
|
|
377
|
+
return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
|
|
378
|
+
}
|
|
356
379
|
function htmlResponse(html) {
|
|
357
380
|
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
358
381
|
}
|
|
@@ -377,7 +400,7 @@ async function startDevServer(options = {}) {
|
|
|
377
400
|
const port = options.port ?? (Number(process.env.PORT) || 4e3);
|
|
378
401
|
const entry = options.entry;
|
|
379
402
|
if (entry) {
|
|
380
|
-
const resolvedEntry = resolve(process.cwd(), entry);
|
|
403
|
+
const resolvedEntry = resolve$1(process.cwd(), entry);
|
|
381
404
|
if (existsSync(resolvedEntry)) {
|
|
382
405
|
console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
|
|
383
406
|
await import(resolvedEntry);
|
|
@@ -403,31 +426,27 @@ async function startDevServer(options = {}) {
|
|
|
403
426
|
}
|
|
404
427
|
//#endregion
|
|
405
428
|
//#region src/build.ts
|
|
406
|
-
/**
|
|
429
|
+
/** Bundle an exported BrickApp with generated handlers and its original configuration. */
|
|
407
430
|
async function buildApplication(options) {
|
|
408
|
-
const entry = resolve
|
|
431
|
+
const entry = resolve(options.entry);
|
|
409
432
|
if (!await Bun.file(entry).exists()) throw new Error(`Brick compiler: entry not found: ${entry}`);
|
|
410
|
-
const outdir = resolve
|
|
433
|
+
const outdir = resolve(options.outdir ?? "dist/brick");
|
|
411
434
|
if (entry === join(outdir, "server.js") || entry === join(outdir, "routes.js")) throw new Error("Brick compiler: output would overwrite the application entry");
|
|
412
435
|
const port = options.port ?? 4e3;
|
|
413
436
|
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Brick compiler: port must be an integer between 0 and 65535");
|
|
414
|
-
await
|
|
415
|
-
const services =
|
|
416
|
-
if (!services.length) throw new Error("Brick compiler: entry registered no services; use a definitions module");
|
|
437
|
+
const app = await loadBrickApp(entry);
|
|
438
|
+
const services = [...app.definition.services];
|
|
417
439
|
const compilation = compileBrickApplication({
|
|
418
440
|
services,
|
|
419
|
-
prefix:
|
|
441
|
+
prefix: app.definition.prefix
|
|
420
442
|
});
|
|
421
443
|
await mkdir(dirname(outdir), { recursive: true });
|
|
422
444
|
const staging = await mkdtemp(join(dirname(outdir), ".brick-build-"));
|
|
423
445
|
try {
|
|
424
446
|
await Bun.write(join(staging, "routes.js"), emitCompiledApplication(compilation.ir));
|
|
425
|
-
const source = `import
|
|
426
|
-
import {
|
|
427
|
-
|
|
428
|
-
import { bind } from "./routes.js";
|
|
429
|
-
const services = getGlobalRegistry().list();
|
|
430
|
-
export const app = brick({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });
|
|
447
|
+
const source = `import { loadCompiledBrickApp } from "@brickkit/cli/compiler";
|
|
448
|
+
import { ir, bind } from "./routes.js";
|
|
449
|
+
export const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), ir, bind);
|
|
431
450
|
if (import.meta.main) {
|
|
432
451
|
const port = Number(process.env.PORT ?? ${port});
|
|
433
452
|
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid PORT");
|
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 { pathToFileURL } from \"node:url\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { compileBrickApplication, emitCompiledApplication } from \"./compiler\";\nimport { aot } from \"elysia/plugin/aot/bun\";\n\nexport interface BuildApplicationOptions {\n /** A module that registers services, without starting a server. */\n entry: string;\n outdir?: string;\n prefix?: string;\n port?: number;\n requestLogging?: boolean;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n}\n\n/** Analyze definitions and bundle the emitted handlers with the user's callbacks. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? \"dist/brick\");\n if (\n entry === join(outdir, \"server.js\") ||\n entry === join(outdir, \"routes.js\")\n )\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = options.port ?? 4000;\n if (!Number.isInteger(port) || port < 0 || port > 65535)\n throw new Error(\n \"Brick compiler: port must be an integer between 0 and 65535\",\n );\n await import(pathToFileURL(entry).href);\n const services = getGlobalRegistry().list();\n if (!services.length)\n throw new Error(\n \"Brick compiler: entry registered no services; use a definitions module\",\n );\n const compilation = compileBrickApplication({\n services,\n prefix: options.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const source = `import ${JSON.stringify(entry)};\nimport { brick } from \"@brickkit/cli\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { bind } from \"./routes.js\";\nconst services = getGlobalRegistry().list();\nexport const app = brick({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });\nif (import.meta.main) {\n const port = Number(process.env.PORT ?? ${port});\n if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(\"Invalid PORT\");\n app.listen(port);\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n const stop = async () => { await app.stop(); process.exit(0); };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n 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,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,IAAI,MACR,KAAK,SAAS,eAAe,GAC7B,KAAK,UAAU,YAAY,IAAI,MAAM,CAAC,IAAI,IAC5C;EACA,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;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"}
|
|
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,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AO,SACV,MAAM,IAAI,eAAe,OAAO,MAAM,iCAAiC;EACzE,MAAM,IAAI,MACR,KAAK,SAAS,eAAe,GAC7B,KAAK,UAAU,YAAY,IAAI,MAAM,CAAC,IAAI,IAC5C;EACA,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;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);
|