@brickkit/cli 0.4.1 → 0.5.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/build.js DELETED
@@ -1,82 +0,0 @@
1
- import { i as emitCompiledApplication, n as compileBrickApplication } from "./compiler2.js";
2
- import { requireBrickApp } from "@brickkit/core";
3
- import { pathToFileURL } from "node:url";
4
- import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
5
- import { dirname, join, resolve } from "node:path";
6
- import { aot } from "elysia/plugin/aot/bun";
7
- //#region src/app-entry.ts
8
- async function loadBrickApp(entry) {
9
- const module = await import(pathToFileURL(resolve(entry)).href);
10
- return requireBrickApp(module.default);
11
- }
12
- //#endregion
13
- //#region src/build.ts
14
- /** Bundle an exported BrickApp with generated handlers and its original configuration. */
15
- async function buildApplication(options) {
16
- const entry = resolve(options.entry);
17
- if (!await Bun.file(entry).exists()) throw new Error(`Brick compiler: entry not found: ${entry}`);
18
- const outdir = resolve(options.outdir ?? "dist/brick");
19
- if (entry === join(outdir, "server.js") || entry === join(outdir, "routes.js")) throw new Error("Brick compiler: output would overwrite the application entry");
20
- const port = options.port ?? 4e3;
21
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Brick compiler: port must be an integer between 1 and 65535");
22
- const app = await loadBrickApp(entry);
23
- const services = [...app.definition.services];
24
- const compilation = compileBrickApplication({
25
- services,
26
- prefix: app.definition.prefix
27
- });
28
- await mkdir(dirname(outdir), { recursive: true });
29
- const staging = await mkdtemp(join(dirname(outdir), ".brick-build-"));
30
- try {
31
- await Bun.write(join(staging, "routes.js"), emitCompiledApplication(compilation.ir));
32
- const source = `import { loadCompiledBrickApp } from "@brickkit/core";
33
- import { ir, bind } from "./routes.js";
34
- export const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), ir, bind);
35
- if (import.meta.main) {
36
- const port = Number(process.env.PORT ?? ${port});
37
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid PORT: must be between 1 and 65535");
38
- app.listen(port);
39
- console.log("Brick compiled server listening on http://localhost:" + app.server.port);
40
- const stop = async () => { await app.stop(); process.exit(0); };
41
- process.once("SIGINT", stop);
42
- process.once("SIGTERM", stop);
43
- }
44
- `;
45
- await Bun.write(join(staging, "entry.ts"), source);
46
- const result = await Bun.build({
47
- entrypoints: [join(staging, "entry.ts")],
48
- target: "bun",
49
- format: "esm",
50
- outdir: staging,
51
- naming: "server.js",
52
- sourcemap: "external",
53
- plugins: options.aot === false ? [] : [aot(join(staging, "entry.ts"), {
54
- target: "bun",
55
- strip: true
56
- })]
57
- });
58
- if (!result.success) throw new AggregateError(result.logs, "Brick compiler: bundling failed");
59
- await Bun.write(join(staging, "brick-ir.json"), JSON.stringify(compilation.ir, null, 2) + "\n");
60
- await mkdir(outdir, { recursive: true });
61
- for (const name of [
62
- "routes.js",
63
- "brick-ir.json",
64
- "server.js.map",
65
- "server.js"
66
- ]) await rename(join(staging, name), join(outdir, name));
67
- return {
68
- outdir,
69
- entry: join(outdir, "server.js"),
70
- ir: compilation.ir
71
- };
72
- } finally {
73
- await rm(staging, {
74
- recursive: true,
75
- force: true
76
- });
77
- }
78
- }
79
- //#endregion
80
- export { loadBrickApp as n, buildApplication as t };
81
-
82
- //# sourceMappingURL=build.js.map
package/dist/build.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"build.js","names":[],"sources":["../src/app-entry.ts","../src/build.ts"],"sourcesContent":["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":";;;;;;;AAMA,eAAsB,aAAa,OAAkC;CACnE,MAAM,SAAS,MAAM,OAAO,cAAc,QAAQ,KAAK,CAAC,CAAC,CAAC;CAC1D,OAAO,gBAAgB,OAAO,OAAO;AACvC;;;;ACOA,eAAsB,iBAAiB,SAAkC;CACvE,MAAM,QAAQ,QAAQ,QAAQ,KAAK;CACnC,IAAI,CAAE,MAAM,IAAI,KAAK,KAAK,CAAC,CAAC,OAAO,GACjC,MAAM,IAAI,MAAM,oCAAoC,OAAO;CAC7D,MAAM,SAAS,QAAQ,QAAQ,UAAU,YAAY;CACrD,IACE,UAAU,KAAK,QAAQ,WAAW,KAClC,UAAU,KAAK,QAAQ,WAAW,GAElC,MAAM,IAAI,MACR,8DACF;CACF,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MACR,6DACF;CACF,MAAM,MAAM,MAAM,aAAa,KAAK;CACpC,MAAM,WAAW,CAAC,GAAG,IAAI,WAAW,QAAQ;CAC5C,MAAM,cAAc,wBAAwB;EAC1C;EACA,QAAQ,IAAI,WAAW;CACzB,CAAC;CACD,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CAChD,MAAM,UAAU,MAAM,QAAQ,KAAK,QAAQ,MAAM,GAAG,eAAe,CAAC;CACpE,IAAI;EACF,MAAM,IAAI,MACR,KAAK,SAAS,WAAW,GACzB,wBAAwB,YAAY,EAAE,CACxC;EACA,MAAM,SAAS;;6DAE0C,KAAK,UAAU,KAAK,EAAE;;4CAEvC,KAAK;;;;;;;;;EAS7C,MAAM,IAAI,MAAM,KAAK,SAAS,UAAU,GAAG,MAAM;EACjD,MAAM,SAAS,MAAM,IAAI,MAAM;GAC7B,aAAa,CAAC,KAAK,SAAS,UAAU,CAAC;GACvC,QAAQ;GACR,QAAQ;GACR,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,268 +0,0 @@
1
- import { getPluginActionRoute } from "@brickkit/core";
2
- import { createHash } from "node:crypto";
3
- //#region src/client-contract.ts
4
- /** Generate browser metadata and transport types from the app's selected services. */
5
- function generateClientContract(app) {
6
- const { services, prefix } = app.definition;
7
- const contract = Object.create(null);
8
- const types = Object.create(null);
9
- const schemas = new SchemaTypes();
10
- for (const service of services) addServiceActions(service, prefix, contract, types, schemas);
11
- return `// Generated by the Brick Vite plugin. Do not edit.
12
- import type { BrickClientAction } from "@brickkit/core/client";
13
-
14
- ${schemas.renderContract(namespaceType(types))}
15
-
16
- export const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});
17
- `;
18
- }
19
- function addServiceActions(service, prefix, contract, types, schemas) {
20
- const namespace = contract[service.name] ?? Object.create(null);
21
- const namespaceTypes = types[service.name] ?? Object.create(null);
22
- contract[service.name] = namespace;
23
- types[service.name] = namespaceTypes;
24
- for (const action of service.listActions()) {
25
- const pluginRoute = getPluginActionRoute(action, prefix);
26
- if (pluginRoute === false) continue;
27
- const { input, output, errors, path, method } = action.config;
28
- let inputType;
29
- let outputType;
30
- try {
31
- inputType = input ? schemas.generate(input) : "unknown";
32
- outputType = output ? schemas.generate(output) : "unknown";
33
- } catch (error) {
34
- throw new Error(`Brick client: cannot generate '${service.name}.${action.name}': ${error.message}`);
35
- }
36
- const metadata = {
37
- kind: "action",
38
- name: action.name,
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 } : {},
42
- config: {
43
- path: pluginRoute?.path ?? path ?? `${prefix}/${service.name}/${action.name}`,
44
- method: pluginRoute?.method ?? method ?? "POST"
45
- }
46
- };
47
- insertAction(pluginRoute?.clientPath ? contract : namespace, pluginRoute?.clientPath ? types : namespaceTypes, metadata, actionType(inputType, outputType, errors), pluginRoute?.clientPath);
48
- }
49
- }
50
- function insertAction(node, typeNode, metadata, type, clientPath) {
51
- const segments = clientPath ?? metadata.name.split(".");
52
- for (const segment of segments.slice(0, -1)) {
53
- if (Object.hasOwn(typeNode, segment) && typeof typeNode[segment] === "string") throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
54
- node[segment] ??= Object.create(null);
55
- typeNode[segment] ??= Object.create(null);
56
- node = node[segment];
57
- typeNode = typeNode[segment];
58
- }
59
- const leaf = segments.at(-1);
60
- if (Object.hasOwn(node, leaf)) throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
61
- node[leaf] = metadata;
62
- typeNode[leaf] = type;
63
- }
64
- function actionType(input, output, errors) {
65
- const codes = Object.keys(errors ?? {});
66
- return `BrickClientAction<${input}, ${output}, ${codes.length ? `Record<${codes.map((code) => JSON.stringify(code)).join(" | ")}, { message: string; status?: number }>` : "{}"}>`;
67
- }
68
- function namespaceType(node) {
69
- return `{\n${Object.entries(node).map(([key, value]) => ` ${JSON.stringify(key)}: ${typeof value === "string" ? value : namespaceType(value)};`).join("\n")}\n}`;
70
- }
71
- var SchemaTypes = class {
72
- aliases = /* @__PURE__ */ new Map();
73
- names = /* @__PURE__ */ new Set([
74
- "AppContract",
75
- "BrickClientAction",
76
- "contract"
77
- ]);
78
- fragments = [];
79
- fragmentIds = /* @__PURE__ */ new Map();
80
- fragment(body) {
81
- let id = this.fragmentIds.get(body);
82
- if (id === void 0) {
83
- id = this.fragments.length;
84
- const size = body.replace(/\0(\d+)\0/g, "").length + [...body.matchAll(/\0(\d+)\0/g)].reduce((total, match) => total + this.fragments[Number(match[1])].size, 0);
85
- const shape = body.replace(/\0(\d+)\0/g, (_, child) => this.fragments[Number(child)].hash);
86
- const hash = createHash("sha256").update(shape).digest("hex");
87
- this.fragments.push({
88
- body,
89
- size,
90
- hash
91
- });
92
- this.fragmentIds.set(body, id);
93
- }
94
- return `\0${id}\0`;
95
- }
96
- renderContract(contract) {
97
- const uses = this.fragments.map(() => 0);
98
- const count = (body, multiplier) => {
99
- for (const match of body.matchAll(/\0(\d+)\0/g)) uses[Number(match[1])] += multiplier;
100
- };
101
- count(contract, 1);
102
- for (const body of this.aliases.values()) count(body, 1);
103
- const shared = /* @__PURE__ */ new Map();
104
- for (let id = this.fragments.length - 1; id >= 0; id--) {
105
- const { body, size, hash } = this.fragments[id];
106
- const nameBase = `BrickSchema_${hash.slice(0, 12)}`;
107
- let name = nameBase;
108
- let suffix = 2;
109
- while (this.names.has(name)) name = `${nameBase}_${suffix++}`;
110
- const declarationCost = `export type ${name} = ;\n\n`.length;
111
- if (uses[id] > 1 && (uses[id] - 1) * size > uses[id] * name.length + declarationCost) {
112
- this.names.add(name);
113
- shared.set(id, name);
114
- }
115
- count(body, shared.has(id) ? 1 : uses[id]);
116
- }
117
- const rendered = [];
118
- const declarations = [];
119
- for (let id = 0; id < this.fragments.length; id++) {
120
- const body = this.fragments[id].body.replace(/\0(\d+)\0/g, (_, child) => rendered[Number(child)]);
121
- const name = shared.get(id);
122
- if (name && (uses[id] - 1) * body.length > uses[id] * name.length + `export type ${name} = ;\n\n`.length) {
123
- declarations.push(`export type ${name} = ${body};\n\n`);
124
- rendered.push(name);
125
- } else rendered.push(body);
126
- }
127
- const render = (body) => body.replace(/\0(\d+)\0/g, (_, id) => rendered[Number(id)]);
128
- return declarations.join("") + [...this.aliases].map(([name, type]) => `export type ${name} = ${render(type)};\n\n`).join("") + `export type AppContract = ${render(contract)};`;
129
- }
130
- generate(root) {
131
- const ids = /* @__PURE__ */ new Map();
132
- const references = [];
133
- const resources = /* @__PURE__ */ new Map();
134
- const active = /* @__PURE__ */ new Set();
135
- const visit = (schema, base) => {
136
- if (!schema || typeof schema !== "object" || active.has(schema)) return;
137
- const currentBase = typeof schema.$id === "string" && schema.$id ? schema : base;
138
- if (!resources.has(schema)) resources.set(schema, currentBase);
139
- if (typeof schema.$ref === "string") references.push({
140
- ref: schema.$ref,
141
- base: currentBase
142
- });
143
- active.add(schema);
144
- try {
145
- if (typeof schema.$id === "string" && schema.$id) ids.set(schema.$id, schema);
146
- for (const key of [
147
- "properties",
148
- "patternProperties",
149
- "$defs",
150
- "definitions"
151
- ]) for (const child of Object.values(schema[key] ?? {})) visit(child, currentBase);
152
- for (const key of [
153
- "anyOf",
154
- "oneOf",
155
- "allOf",
156
- "prefixItems"
157
- ]) for (const child of schema[key] ?? []) visit(child, currentBase);
158
- for (const key of [
159
- "items",
160
- "additionalProperties",
161
- "not"
162
- ]) if (Array.isArray(schema[key])) schema[key].forEach((child) => visit(child, currentBase));
163
- else visit(schema[key], currentBase);
164
- } finally {
165
- active.delete(schema);
166
- }
167
- };
168
- visit(root, root);
169
- const resolve = (reference, base) => {
170
- const hashIndex = reference.indexOf("#");
171
- const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);
172
- const fragment = hashIndex === -1 ? void 0 : reference.slice(hashIndex + 1);
173
- let target = id ? ids.get(id) : base;
174
- if (fragment) {
175
- if (!fragment.startsWith("/")) return void 0;
176
- try {
177
- for (const part of decodeURIComponent(fragment).slice(1).split("/")) {
178
- const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
179
- if (!target || !Object.hasOwn(target, key)) return void 0;
180
- target = target[key];
181
- }
182
- } catch {
183
- return;
184
- }
185
- }
186
- return typeof target === "boolean" || target && typeof target === "object" ? target : void 0;
187
- };
188
- const targets = new Set(references.map(({ ref, base }) => resolve(ref, base)).filter((value) => value !== void 0));
189
- const names = /* @__PURE__ */ new Map();
190
- const emit = (schema, inline = false, base = root) => {
191
- const body = emitInline(schema, inline, base);
192
- if (schema && !schema.$ref && !Object.hasOwn(schema, "const") && (schema.anyOf || schema.oneOf || schema.allOf || schema.enum?.length > 1 || schema.type === "array" || schema.type === "object")) return this.fragment(body);
193
- return body;
194
- };
195
- const emitInline = (schema, inline, base) => {
196
- if (schema === void 0 || schema === true) return "unknown";
197
- if (schema === false || schema.not && !Object.keys(schema.not).length) return "never";
198
- const currentBase = schema && typeof schema === "object" && typeof schema.$id === "string" && schema.$id ? schema : base;
199
- if (!inline && targets.has(schema)) {
200
- const existing = names.get(schema);
201
- if (existing) return existing;
202
- const hint = schema.title ?? schema.$id ?? "Schema";
203
- let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, "_");
204
- if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;
205
- nameBase = `Brick${nameBase}`;
206
- let name = nameBase;
207
- let suffix = 2;
208
- while (this.names.has(name)) {
209
- name = `${nameBase}_${suffix}`;
210
- suffix += 1;
211
- }
212
- this.names.add(name);
213
- names.set(schema, name);
214
- this.aliases.set(name, emit(schema, true, currentBase));
215
- return name;
216
- }
217
- if (schema.$ref) {
218
- const target = resolve(schema.$ref, currentBase);
219
- if (target === void 0) throw new Error(`unresolved schema reference '${schema.$ref}'`);
220
- const targetBase = target && typeof target === "object" ? resources.get(target) ?? root : currentBase;
221
- return emit(target, false, targetBase);
222
- }
223
- if (Object.hasOwn(schema, "const")) return JSON.stringify(schema.const);
224
- if (schema.enum) return schema.enum.map((value) => JSON.stringify(value)).join(" | ") || "never";
225
- if (schema.anyOf || schema.oneOf) return `(${(schema.anyOf ?? schema.oneOf).map((child) => emit(child, false, currentBase)).join(" | ")})`;
226
- if (schema.allOf) return `(${schema.allOf.map((child) => emit(child, false, currentBase)).join(" & ")})`;
227
- switch (schema.type) {
228
- case "string": return "string";
229
- case "number":
230
- case "integer": return "number";
231
- case "boolean": return "boolean";
232
- case "null": return "null";
233
- case "undefined":
234
- case "void": return "undefined";
235
- case "array":
236
- if (Array.isArray(schema.items)) return `[${schema.items.map((child) => emit(child, false, currentBase)).join(", ")}]`;
237
- return `Array<${emit(schema.items, false, currentBase)}>`;
238
- case "object": {
239
- const entries = Object.entries(schema.properties ?? {});
240
- const properties = entries.map(([key, value]) => `${JSON.stringify(key)}${schema.required?.includes(key) ? "" : "?"}: ${emit(value, false, currentBase)};`);
241
- const indexParts = Object.values(schema.patternProperties ?? {}).map((child) => emit(child, false, currentBase));
242
- if (schema.additionalProperties) indexParts.push(emit(schema.additionalProperties, false, currentBase));
243
- let indexType;
244
- if (indexParts.length) {
245
- for (const [, value] of entries) {
246
- const propType = emit(value, false, currentBase);
247
- if (!indexParts.includes(propType)) indexParts.push(propType);
248
- }
249
- indexType = indexParts.join(" | ");
250
- }
251
- const object = `{ ${properties.join(" ")} }`;
252
- if (indexType) {
253
- const index = `{ [key: string]: ${indexType} }`;
254
- return properties.length ? `${object} & ${index}` : index;
255
- }
256
- return object;
257
- }
258
- case void 0: return "unknown";
259
- default: throw new Error(`unsupported transport schema type '${schema.type}'`);
260
- }
261
- };
262
- return emit(root);
263
- }
264
- };
265
- //#endregion
266
- export { generateClientContract as t };
267
-
268
- //# sourceMappingURL=client-contract.js.map
@@ -1 +0,0 @@
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,SAAS,KAAK,IAAI;GAC9C,aAAa,SAAS,QAAQ,SAAS,MAAM,IA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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,3 +0,0 @@
1
- import { n as emitHandlerFactory, t as emitCompiledApplication } from "./emit.js";
2
- import { BrickIR, CompiledApplication, CompiledHandler, CompiledRoute, HandlerFactory, RouteIR, RouteMethod, bindCompiledApplication, compileBrickApplication, loadCompiledBrickApp } from "@brickkit/core";
3
- export { type BrickIR, type CompiledApplication, type CompiledHandler, type CompiledRoute, type HandlerFactory, type RouteIR, type RouteMethod, bindCompiledApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, loadCompiledBrickApp };
package/dist/compiler.js DELETED
@@ -1 +0,0 @@
1
- export { t as bindCompiledApplication, n as compileBrickApplication, i as emitCompiledApplication, a as emitHandlerFactory, r as loadCompiledBrickApp } from "./compiler2.js";
package/dist/compiler2.js DELETED
@@ -1,10 +0,0 @@
1
- import { bindCompiledApplication, compileBrickApplication, emitHandlerFactory, loadCompiledBrickApp } from "@brickkit/core";
2
- //#region src/compiler/emit.ts
3
- /** An ES module of real JS functions; it never stringifies application callbacks. */
4
- function emitCompiledApplication(ir, runtimeImport = "@brickkit/core") {
5
- return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\nconst factories = [\n${ir.routes.map(emitHandlerFactory).join(",\n")}\n];\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\n`;
6
- }
7
- //#endregion
8
- export { emitHandlerFactory as a, emitCompiledApplication as i, compileBrickApplication as n, loadCompiledBrickApp as r, bindCompiledApplication as t };
9
-
10
- //# sourceMappingURL=compiler2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"compiler2.js","names":[],"sources":["../src/compiler/emit.ts"],"sourcesContent":["import { emitHandlerFactory, type BrickIR } from \"@brickkit/core\";\n\n/** An ES module of real JS functions; it never stringifies application callbacks. */\nexport function emitCompiledApplication(\n ir: BrickIR,\n runtimeImport = \"@brickkit/core\",\n): string {\n return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\\nconst factories = [\\n${ir.routes.map(emitHandlerFactory).join(\",\\n\")}\\n];\\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\\n`;\n}\n\nexport { emitHandlerFactory };\nexport type { BrickIR };\n"],"mappings":";;;AAGA,SAAgB,wBACd,IACA,gBAAgB,kBACR;CACR,OAAO,+HAA+H,KAAK,UAAU,aAAa,EAAE,kCAAkC,KAAK,UAAU,KAAK,UAAU,EAAE,CAAC,EAAE,2BAA2B,GAAG,OAAO,IAAI,kBAAkB,CAAC,CAAC,KAAK,KAAK,EAAE;AACpT"}
package/dist/emit.d.ts DELETED
@@ -1,7 +0,0 @@
1
- import { BrickIR, emitHandlerFactory } from "@brickkit/core";
2
- //#region src/compiler/emit.d.ts
3
- /** An ES module of real JS functions; it never stringifies application callbacks. */
4
- declare function emitCompiledApplication(ir: BrickIR, runtimeImport?: string): string;
5
- //#endregion
6
- export { emitHandlerFactory as n, emitCompiledApplication as t };
7
- //# sourceMappingURL=emit.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"emit.d.ts","names":[],"sources":["../src/compiler/emit.ts"],"mappings":";;;iBAGgB,wBACd,IAAI,SACJ"}
@@ -1,13 +0,0 @@
1
- //#region src/port-utils.ts
2
- function parsePort(portStr, envPort) {
3
- let port;
4
- if (portStr !== void 0) port = Number(portStr);
5
- else if (envPort !== void 0 && envPort !== "") port = Number(envPort);
6
- else port = 4e3;
7
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port: ${port}. Port must be an integer between 1 and 65535`);
8
- return port;
9
- }
10
- //#endregion
11
- export { parsePort as t };
12
-
13
- //# sourceMappingURL=port-utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"port-utils.js","names":[],"sources":["../src/port-utils.ts"],"sourcesContent":["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 && envPort !== \"\") {\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"],"mappings":";AAAA,SAAgB,UACd,SACA,SACQ;CACR,IAAI;CACJ,IAAI,YAAY,KAAA,GACd,OAAO,OAAO,OAAO;MAChB,IAAI,YAAY,KAAA,KAAa,YAAY,IAC9C,OAAO,OAAO,OAAO;MAErB,OAAO;CAGT,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MACR,iBAAiB,KAAK,8CACxB;CAEF,OAAO;AACT"}