@brickkit/core 0.3.0-beta.5 → 0.4.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/README.md +47 -27
- package/dist/chunks/client.d.ts +23 -8
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js.map +1 -1
- package/dist/client.js +1 -2
- package/dist/index.d.ts +68 -39
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +484 -275
- package/dist/index.js.map +1 -1
- package/package.json +20 -7
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as isBrickTransportError, i as isBrickServerError, n as BrickTransportError, o as ActionExecutionError, r as createBrickClient, s as ValidationError, t as BrickServerError } from "./chunks/client.js";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import { Type } from "@sinclair/typebox";
|
|
3
|
+
import { Type, Type as t } from "@sinclair/typebox";
|
|
4
4
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
5
5
|
import { Elysia } from "elysia";
|
|
6
6
|
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
@@ -12,6 +12,111 @@ import { dirname } from "node:path";
|
|
|
12
12
|
//#region \0rolldown/runtime.js
|
|
13
13
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
14
14
|
//#endregion
|
|
15
|
+
//#region src/compiler/ir.ts
|
|
16
|
+
function freezeIR(value) {
|
|
17
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
18
|
+
for (const child of Object.values(value)) freezeIR(child);
|
|
19
|
+
Object.freeze(value);
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function schemaSnapshot(schema) {
|
|
24
|
+
return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
|
|
25
|
+
}
|
|
26
|
+
function analyzeApplication(services, prefix = "/api") {
|
|
27
|
+
for (const service of services) service.build();
|
|
28
|
+
return analyzeDeclaredApplication(services, prefix);
|
|
29
|
+
}
|
|
30
|
+
/** Inspect current declarations without closing service/plugin setup. */
|
|
31
|
+
function analyzeDeclaredApplication(services, prefix = "/api") {
|
|
32
|
+
if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
|
|
33
|
+
const names = /* @__PURE__ */ new Set();
|
|
34
|
+
for (const service of services) {
|
|
35
|
+
if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
|
|
36
|
+
names.add(service.name);
|
|
37
|
+
}
|
|
38
|
+
const routes = [];
|
|
39
|
+
const bindings = [];
|
|
40
|
+
const registered = /* @__PURE__ */ new Map();
|
|
41
|
+
const diagnostics = [];
|
|
42
|
+
const add = (service, action, method, path, kind) => {
|
|
43
|
+
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
44
|
+
const plugin = getPluginActionRoute(action, prefix) !== void 0;
|
|
45
|
+
const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
46
|
+
const previous = registered.get(key);
|
|
47
|
+
if (previous) {
|
|
48
|
+
if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
49
|
+
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
53
|
+
registered.set(key, {
|
|
54
|
+
name: `${service.name}.${action.name}`,
|
|
55
|
+
plugin
|
|
56
|
+
});
|
|
57
|
+
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");
|
|
58
|
+
const coercions = [];
|
|
59
|
+
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
60
|
+
key,
|
|
61
|
+
type: "number"
|
|
62
|
+
});
|
|
63
|
+
else if (prop.type === "boolean") coercions.push({
|
|
64
|
+
key,
|
|
65
|
+
type: "boolean"
|
|
66
|
+
});
|
|
67
|
+
routes.push({
|
|
68
|
+
method,
|
|
69
|
+
path,
|
|
70
|
+
service: service.name,
|
|
71
|
+
action: action.name,
|
|
72
|
+
kind,
|
|
73
|
+
input: Boolean(action.config.input),
|
|
74
|
+
output: Boolean(action.config.output),
|
|
75
|
+
context: typeof service.options.context === "function",
|
|
76
|
+
authorize: typeof action.config.authorize === "function",
|
|
77
|
+
inputPrecedence: readLike ? [
|
|
78
|
+
"query",
|
|
79
|
+
"params",
|
|
80
|
+
"body"
|
|
81
|
+
] : [
|
|
82
|
+
"params",
|
|
83
|
+
"body",
|
|
84
|
+
"query"
|
|
85
|
+
],
|
|
86
|
+
coercions,
|
|
87
|
+
inputSchema: schemaSnapshot(action.config.input),
|
|
88
|
+
outputSchema: schemaSnapshot(action.config.output)
|
|
89
|
+
});
|
|
90
|
+
bindings.push({
|
|
91
|
+
service,
|
|
92
|
+
action
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
for (const service of services) for (const action of service.listActions()) {
|
|
96
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
97
|
+
if (pluginRoute === false) continue;
|
|
98
|
+
const path = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
99
|
+
add(service, action, pluginRoute?.method ?? action.config.method ?? "POST", path, "action");
|
|
100
|
+
}
|
|
101
|
+
const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
|
|
102
|
+
service: service.name,
|
|
103
|
+
name: contribution.name,
|
|
104
|
+
metadata: schemaSnapshot(contribution.describe?.())
|
|
105
|
+
})));
|
|
106
|
+
return {
|
|
107
|
+
ir: freezeIR({
|
|
108
|
+
version: 1,
|
|
109
|
+
target: "bun-elysia",
|
|
110
|
+
prefix,
|
|
111
|
+
services: [...names],
|
|
112
|
+
routes,
|
|
113
|
+
preparations,
|
|
114
|
+
diagnostics
|
|
115
|
+
}),
|
|
116
|
+
bindings
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
15
120
|
//#region src/registry.ts
|
|
16
121
|
var ServiceRegistry = class {
|
|
17
122
|
_revision = 0;
|
|
@@ -23,8 +128,16 @@ var ServiceRegistry = class {
|
|
|
23
128
|
this._revision++;
|
|
24
129
|
}
|
|
25
130
|
services = /* @__PURE__ */ new Map();
|
|
131
|
+
routes = /* @__PURE__ */ new Map();
|
|
132
|
+
/** Remember the actual registered routes for subsequent registry exports. */
|
|
133
|
+
setApplicationRoutes(application) {
|
|
134
|
+
for (const service of application.services) this.routes.set(service, application.routes.filter((route) => route.service === service.name));
|
|
135
|
+
this.touch();
|
|
136
|
+
}
|
|
26
137
|
register(service) {
|
|
27
138
|
if (this.services.has(service.name)) console.warn(`[Brick-TS] Service '${service.name}' is already registered. Overwriting.`);
|
|
139
|
+
const previous = this.services.get(service.name);
|
|
140
|
+
if (previous) this.routes.delete(previous);
|
|
28
141
|
this.services.set(service.name, service);
|
|
29
142
|
this.touch();
|
|
30
143
|
}
|
|
@@ -39,12 +152,28 @@ var ServiceRegistry = class {
|
|
|
39
152
|
}
|
|
40
153
|
clear() {
|
|
41
154
|
this.services.clear();
|
|
155
|
+
this.routes.clear();
|
|
42
156
|
this.touch();
|
|
43
157
|
}
|
|
44
|
-
exportArchitecture() {
|
|
158
|
+
exportArchitecture(application) {
|
|
45
159
|
return {
|
|
46
160
|
version: "1.0.0",
|
|
47
|
-
services: this.list().map((
|
|
161
|
+
services: (application?.services ?? this.list()).map((service) => {
|
|
162
|
+
const routes = application ? application.routes.filter((route) => route.service === service.name) : this.routes.get(service) ?? analyzeDeclaredApplication([service]).ir.routes;
|
|
163
|
+
const byAction = new Map(routes.map((route) => [route.action, route]));
|
|
164
|
+
const schema = service.introspect();
|
|
165
|
+
return {
|
|
166
|
+
...schema,
|
|
167
|
+
actions: schema.actions.map((action) => {
|
|
168
|
+
const route = byAction.get(action.name);
|
|
169
|
+
return route ? {
|
|
170
|
+
...action,
|
|
171
|
+
method: route.method,
|
|
172
|
+
path: route.path
|
|
173
|
+
} : action;
|
|
174
|
+
})
|
|
175
|
+
};
|
|
176
|
+
})
|
|
48
177
|
};
|
|
49
178
|
}
|
|
50
179
|
};
|
|
@@ -98,6 +227,7 @@ const defaultLogger$1 = {
|
|
|
98
227
|
};
|
|
99
228
|
const DEFAULT_REQUEST$3 = new Request("http://localhost");
|
|
100
229
|
let _defaultCtxSeq = 0;
|
|
230
|
+
const RESOLVED_SYMBOL$1 = Symbol("resolved");
|
|
101
231
|
const standardErrorDefaults = {
|
|
102
232
|
BAD_REQUEST: {
|
|
103
233
|
status: 400,
|
|
@@ -125,7 +255,7 @@ const standardErrorDefaults = {
|
|
|
125
255
|
}
|
|
126
256
|
};
|
|
127
257
|
function createDefaultContext(partial) {
|
|
128
|
-
if (partial?.
|
|
258
|
+
if (partial?.[RESOLVED_SYMBOL$1]) return partial;
|
|
129
259
|
const seq = (++_defaultCtxSeq).toString(36);
|
|
130
260
|
return {
|
|
131
261
|
request: partial?.request ?? DEFAULT_REQUEST$3,
|
|
@@ -137,7 +267,7 @@ function createDefaultContext(partial) {
|
|
|
137
267
|
services: partial?.services || {},
|
|
138
268
|
metadata: partial?.metadata || {},
|
|
139
269
|
...partial,
|
|
140
|
-
|
|
270
|
+
[RESOLVED_SYMBOL$1]: true
|
|
141
271
|
};
|
|
142
272
|
}
|
|
143
273
|
function buildErrorHelpers(errorsDef) {
|
|
@@ -179,12 +309,10 @@ function defineAction(config) {
|
|
|
179
309
|
};
|
|
180
310
|
actionFn.execute = async (params) => {
|
|
181
311
|
let fullCtx;
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
else fullCtx = createDefaultContext(params?.ctx);
|
|
187
|
-
}
|
|
312
|
+
const boundService = actionFn.service;
|
|
313
|
+
if (params?.ctx?.[RESOLVED_SYMBOL$1] === boundService) fullCtx = params.ctx;
|
|
314
|
+
else if (boundService && typeof boundService.resolveContext === "function") fullCtx = await boundService.resolveContext(params?.ctx);
|
|
315
|
+
else fullCtx = createDefaultContext(params?.ctx);
|
|
188
316
|
if (!fullCtx.db) {
|
|
189
317
|
if (actionFn.service?.getDb()) fullCtx.db = actionFn.service.getDb();
|
|
190
318
|
else if (actionFn.serviceName) {
|
|
@@ -218,7 +346,7 @@ function defineAction(config) {
|
|
|
218
346
|
}
|
|
219
347
|
//#endregion
|
|
220
348
|
//#region src/plugin.ts
|
|
221
|
-
const pluginKind = Symbol("
|
|
349
|
+
const pluginKind = Symbol.for("brickkit.plugin.kind");
|
|
222
350
|
function defineServicePlugin(definition) {
|
|
223
351
|
validateName(definition.name);
|
|
224
352
|
return Object.freeze({
|
|
@@ -296,7 +424,9 @@ function getPluginActionRoute(action, prefix = "/api") {
|
|
|
296
424
|
return {
|
|
297
425
|
path: pathOf(binding, prefix),
|
|
298
426
|
method: binding.method,
|
|
299
|
-
clientPath: binding.clientPath
|
|
427
|
+
clientPath: binding.clientPath,
|
|
428
|
+
plugin: binding.plugin,
|
|
429
|
+
resource: binding.resource?.name
|
|
300
430
|
};
|
|
301
431
|
}
|
|
302
432
|
function getPluginEndpoints(service, prefix = "/api") {
|
|
@@ -371,6 +501,7 @@ function installPlugin(service, resource, descriptor) {
|
|
|
371
501
|
return {
|
|
372
502
|
service,
|
|
373
503
|
resource,
|
|
504
|
+
plugin: descriptor.name,
|
|
374
505
|
path,
|
|
375
506
|
method: config.method,
|
|
376
507
|
scope,
|
|
@@ -381,13 +512,15 @@ function installPlugin(service, resource, descriptor) {
|
|
|
381
512
|
action(config) {
|
|
382
513
|
const binding = bindingFor(config);
|
|
383
514
|
for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, match[1])) throw new Error(`Plugin action path parameter '${match[1]}' must be declared in its input schema`);
|
|
384
|
-
const name = `${resource ? `${resource.name}.` : ""}${
|
|
385
|
-
if (service.actions.has(name)) throw new Error(`Duplicate plugin action '${name}'`);
|
|
515
|
+
const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
|
|
516
|
+
if (service.actions.has(name)) throw new Error(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
|
|
386
517
|
const { scope: _scope, ...actionConfig } = config;
|
|
387
518
|
const action = defineAction({
|
|
388
519
|
...actionConfig,
|
|
389
520
|
name
|
|
390
521
|
});
|
|
522
|
+
action.plugin = descriptor.name;
|
|
523
|
+
if (resource) action.resource = resource.name;
|
|
391
524
|
service.action(action);
|
|
392
525
|
ownedActions.add(action);
|
|
393
526
|
state.actions.set(action, binding);
|
|
@@ -474,15 +607,23 @@ function restoreMap(target, snapshot) {
|
|
|
474
607
|
for (const [key, value] of snapshot) target.set(key, value);
|
|
475
608
|
}
|
|
476
609
|
//#endregion
|
|
477
|
-
//#region src/
|
|
478
|
-
let _srvSeq = 0;
|
|
610
|
+
//#region src/compiler/runtime.ts
|
|
479
611
|
const EMPTY_SERVICES$2 = Object.freeze({});
|
|
480
612
|
const DEFAULT_REQUEST$2 = new Request("http://localhost");
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
613
|
+
let sequence = 0;
|
|
614
|
+
function isNonEmpty$1(value) {
|
|
615
|
+
if (value == null) return false;
|
|
616
|
+
for (const _ in value) return true;
|
|
484
617
|
return false;
|
|
485
618
|
}
|
|
619
|
+
/** Retains Brick's existing source precedence and treatment of empty bodies. */
|
|
620
|
+
function mergeInput(first, second, third) {
|
|
621
|
+
const a = isNonEmpty$1(first), b = isNonEmpty$1(second), c = isNonEmpty$1(third);
|
|
622
|
+
if (a && !b && !c) return first;
|
|
623
|
+
if (b && !a && !c) return second;
|
|
624
|
+
if (c && !a && !b) return third;
|
|
625
|
+
if (a || b || c) return Object.assign({}, first, second, third);
|
|
626
|
+
}
|
|
486
627
|
const MAX_INPUT_DEPTH = 128;
|
|
487
628
|
function inputTooDeep(value) {
|
|
488
629
|
if (!value || typeof value !== "object") return false;
|
|
@@ -503,6 +644,57 @@ function inputTooDeep(value) {
|
|
|
503
644
|
}
|
|
504
645
|
return false;
|
|
505
646
|
}
|
|
647
|
+
function checkDepth(value, action) {
|
|
648
|
+
if (!inputTooDeep(value)) return;
|
|
649
|
+
throw new ValidationError(`Validation failed for action '${action}' input`, [{
|
|
650
|
+
path: "",
|
|
651
|
+
message: "Input exceeds maximum nesting depth"
|
|
652
|
+
}]);
|
|
653
|
+
}
|
|
654
|
+
function validate(check, value, action, stage) {
|
|
655
|
+
if (check.Check(value)) return;
|
|
656
|
+
const errors = Array.from(check.Errors(value)).map((err) => ({
|
|
657
|
+
path: err.path,
|
|
658
|
+
message: err.message,
|
|
659
|
+
value: err.value
|
|
660
|
+
}));
|
|
661
|
+
throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
|
|
662
|
+
}
|
|
663
|
+
function mapError(err, set) {
|
|
664
|
+
if (err instanceof ValidationError || err instanceof ActionExecutionError) {
|
|
665
|
+
set.status = err.status || 400;
|
|
666
|
+
return err.toJSON();
|
|
667
|
+
}
|
|
668
|
+
set.status = 500;
|
|
669
|
+
return {
|
|
670
|
+
name: "InternalServerError",
|
|
671
|
+
message: err?.message || "An unexpected error occurred",
|
|
672
|
+
status: 500
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
const compilerRuntime = Object.freeze({
|
|
676
|
+
emptyServices: EMPTY_SERVICES$2,
|
|
677
|
+
defaultRequest: DEFAULT_REQUEST$2,
|
|
678
|
+
nextSequence: () => (++sequence).toString(36),
|
|
679
|
+
mergeInput,
|
|
680
|
+
checkDepth,
|
|
681
|
+
validate,
|
|
682
|
+
mapError,
|
|
683
|
+
isThenable: (value) => value != null && typeof value.then === "function",
|
|
684
|
+
deny: (action) => {
|
|
685
|
+
throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${action}'`, 403);
|
|
686
|
+
}
|
|
687
|
+
});
|
|
688
|
+
//#endregion
|
|
689
|
+
//#region src/action-handler.ts
|
|
690
|
+
let _srvSeq = 0;
|
|
691
|
+
const EMPTY_SERVICES$1 = Object.freeze({});
|
|
692
|
+
const DEFAULT_REQUEST$1 = new Request("http://localhost");
|
|
693
|
+
function isNonEmpty(obj) {
|
|
694
|
+
if (obj == null) return false;
|
|
695
|
+
for (const _ in obj) return true;
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
506
698
|
function compileRoutePlan(service, action, routePath, method) {
|
|
507
699
|
const actionName = action.name;
|
|
508
700
|
const serviceName = service.name;
|
|
@@ -595,9 +787,9 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
595
787
|
}
|
|
596
788
|
}
|
|
597
789
|
}
|
|
598
|
-
const hasP = isNonEmpty
|
|
599
|
-
const hasB = isNonEmpty
|
|
600
|
-
const hasQ = isNonEmpty
|
|
790
|
+
const hasP = isNonEmpty(params);
|
|
791
|
+
const hasB = isNonEmpty(body);
|
|
792
|
+
const hasQ = isNonEmpty(coercedQuery);
|
|
601
793
|
if (plan.isGetLike) {
|
|
602
794
|
if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
603
795
|
else if (hasP && !hasQ && !hasB) input = params;
|
|
@@ -609,12 +801,12 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
609
801
|
else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
|
|
610
802
|
}
|
|
611
803
|
const ctx = {
|
|
612
|
-
request: request instanceof Request ? request : DEFAULT_REQUEST$
|
|
804
|
+
request: request instanceof Request ? request : DEFAULT_REQUEST$1,
|
|
613
805
|
traceId,
|
|
614
806
|
requestId,
|
|
615
807
|
db: plan.cachedDb ?? plan.service.getDb(),
|
|
616
808
|
logger: plan.logger,
|
|
617
|
-
services: EMPTY_SERVICES$
|
|
809
|
+
services: EMPTY_SERVICES$1,
|
|
618
810
|
metadata: { headers },
|
|
619
811
|
_resolved: true
|
|
620
812
|
};
|
|
@@ -682,211 +874,104 @@ function createActionHandler(service, action, routePath, method) {
|
|
|
682
874
|
return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
|
|
683
875
|
}
|
|
684
876
|
//#endregion
|
|
685
|
-
//#region src/compiler/
|
|
686
|
-
function
|
|
687
|
-
if (
|
|
688
|
-
|
|
689
|
-
|
|
877
|
+
//#region src/compiler/handler.ts
|
|
878
|
+
function coerceQueryValue(value, type) {
|
|
879
|
+
if (type === "number" && value !== void 0) {
|
|
880
|
+
const number = Number(value);
|
|
881
|
+
return Number.isNaN(number) ? value : number;
|
|
690
882
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
|
|
695
|
-
}
|
|
696
|
-
function analyzeApplication(services, prefix = "/api") {
|
|
697
|
-
if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
|
|
698
|
-
const names = /* @__PURE__ */ new Set();
|
|
699
|
-
for (const service of services) {
|
|
700
|
-
if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
|
|
701
|
-
names.add(service.name);
|
|
702
|
-
service.build();
|
|
883
|
+
if (type === "boolean") {
|
|
884
|
+
if (value === "true" || value === "1") return true;
|
|
885
|
+
if (value === "false" || value === "0") return false;
|
|
703
886
|
}
|
|
704
|
-
|
|
705
|
-
const bindings = [];
|
|
706
|
-
const registered = /* @__PURE__ */ new Map();
|
|
707
|
-
const diagnostics = [];
|
|
708
|
-
const add = (service, action, method, path, kind) => {
|
|
709
|
-
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
710
|
-
const plugin = getPluginActionRoute(action, prefix) !== void 0;
|
|
711
|
-
const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
712
|
-
const previous = registered.get(key);
|
|
713
|
-
if (previous) {
|
|
714
|
-
if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
715
|
-
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
|
|
716
|
-
return;
|
|
717
|
-
}
|
|
718
|
-
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
719
|
-
registered.set(key, {
|
|
720
|
-
name: `${service.name}.${action.name}`,
|
|
721
|
-
plugin
|
|
722
|
-
});
|
|
723
|
-
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");
|
|
724
|
-
const coercions = [];
|
|
725
|
-
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
726
|
-
key,
|
|
727
|
-
type: "number"
|
|
728
|
-
});
|
|
729
|
-
else if (prop.type === "boolean") coercions.push({
|
|
730
|
-
key,
|
|
731
|
-
type: "boolean"
|
|
732
|
-
});
|
|
733
|
-
routes.push({
|
|
734
|
-
method,
|
|
735
|
-
path,
|
|
736
|
-
service: service.name,
|
|
737
|
-
action: action.name,
|
|
738
|
-
kind,
|
|
739
|
-
input: Boolean(action.config.input),
|
|
740
|
-
output: Boolean(action.config.output),
|
|
741
|
-
context: typeof service.options.context === "function",
|
|
742
|
-
authorize: typeof action.config.authorize === "function",
|
|
743
|
-
inputPrecedence: readLike ? [
|
|
744
|
-
"query",
|
|
745
|
-
"params",
|
|
746
|
-
"body"
|
|
747
|
-
] : [
|
|
748
|
-
"params",
|
|
749
|
-
"body",
|
|
750
|
-
"query"
|
|
751
|
-
],
|
|
752
|
-
coercions,
|
|
753
|
-
inputSchema: schemaSnapshot(action.config.input),
|
|
754
|
-
outputSchema: schemaSnapshot(action.config.output)
|
|
755
|
-
});
|
|
756
|
-
bindings.push({
|
|
757
|
-
service,
|
|
758
|
-
action
|
|
759
|
-
});
|
|
760
|
-
};
|
|
761
|
-
for (const service of services) for (const action of service.listActions()) {
|
|
762
|
-
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
763
|
-
if (pluginRoute === false) continue;
|
|
764
|
-
const path = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
765
|
-
add(service, action, pluginRoute?.method ?? action.config.method ?? "POST", path, "action");
|
|
766
|
-
}
|
|
767
|
-
const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
|
|
768
|
-
service: service.name,
|
|
769
|
-
name: contribution.name,
|
|
770
|
-
metadata: schemaSnapshot(contribution.describe?.())
|
|
771
|
-
})));
|
|
772
|
-
return {
|
|
773
|
-
ir: freezeIR({
|
|
774
|
-
version: 1,
|
|
775
|
-
target: "bun-elysia",
|
|
776
|
-
prefix,
|
|
777
|
-
services: [...names],
|
|
778
|
-
routes,
|
|
779
|
-
preparations,
|
|
780
|
-
diagnostics
|
|
781
|
-
}),
|
|
782
|
-
bindings
|
|
783
|
-
};
|
|
887
|
+
return value;
|
|
784
888
|
}
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
for (const [index, coercion] of route.coercions.entries()) {
|
|
797
|
-
const key = JSON.stringify(coercion.key);
|
|
798
|
-
input.push(`const v${index} = query[${key}];`);
|
|
799
|
-
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}; }`);
|
|
800
|
-
else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
|
|
889
|
+
/** Bind route metadata with ordinary closures; emitted factories remain build-only. */
|
|
890
|
+
function createHandlerFactory(route) {
|
|
891
|
+
return (binding, runtime) => {
|
|
892
|
+
const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
|
|
893
|
+
const readLike = route.inputPrecedence[0] === "query";
|
|
894
|
+
const objectInput = binding.action.config.input?.type === "object";
|
|
895
|
+
const readInput = route.input ? ({ params, body, query }) => {
|
|
896
|
+
let coercedQuery = query;
|
|
897
|
+
if (query && route.coercions.length) {
|
|
898
|
+
coercedQuery = { ...query };
|
|
899
|
+
for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type);
|
|
801
900
|
}
|
|
802
|
-
input.
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
if (
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
message: err?.message || "An unexpected error occurred",
|
|
875
|
-
status: 500
|
|
901
|
+
let input = readLike ? runtime.mergeInput(coercedQuery, params, body) : runtime.mergeInput(params, body, coercedQuery);
|
|
902
|
+
if (objectInput) input ??= {};
|
|
903
|
+
return input;
|
|
904
|
+
} : () => void 0;
|
|
905
|
+
const validateInput = (input) => {
|
|
906
|
+
if (inputChecker) {
|
|
907
|
+
runtime.checkDepth(input, route.action);
|
|
908
|
+
runtime.validate(inputChecker, input, route.action, "input");
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
const validateOutput = (result) => {
|
|
912
|
+
if (route.output && outputChecker) runtime.validate(outputChecker, result, route.action, "output");
|
|
913
|
+
return result;
|
|
914
|
+
};
|
|
915
|
+
const createContext = ({ headers, request, set }) => {
|
|
916
|
+
const seq = runtime.nextSequence();
|
|
917
|
+
const traceId = headers?.["x-trace-id"] || "tr_" + seq;
|
|
918
|
+
const requestId = headers?.["x-request-id"] || "req_" + seq;
|
|
919
|
+
if (set?.headers) {
|
|
920
|
+
set.headers["x-trace-id"] = traceId;
|
|
921
|
+
set.headers["x-request-id"] = requestId;
|
|
922
|
+
}
|
|
923
|
+
return {
|
|
924
|
+
request: request instanceof Request ? request : runtime.defaultRequest,
|
|
925
|
+
traceId,
|
|
926
|
+
requestId,
|
|
927
|
+
db: cachedDb ?? service.getDb(),
|
|
928
|
+
logger,
|
|
929
|
+
services: runtime.emptyServices,
|
|
930
|
+
metadata: { headers },
|
|
931
|
+
_resolved: true
|
|
932
|
+
};
|
|
933
|
+
};
|
|
934
|
+
if (contextHook || authorize) return async function brickAction(context) {
|
|
935
|
+
const input = readInput(context);
|
|
936
|
+
const ctx = createContext(context);
|
|
937
|
+
try {
|
|
938
|
+
if (contextHook) {
|
|
939
|
+
const extra = await contextHook(ctx);
|
|
940
|
+
if (extra) Object.assign(ctx, extra);
|
|
941
|
+
}
|
|
942
|
+
validateInput(input);
|
|
943
|
+
if (authorize && !await authorize({
|
|
944
|
+
ctx,
|
|
945
|
+
input,
|
|
946
|
+
user: ctx.user
|
|
947
|
+
})) runtime.deny(route.action);
|
|
948
|
+
return validateOutput(await execute({
|
|
949
|
+
input,
|
|
950
|
+
ctx,
|
|
951
|
+
error: errorBuilder
|
|
952
|
+
}));
|
|
953
|
+
} catch (err) {
|
|
954
|
+
return runtime.mapError(err, context.set);
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
return function brickAction(context) {
|
|
958
|
+
const input = readInput(context);
|
|
959
|
+
const ctx = createContext(context);
|
|
960
|
+
try {
|
|
961
|
+
validateInput(input);
|
|
962
|
+
const result = execute({
|
|
963
|
+
input,
|
|
964
|
+
ctx,
|
|
965
|
+
error: errorBuilder
|
|
966
|
+
});
|
|
967
|
+
if (runtime.isThenable(result)) return Promise.resolve(result).then(validateOutput).catch((err) => runtime.mapError(err, context.set));
|
|
968
|
+
return validateOutput(result);
|
|
969
|
+
} catch (err) {
|
|
970
|
+
return runtime.mapError(err, context.set);
|
|
971
|
+
}
|
|
972
|
+
};
|
|
876
973
|
};
|
|
877
974
|
}
|
|
878
|
-
const compilerRuntime = Object.freeze({
|
|
879
|
-
emptyServices: EMPTY_SERVICES$1,
|
|
880
|
-
defaultRequest: DEFAULT_REQUEST$1,
|
|
881
|
-
nextSequence: () => (++sequence).toString(36),
|
|
882
|
-
mergeInput,
|
|
883
|
-
validate,
|
|
884
|
-
mapError,
|
|
885
|
-
isThenable: (value) => value != null && typeof value.then === "function",
|
|
886
|
-
deny: (action) => {
|
|
887
|
-
throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${action}'`, 403);
|
|
888
|
-
}
|
|
889
|
-
});
|
|
890
975
|
//#endregion
|
|
891
976
|
//#region src/app-entry.ts
|
|
892
977
|
function isBrickApp(app) {
|
|
@@ -933,12 +1018,12 @@ function bindAnalyzed(ir, bindings, factories) {
|
|
|
933
1018
|
routes: Object.freeze(routes)
|
|
934
1019
|
});
|
|
935
1020
|
}
|
|
936
|
-
/** Startup compiler: analyzes once,
|
|
1021
|
+
/** Startup compiler: analyzes once, then binds live callbacks. */
|
|
937
1022
|
function compileBrickApplication(options) {
|
|
938
1023
|
const bind = buildBindings.get(applicationKey(options.services, options.prefix));
|
|
939
1024
|
if (bind && options.mode !== "generic") return bind(options.services);
|
|
940
1025
|
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
941
|
-
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(
|
|
1026
|
+
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(createHandlerFactory);
|
|
942
1027
|
if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
|
|
943
1028
|
return bindAnalyzed(ir, bindings, factories);
|
|
944
1029
|
}
|
|
@@ -951,6 +1036,44 @@ function bindCompiledApplication(ir, services, factories) {
|
|
|
951
1036
|
return bindAnalyzed(ir, analyzed.bindings, factories);
|
|
952
1037
|
}
|
|
953
1038
|
//#endregion
|
|
1039
|
+
//#region src/access.ts
|
|
1040
|
+
/**
|
|
1041
|
+
* Cross-copy access metadata protocol. CRUD enforces its access policy
|
|
1042
|
+
* inside `execute`, so `config.authorize` is absent and introspection
|
|
1043
|
+
* can't see it. The plugin stamps each action under this process-global
|
|
1044
|
+
* symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
|
|
1045
|
+
* the binding survives a second copy of core (bundler SSR, Vitest),
|
|
1046
|
+
* same as the plugin action-binding key.
|
|
1047
|
+
*/
|
|
1048
|
+
const ACTION_ACCESS_KEY = Symbol.for("brickkit.action.access");
|
|
1049
|
+
function setActionAccess(action, info) {
|
|
1050
|
+
action[ACTION_ACCESS_KEY] = {
|
|
1051
|
+
hasAuthorize: info.hasAuthorize,
|
|
1052
|
+
hasScope: info.hasScope,
|
|
1053
|
+
policy: info.policy
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
function getActionAccess(action) {
|
|
1057
|
+
const meta = action[ACTION_ACCESS_KEY];
|
|
1058
|
+
const configAuthorize = Boolean(action?.config && typeof action.config === "object" && "authorize" in action.config && typeof action.config.authorize === "function");
|
|
1059
|
+
if (!meta) return {
|
|
1060
|
+
hasAuthorize: configAuthorize,
|
|
1061
|
+
hasScope: false,
|
|
1062
|
+
policy: configAuthorize ? "authorized" : "public"
|
|
1063
|
+
};
|
|
1064
|
+
const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
|
|
1065
|
+
const hasScope = Boolean(meta.hasScope);
|
|
1066
|
+
let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
|
|
1067
|
+
if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
|
|
1068
|
+
else if (policy !== "public" && !hasAuthorize) policy = "public";
|
|
1069
|
+
else if (policy === "scoped" && !hasScope) policy = "authorized";
|
|
1070
|
+
return {
|
|
1071
|
+
hasAuthorize,
|
|
1072
|
+
hasScope,
|
|
1073
|
+
policy
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
//#endregion
|
|
954
1077
|
//#region src/openapi.ts
|
|
955
1078
|
function generateOpenApiSpec(options = {}) {
|
|
956
1079
|
const title = options.title ?? "Brick-TS API Mesh";
|
|
@@ -972,7 +1095,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
972
1095
|
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
973
1096
|
if (!paths[actionPath]) paths[actionPath] = {};
|
|
974
1097
|
if (paths[actionPath][method]) continue;
|
|
975
|
-
const hasAuth =
|
|
1098
|
+
const hasAuth = getActionAccess(action).hasAuthorize;
|
|
976
1099
|
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
977
1100
|
const responses = {};
|
|
978
1101
|
if (action.config.output) responses["200"] = {
|
|
@@ -1036,6 +1159,8 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1036
1159
|
summary: `${service.name}.${action.name}`,
|
|
1037
1160
|
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1038
1161
|
tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
|
|
1162
|
+
...action.plugin ? { "x-brick-plugin": action.plugin } : {},
|
|
1163
|
+
...action.resource ? { "x-brick-resource": action.resource } : {},
|
|
1039
1164
|
responses
|
|
1040
1165
|
};
|
|
1041
1166
|
const inputSchema = action.config.input;
|
|
@@ -1375,8 +1500,8 @@ function resolveEndpointDb(service, services) {
|
|
|
1375
1500
|
/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
|
|
1376
1501
|
function createEndpointHandler(def, services) {
|
|
1377
1502
|
return async ({ params, body, query, headers, request, set }) => {
|
|
1378
|
-
const traceId = headers?.["x-trace-id"] || `tr_${
|
|
1379
|
-
const requestId = headers?.["x-request-id"] || `req_${
|
|
1503
|
+
const traceId = headers?.["x-trace-id"] || `tr_${crypto.randomUUID()}`;
|
|
1504
|
+
const requestId = headers?.["x-request-id"] || `req_${crypto.randomUUID()}`;
|
|
1380
1505
|
if (set?.headers) {
|
|
1381
1506
|
set.headers["x-trace-id"] = traceId;
|
|
1382
1507
|
set.headers["x-request-id"] = requestId;
|
|
@@ -1476,10 +1601,6 @@ function brick(options = {}) {
|
|
|
1476
1601
|
uptime: process.uptime(),
|
|
1477
1602
|
timestamp: Date.now()
|
|
1478
1603
|
}));
|
|
1479
|
-
app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(), () => {
|
|
1480
|
-
const registry = getGlobalRegistry();
|
|
1481
|
-
return [registry, registry.revision];
|
|
1482
|
-
}) : () => getGlobalRegistry().exportArchitecture());
|
|
1483
1604
|
const requestLogging = options.requestLogging ?? true;
|
|
1484
1605
|
if (requestLogging !== false) {
|
|
1485
1606
|
const pluginOpts = requestLogging === true ? {} : requestLogging;
|
|
@@ -1548,7 +1669,7 @@ function brick(options = {}) {
|
|
|
1548
1669
|
const key = routeKey(method, path);
|
|
1549
1670
|
if (registeredRoutes.has(key)) {
|
|
1550
1671
|
if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
1551
|
-
return;
|
|
1672
|
+
return false;
|
|
1552
1673
|
}
|
|
1553
1674
|
switch (method) {
|
|
1554
1675
|
case "GET":
|
|
@@ -1566,6 +1687,7 @@ function brick(options = {}) {
|
|
|
1566
1687
|
case "DELETE": app.delete(path, handler);
|
|
1567
1688
|
}
|
|
1568
1689
|
registeredRoutes.set(key, plugin);
|
|
1690
|
+
return true;
|
|
1569
1691
|
};
|
|
1570
1692
|
const mountEndpoint = (def, plugin = false) => {
|
|
1571
1693
|
mountRoute(def.method, def.path, createEndpointHandler(def, services), plugin);
|
|
@@ -1575,10 +1697,6 @@ function brick(options = {}) {
|
|
|
1575
1697
|
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
1576
1698
|
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
1577
1699
|
const brickApp = app;
|
|
1578
|
-
Object.defineProperty(brickApp, "definition", { value: Object.freeze({
|
|
1579
|
-
services: Object.freeze([...services]),
|
|
1580
|
-
prefix
|
|
1581
|
-
}) });
|
|
1582
1700
|
brickApp.endpoint = (def) => {
|
|
1583
1701
|
mountEndpoint(def);
|
|
1584
1702
|
};
|
|
@@ -1589,13 +1707,25 @@ function brick(options = {}) {
|
|
|
1589
1707
|
mode: options.compiler === false ? "generic" : "specialized"
|
|
1590
1708
|
});
|
|
1591
1709
|
if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
|
|
1710
|
+
const mountedRoutes = [];
|
|
1592
1711
|
for (const route of compilation.routes) {
|
|
1593
1712
|
const action = services.find((candidate) => candidate.name === route.ir.service).listActions().find((candidate) => candidate.name === route.ir.action);
|
|
1594
|
-
mountRoute(route.ir.method, route.ir.path, (context) => {
|
|
1713
|
+
if (mountRoute(route.ir.method, route.ir.path, (context) => {
|
|
1595
1714
|
const result = route.handler(context);
|
|
1596
1715
|
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
1597
|
-
}, getPluginActionRoute(action, prefix) !== void 0);
|
|
1716
|
+
}, getPluginActionRoute(action, prefix) !== void 0)) mountedRoutes.push(route.ir);
|
|
1598
1717
|
}
|
|
1718
|
+
const definition = Object.freeze({
|
|
1719
|
+
services: Object.freeze([...services]),
|
|
1720
|
+
prefix,
|
|
1721
|
+
routes: Object.freeze(mountedRoutes)
|
|
1722
|
+
});
|
|
1723
|
+
Object.defineProperty(brickApp, "definition", { value: definition });
|
|
1724
|
+
getGlobalRegistry().setApplicationRoutes(definition);
|
|
1725
|
+
app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
|
|
1726
|
+
const registry = getGlobalRegistry();
|
|
1727
|
+
return [registry, registry.revision];
|
|
1728
|
+
}) : () => getGlobalRegistry().exportArchitecture(definition));
|
|
1599
1729
|
return brickApp;
|
|
1600
1730
|
}
|
|
1601
1731
|
function jsonActionResult(value) {
|
|
@@ -1620,6 +1750,60 @@ function cachedJsonRoute(build, revision) {
|
|
|
1620
1750
|
};
|
|
1621
1751
|
}
|
|
1622
1752
|
//#endregion
|
|
1753
|
+
//#region src/compiler/emit.ts
|
|
1754
|
+
/** Emits framework code only. User callbacks remain closures bound separately. */
|
|
1755
|
+
function emitHandlerFactory(route) {
|
|
1756
|
+
const name = JSON.stringify(route.action);
|
|
1757
|
+
const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
|
|
1758
|
+
const input = ["let input;"];
|
|
1759
|
+
if (route.input) {
|
|
1760
|
+
input.push("let coercedQuery = query;");
|
|
1761
|
+
if (route.coercions.length) {
|
|
1762
|
+
input.push("if (query) {", "coercedQuery = { ...query };");
|
|
1763
|
+
for (const [index, coercion] of route.coercions.entries()) {
|
|
1764
|
+
const key = JSON.stringify(coercion.key);
|
|
1765
|
+
input.push(`const v${index} = query[${key}];`);
|
|
1766
|
+
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}; }`);
|
|
1767
|
+
else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
|
|
1768
|
+
}
|
|
1769
|
+
input.push("}");
|
|
1770
|
+
}
|
|
1771
|
+
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
|
|
1772
|
+
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
1773
|
+
}
|
|
1774
|
+
const asyncStages = route.context || route.authorize;
|
|
1775
|
+
const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
|
|
1776
|
+
const validation = route.input ? `checkDepth(input, ${name}); validate(inputChecker, input, ${name}, "input");` : "";
|
|
1777
|
+
const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : "";
|
|
1778
|
+
const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
|
|
1779
|
+
const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
|
|
1780
|
+
if (isThenable(result)) return Promise.resolve(result).then(value => {
|
|
1781
|
+
${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
|
|
1782
|
+
return value;
|
|
1783
|
+
}).catch(err => mapError(err, set));
|
|
1784
|
+
${output}
|
|
1785
|
+
return result;`;
|
|
1786
|
+
return `function bindAction(binding, runtime) {
|
|
1787
|
+
const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
|
|
1788
|
+
const { nextSequence, defaultRequest, emptyServices, mergeInput, checkDepth, validate, deny, mapError, isThenable } = runtime;
|
|
1789
|
+
return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
|
|
1790
|
+
const seq = nextSequence();
|
|
1791
|
+
const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
|
|
1792
|
+
const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
|
|
1793
|
+
if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
|
|
1794
|
+
${input.join("\n")}
|
|
1795
|
+
const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
|
|
1796
|
+
db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
|
|
1797
|
+
try {
|
|
1798
|
+
${context}
|
|
1799
|
+
${validation}
|
|
1800
|
+
${authorization}
|
|
1801
|
+
${execute}
|
|
1802
|
+
} catch (err) { return mapError(err, set); }
|
|
1803
|
+
};
|
|
1804
|
+
}`;
|
|
1805
|
+
}
|
|
1806
|
+
//#endregion
|
|
1623
1807
|
//#region src/tool.ts
|
|
1624
1808
|
function defineTool(config) {
|
|
1625
1809
|
if (config.input && config.input.type !== "object") throw new Error(`Tool '${config.name}' input must be an object schema`);
|
|
@@ -1631,12 +1815,8 @@ function isTool(value) {
|
|
|
1631
1815
|
return typeof value === "function" && value.kind === "tool";
|
|
1632
1816
|
}
|
|
1633
1817
|
//#endregion
|
|
1634
|
-
//#region src/db/load.ts
|
|
1635
|
-
function loadDriver(id) {
|
|
1636
|
-
return (globalThis.require ?? createRequire(import.meta.url))(id);
|
|
1637
|
-
}
|
|
1638
|
-
//#endregion
|
|
1639
1818
|
//#region src/db/sqlite.ts
|
|
1819
|
+
const requireSQLite = createRequire(import.meta.url);
|
|
1640
1820
|
/**
|
|
1641
1821
|
* Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
|
|
1642
1822
|
* and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
|
|
@@ -1649,7 +1829,7 @@ function createSQLiteDatabase(config = {}) {
|
|
|
1649
1829
|
let Database;
|
|
1650
1830
|
let drizzle;
|
|
1651
1831
|
try {
|
|
1652
|
-
({Database} =
|
|
1832
|
+
({Database} = requireSQLite("bun:sqlite"));
|
|
1653
1833
|
({drizzle} = __require("drizzle-orm/bun-sqlite"));
|
|
1654
1834
|
} catch (err) {
|
|
1655
1835
|
throw new Error(`[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`);
|
|
@@ -2013,6 +2193,7 @@ const DEFAULT_REQUEST = new Request("http://localhost");
|
|
|
2013
2193
|
const EMPTY_SERVICES = Object.freeze({});
|
|
2014
2194
|
const EMPTY_METADATA = Object.freeze({});
|
|
2015
2195
|
let _ctxSeq = 0;
|
|
2196
|
+
const RESOLVED_SYMBOL = Symbol("resolved");
|
|
2016
2197
|
var ServiceImpl = class {
|
|
2017
2198
|
name;
|
|
2018
2199
|
options;
|
|
@@ -2131,15 +2312,16 @@ var ServiceImpl = class {
|
|
|
2131
2312
|
/**
|
|
2132
2313
|
* Resolves the complete service execution context once per incoming request.
|
|
2133
2314
|
* Merges framework BaseContext with the service's custom context hook.
|
|
2315
|
+
* Always rebuilds context for this service to prevent caller context from overriding.
|
|
2134
2316
|
*/
|
|
2135
2317
|
resolveContext(callCtx) {
|
|
2136
|
-
if (callCtx?.
|
|
2318
|
+
if (callCtx?.[RESOLVED_SYMBOL] === this) return Promise.resolve(callCtx);
|
|
2137
2319
|
return this._resolveContextSlow(callCtx);
|
|
2138
2320
|
}
|
|
2139
2321
|
async _resolveContextSlow(callCtx) {
|
|
2140
2322
|
const seq = ++_ctxSeq;
|
|
2141
2323
|
const req = callCtx?.request ?? DEFAULT_REQUEST;
|
|
2142
|
-
const db =
|
|
2324
|
+
const db = this.getDb();
|
|
2143
2325
|
const logger = callCtx?.logger ?? defaultLogger;
|
|
2144
2326
|
const traceId = callCtx?.traceId ?? `tr_${seq.toString(36)}`;
|
|
2145
2327
|
const requestId = callCtx?.requestId ?? `req_${seq.toString(36)}`;
|
|
@@ -2154,9 +2336,10 @@ var ServiceImpl = class {
|
|
|
2154
2336
|
requestId,
|
|
2155
2337
|
services,
|
|
2156
2338
|
metadata,
|
|
2157
|
-
|
|
2339
|
+
[RESOLVED_SYMBOL]: this
|
|
2158
2340
|
};
|
|
2159
|
-
if (callCtx
|
|
2341
|
+
if (callCtx?.user !== void 0) finalCtx.user = callCtx.user;
|
|
2342
|
+
if (callCtx?.caller !== void 0) finalCtx.caller = callCtx.caller;
|
|
2160
2343
|
return finalCtx;
|
|
2161
2344
|
}
|
|
2162
2345
|
const fullBaseCtx = {
|
|
@@ -2169,12 +2352,23 @@ var ServiceImpl = class {
|
|
|
2169
2352
|
metadata
|
|
2170
2353
|
};
|
|
2171
2354
|
const resolvedExtra = await this.options.context(fullBaseCtx);
|
|
2172
|
-
|
|
2355
|
+
const finalCtx = {
|
|
2173
2356
|
...fullBaseCtx,
|
|
2174
2357
|
...resolvedExtra,
|
|
2175
|
-
|
|
2176
|
-
_resolved: true
|
|
2358
|
+
[RESOLVED_SYMBOL]: this
|
|
2177
2359
|
};
|
|
2360
|
+
if (callCtx) {
|
|
2361
|
+
for (const [key, value] of Object.entries(callCtx)) if (![
|
|
2362
|
+
"db",
|
|
2363
|
+
"request",
|
|
2364
|
+
"logger",
|
|
2365
|
+
"services",
|
|
2366
|
+
"metadata",
|
|
2367
|
+
"_resolved",
|
|
2368
|
+
RESOLVED_SYMBOL
|
|
2369
|
+
].includes(key)) finalCtx[key] = value;
|
|
2370
|
+
}
|
|
2371
|
+
return finalCtx;
|
|
2178
2372
|
}
|
|
2179
2373
|
introspect() {
|
|
2180
2374
|
const databaseConfig = this.database ? {
|
|
@@ -2185,23 +2379,27 @@ var ServiceImpl = class {
|
|
|
2185
2379
|
const { database: _database, ...options } = this.options;
|
|
2186
2380
|
return {
|
|
2187
2381
|
name: this.name,
|
|
2188
|
-
options
|
|
2189
|
-
...options,
|
|
2190
|
-
database: databaseConfig
|
|
2191
|
-
},
|
|
2382
|
+
options,
|
|
2192
2383
|
hasDatabase: Boolean(this.database),
|
|
2193
2384
|
databaseConfig,
|
|
2194
|
-
actions: this.listActions().map((act) =>
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2385
|
+
actions: this.listActions().map((act) => {
|
|
2386
|
+
const access = getActionAccess(act);
|
|
2387
|
+
return {
|
|
2388
|
+
name: act.name,
|
|
2389
|
+
serviceName: this.name,
|
|
2390
|
+
...act.plugin ? { plugin: act.plugin } : {},
|
|
2391
|
+
...act.resource ? { resource: act.resource } : {},
|
|
2392
|
+
description: act.config.description,
|
|
2393
|
+
inputSchema: act.config.input,
|
|
2394
|
+
outputSchema: act.config.output,
|
|
2395
|
+
hasAuthorize: access.hasAuthorize,
|
|
2396
|
+
hasScope: access.hasScope,
|
|
2397
|
+
accessPolicy: access.policy,
|
|
2398
|
+
errors: act.config.errors,
|
|
2399
|
+
emits: act.config.emits,
|
|
2400
|
+
tags: act.config.tags
|
|
2401
|
+
};
|
|
2402
|
+
}),
|
|
2205
2403
|
resources: this.listResources().map((res) => ({ name: res.name }))
|
|
2206
2404
|
};
|
|
2207
2405
|
}
|
|
@@ -2222,14 +2420,25 @@ function createServiceProxy(serviceName, options = {}) {
|
|
|
2222
2420
|
if (!service) throw new Error(`[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`);
|
|
2223
2421
|
const action = service.getAction(actionName);
|
|
2224
2422
|
if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
|
|
2225
|
-
const
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2423
|
+
const dangerousFields = /* @__PURE__ */ new Set([
|
|
2424
|
+
"db",
|
|
2425
|
+
"request",
|
|
2426
|
+
"logger",
|
|
2427
|
+
"services",
|
|
2428
|
+
"metadata",
|
|
2429
|
+
"_resolved"
|
|
2430
|
+
]);
|
|
2431
|
+
const envelopeCtx = {};
|
|
2432
|
+
if (options.context) {
|
|
2433
|
+
for (const [key, value] of Object.entries(options.context)) if (!dangerousFields.has(key)) envelopeCtx[key] = value;
|
|
2434
|
+
}
|
|
2435
|
+
if (callCtx) {
|
|
2436
|
+
for (const [key, value] of Object.entries(callCtx)) if (!dangerousFields.has(key)) envelopeCtx[key] = value;
|
|
2437
|
+
}
|
|
2438
|
+
if (!envelopeCtx.caller) envelopeCtx.caller = serviceName;
|
|
2230
2439
|
return action.execute({
|
|
2231
2440
|
input: payload,
|
|
2232
|
-
ctx:
|
|
2441
|
+
ctx: envelopeCtx
|
|
2233
2442
|
});
|
|
2234
2443
|
} else throw new Error(`[Brick-TS RPC] Remote microservice dispatch for '${serviceName}.${actionName}' is not yet configured for this environment.`);
|
|
2235
2444
|
};
|
|
@@ -2357,6 +2566,6 @@ function createMcpHandler(options) {
|
|
|
2357
2566
|
};
|
|
2358
2567
|
}
|
|
2359
2568
|
//#endregion
|
|
2360
|
-
export { ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type,
|
|
2569
|
+
export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, setActionAccess, sql, sqliteTable, swaggerDocsHTML, syncSchema, t, text, toOpenApiPath, uniqueIndex, validateWithSchema };
|
|
2361
2570
|
|
|
2362
2571
|
//# sourceMappingURL=index.js.map
|