@brickkit/cli 0.3.0-beta.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.d.ts CHANGED
@@ -1 +1,5 @@
1
- export {}
1
+ import { Command } from "commander";
2
+ //#region src/bin.d.ts
3
+ export declare function createProgram(): Command;
4
+ //#endregion
5
+ //# sourceMappingURL=bin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.d.ts","names":[],"sources":["../src/bin.ts"],"mappings":";;wBAkDgB,iBAAiB"}
package/dist/bin.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env bun
2
- import { n as loadBrickApp, r as startDevServer, t as buildApplication } from "./build.js";
2
+ import { i as startProdServer, n as loadBrickApp, r as startDevServer, t as buildApplication } from "./build.js";
3
3
  import { t as generateClientContract } from "./client-contract.js";
4
4
  import { generateOpenApiSpec, getGlobalRegistry } from "@brickkit/core";
5
5
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
6
6
  import { dirname, join, resolve } from "node:path";
7
7
  import { randomUUID } from "node:crypto";
8
+ import { Command, InvalidArgumentError } from "commander";
8
9
  //#region src/client-contract-file.ts
9
10
  /** Generate a client contract without loading Vite or starting a server. */
10
11
  async function writeClientContract(entryPath, outputPath) {
@@ -28,96 +29,128 @@ async function writeClientContract(entryPath, outputPath) {
28
29
  return output;
29
30
  }
30
31
  //#endregion
32
+ //#region src/port-utils.ts
33
+ function parsePort(portStr, envPort) {
34
+ let port;
35
+ if (portStr !== void 0) port = Number(portStr);
36
+ else if (envPort !== void 0) port = Number(envPort);
37
+ else port = 4e3;
38
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port: ${port}. Port must be an integer between 1 and 65535`);
39
+ return port;
40
+ }
41
+ //#endregion
31
42
  //#region src/bin.ts
32
- const args = process.argv.slice(2);
33
- const command = args[0] || "dev";
34
- async function main() {
35
- switch (command) {
36
- case "dev":
37
- case "start": {
38
- const entry = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
39
- const portArgIdx = args.indexOf("--port");
40
- const port = portArgIdx !== -1 ? Number(args[portArgIdx + 1]) : 4e3;
41
- await startDevServer({
42
- entry,
43
- port
44
- });
45
- break;
46
- }
47
- case "build": {
48
- const entry = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
49
- if (!entry) throw new Error("Usage: brick build <app.ts> [--outdir <directory>] [--port <number>] [--no-aot]");
50
- 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.");
51
- const value = (flag) => {
52
- const index = args.indexOf(flag);
53
- if (index === -1) return void 0;
54
- if (!args[index + 1] || args[index + 1].startsWith("--")) throw new Error(`Missing value for ${flag}`);
55
- return args[index + 1];
56
- };
57
- const port = value("--port");
58
- const result = await buildApplication({
59
- entry,
60
- outdir: value("--outdir"),
61
- port: port === void 0 ? void 0 : Number(port),
62
- aot: !args.includes("--no-aot")
63
- });
64
- for (const warning of result.ir.diagnostics) console.warn(`[Brick compiler] ${warning}`);
65
- console.log(`Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`);
66
- console.log(`IR: ${result.outdir}/brick-ir.json`);
67
- console.log(`Run: bun ${result.entry}`);
68
- break;
69
- }
70
- case "gen": {
71
- const subCommand = args[1];
72
- if (subCommand === "client") {
73
- const entry = args[2];
74
- if (!entry || entry.startsWith("-")) throw new Error("Usage: brick gen client <entry> [--output <file>]");
75
- if (args.length > 3 && (args[3] !== "--output" || !args[4] || args[4].startsWith("-") || args.length > 5)) throw new Error("Usage: brick gen client <entry> [--output <file>]");
76
- const output = await writeClientContract(entry, args[4]);
77
- console.log(`Client contract written to ${output}`);
78
- break;
79
- }
80
- if (subCommand === "openapi") {
81
- const outIdx = args.indexOf("--output");
82
- const outputFile = outIdx !== -1 ? args[outIdx + 1] : void 0;
83
- const spec = generateOpenApiSpec();
84
- const jsonOutput = JSON.stringify(spec, null, 2);
85
- if (outputFile) {
86
- await Bun.write(outputFile, jsonOutput);
87
- console.log(`✅ OpenAPI 3.1 specification written to ${outputFile}`);
88
- } else console.log(jsonOutput);
89
- break;
90
- }
91
- console.error(`Unknown generator: ${subCommand}. Available: openapi, client`);
92
- process.exit(1);
93
- break;
94
- }
95
- case "info":
96
- case "services": {
97
- const registry = getGlobalRegistry();
98
- console.log(JSON.stringify(registry.exportArchitecture(), null, 2));
99
- break;
100
- }
101
- default:
102
- console.log(`
103
- 🧱 Brick-TS CLI
43
+ const CLI_VERSION = "0.3.0";
44
+ const PORT_HELP = "Port to listen on (CLI --port overrides PORT env, default 4000)";
45
+ const PORT_RESOLUTION_HELP = `
46
+ Port Resolution (dev/start commands):
47
+ - CLI --port flag takes precedence
48
+ - Falls back to PORT environment variable
49
+ - Defaults to 4000 if neither is set
50
+ - Valid range: 1-65535
104
51
 
52
+ Examples:
53
+ brick dev app.ts # port 4000 (default)
54
+ brick dev app.ts --port 5000 # port 5000 (explicit)
55
+ PORT=3000 brick dev app.ts # port 3000 (from env)
56
+ brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)
57
+ `;
58
+ function parsePortOption(value) {
59
+ try {
60
+ return parsePort(value, void 0);
61
+ } catch (err) {
62
+ throw new InvalidArgumentError(err.message);
63
+ }
64
+ }
65
+ function parseFileOption(value, usage) {
66
+ if (value.startsWith("-")) throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);
67
+ return value;
68
+ }
69
+ function resolveDevPort(cliPort) {
70
+ if (cliPort !== void 0) return cliPort;
71
+ return parsePort(void 0, process.env.PORT);
72
+ }
73
+ function createProgram() {
74
+ const program = new Command();
75
+ program.name("brick").description("🧱 Brick-TS CLI").version(CLI_VERSION).showHelpAfterError().addHelpText("after", `
105
76
  Usage:
106
- brick dev [entry] [--port <number>] Start development server with live reload
107
- brick start [entry] Start production server
108
- brick build <app.ts> [--outdir <dir>] [--no-aot] Compile a default-exported BrickApp into a Bun server
109
- brick gen openapi [--output <file>] Generate OpenAPI 3.1 JSON specification
110
- brick gen client <entry> [--output <file>] Generate a typed browser client contract
111
- brick info Export architecture JSON schema
112
- `);
113
- process.exit(0);
77
+ brick dev [entry] [--port <number>] Start development server with live reload
78
+ brick start [entry] [--port <number>] Start production server
79
+ brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server
80
+ brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification
81
+ brick gen client <entry> [--output <file>] Generate a typed browser client contract
82
+ brick info <entry> Export architecture JSON schema
83
+ ${PORT_RESOLUTION_HELP}`);
84
+ program.command("dev").description("Start development server with live reload").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
85
+ const port = resolveDevPort(opts.port);
86
+ await startDevServer({
87
+ entry,
88
+ port
89
+ });
90
+ });
91
+ program.command("start").description("Start production server").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
92
+ const port = resolveDevPort(opts.port);
93
+ await startProdServer({
94
+ entry,
95
+ port
96
+ });
97
+ });
98
+ program.command("build").description("Compile a default-exported BrickApp into a Bun server").argument("<entry>", "Application entry file (must default-export a BrickApp)").option("--outdir <dir>", "Output directory", (v) => parseFileOption(v, "Usage: brick build <app.ts> [--outdir <directory>]")).option("--port <number>", "Default listening port", parsePortOption).option("--no-aot", "Disable ahead-of-time compilation").option("--prefix <path>", "DEPRECATED: configure prefix in brick() app instead").option("--no-request-logging", "DEPRECATED: configure requestLogging in brick() app instead").action(async (entry, opts) => {
99
+ if (opts.prefix !== void 0 || opts.requestLogging === false) throw new Error("Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.");
100
+ const result = await buildApplication({
101
+ entry,
102
+ outdir: opts.outdir,
103
+ port: opts.port,
104
+ aot: opts.aot
105
+ });
106
+ for (const warning of result.ir.diagnostics) console.warn(`[Brick compiler] ${warning}`);
107
+ console.log(`Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`);
108
+ console.log(`IR: ${result.outdir}/brick-ir.json`);
109
+ console.log(`Run: bun ${result.entry}`);
110
+ });
111
+ const gen = program.command("gen").description("Generate artifacts from a BrickApp entry").argument("[subcommand]", "Generator to run (openapi, client)").action((subcommand) => {
112
+ console.error(`Unknown generator: ${subcommand ?? "(none)"}. Available: openapi, client`);
113
+ process.exit(1);
114
+ });
115
+ gen.command("openapi").description("Generate OpenAPI 3.1 JSON specification").argument("<entry>", "Application entry file").option("--output <file>", "Write specification to file instead of stdout", (v) => parseFileOption(v, "Usage: brick gen openapi <entry> [--output <file>]")).action(async (entry, opts) => {
116
+ const app = await loadBrickApp(entry);
117
+ const spec = generateOpenApiSpec({
118
+ services: [...app.definition.services],
119
+ prefix: app.definition.prefix
120
+ });
121
+ const jsonOutput = JSON.stringify(spec, null, 2);
122
+ if (opts.output) {
123
+ await Bun.write(opts.output, jsonOutput);
124
+ console.log(`✅ OpenAPI 3.1 specification written to ${opts.output}`);
125
+ } else console.log(jsonOutput);
126
+ });
127
+ gen.command("client").description("Generate a typed browser client contract").argument("<entry>", "Application entry file").option("--output <file>", "Write contract to file (default _brick/contract.ts)", (v) => parseFileOption(v, "Usage: brick gen client <entry> [--output <file>]")).action(async (entry, opts) => {
128
+ const output = await writeClientContract(entry, opts.output);
129
+ console.log(`Client contract written to ${output}`);
130
+ });
131
+ program.command("info").alias("services").description("Export architecture JSON schema").argument("<entry>", "Application entry file").action(async (entry) => {
132
+ const app = await loadBrickApp(entry);
133
+ const architecture = getGlobalRegistry().exportArchitecture(app.definition);
134
+ console.log(JSON.stringify(architecture, null, 2));
135
+ });
136
+ return program;
137
+ }
138
+ async function main() {
139
+ const program = createProgram();
140
+ if (process.argv.slice(2).length === 0) {
141
+ const port = parsePort(void 0, process.env.PORT);
142
+ await startDevServer({ port });
143
+ return;
114
144
  }
145
+ await program.parseAsync(process.argv);
115
146
  }
116
147
  main().catch((err) => {
148
+ if (err?.exitCode !== void 0) process.exit(err.exitCode);
149
+ if (err?.code?.startsWith?.("commander.")) process.exit(1);
117
150
  console.error("Fatal error:", err);
118
151
  process.exit(1);
119
152
  });
120
153
  //#endregion
121
- export {};
154
+ export { createProgram };
122
155
 
123
156
  //# sourceMappingURL=bin.js.map
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 { 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(0);\n }\n}\n\nmain().catch((err) => {\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;AAOA,eAAsB,oBACpB,WACA,YACA;CACA,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,SAAS,QAAQ,cAAc,oBAAoB;CACzD,IAAI,UAAU,QACZ,MAAM,IAAI,MAAM,0DAA0D;CAC5E,MAAM,MAAM,MAAM,aAAa,KAAK;CACpC,MAAM,SAAS,uBAAuB,GAAG;CAKzC,IAAI,MAJmB,SAAS,QAAQ,MAAM,CAAC,CAAC,OAAO,UAAU;EAC/D,IAAI,MAAM,SAAS,UAAU,MAAM;CAErC,CAAC,MACgB,QAAQ;EACvB,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EAChD,MAAM,YAAY,KAChB,QAAQ,MAAM,GACd,mBAAmB,WAAW,EAAE,KAClC;EACA,IAAI;GACF,MAAM,UAAU,WAAW,QAAQ,EAAE,MAAM,KAAK,CAAC;GACjD,MAAM,OAAO,WAAW,MAAM;EAChC,UAAU;GACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;EACrC;CACF;CACA,OAAO;AACT;;;AC7BA,MAAM,OAAO,QAAQ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-file.ts","../src/port-utils.ts","../package.json","../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","export function parsePort(\n portStr: string | undefined,\n envPort?: string | undefined,\n): number {\n let port: number | undefined;\n if (portStr !== undefined) {\n port = Number(portStr);\n } else if (envPort !== undefined) {\n port = Number(envPort);\n } else {\n port = 4000;\n }\n\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n return port;\n}\n","","#!/usr/bin/env bun\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { startDevServer, startProdServer } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { generateOpenApiSpec, getGlobalRegistry } from \"@brickkit/core\";\nimport { parsePort } from \"./port-utils\";\nimport { loadBrickApp } from \"./app-entry\";\nimport cliPkg from \"../package.json\";\n\n// Single source of truth for the CLI version (inlined at build time).\nconst CLI_VERSION: string = cliPkg.version;\n\nconst PORT_HELP =\n \"Port to listen on (CLI --port overrides PORT env, default 4000)\";\n\nconst PORT_RESOLUTION_HELP = `\nPort Resolution (dev/start commands):\n - CLI --port flag takes precedence\n - Falls back to PORT environment variable\n - Defaults to 4000 if neither is set\n - Valid range: 1-65535\n\nExamples:\n brick dev app.ts # port 4000 (default)\n brick dev app.ts --port 5000 # port 5000 (explicit)\n PORT=3000 brick dev app.ts # port 3000 (from env)\n brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)\n`;\n\nfunction parsePortOption(value: string): number {\n try {\n return parsePort(value, undefined);\n } catch (err) {\n throw new InvalidArgumentError((err as Error).message);\n }\n}\n\nfunction parseFileOption(value: string, usage: string): string {\n if (value.startsWith(\"-\")) {\n throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);\n }\n return value;\n}\n\nfunction resolveDevPort(cliPort: number | undefined): number {\n if (cliPort !== undefined) return cliPort;\n return parsePort(undefined, process.env.PORT);\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name(\"brick\")\n .description(\"🧱 Brick-TS CLI\")\n .version(CLI_VERSION)\n .showHelpAfterError()\n .addHelpText(\n \"after\",\n `\nUsage:\n brick dev [entry] [--port <number>] Start development server with live reload\n brick start [entry] [--port <number>] Start production server\n brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server\n brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick gen client <entry> [--output <file>] Generate a typed browser client contract\n brick info <entry> Export architecture JSON schema\n${PORT_RESOLUTION_HELP}`,\n );\n\n program\n .command(\"dev\")\n .description(\"Start development server with live reload\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(async (entry: string | undefined, opts: { port?: number }) => {\n const port = resolveDevPort(opts.port);\n await startDevServer({ entry, port });\n });\n\n program\n .command(\"start\")\n .description(\"Start production server\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(async (entry: string | undefined, opts: { port?: number }) => {\n const port = resolveDevPort(opts.port);\n await startProdServer({ entry, port });\n });\n\n program\n .command(\"build\")\n .description(\"Compile a default-exported BrickApp into a Bun server\")\n .argument(\n \"<entry>\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--outdir <dir>\", \"Output directory\", (v: string) =>\n parseFileOption(v, \"Usage: brick build <app.ts> [--outdir <directory>]\"),\n )\n .option(\"--port <number>\", \"Default listening port\", parsePortOption)\n .option(\"--no-aot\", \"Disable ahead-of-time compilation\")\n .option(\n \"--prefix <path>\",\n \"DEPRECATED: configure prefix in brick() app instead\",\n )\n .option(\n \"--no-request-logging\",\n \"DEPRECATED: configure requestLogging in brick() app instead\",\n )\n .action(\n async (\n entry: string,\n opts: {\n outdir?: string;\n port?: number;\n aot?: boolean;\n prefix?: string;\n requestLogging?: boolean;\n },\n ) => {\n if (opts.prefix !== undefined || opts.requestLogging === false) {\n throw new Error(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n }\n const result = await buildApplication({\n entry,\n outdir: opts.outdir,\n port: opts.port,\n aot: opts.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 },\n );\n\n const gen = program\n .command(\"gen\")\n .description(\"Generate artifacts from a BrickApp entry\")\n .argument(\"[subcommand]\", \"Generator to run (openapi, client)\")\n .action((subcommand: string | undefined) => {\n console.error(\n `Unknown generator: ${subcommand ?? \"(none)\"}. Available: openapi, client`,\n );\n process.exit(1);\n });\n\n gen\n .command(\"openapi\")\n .description(\"Generate OpenAPI 3.1 JSON specification\")\n .argument(\"<entry>\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write specification to file instead of stdout\",\n (v: string) =>\n parseFileOption(\n v,\n \"Usage: brick gen openapi <entry> [--output <file>]\",\n ),\n )\n .action(async (entry: string, opts: { output?: string }) => {\n const app = await loadBrickApp(entry);\n const spec = generateOpenApiSpec({\n services: [...app.definition.services],\n prefix: app.definition.prefix,\n });\n const jsonOutput = JSON.stringify(spec, null, 2);\n if (opts.output) {\n await Bun.write(opts.output, jsonOutput);\n console.log(`✅ OpenAPI 3.1 specification written to ${opts.output}`);\n } else {\n console.log(jsonOutput);\n }\n });\n\n gen\n .command(\"client\")\n .description(\"Generate a typed browser client contract\")\n .argument(\"<entry>\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write contract to file (default _brick/contract.ts)\",\n (v: string) =>\n parseFileOption(v, \"Usage: brick gen client <entry> [--output <file>]\"),\n )\n .action(async (entry: string, opts: { output?: string }) => {\n const output = await writeClientContract(entry, opts.output);\n console.log(`Client contract written to ${output}`);\n });\n\n program\n .command(\"info\")\n .alias(\"services\")\n .description(\"Export architecture JSON schema\")\n .argument(\"<entry>\", \"Application entry file\")\n .action(async (entry: string) => {\n const app = await loadBrickApp(entry);\n const architecture = getGlobalRegistry().exportArchitecture(\n app.definition,\n );\n console.log(JSON.stringify(architecture, null, 2));\n });\n\n return program;\n}\n\nasync function main() {\n const program = createProgram();\n // Preserve legacy behavior: bare `brick` starts the dev server.\n const userArgs = process.argv.slice(2);\n if (userArgs.length === 0) {\n const port = parsePort(undefined, process.env.PORT);\n await startDevServer({ port });\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((err) => {\n // Commander already prints validation errors (missing arg, unknown option,\n // invalid port) and exits. Only print Fatal error for action failures.\n if (err?.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n if (err?.code?.startsWith?.(\"commander.\")) {\n process.exit(1);\n }\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;AAOA,eAAsB,oBACpB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W,wBAAwB,CAAC,CAC7C,OACC,mBACA,wDACC,MACC,gBAAgB,GAAG,mDAAmD,CAC1E,CAAC,CACA,OAAO,OAAO,OAAe,SAA8B;EAC1D,MAAM,SAAS,MAAM,oBAAoB,OAAO,KAAK,MAAM;EAC3D,QAAQ,IAAI,8BAA8B,QAAQ;CACpD,CAAC;CAEH,QACG,QAAQ,MAAM,CAAC,CACf,MAAM,UAAU,CAAC,CACjB,YAAY,iCAAiC,CAAC,CAC9C,SAAS,WAAW,wBAAwB,CAAC,CAC7C,OAAO,OAAO,UAAkB;EAC/B,MAAM,MAAM,MAAM,aAAa,KAAK;EACpC,MAAM,eAAe,kBAAkB,CAAC,CAAC,mBACvC,IAAI,UACN;EACA,QAAQ,IAAI,KAAK,UAAU,cAAc,MAAM,CAAC,CAAC;CACnD,CAAC;CAEH,OAAO;AACT;AAEA,eAAe,OAAO;CACpB,MAAM,UAAU,cAAc;CAG9B,IADiB,QAAQ,KAAK,MAAM,CACzB,CAAC,CAAC,WAAW,GAAG;EACzB,MAAM,OAAO,UAAU,KAAA,GAAW,QAAQ,IAAI,IAAI;EAClD,MAAM,eAAe,EAAE,KAAK,CAAC;EAC7B;CACF;CACA,MAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAGpB,IAAI,KAAK,aAAa,KAAA,GACpB,QAAQ,KAAK,IAAI,QAAQ;CAE3B,IAAI,KAAK,MAAM,aAAa,YAAY,GACtC,QAAQ,KAAK,CAAC;CAEhB,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/dist/build.js CHANGED
@@ -1,40 +1,136 @@
1
1
  import { i as emitCompiledApplication, n as compileBrickApplication } from "./compiler2.js";
2
- import { brick, getGlobalRegistry, requireBrickApp } from "@brickkit/core";
3
- import { existsSync } from "fs";
2
+ import { brick, getPluginActionRoute, requireBrickApp, resetGlobalRegistry } from "@brickkit/core";
3
+ import { existsSync, watch } from "fs";
4
4
  import { resolve } from "path";
5
5
  import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
6
6
  import { dirname, join, resolve as resolve$1 } from "node:path";
7
7
  import { aot } from "elysia/plugin/aot/bun";
8
8
  import { pathToFileURL } from "node:url";
9
9
  //#region src/runner.ts
10
- async function startDevServer(options = {}) {
11
- const port = options.port ?? (Number(process.env.PORT) || 4e3);
12
- const entry = options.entry;
13
- if (entry) {
14
- const resolvedEntry = resolve(process.cwd(), entry);
15
- if (existsSync(resolvedEntry)) {
16
- console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
17
- await import(resolvedEntry);
18
- } else console.warn(`[Brick-TS] Specified entry not found: ${resolvedEntry}`);
10
+ let currentServer = null;
11
+ async function closeServer() {
12
+ if (currentServer) try {
13
+ await currentServer.stop?.();
14
+ currentServer = null;
15
+ await new Promise((resolve) => setTimeout(resolve, 100));
16
+ } catch (err) {
17
+ console.error("Error closing server:", err);
19
18
  }
20
- const services = getGlobalRegistry().list();
21
- console.log(`\n🧱 Brick-TS Development Server`);
19
+ }
20
+ async function createServer(options, label) {
21
+ let port;
22
+ if (options.port !== void 0) port = options.port;
23
+ else if (process.env.PORT !== void 0 && process.env.PORT !== "") port = Number(process.env.PORT);
24
+ else port = 4e3;
25
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port: ${port}. Port must be an integer between 1 and 65535`);
26
+ const app = brick({
27
+ port,
28
+ prefix: options.prefix
29
+ });
30
+ currentServer = await app.listen({ port });
31
+ const prefix = app.definition.prefix;
32
+ const services = app.definition.services;
33
+ console.log(`\n🧱 Brick-TS ${label} Server`);
22
34
  console.log(` Registered Services: ${services.length}`);
23
35
  for (const svc of services) {
24
- console.log(` • ${svc.name} (${svc.listActions().length} actions)`);
25
- if (typeof svc.listResources === "function") for (const res of svc.listResources()) console.log(` -> Resource: /api/${res.name} (REST: GET, POST, /:id: GET, PATCH, DELETE)`);
26
- for (const act of svc.listActions()) console.log(` -> Action: /api/${svc.name}/${act.name}`);
36
+ const actions = svc.listActions();
37
+ console.log(` • ${svc.name} (${actions.length} actions)`);
38
+ for (const act of actions) {
39
+ const pluginRoute = getPluginActionRoute(act, prefix);
40
+ if (pluginRoute === false) continue;
41
+ const method = pluginRoute?.method ?? act.config.method ?? "POST";
42
+ const path = pluginRoute?.path ?? act.config.path ?? `${prefix}/${svc.name}/${act.name}`;
43
+ console.log(` -> ${method.padEnd(6)} ${path}`);
44
+ }
45
+ }
46
+ console.log(`\n⚡ API Gateway running on: http://localhost:${port}`);
47
+ console.log(`🩺 Health check: http://localhost:${port}/_health`);
48
+ console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\n`);
49
+ return app;
50
+ }
51
+ async function startProdServer(options = {}) {
52
+ const entry = options.entry;
53
+ if (entry) {
54
+ const resolvedEntry = resolve(process.cwd(), entry);
55
+ if (!existsSync(resolvedEntry)) {
56
+ console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);
57
+ process.exit(1);
58
+ }
59
+ console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
60
+ await import(resolvedEntry);
27
61
  }
62
+ const port = options.port !== void 0 ? options.port : process.env.PORT !== void 0 && process.env.PORT !== "" ? Number(process.env.PORT) : 4e3;
63
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port: ${port}. Port must be an integer between 1 and 65535`);
28
64
  const app = brick({
29
65
  port,
30
66
  prefix: options.prefix
31
67
  });
68
+ const prefix = app.definition.prefix;
69
+ const services = app.definition.services;
70
+ console.log(`\n🧱 Brick-TS Production Server`);
71
+ console.log(` Registered Services: ${services.length}`);
72
+ for (const svc of services) {
73
+ const actions = svc.listActions();
74
+ console.log(` • ${svc.name} (${actions.length} actions)`);
75
+ for (const act of actions) {
76
+ const pluginRoute = getPluginActionRoute(act, prefix);
77
+ if (pluginRoute === false) continue;
78
+ const method = pluginRoute?.method ?? act.config.method ?? "POST";
79
+ const path = pluginRoute?.path ?? act.config.path ?? `${prefix}/${svc.name}/${act.name}`;
80
+ console.log(` -> ${method.padEnd(6)} ${path}`);
81
+ }
82
+ }
32
83
  app.listen(port);
33
84
  console.log(`\n⚡ API Gateway running on: http://localhost:${port}`);
34
85
  console.log(`🩺 Health check: http://localhost:${port}/_health`);
35
86
  console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\n`);
36
87
  return app;
37
88
  }
89
+ async function startDevServer(options = {}) {
90
+ const entry = options.entry;
91
+ if (entry) {
92
+ const resolvedEntry = resolve(process.cwd(), entry);
93
+ if (!existsSync(resolvedEntry)) {
94
+ console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);
95
+ process.exit(1);
96
+ }
97
+ console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
98
+ await import(resolvedEntry);
99
+ }
100
+ const app = await createServer(options, "Development");
101
+ const cwd = process.cwd();
102
+ const watchDirs = [
103
+ resolve(cwd, "src"),
104
+ resolve(cwd, "app"),
105
+ entry ? resolve(cwd, entry).replace(/\/[^/]+$/, "") : null
106
+ ].filter(Boolean);
107
+ let isRestarting = false;
108
+ for (const dir of watchDirs) {
109
+ if (!existsSync(dir)) continue;
110
+ watch(dir, { recursive: true }, async (eventType, filename) => {
111
+ if (!filename || filename.includes("node_modules") || isRestarting) return;
112
+ isRestarting = true;
113
+ await new Promise((resolve) => setTimeout(resolve, 100));
114
+ console.log(`\n📝 Changes detected in ${filename}. Restarting server...`);
115
+ try {
116
+ await closeServer();
117
+ resetGlobalRegistry();
118
+ if (entry) {
119
+ const resolvedEntry = resolve(process.cwd(), entry);
120
+ if (existsSync(resolvedEntry)) await import(resolvedEntry);
121
+ }
122
+ await createServer(options, "Development");
123
+ } catch (err) {
124
+ console.error("Error restarting server:", err);
125
+ isRestarting = false;
126
+ return;
127
+ }
128
+ isRestarting = false;
129
+ });
130
+ }
131
+ console.log(`\n👀 Watching for changes in: ${watchDirs.join(", ")}`);
132
+ return app;
133
+ }
38
134
  //#endregion
39
135
  //#region src/app-entry.ts
40
136
  async function loadBrickApp(entry) {
@@ -50,7 +146,7 @@ async function buildApplication(options) {
50
146
  const outdir = resolve$1(options.outdir ?? "dist/brick");
51
147
  if (entry === join(outdir, "server.js") || entry === join(outdir, "routes.js")) throw new Error("Brick compiler: output would overwrite the application entry");
52
148
  const port = options.port ?? 4e3;
53
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Brick compiler: port must be an integer between 0 and 65535");
149
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Brick compiler: port must be an integer between 1 and 65535");
54
150
  const app = await loadBrickApp(entry);
55
151
  const services = [...app.definition.services];
56
152
  const compilation = compileBrickApplication({
@@ -66,7 +162,7 @@ import { ir, bind } from "./routes.js";
66
162
  export const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), ir, bind);
67
163
  if (import.meta.main) {
68
164
  const port = Number(process.env.PORT ?? ${port});
69
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid PORT");
165
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid PORT: must be between 1 and 65535");
70
166
  app.listen(port);
71
167
  console.log("Brick compiled server listening on http://localhost:" + app.server.port);
72
168
  const stop = async () => { await app.stop(); process.exit(0); };
@@ -109,6 +205,6 @@ if (import.meta.main) {
109
205
  }
110
206
  }
111
207
  //#endregion
112
- export { loadBrickApp as n, startDevServer as r, buildApplication as t };
208
+ export { startProdServer as i, loadBrickApp as n, startDevServer as r, buildApplication as t };
113
209
 
114
210
  //# sourceMappingURL=build.js.map
package/dist/build.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","names":["resolve","resolve"],"sources":["../src/runner.ts","../src/app-entry.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { getGlobalRegistry, brick } from \"@brickkit/core\";\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 { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { isBrickApp, requireBrickApp, type BrickApp } from \"@brickkit/core\";\n\nexport { isBrickApp, requireBrickApp, type BrickApp };\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 { 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/core\";\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":";;;;;;;;;AAUA,eAAsB,eAAe,UAA4B,CAAC,GAAG;CACnE,MAAM,OAAO,QAAQ,SAAS,OAAO,QAAQ,IAAI,IAAI,KAAK;CAC1D,MAAM,QAAQ,QAAQ;CAEtB,IAAI,OAAO;EACT,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,GAAG,KAAK;EAClD,IAAI,WAAW,aAAa,GAAG;GAC7B,QAAQ,IAAI,yCAAyC,eAAe;GACpE,MAAM,OAAO;EACf,OACE,QAAQ,KAAK,yCAAyC,eAAe;CAEzE;CAGA,MAAM,WADW,kBACO,CAAC,CAAC,KAAK;CAE/B,QAAQ,IAAI,kCAAkC;CAC9C,QAAQ,IAAI,2BAA2B,SAAS,QAAQ;CAExD,KAAK,MAAM,OAAO,UAAU;EAC1B,QAAQ,IAAI,QAAQ,IAAI,KAAK,IAAI,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU;EACpE,IAAI,OAAQ,IAAY,kBAAkB,YACxC,KAAK,MAAM,OAAQ,IAAY,cAAc,GAC3C,QAAQ,IACN,0BAA0B,IAAI,KAAK,6CACrC;EAGJ,KAAK,MAAM,OAAO,IAAI,YAAY,GAChC,QAAQ,IAAI,0BAA0B,IAAI,KAAK,GAAG,IAAI,MAAM;CAEhE;CAEA,MAAM,MAAM,MAAM;EAChB;EACA,QAAQ,QAAQ;CAClB,CAAC;CAED,IAAI,OAAO,IAAI;CAEf,QAAQ,IAAI,gDAAgD,MAAM;CAClE,QAAQ,IAAI,4CAA4C,KAAK,SAAS;CACtE,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QAAQ;GACR,QAAQ;GACR,WAAW;GACX,SACE,QAAQ,QAAQ,QACZ,CAAC,IACD,CAAC,IAAI,KAAK,SAAS,UAAU,GAAG;IAAE,QAAQ;IAAO,OAAO;GAAK,CAAC,CAAC;EACvE,CAAC;EACD,IAAI,CAAC,OAAO,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"}
1
+ {"version":3,"file":"build.js","names":["resolve","resolve"],"sources":["../src/runner.ts","../src/app-entry.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"fs\";\nimport { watch } from \"fs\";\nimport { resolve } from \"path\";\nimport {\n brick,\n getPluginActionRoute,\n resetGlobalRegistry,\n} from \"@brickkit/core\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n}\n\nlet currentServer: any = null;\n\nasync function closeServer() {\n if (currentServer) {\n try {\n await currentServer.stop?.();\n currentServer = null;\n await new Promise((resolve) => setTimeout(resolve, 100));\n } catch (err) {\n console.error(\"Error closing server:\", err);\n }\n }\n}\n\nasync function createServer(options: DevServerOptions, label: string) {\n let port: number;\n if (options.port !== undefined) {\n port = options.port;\n } else if (process.env.PORT !== undefined && process.env.PORT !== \"\") {\n port = Number(process.env.PORT);\n } else {\n port = 4000;\n }\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\n });\n\n currentServer = await app.listen({ port });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS ${label} Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\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\nexport async function startProdServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n }\n\n const port =\n options.port !== undefined\n ? options.port\n : process.env.PORT !== undefined && process.env.PORT !== \"\"\n ? Number(process.env.PORT)\n : 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\n });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS Production Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\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\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n }\n\n const app = await createServer(options, \"Development\");\n\n const cwd = process.cwd();\n const watchDirs = [\n resolve(cwd, \"src\"),\n resolve(cwd, \"app\"),\n entry ? resolve(cwd, entry).replace(/\\/[^/]+$/, \"\") : null,\n ].filter(Boolean) as string[];\n\n let isRestarting = false;\n\n for (const dir of watchDirs) {\n if (!existsSync(dir)) continue;\n\n watch(dir, { recursive: true }, async (eventType, filename) => {\n if (!filename || filename.includes(\"node_modules\") || isRestarting)\n return;\n\n isRestarting = true;\n\n await new Promise((resolve) => setTimeout(resolve, 100));\n\n console.log(`\\n📝 Changes detected in ${filename}. Restarting server...`);\n\n try {\n await closeServer();\n resetGlobalRegistry();\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (existsSync(resolvedEntry)) {\n await import(resolvedEntry);\n }\n }\n\n await createServer(options, \"Development\");\n } catch (err) {\n console.error(\"Error restarting server:\", err);\n isRestarting = false;\n return;\n }\n\n isRestarting = false;\n });\n }\n\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n\n return app;\n}\n","import { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { isBrickApp, requireBrickApp, type BrickApp } from \"@brickkit/core\";\n\nexport { isBrickApp, requireBrickApp, type BrickApp };\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 { 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 < 1 || port > 65535)\n throw new Error(\n \"Brick compiler: port must be an integer between 1 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/core\";\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 < 1 || port > 65535) throw new Error(\"Invalid PORT: must be between 1 and 65535\");\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":";;;;;;;;;AAeA,IAAI,gBAAqB;AAEzB,eAAe,cAAc;CAC3B,IAAI,eACF,IAAI;EACF,MAAM,cAAc,OAAO;EAC3B,gBAAgB;EAChB,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;CACzD,SAAS,KAAK;EACZ,QAAQ,MAAM,yBAAyB,GAAG;CAC5C;AAEJ;AAEA,eAAe,aAAa,SAA2B,OAAe;CACpE,IAAI;CACJ,IAAI,QAAQ,SAAS,KAAA,GACnB,OAAO,QAAQ;MACV,IAAI,QAAQ,IAAI,SAAS,KAAA,KAAa,QAAQ,IAAI,SAAS,IAChE,OAAO,OAAO,QAAQ,IAAI,IAAI;MAE9B,OAAO;CAET,IAAI,CAAC,OAAO,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,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"}
@@ -37,6 +37,8 @@ function addServiceActions(service, prefix, contract, types, schemas) {
37
37
  kind: "action",
38
38
  name: action.name,
39
39
  serviceName: service.name,
40
+ ...action.plugin ? { plugin: action.plugin } : pluginRoute?.plugin ? { plugin: pluginRoute.plugin } : {},
41
+ ...action.resource ? { resource: action.resource } : pluginRoute?.resource ? { resource: pluginRoute.resource } : {},
40
42
  config: {
41
43
  path: pluginRoute?.path ?? path ?? `${prefix}/${service.name}/${action.name}`,
42
44
  method: pluginRoute?.method ?? method ?? "POST"
@@ -1 +1 @@
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,O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,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 ...((action as { plugin?: string }).plugin\n ? { plugin: (action as { plugin?: string }).plugin }\n : pluginRoute?.plugin\n ? { plugin: pluginRoute.plugin }\n : {}),\n ...((action as { resource?: string }).resource\n ? { resource: (action as { resource?: string }).resource }\n : pluginRoute?.resource\n ? { resource: pluginRoute.resource }\n : {}),\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,MAAM,EAAE,OAAO,QAAQ,QAAQ,MAAM,WAAW,OAAO;EACvD,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,YAAY,QAAQ,QAAQ,S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;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 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["BrickApp"],"sources":["../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;UAIiB;EACf;EACA;EACA;;wBAGoB,eAAe,UAAS,mBAAqB,iCAAA;;;UCJlD;;EAEf;EACA;EACA;;EAEA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;;;;;;wBCVvD,uBAAuB,KAAKA"}
1
+ {"version":3,"file":"index.d.ts","names":["BrickApp"],"sources":["../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;UASiB;EACf;EACA;EACA;;wBAmIoB,eAAe,UAAS,mBAAqB,iCAAA;;;UCzIlD;;EAEf;EACA;EACA;;EAEA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;;;;;;wBCVvD,uBAAuB,KAAKA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brickkit/cli",
3
- "version": "0.3.0-beta.4",
3
+ "version": "0.3.0",
4
4
  "description": "CLI and server engine for Brick-TS",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -49,8 +49,9 @@
49
49
  "format:check": "oxfmt --check ."
50
50
  },
51
51
  "dependencies": {
52
- "@brickkit/core": "^0.3.0-beta.4",
52
+ "@brickkit/core": "^0.3.0",
53
53
  "@sinclair/typebox": "^0.34.0",
54
+ "commander": "^15.0.0",
54
55
  "elysia": "2.0.0-beta.29"
55
56
  },
56
57
  "devDependencies": {