@brickkit/core 0.3.0-beta.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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((s) => s.introspect())
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?._resolved) return 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
- _resolved: true
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
- if (params?.ctx?._resolved) fullCtx = params.ctx;
183
- else {
184
- const boundService = actionFn.service;
185
- if (boundService && typeof boundService.resolveContext === "function") fullCtx = await boundService.resolveContext(params?.ctx);
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("Brick plugin");
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}.` : ""}${descriptor.name}.${config.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/action-handler.ts
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
- function isNonEmpty$1(obj) {
482
- if (obj == null) return false;
483
- for (const _ in obj) return true;
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$1(params);
599
- const hasB = isNonEmpty$1(body);
600
- const hasQ = isNonEmpty$1(coercedQuery);
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$2,
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$2,
809
+ services: EMPTY_SERVICES$1,
618
810
  metadata: { headers },
619
811
  _resolved: true
620
812
  };
@@ -682,107 +874,6 @@ function createActionHandler(service, action, routePath, method) {
682
874
  return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
683
875
  }
684
876
  //#endregion
685
- //#region src/compiler/ir.ts
686
- function freezeIR(value) {
687
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
688
- for (const child of Object.values(value)) freezeIR(child);
689
- Object.freeze(value);
690
- }
691
- return value;
692
- }
693
- function schemaSnapshot(schema) {
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();
703
- }
704
- const routes = [];
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
- };
784
- }
785
- //#endregion
786
877
  //#region src/compiler/emit.ts
787
878
  /** Emits framework code only. User callbacks remain closures bound separately. */
788
879
  function emitHandlerFactory(route) {
@@ -806,7 +897,7 @@ function emitHandlerFactory(route) {
806
897
  }
807
898
  const asyncStages = route.context || route.authorize;
808
899
  const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
809
- const validation = route.input ? `validate(inputChecker, input, ${name}, "input");` : "";
900
+ const validation = route.input ? `checkDepth(input, ${name}); validate(inputChecker, input, ${name}, "input");` : "";
810
901
  const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : "";
811
902
  const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
812
903
  const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
@@ -818,7 +909,7 @@ ${output}
818
909
  return result;`;
819
910
  return `function bindAction(binding, runtime) {
820
911
  const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
821
- const { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;
912
+ const { nextSequence, defaultRequest, emptyServices, mergeInput, checkDepth, validate, deny, mapError, isThenable } = runtime;
822
913
  return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
823
914
  const seq = nextSequence();
824
915
  const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
@@ -837,57 +928,6 @@ ${execute}
837
928
  }`;
838
929
  }
839
930
  //#endregion
840
- //#region src/compiler/runtime.ts
841
- const EMPTY_SERVICES$1 = Object.freeze({});
842
- const DEFAULT_REQUEST$1 = new Request("http://localhost");
843
- let sequence = 0;
844
- function isNonEmpty(value) {
845
- if (value == null) return false;
846
- for (const _ in value) return true;
847
- return false;
848
- }
849
- /** Retains Brick's existing source precedence and treatment of empty bodies. */
850
- function mergeInput(first, second, third) {
851
- const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);
852
- if (a && !b && !c) return first;
853
- if (b && !a && !c) return second;
854
- if (c && !a && !b) return third;
855
- if (a || b || c) return Object.assign({}, first, second, third);
856
- }
857
- function validate(check, value, action, stage) {
858
- if (check.Check(value)) return;
859
- const errors = Array.from(check.Errors(value)).map((err) => ({
860
- path: err.path,
861
- message: err.message,
862
- value: err.value
863
- }));
864
- throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
865
- }
866
- function mapError(err, set) {
867
- if (err instanceof ValidationError || err instanceof ActionExecutionError) {
868
- set.status = err.status || 400;
869
- return err.toJSON();
870
- }
871
- set.status = 500;
872
- return {
873
- name: "InternalServerError",
874
- message: err?.message || "An unexpected error occurred",
875
- status: 500
876
- };
877
- }
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
- //#endregion
891
931
  //#region src/app-entry.ts
892
932
  function isBrickApp(app) {
893
933
  if (!app || typeof app !== "object") return false;
@@ -951,6 +991,44 @@ function bindCompiledApplication(ir, services, factories) {
951
991
  return bindAnalyzed(ir, analyzed.bindings, factories);
952
992
  }
953
993
  //#endregion
994
+ //#region src/access.ts
995
+ /**
996
+ * Cross-copy access metadata protocol. CRUD enforces its access policy
997
+ * inside `execute`, so `config.authorize` is absent and introspection
998
+ * can't see it. The plugin stamps each action under this process-global
999
+ * symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
1000
+ * the binding survives a second copy of core (bundler SSR, Vitest),
1001
+ * same as the plugin action-binding key.
1002
+ */
1003
+ const ACTION_ACCESS_KEY = Symbol.for("brickkit.action.access");
1004
+ function setActionAccess(action, info) {
1005
+ action[ACTION_ACCESS_KEY] = {
1006
+ hasAuthorize: info.hasAuthorize,
1007
+ hasScope: info.hasScope,
1008
+ policy: info.policy
1009
+ };
1010
+ }
1011
+ function getActionAccess(action) {
1012
+ const meta = action[ACTION_ACCESS_KEY];
1013
+ const configAuthorize = Boolean(action?.config && typeof action.config === "object" && "authorize" in action.config && typeof action.config.authorize === "function");
1014
+ if (!meta) return {
1015
+ hasAuthorize: configAuthorize,
1016
+ hasScope: false,
1017
+ policy: configAuthorize ? "authorized" : "public"
1018
+ };
1019
+ const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
1020
+ const hasScope = Boolean(meta.hasScope);
1021
+ let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
1022
+ if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
1023
+ else if (policy !== "public" && !hasAuthorize) policy = "public";
1024
+ else if (policy === "scoped" && !hasScope) policy = "authorized";
1025
+ return {
1026
+ hasAuthorize,
1027
+ hasScope,
1028
+ policy
1029
+ };
1030
+ }
1031
+ //#endregion
954
1032
  //#region src/openapi.ts
955
1033
  function generateOpenApiSpec(options = {}) {
956
1034
  const title = options.title ?? "Brick-TS API Mesh";
@@ -972,7 +1050,7 @@ function generateOpenApiSpec(options = {}) {
972
1050
  const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
973
1051
  if (!paths[actionPath]) paths[actionPath] = {};
974
1052
  if (paths[actionPath][method]) continue;
975
- const hasAuth = Boolean(action.config.authorize);
1053
+ const hasAuth = getActionAccess(action).hasAuthorize;
976
1054
  if (hasAuth) hasAnyAuthorizedAction = true;
977
1055
  const responses = {};
978
1056
  if (action.config.output) responses["200"] = {
@@ -1036,6 +1114,8 @@ function generateOpenApiSpec(options = {}) {
1036
1114
  summary: `${service.name}.${action.name}`,
1037
1115
  description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
1038
1116
  tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
1117
+ ...action.plugin ? { "x-brick-plugin": action.plugin } : {},
1118
+ ...action.resource ? { "x-brick-resource": action.resource } : {},
1039
1119
  responses
1040
1120
  };
1041
1121
  const inputSchema = action.config.input;
@@ -1375,8 +1455,8 @@ function resolveEndpointDb(service, services) {
1375
1455
  /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
1376
1456
  function createEndpointHandler(def, services) {
1377
1457
  return async ({ params, body, query, headers, request, set }) => {
1378
- const traceId = headers?.["x-trace-id"] || `tr_${Math.random().toString(36).substring(2, 10)}`;
1379
- const requestId = headers?.["x-request-id"] || `req_${Math.random().toString(36).substring(2, 10)}`;
1458
+ const traceId = headers?.["x-trace-id"] || `tr_${crypto.randomUUID()}`;
1459
+ const requestId = headers?.["x-request-id"] || `req_${crypto.randomUUID()}`;
1380
1460
  if (set?.headers) {
1381
1461
  set.headers["x-trace-id"] = traceId;
1382
1462
  set.headers["x-request-id"] = requestId;
@@ -1476,10 +1556,6 @@ function brick(options = {}) {
1476
1556
  uptime: process.uptime(),
1477
1557
  timestamp: Date.now()
1478
1558
  }));
1479
- app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(), () => {
1480
- const registry = getGlobalRegistry();
1481
- return [registry, registry.revision];
1482
- }) : () => getGlobalRegistry().exportArchitecture());
1483
1559
  const requestLogging = options.requestLogging ?? true;
1484
1560
  if (requestLogging !== false) {
1485
1561
  const pluginOpts = requestLogging === true ? {} : requestLogging;
@@ -1548,7 +1624,7 @@ function brick(options = {}) {
1548
1624
  const key = routeKey(method, path);
1549
1625
  if (registeredRoutes.has(key)) {
1550
1626
  if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
1551
- return;
1627
+ return false;
1552
1628
  }
1553
1629
  switch (method) {
1554
1630
  case "GET":
@@ -1566,6 +1642,7 @@ function brick(options = {}) {
1566
1642
  case "DELETE": app.delete(path, handler);
1567
1643
  }
1568
1644
  registeredRoutes.set(key, plugin);
1645
+ return true;
1569
1646
  };
1570
1647
  const mountEndpoint = (def, plugin = false) => {
1571
1648
  mountRoute(def.method, def.path, createEndpointHandler(def, services), plugin);
@@ -1575,10 +1652,6 @@ function brick(options = {}) {
1575
1652
  for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
1576
1653
  for (const def of options.endpoints ?? []) mountEndpoint(def);
1577
1654
  const brickApp = app;
1578
- Object.defineProperty(brickApp, "definition", { value: Object.freeze({
1579
- services: Object.freeze([...services]),
1580
- prefix
1581
- }) });
1582
1655
  brickApp.endpoint = (def) => {
1583
1656
  mountEndpoint(def);
1584
1657
  };
@@ -1589,13 +1662,25 @@ function brick(options = {}) {
1589
1662
  mode: options.compiler === false ? "generic" : "specialized"
1590
1663
  });
1591
1664
  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");
1665
+ const mountedRoutes = [];
1592
1666
  for (const route of compilation.routes) {
1593
1667
  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) => {
1668
+ if (mountRoute(route.ir.method, route.ir.path, (context) => {
1595
1669
  const result = route.handler(context);
1596
1670
  return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
1597
- }, getPluginActionRoute(action, prefix) !== void 0);
1671
+ }, getPluginActionRoute(action, prefix) !== void 0)) mountedRoutes.push(route.ir);
1598
1672
  }
1673
+ const definition = Object.freeze({
1674
+ services: Object.freeze([...services]),
1675
+ prefix,
1676
+ routes: Object.freeze(mountedRoutes)
1677
+ });
1678
+ Object.defineProperty(brickApp, "definition", { value: definition });
1679
+ getGlobalRegistry().setApplicationRoutes(definition);
1680
+ app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
1681
+ const registry = getGlobalRegistry();
1682
+ return [registry, registry.revision];
1683
+ }) : () => getGlobalRegistry().exportArchitecture(definition));
1599
1684
  return brickApp;
1600
1685
  }
1601
1686
  function jsonActionResult(value) {
@@ -2013,6 +2098,7 @@ const DEFAULT_REQUEST = new Request("http://localhost");
2013
2098
  const EMPTY_SERVICES = Object.freeze({});
2014
2099
  const EMPTY_METADATA = Object.freeze({});
2015
2100
  let _ctxSeq = 0;
2101
+ const RESOLVED_SYMBOL = Symbol("resolved");
2016
2102
  var ServiceImpl = class {
2017
2103
  name;
2018
2104
  options;
@@ -2131,15 +2217,16 @@ var ServiceImpl = class {
2131
2217
  /**
2132
2218
  * Resolves the complete service execution context once per incoming request.
2133
2219
  * Merges framework BaseContext with the service's custom context hook.
2220
+ * Always rebuilds context for this service to prevent caller context from overriding.
2134
2221
  */
2135
2222
  resolveContext(callCtx) {
2136
- if (callCtx?._resolved) return Promise.resolve(callCtx);
2223
+ if (callCtx?.[RESOLVED_SYMBOL] === this) return Promise.resolve(callCtx);
2137
2224
  return this._resolveContextSlow(callCtx);
2138
2225
  }
2139
2226
  async _resolveContextSlow(callCtx) {
2140
2227
  const seq = ++_ctxSeq;
2141
2228
  const req = callCtx?.request ?? DEFAULT_REQUEST;
2142
- const db = callCtx?.db ?? this.getDb();
2229
+ const db = this.getDb();
2143
2230
  const logger = callCtx?.logger ?? defaultLogger;
2144
2231
  const traceId = callCtx?.traceId ?? `tr_${seq.toString(36)}`;
2145
2232
  const requestId = callCtx?.requestId ?? `req_${seq.toString(36)}`;
@@ -2154,9 +2241,10 @@ var ServiceImpl = class {
2154
2241
  requestId,
2155
2242
  services,
2156
2243
  metadata,
2157
- _resolved: true
2244
+ [RESOLVED_SYMBOL]: this
2158
2245
  };
2159
- if (callCtx) Object.assign(finalCtx, callCtx, { _resolved: true });
2246
+ if (callCtx?.user !== void 0) finalCtx.user = callCtx.user;
2247
+ if (callCtx?.caller !== void 0) finalCtx.caller = callCtx.caller;
2160
2248
  return finalCtx;
2161
2249
  }
2162
2250
  const fullBaseCtx = {
@@ -2169,12 +2257,23 @@ var ServiceImpl = class {
2169
2257
  metadata
2170
2258
  };
2171
2259
  const resolvedExtra = await this.options.context(fullBaseCtx);
2172
- return {
2260
+ const finalCtx = {
2173
2261
  ...fullBaseCtx,
2174
2262
  ...resolvedExtra,
2175
- ...callCtx,
2176
- _resolved: true
2263
+ [RESOLVED_SYMBOL]: this
2177
2264
  };
2265
+ if (callCtx) {
2266
+ for (const [key, value] of Object.entries(callCtx)) if (![
2267
+ "db",
2268
+ "request",
2269
+ "logger",
2270
+ "services",
2271
+ "metadata",
2272
+ "_resolved",
2273
+ RESOLVED_SYMBOL
2274
+ ].includes(key)) finalCtx[key] = value;
2275
+ }
2276
+ return finalCtx;
2178
2277
  }
2179
2278
  introspect() {
2180
2279
  const databaseConfig = this.database ? {
@@ -2185,23 +2284,27 @@ var ServiceImpl = class {
2185
2284
  const { database: _database, ...options } = this.options;
2186
2285
  return {
2187
2286
  name: this.name,
2188
- options: {
2189
- ...options,
2190
- database: databaseConfig
2191
- },
2287
+ options,
2192
2288
  hasDatabase: Boolean(this.database),
2193
2289
  databaseConfig,
2194
- actions: this.listActions().map((act) => ({
2195
- name: act.name,
2196
- serviceName: this.name,
2197
- description: act.config.description,
2198
- inputSchema: act.config.input,
2199
- outputSchema: act.config.output,
2200
- hasAuthorize: Boolean(act.config.authorize),
2201
- errors: act.config.errors,
2202
- emits: act.config.emits,
2203
- tags: act.config.tags
2204
- })),
2290
+ actions: this.listActions().map((act) => {
2291
+ const access = getActionAccess(act);
2292
+ return {
2293
+ name: act.name,
2294
+ serviceName: this.name,
2295
+ ...act.plugin ? { plugin: act.plugin } : {},
2296
+ ...act.resource ? { resource: act.resource } : {},
2297
+ description: act.config.description,
2298
+ inputSchema: act.config.input,
2299
+ outputSchema: act.config.output,
2300
+ hasAuthorize: access.hasAuthorize,
2301
+ hasScope: access.hasScope,
2302
+ accessPolicy: access.policy,
2303
+ errors: act.config.errors,
2304
+ emits: act.config.emits,
2305
+ tags: act.config.tags
2306
+ };
2307
+ }),
2205
2308
  resources: this.listResources().map((res) => ({ name: res.name }))
2206
2309
  };
2207
2310
  }
@@ -2222,14 +2325,25 @@ function createServiceProxy(serviceName, options = {}) {
2222
2325
  if (!service) throw new Error(`[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`);
2223
2326
  const action = service.getAction(actionName);
2224
2327
  if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
2225
- const mergedCtx = {
2226
- ...options.context,
2227
- ...callCtx
2228
- };
2229
- if (!mergedCtx.db && service.getDb()) mergedCtx.db = service.getDb();
2328
+ const dangerousFields = /* @__PURE__ */ new Set([
2329
+ "db",
2330
+ "request",
2331
+ "logger",
2332
+ "services",
2333
+ "metadata",
2334
+ "_resolved"
2335
+ ]);
2336
+ const envelopeCtx = {};
2337
+ if (options.context) {
2338
+ for (const [key, value] of Object.entries(options.context)) if (!dangerousFields.has(key)) envelopeCtx[key] = value;
2339
+ }
2340
+ if (callCtx) {
2341
+ for (const [key, value] of Object.entries(callCtx)) if (!dangerousFields.has(key)) envelopeCtx[key] = value;
2342
+ }
2343
+ if (!envelopeCtx.caller) envelopeCtx.caller = serviceName;
2230
2344
  return action.execute({
2231
2345
  input: payload,
2232
- ctx: mergedCtx
2346
+ ctx: envelopeCtx
2233
2347
  });
2234
2348
  } else throw new Error(`[Brick-TS RPC] Remote microservice dispatch for '${serviceName}.${actionName}' is not yet configured for this environment.`);
2235
2349
  };
@@ -2357,6 +2471,6 @@ function createMcpHandler(options) {
2357
2471
  };
2358
2472
  }
2359
2473
  //#endregion
2360
- export { ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, Type as t, 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, 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, sql, sqliteTable, swaggerDocsHTML, syncSchema, text, toOpenApiPath, uniqueIndex, validateWithSchema };
2474
+ export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, Type as t, 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, text, toOpenApiPath, uniqueIndex, validateWithSchema };
2361
2475
 
2362
2476
  //# sourceMappingURL=index.js.map