@brickkit/cli 0.3.0-beta.1 → 0.3.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/bin.js +2 -3
- package/dist/bin.js.map +1 -1
- package/dist/build.js +16 -375
- package/dist/build.js.map +1 -1
- package/dist/client-contract.js +12 -78
- package/dist/client-contract.js.map +1 -1
- package/dist/compiler.d.ts +3 -150
- package/dist/compiler.js +1 -1
- package/dist/compiler2.js +3 -493
- package/dist/compiler2.js.map +1 -1
- package/dist/emit.d.ts +7 -0
- package/dist/emit.d.ts.map +1 -0
- package/dist/index.d.ts +6 -66
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/vite.js +1 -1
- package/dist/vite.js.map +1 -1
- package/package.json +2 -2
- package/dist/compiler.d.ts.map +0 -1
- package/dist/compiler2.d.ts +0 -2
package/dist/compiler2.js
CHANGED
|
@@ -1,500 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { resolve } from "node:path";
|
|
3
|
-
import { pathToFileURL } from "node:url";
|
|
4
|
-
//#region src/action-handler.ts
|
|
5
|
-
let _srvSeq = 0;
|
|
6
|
-
const EMPTY_SERVICES$1 = Object.freeze({});
|
|
7
|
-
const DEFAULT_REQUEST$1 = new Request("http://localhost");
|
|
8
|
-
function isNonEmpty$1(obj) {
|
|
9
|
-
if (obj == null) return false;
|
|
10
|
-
for (const _ in obj) return true;
|
|
11
|
-
return false;
|
|
12
|
-
}
|
|
13
|
-
function compileRoutePlan(service, action, routePath, method) {
|
|
14
|
-
const actionName = action.name;
|
|
15
|
-
const serviceName = service.name;
|
|
16
|
-
const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
|
|
17
|
-
const inputSchema = action.config?.input;
|
|
18
|
-
const outputSchema = action.config?.output;
|
|
19
|
-
const hasInput = Boolean(inputSchema);
|
|
20
|
-
const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
|
|
21
|
-
const outputChecker = outputSchema ? getCompiledCheck(outputSchema) : void 0;
|
|
22
|
-
let coercions;
|
|
23
|
-
if (inputSchema && typeof inputSchema.properties === "object") {
|
|
24
|
-
const list = [];
|
|
25
|
-
for (const [key, prop] of Object.entries(inputSchema.properties)) {
|
|
26
|
-
const type = prop?.type;
|
|
27
|
-
if (type === "number" || type === "integer") list.push({
|
|
28
|
-
key,
|
|
29
|
-
isNumber: true,
|
|
30
|
-
isBoolean: false
|
|
31
|
-
});
|
|
32
|
-
else if (type === "boolean") list.push({
|
|
33
|
-
key,
|
|
34
|
-
isNumber: false,
|
|
35
|
-
isBoolean: true
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
if (list.length > 0) coercions = list;
|
|
39
|
-
}
|
|
40
|
-
const contextHook = service.options?.context;
|
|
41
|
-
const hasContextHook = typeof contextHook === "function";
|
|
42
|
-
const authorize = action.config?.authorize;
|
|
43
|
-
const hasAuthorize = typeof authorize === "function";
|
|
44
|
-
const execute = action.config?.execute;
|
|
45
|
-
const tag = `[${serviceName}:${actionName}]`;
|
|
46
|
-
const logger = {
|
|
47
|
-
info: (...args) => console.log(tag, ...args),
|
|
48
|
-
warn: (...args) => console.warn(tag, ...args),
|
|
49
|
-
error: (...args) => console.error(tag, ...args),
|
|
50
|
-
debug: (...args) => console.debug(tag, ...args)
|
|
51
|
-
};
|
|
52
|
-
const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
|
|
53
|
-
const cachedDb = service.getDb();
|
|
54
|
-
return {
|
|
55
|
-
service,
|
|
56
|
-
action,
|
|
57
|
-
actionName,
|
|
58
|
-
serviceName,
|
|
59
|
-
routePath,
|
|
60
|
-
method,
|
|
61
|
-
isGetLike,
|
|
62
|
-
hasInput,
|
|
63
|
-
hasContextHook,
|
|
64
|
-
contextHook,
|
|
65
|
-
hasAuthorize,
|
|
66
|
-
authorize,
|
|
67
|
-
execute,
|
|
68
|
-
inputChecker,
|
|
69
|
-
outputChecker,
|
|
70
|
-
coercions,
|
|
71
|
-
logger,
|
|
72
|
-
errorBuilder,
|
|
73
|
-
cachedDb
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
async function executeCompiledRoute(plan, elysiaCtx) {
|
|
77
|
-
const { params, body, query, headers, request, set } = elysiaCtx;
|
|
78
|
-
const seq = (++_srvSeq).toString(36);
|
|
79
|
-
const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
|
|
80
|
-
const requestId = headers && headers["x-request-id"] || `req_${seq}`;
|
|
81
|
-
if (set?.headers) {
|
|
82
|
-
set.headers["x-trace-id"] = traceId;
|
|
83
|
-
set.headers["x-request-id"] = requestId;
|
|
84
|
-
}
|
|
85
|
-
let input;
|
|
86
|
-
if (plan.hasInput) {
|
|
87
|
-
let coercedQuery = query;
|
|
88
|
-
if (query && plan.coercions && plan.coercions.length > 0) {
|
|
89
|
-
coercedQuery = { ...query };
|
|
90
|
-
for (let i = 0; i < plan.coercions.length; i++) {
|
|
91
|
-
const c = plan.coercions[i];
|
|
92
|
-
const val = query[c.key];
|
|
93
|
-
if (val !== void 0) {
|
|
94
|
-
if (c.isNumber) {
|
|
95
|
-
const num = Number(val);
|
|
96
|
-
if (!isNaN(num)) coercedQuery[c.key] = num;
|
|
97
|
-
} else if (c.isBoolean) {
|
|
98
|
-
if (val === "true" || val === "1") coercedQuery[c.key] = true;
|
|
99
|
-
else if (val === "false" || val === "0") coercedQuery[c.key] = false;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
const hasP = isNonEmpty$1(params);
|
|
105
|
-
const hasB = isNonEmpty$1(body);
|
|
106
|
-
const hasQ = isNonEmpty$1(coercedQuery);
|
|
107
|
-
if (plan.isGetLike) {
|
|
108
|
-
if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
109
|
-
else if (hasP && !hasQ && !hasB) input = params;
|
|
110
|
-
else if (hasB && !hasP && !hasQ) input = body;
|
|
111
|
-
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, params, body);
|
|
112
|
-
} else if (hasB && !hasP && !hasQ) input = body;
|
|
113
|
-
else if (hasP && !hasB && !hasQ) input = params;
|
|
114
|
-
else if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
115
|
-
else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
|
|
116
|
-
}
|
|
117
|
-
const ctx = {
|
|
118
|
-
request: request instanceof Request ? request : DEFAULT_REQUEST$1,
|
|
119
|
-
traceId,
|
|
120
|
-
requestId,
|
|
121
|
-
db: plan.cachedDb ?? plan.service.getDb(),
|
|
122
|
-
logger: plan.logger,
|
|
123
|
-
services: EMPTY_SERVICES$1,
|
|
124
|
-
metadata: { headers },
|
|
125
|
-
_resolved: true
|
|
126
|
-
};
|
|
127
|
-
try {
|
|
128
|
-
if (plan.hasContextHook) {
|
|
129
|
-
const extra = plan.contextHook(ctx);
|
|
130
|
-
const resolved = extra instanceof Promise ? await extra : extra;
|
|
131
|
-
if (resolved) Object.assign(ctx, resolved);
|
|
132
|
-
}
|
|
133
|
-
if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
|
|
134
|
-
if (plan.hasInput && plan.inputChecker) {
|
|
135
|
-
if (!plan.inputChecker.Check(input)) {
|
|
136
|
-
const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
|
|
137
|
-
path: err.path,
|
|
138
|
-
message: err.message,
|
|
139
|
-
value: err.value
|
|
140
|
-
}));
|
|
141
|
-
throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
if (plan.hasAuthorize) {
|
|
145
|
-
const authRes = plan.authorize({
|
|
146
|
-
ctx,
|
|
147
|
-
input,
|
|
148
|
-
user: ctx.user
|
|
149
|
-
});
|
|
150
|
-
if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${plan.actionName}'`, 403);
|
|
151
|
-
}
|
|
152
|
-
const execRes = plan.execute({
|
|
153
|
-
input,
|
|
154
|
-
ctx,
|
|
155
|
-
error: plan.errorBuilder
|
|
156
|
-
});
|
|
157
|
-
const result = execRes instanceof Promise ? await execRes : execRes;
|
|
158
|
-
if (plan.outputChecker) {
|
|
159
|
-
if (!plan.outputChecker.Check(result)) {
|
|
160
|
-
const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
|
|
161
|
-
path: err.path,
|
|
162
|
-
message: err.message,
|
|
163
|
-
value: err.value
|
|
164
|
-
}));
|
|
165
|
-
throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
return result;
|
|
169
|
-
} catch (err) {
|
|
170
|
-
if (err instanceof ValidationError || err instanceof ActionExecutionError) {
|
|
171
|
-
set.status = err.status || 400;
|
|
172
|
-
return err.toJSON();
|
|
173
|
-
}
|
|
174
|
-
set.status = 500;
|
|
175
|
-
return {
|
|
176
|
-
name: "InternalServerError",
|
|
177
|
-
message: err.message || "An unexpected error occurred",
|
|
178
|
-
status: 500
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
//#endregion
|
|
183
|
-
//#region src/compiler/ir.ts
|
|
184
|
-
function freezeIR(value) {
|
|
185
|
-
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
186
|
-
for (const child of Object.values(value)) freezeIR(child);
|
|
187
|
-
Object.freeze(value);
|
|
188
|
-
}
|
|
189
|
-
return value;
|
|
190
|
-
}
|
|
191
|
-
function schemaSnapshot(schema) {
|
|
192
|
-
return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
|
|
193
|
-
}
|
|
194
|
-
function analyzeApplication(services, prefix = "/api") {
|
|
195
|
-
if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
|
|
196
|
-
const names = /* @__PURE__ */ new Set();
|
|
197
|
-
for (const service of services) {
|
|
198
|
-
if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
|
|
199
|
-
names.add(service.name);
|
|
200
|
-
service.build();
|
|
201
|
-
}
|
|
202
|
-
const routes = [];
|
|
203
|
-
const bindings = [];
|
|
204
|
-
const registered = /* @__PURE__ */ new Map();
|
|
205
|
-
const diagnostics = [];
|
|
206
|
-
const add = (service, action, method, path, kind) => {
|
|
207
|
-
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
208
|
-
const key = `${method} ${path}`;
|
|
209
|
-
const previous = registered.get(key);
|
|
210
|
-
if (previous) {
|
|
211
|
-
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`);
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
214
|
-
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
215
|
-
registered.set(key, `${service.name}.${action.name}`);
|
|
216
|
-
const readLike = method === "GET" || action.name.startsWith("get") || action.name.endsWith(".get") || action.name.startsWith("list") || action.name.endsWith(".list") || action.name.startsWith("find") || action.name.startsWith("read");
|
|
217
|
-
const coercions = [];
|
|
218
|
-
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
219
|
-
key,
|
|
220
|
-
type: "number"
|
|
221
|
-
});
|
|
222
|
-
else if (prop.type === "boolean") coercions.push({
|
|
223
|
-
key,
|
|
224
|
-
type: "boolean"
|
|
225
|
-
});
|
|
226
|
-
routes.push({
|
|
227
|
-
method,
|
|
228
|
-
path,
|
|
229
|
-
service: service.name,
|
|
230
|
-
action: action.name,
|
|
231
|
-
kind,
|
|
232
|
-
input: Boolean(action.config.input),
|
|
233
|
-
output: Boolean(action.config.output),
|
|
234
|
-
context: typeof service.options.context === "function",
|
|
235
|
-
authorize: typeof action.config.authorize === "function",
|
|
236
|
-
inputPrecedence: readLike ? [
|
|
237
|
-
"query",
|
|
238
|
-
"params",
|
|
239
|
-
"body"
|
|
240
|
-
] : [
|
|
241
|
-
"params",
|
|
242
|
-
"body",
|
|
243
|
-
"query"
|
|
244
|
-
],
|
|
245
|
-
coercions,
|
|
246
|
-
inputSchema: schemaSnapshot(action.config.input),
|
|
247
|
-
outputSchema: schemaSnapshot(action.config.output)
|
|
248
|
-
});
|
|
249
|
-
bindings.push({
|
|
250
|
-
service,
|
|
251
|
-
action
|
|
252
|
-
});
|
|
253
|
-
};
|
|
254
|
-
for (const service of services) {
|
|
255
|
-
for (const resource of service.listResources()) {
|
|
256
|
-
const collection = `${prefix}/${resource.name}`;
|
|
257
|
-
const item = `${collection}/:id`;
|
|
258
|
-
for (const [operation, method, path] of [
|
|
259
|
-
[
|
|
260
|
-
"list",
|
|
261
|
-
"GET",
|
|
262
|
-
collection
|
|
263
|
-
],
|
|
264
|
-
[
|
|
265
|
-
"create",
|
|
266
|
-
"POST",
|
|
267
|
-
collection
|
|
268
|
-
],
|
|
269
|
-
[
|
|
270
|
-
"get",
|
|
271
|
-
"GET",
|
|
272
|
-
item
|
|
273
|
-
],
|
|
274
|
-
[
|
|
275
|
-
"update",
|
|
276
|
-
"PATCH",
|
|
277
|
-
item
|
|
278
|
-
],
|
|
279
|
-
[
|
|
280
|
-
"update",
|
|
281
|
-
"PUT",
|
|
282
|
-
item
|
|
283
|
-
],
|
|
284
|
-
[
|
|
285
|
-
"delete",
|
|
286
|
-
"DELETE",
|
|
287
|
-
item
|
|
288
|
-
]
|
|
289
|
-
]) {
|
|
290
|
-
const action = resource.actions[operation];
|
|
291
|
-
if (action) add(service, action, method, path, "resource");
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
for (const action of service.listActions()) {
|
|
295
|
-
const path = action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
296
|
-
add(service, action, action.config.method ?? "POST", path, "action");
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
const reads = services.flatMap((service) => service.listResources().flatMap((resource) => {
|
|
300
|
-
const queries = describeResourceReads(service, resource);
|
|
301
|
-
return queries ? [queries] : [];
|
|
302
|
-
}));
|
|
303
|
-
return {
|
|
304
|
-
ir: freezeIR({
|
|
305
|
-
version: 1,
|
|
306
|
-
target: "bun-elysia",
|
|
307
|
-
prefix,
|
|
308
|
-
services: [...names],
|
|
309
|
-
routes,
|
|
310
|
-
reads,
|
|
311
|
-
diagnostics
|
|
312
|
-
}),
|
|
313
|
-
bindings
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
//#endregion
|
|
1
|
+
import { bindCompiledApplication, compileBrickApplication, emitHandlerFactory, loadCompiledBrickApp } from "@brickkit/core";
|
|
317
2
|
//#region src/compiler/emit.ts
|
|
318
|
-
/** Emits framework code only. User callbacks remain closures bound separately. */
|
|
319
|
-
function emitHandlerFactory(route) {
|
|
320
|
-
const name = JSON.stringify(route.action);
|
|
321
|
-
const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
|
|
322
|
-
const input = ["let input;"];
|
|
323
|
-
if (route.input) {
|
|
324
|
-
input.push("let coercedQuery = query;");
|
|
325
|
-
if (route.coercions.length) {
|
|
326
|
-
input.push("if (query) {", "coercedQuery = { ...query };");
|
|
327
|
-
for (const [index, coercion] of route.coercions.entries()) {
|
|
328
|
-
const key = JSON.stringify(coercion.key);
|
|
329
|
-
input.push(`const v${index} = query[${key}];`);
|
|
330
|
-
if (coercion.type === "number") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);
|
|
331
|
-
else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
|
|
332
|
-
}
|
|
333
|
-
input.push("}");
|
|
334
|
-
}
|
|
335
|
-
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
|
|
336
|
-
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
337
|
-
}
|
|
338
|
-
const asyncStages = route.context || route.authorize;
|
|
339
|
-
const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
|
|
340
|
-
const validation = route.input ? `validate(inputChecker, input, ${name}, "input");` : "";
|
|
341
|
-
const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : "";
|
|
342
|
-
const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
|
|
343
|
-
const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
|
|
344
|
-
if (isThenable(result)) return Promise.resolve(result).then(value => {
|
|
345
|
-
${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
|
|
346
|
-
return value;
|
|
347
|
-
}).catch(err => mapError(err, set));
|
|
348
|
-
${output}
|
|
349
|
-
return result;`;
|
|
350
|
-
return `function bindAction(binding, runtime) {
|
|
351
|
-
const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
|
|
352
|
-
const { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;
|
|
353
|
-
return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
|
|
354
|
-
const seq = nextSequence();
|
|
355
|
-
const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
|
|
356
|
-
const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
|
|
357
|
-
if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
|
|
358
|
-
${input.join("\n")}
|
|
359
|
-
const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
|
|
360
|
-
db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
|
|
361
|
-
try {
|
|
362
|
-
${context}
|
|
363
|
-
${validation}
|
|
364
|
-
${authorization}
|
|
365
|
-
${execute}
|
|
366
|
-
} catch (err) { return mapError(err, set); }
|
|
367
|
-
};
|
|
368
|
-
}`;
|
|
369
|
-
}
|
|
370
3
|
/** An ES module of real JS functions; it never stringifies application callbacks. */
|
|
371
|
-
function emitCompiledApplication(ir, runtimeImport = "@brickkit/
|
|
4
|
+
function emitCompiledApplication(ir, runtimeImport = "@brickkit/core") {
|
|
372
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`;
|
|
373
6
|
}
|
|
374
7
|
//#endregion
|
|
375
|
-
|
|
376
|
-
const EMPTY_SERVICES = Object.freeze({});
|
|
377
|
-
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
378
|
-
let sequence = 0;
|
|
379
|
-
function isNonEmpty(value) {
|
|
380
|
-
if (value == null) return false;
|
|
381
|
-
for (const _ in value) return true;
|
|
382
|
-
return false;
|
|
383
|
-
}
|
|
384
|
-
/** Retains Brick's existing source precedence and treatment of empty bodies. */
|
|
385
|
-
function mergeInput(first, second, third) {
|
|
386
|
-
const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);
|
|
387
|
-
if (a && !b && !c) return first;
|
|
388
|
-
if (b && !a && !c) return second;
|
|
389
|
-
if (c && !a && !b) return third;
|
|
390
|
-
if (a || b || c) return Object.assign({}, first, second, third);
|
|
391
|
-
}
|
|
392
|
-
function validate(check, value, action, stage) {
|
|
393
|
-
if (check.Check(value)) return;
|
|
394
|
-
const errors = Array.from(check.Errors(value)).map((err) => ({
|
|
395
|
-
path: err.path,
|
|
396
|
-
message: err.message,
|
|
397
|
-
value: err.value
|
|
398
|
-
}));
|
|
399
|
-
throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
|
|
400
|
-
}
|
|
401
|
-
function mapError(err, set) {
|
|
402
|
-
if (err instanceof ValidationError || err instanceof ActionExecutionError) {
|
|
403
|
-
set.status = err.status || 400;
|
|
404
|
-
return err.toJSON();
|
|
405
|
-
}
|
|
406
|
-
set.status = 500;
|
|
407
|
-
return {
|
|
408
|
-
name: "InternalServerError",
|
|
409
|
-
message: err?.message || "An unexpected error occurred",
|
|
410
|
-
status: 500
|
|
411
|
-
};
|
|
412
|
-
}
|
|
413
|
-
const compilerRuntime = Object.freeze({
|
|
414
|
-
emptyServices: EMPTY_SERVICES,
|
|
415
|
-
defaultRequest: DEFAULT_REQUEST,
|
|
416
|
-
nextSequence: () => (++sequence).toString(36),
|
|
417
|
-
mergeInput,
|
|
418
|
-
validate,
|
|
419
|
-
mapError,
|
|
420
|
-
isThenable: (value) => value != null && typeof value.then === "function",
|
|
421
|
-
deny: (action) => {
|
|
422
|
-
throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${action}'`, 403);
|
|
423
|
-
}
|
|
424
|
-
});
|
|
425
|
-
//#endregion
|
|
426
|
-
//#region src/app-entry.ts
|
|
427
|
-
function isBrickApp(app) {
|
|
428
|
-
if (!app || typeof app !== "object") return false;
|
|
429
|
-
return "endpoint" in app && typeof app.endpoint === "function" && "fetch" in app && typeof app.fetch === "function" && "listen" in app && typeof app.listen === "function" && "definition" in app && !!app.definition && typeof app.definition === "object" && "services" in app.definition && Array.isArray(app.definition.services) && "prefix" in app.definition && typeof app.definition.prefix === "string";
|
|
430
|
-
}
|
|
431
|
-
function requireBrickApp(app) {
|
|
432
|
-
if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
433
|
-
if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
|
|
434
|
-
return app;
|
|
435
|
-
}
|
|
436
|
-
async function loadBrickApp(entry) {
|
|
437
|
-
return requireBrickApp((await import(pathToFileURL(resolve(entry)).href)).default);
|
|
438
|
-
}
|
|
439
|
-
//#endregion
|
|
440
|
-
//#region src/compiler.ts
|
|
441
|
-
const buildBindings = /* @__PURE__ */ new Map();
|
|
442
|
-
function applicationKey(services, prefix = "/api") {
|
|
443
|
-
return JSON.stringify([prefix, services.map((service) => service.name)]);
|
|
444
|
-
}
|
|
445
|
-
/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
|
|
446
|
-
async function loadCompiledBrickApp(load, ir, bind) {
|
|
447
|
-
const key = JSON.stringify([ir.prefix, ir.services]);
|
|
448
|
-
if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
|
|
449
|
-
buildBindings.set(key, bind);
|
|
450
|
-
try {
|
|
451
|
-
const app = requireBrickApp((await load()).default);
|
|
452
|
-
if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
|
|
453
|
-
return app;
|
|
454
|
-
} finally {
|
|
455
|
-
buildBindings.delete(key);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
function bindAnalyzed(ir, bindings, factories) {
|
|
459
|
-
if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
|
|
460
|
-
const routes = ir.routes.map((route, index) => {
|
|
461
|
-
const { service, action } = bindings[index];
|
|
462
|
-
const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
|
|
463
|
-
const handler = factories[index](plan, compilerRuntime);
|
|
464
|
-
return Object.freeze({
|
|
465
|
-
ir: route,
|
|
466
|
-
handler
|
|
467
|
-
});
|
|
468
|
-
});
|
|
469
|
-
return Object.freeze({
|
|
470
|
-
ir: freezeIR(ir),
|
|
471
|
-
routes: Object.freeze(routes)
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
|
|
475
|
-
function compileBrickApplication(options) {
|
|
476
|
-
const bind = buildBindings.get(applicationKey(options.services, options.prefix));
|
|
477
|
-
if (bind && options.mode !== "generic") return bind(options.services);
|
|
478
|
-
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
479
|
-
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
|
|
480
|
-
if (options.mode !== "generic") for (const service of options.services) {
|
|
481
|
-
prepareResourceReads(service);
|
|
482
|
-
prepareResourceWrites(service);
|
|
483
|
-
}
|
|
484
|
-
return bindAnalyzed(ir, bindings, factories);
|
|
485
|
-
}
|
|
486
|
-
/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
|
|
487
|
-
function bindCompiledApplication(ir, services, factories) {
|
|
488
|
-
if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
|
|
489
|
-
const analyzed = analyzeApplication(services, ir.prefix);
|
|
490
|
-
if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
|
|
491
|
-
for (const service of services) {
|
|
492
|
-
prepareResourceReads(service);
|
|
493
|
-
prepareResourceWrites(service);
|
|
494
|
-
}
|
|
495
|
-
return bindAnalyzed(ir, analyzed.bindings, factories);
|
|
496
|
-
}
|
|
497
|
-
//#endregion
|
|
498
|
-
export { emitCompiledApplication as a, loadBrickApp as i, compileBrickApplication as n, emitHandlerFactory as o, loadCompiledBrickApp as r, bindCompiledApplication as t };
|
|
8
|
+
export { emitHandlerFactory as a, emitCompiledApplication as i, compileBrickApplication as n, loadCompiledBrickApp as r, bindCompiledApplication as t };
|
|
499
9
|
|
|
500
10
|
//# sourceMappingURL=compiler2.js.map
|
package/dist/compiler2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compiler2.js","names":["EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty"],"sources":["../src/action-handler.ts","../src/compiler/ir.ts","../src/compiler/emit.ts","../src/compiler/runtime.ts","../src/app-entry.ts","../src/compiler.ts"],"sourcesContent":["import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n getCompiledCheck,\n buildErrorHelpers,\n} from \"@brickkit/core\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n const outputChecker = outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{ key: string; isNumber: boolean; isBoolean: boolean }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{ key: string; isNumber: boolean; isBoolean: boolean }> =\n [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = {\n info: (...args) => console.log(tag, ...args),\n warn: (...args) => console.warn(tag, ...args),\n error: (...args) => console.error(tag, ...args),\n debug: (...args) => console.debug(tag, ...args),\n };\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n const hasP = isNonEmpty(params);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = params;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, params, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = params;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, params, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${plan.actionName}'`,\n 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n}\n\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import {\n type Service,\n type Action,\n describeResourceReads,\n type ResourceReadQueries,\n} from \"@brickkit/core\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\" | \"resource\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly reads: readonly ResourceReadQueries[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n service.build();\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, string>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const key = `${method} ${path}`;\n const previous = registered.get(key);\n if (previous) {\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, `${service.name}.${action.name}`);\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" }[] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\")\n coercions.push({ key, type: \"boolean\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\n bindings.push({ service, action });\n };\n for (const service of services) {\n for (const resource of service.listResources()) {\n const collection = `${prefix}/${resource.name}`;\n const item = `${collection}/:id`;\n for (const [operation, method, path] of [\n [\"list\", \"GET\", collection],\n [\"create\", \"POST\", collection],\n [\"get\", \"GET\", item],\n [\"update\", \"PATCH\", item],\n [\"update\", \"PUT\", item],\n [\"delete\", \"DELETE\", item],\n ] as const) {\n const action = resource.actions[operation];\n if (action) add(service, action, method, path, \"resource\");\n }\n }\n for (const action of service.listActions()) {\n const path =\n action.config.path ?? `${prefix}/${service.name}/${action.name}`;\n add(service, action, action.config.method ?? \"POST\", path, \"action\");\n }\n }\n const reads = services.flatMap((service) =>\n service.listResources().flatMap((resource) => {\n const queries = describeResourceReads(service, resource);\n return queries ? [queries] : [];\n }),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n reads,\n diagnostics,\n });\n return { ir, bindings };\n}\n","import type { BrickIR, RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input\n ? \"params, body, query, headers, request, set\"\n : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\")\n input.push(\n `if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`,\n );\n else\n input.push(\n `if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`,\n );\n }\n input.push(\"}\");\n }\n input.push(\n `input = mergeInput(${route.inputPrecedence.map((source) => (source === \"query\" ? \"coercedQuery\" : source)).join(\", \")});`,\n );\n if ((route.inputSchema as { type?: string } | undefined)?.type === \"object\")\n input.push(\"input ??= {};\");\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context\n ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\"\n : \"\";\n const validation = route.input\n ? `validate(inputChecker, input, ${name}, \"input\");`\n : \"\";\n const authorization = route.authorize\n ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});`\n : \"\";\n const output = route.output\n ? `validate(outputChecker, result, ${name}, \"output\");`\n : \"\";\n const execute = asyncStages\n ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;`\n : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set); }\n};\n}`;\n}\n\n/** An ES module of real JS functions; it never stringifies application callbacks. */\nexport function emitCompiledApplication(\n ir: BrickIR,\n runtimeImport = \"@brickkit/cli/compiler\",\n): string {\n return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\\nconst factories = [\\n${ir.routes.map(emitHandlerFactory).join(\",\\n\")}\\n];\\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\\n`;\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"@brickkit/core\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true;\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction mapError(err: any, set: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n deny: (action: string): never => {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${action}'`,\n 403,\n );\n },\n});\n","import { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { BrickApp } from \"./endpoints\";\n\nexport function isBrickApp(app: unknown): app is BrickApp {\n if (!app || typeof app !== \"object\") return false;\n return (\n \"endpoint\" in app &&\n typeof app.endpoint === \"function\" &&\n \"fetch\" in app &&\n typeof app.fetch === \"function\" &&\n \"listen\" in app &&\n typeof app.listen === \"function\" &&\n \"definition\" in app &&\n !!app.definition &&\n typeof app.definition === \"object\" &&\n \"services\" in app.definition &&\n Array.isArray(app.definition.services) &&\n \"prefix\" in app.definition &&\n typeof app.definition.prefix === \"string\"\n );\n}\n\nexport function requireBrickApp(app: unknown): BrickApp {\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n if (app.server)\n throw new Error(\n \"Brick: the app entry must not call .listen(); use a separate server bootstrap.\",\n );\n return app;\n}\n\nexport async function loadBrickApp(entry: string): Promise<BrickApp> {\n const module = await import(pathToFileURL(resolve(entry)).href);\n return requireBrickApp(module.default);\n}\n","import {\n type Service,\n prepareResourceReads,\n prepareResourceWrites,\n} from \"@brickkit/core\";\nimport { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport { emitHandlerFactory } from \"./compiler/emit\";\nimport {\n compilerRuntime,\n type CompiledHandler,\n type HandlerFactory,\n} from \"./compiler/runtime\";\nimport { requireBrickApp } from \"./app-entry\";\n\ntype ApplicationBinder = (services: Service<any, any>[]) => CompiledApplication;\nconst buildBindings = new Map<string, ApplicationBinder>();\n\nfunction applicationKey(\n services: readonly Service<any, any>[],\n prefix = \"/api\",\n) {\n return JSON.stringify([prefix, services.map((service) => service.name)]);\n}\n\n/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */\nexport async function loadCompiledBrickApp(\n load: () => Promise<{ default: unknown }>,\n ir: BrickIR,\n bind: ApplicationBinder,\n) {\n const key = JSON.stringify([ir.prefix, ir.services]);\n if (buildBindings.has(key))\n throw new Error(\"Brick compiler: overlapping compiled app imports\");\n buildBindings.set(key, bind);\n try {\n const app = requireBrickApp((await load()).default);\n if (applicationKey(app.definition.services, app.definition.prefix) !== key)\n throw new Error(\n \"Brick compiler: app services/prefix changed; rebuild the application\",\n );\n return app;\n } finally {\n buildBindings.delete(key);\n }\n}\n\nexport { emitCompiledApplication, emitHandlerFactory } from \"./compiler/emit\";\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(\n compileRoutePlan(service, action, route.path, route.method),\n );\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const bind = buildBindings.get(\n applicationKey(options.services, options.prefix),\n );\n if (bind && options.mode !== \"generic\") return bind(options.services);\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] =\n options.mode === \"generic\"\n ? ir.routes.map(\n () => (plan) => (context) => executeCompiledRoute(plan, context),\n )\n : ir.routes.map(\n (route) =>\n new Function(\n `return (${emitHandlerFactory(route)});`,\n )() as HandlerFactory,\n );\n if (options.mode !== \"generic\")\n for (const service of options.services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n for (const service of services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n"],"mappings":";;;;AAWA,IAAI,UAAU;AACd,MAAMA,mBAAiB,OAAO,OAAO,CAAC,CAAC;AACvC,MAAMC,oBAAkB,IAAI,QAAQ,kBAAkB;AAEtD,SAASC,aAAW,KAAmB;CACrC,IAAI,OAAO,MAAM,OAAO;CACxB,KAAK,MAAM,KAAK,KAAK,OAAO;CAC5B,OAAO;AACT;AAEA,SAAgB,iBACd,SACA,QACA,WACA,QACmB;CACnB,MAAM,aAAa,OAAO;CAC1B,MAAM,cAAc,QAAQ;CAC5B,MAAM,YACJ,WAAW,SACX,WAAW,WAAW,KAAK,KAC3B,WAAW,SAAS,MAAM,KAC1B,WAAW,WAAW,MAAM,KAC5B,WAAW,SAAS,OAAO,KAC3B,WAAW,WAAW,MAAM,KAC5B,WAAW,WAAW,MAAM;CAE9B,MAAM,cAAc,OAAO,QAAQ;CACnC,MAAM,eAAe,OAAO,QAAQ;CACpC,MAAM,WAAW,QAAQ,WAAW;C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I,QAAQ,SAAS,WACnB,KAAK,MAAM,WAAW,QAAQ,UAAU;EACtC,qBAAqB,OAAO;EAC5B,sBAAsB,OAAO;CAC/B;CACF,OAAO,aAAa,IAAI,UAAU,SAAS;AAC7C;;AAGA,SAAgB,wBACd,IACA,UACA,WACqB;CACrB,IAAI,GAAG,YAAY,KAAK,GAAG,WAAW,cACpC,MAAM,IAAI,MACR,2EACF;CACF,MAAM,WAAW,mBAAmB,UAAU,GAAG,MAAM;CACvD,IAAI,KAAK,UAAU,SAAS,EAAE,MAAM,KAAK,UAAU,EAAE,GACnD,MAAM,IAAI,MACR,8FACF;CACF,KAAK,MAAM,WAAW,UAAU;EAC9B,qBAAqB,OAAO;EAC5B,sBAAsB,OAAO;CAC/B;CACA,OAAO,aAAa,IAAI,SAAS,UAAU,SAAS;AACtD"}
|
|
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
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emit.d.ts","names":[],"sources":["../src/compiler/emit.ts"],"mappings":";;;iBAGgB,wBACd,IAAI,SACJ"}
|