@brickkit/core 0.3.0-beta.2 → 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/dist/index.d.ts +228 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1112 -245
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { a as isBrickTransportError, i as isBrickServerError, n as BrickTranspor
|
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { Type } from "@sinclair/typebox";
|
|
4
4
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
5
|
+
import { Elysia } from "elysia";
|
|
5
6
|
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
6
7
|
import postgres from "postgres";
|
|
7
8
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
@@ -95,7 +96,7 @@ const defaultLogger$1 = {
|
|
|
95
96
|
error: (...args) => console.error("[ERROR]", ...args),
|
|
96
97
|
debug: (...args) => console.debug("[DEBUG]", ...args)
|
|
97
98
|
};
|
|
98
|
-
const DEFAULT_REQUEST$
|
|
99
|
+
const DEFAULT_REQUEST$3 = new Request("http://localhost");
|
|
99
100
|
let _defaultCtxSeq = 0;
|
|
100
101
|
const standardErrorDefaults = {
|
|
101
102
|
BAD_REQUEST: {
|
|
@@ -127,7 +128,7 @@ function createDefaultContext(partial) {
|
|
|
127
128
|
if (partial?._resolved) return partial;
|
|
128
129
|
const seq = (++_defaultCtxSeq).toString(36);
|
|
129
130
|
return {
|
|
130
|
-
request: partial?.request ?? DEFAULT_REQUEST$
|
|
131
|
+
request: partial?.request ?? DEFAULT_REQUEST$3,
|
|
131
132
|
traceId: partial?.traceId || `tr_${seq}`,
|
|
132
133
|
requestId: partial?.requestId || `req_${seq}`,
|
|
133
134
|
db: partial?.db,
|
|
@@ -473,77 +474,621 @@ function restoreMap(target, snapshot) {
|
|
|
473
474
|
for (const [key, value] of snapshot) target.set(key, value);
|
|
474
475
|
}
|
|
475
476
|
//#endregion
|
|
476
|
-
//#region src/
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
return
|
|
477
|
+
//#region src/action-handler.ts
|
|
478
|
+
let _srvSeq = 0;
|
|
479
|
+
const EMPTY_SERVICES$2 = Object.freeze({});
|
|
480
|
+
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;
|
|
484
|
+
return false;
|
|
482
485
|
}
|
|
483
|
-
|
|
484
|
-
|
|
486
|
+
const MAX_INPUT_DEPTH = 128;
|
|
487
|
+
function inputTooDeep(value) {
|
|
488
|
+
if (!value || typeof value !== "object") return false;
|
|
489
|
+
const stack = [{
|
|
490
|
+
node: value,
|
|
491
|
+
depth: 0
|
|
492
|
+
}];
|
|
493
|
+
while (stack.length > 0) {
|
|
494
|
+
const { node, depth } = stack.pop();
|
|
495
|
+
if (depth > MAX_INPUT_DEPTH) return true;
|
|
496
|
+
if (node && typeof node === "object") {
|
|
497
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
498
|
+
for (const child of children) if (child && typeof child === "object") stack.push({
|
|
499
|
+
node: child,
|
|
500
|
+
depth: depth + 1
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return false;
|
|
485
505
|
}
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
506
|
+
function compileRoutePlan(service, action, routePath, method) {
|
|
507
|
+
const actionName = action.name;
|
|
508
|
+
const serviceName = service.name;
|
|
509
|
+
const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
|
|
510
|
+
const inputSchema = action.config?.input;
|
|
511
|
+
const outputSchema = action.config?.output;
|
|
512
|
+
const hasInput = Boolean(inputSchema);
|
|
513
|
+
const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
|
|
514
|
+
const runtimeOutputSchema = action.outputValidationSchema ?? outputSchema;
|
|
515
|
+
const outputChecker = runtimeOutputSchema ? getCompiledCheck(runtimeOutputSchema) : void 0;
|
|
516
|
+
let coercions;
|
|
517
|
+
if (inputSchema && typeof inputSchema.properties === "object") {
|
|
518
|
+
const list = [];
|
|
519
|
+
for (const [key, prop] of Object.entries(inputSchema.properties)) {
|
|
520
|
+
const type = prop?.type;
|
|
521
|
+
if (type === "number" || type === "integer") list.push({
|
|
522
|
+
key,
|
|
523
|
+
isNumber: true,
|
|
524
|
+
isBoolean: false
|
|
525
|
+
});
|
|
526
|
+
else if (type === "boolean") list.push({
|
|
527
|
+
key,
|
|
528
|
+
isNumber: false,
|
|
529
|
+
isBoolean: true
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
if (list.length > 0) coercions = list;
|
|
533
|
+
}
|
|
534
|
+
const contextHook = service.options?.context;
|
|
535
|
+
const hasContextHook = typeof contextHook === "function";
|
|
536
|
+
const authorize = action.config?.authorize;
|
|
537
|
+
const hasAuthorize = typeof authorize === "function";
|
|
538
|
+
const execute = action.config?.execute;
|
|
539
|
+
const tag = `[${serviceName}:${actionName}]`;
|
|
540
|
+
const logger = {
|
|
541
|
+
info: (...args) => console.log(tag, ...args),
|
|
542
|
+
warn: (...args) => console.warn(tag, ...args),
|
|
543
|
+
error: (...args) => console.error(tag, ...args),
|
|
544
|
+
debug: (...args) => console.debug(tag, ...args)
|
|
545
|
+
};
|
|
546
|
+
const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
|
|
547
|
+
const cachedDb = service.getDb();
|
|
548
|
+
return {
|
|
549
|
+
service,
|
|
550
|
+
action,
|
|
551
|
+
actionName,
|
|
552
|
+
serviceName,
|
|
553
|
+
routePath,
|
|
554
|
+
method,
|
|
555
|
+
isGetLike,
|
|
556
|
+
hasInput,
|
|
557
|
+
hasContextHook,
|
|
558
|
+
contextHook,
|
|
559
|
+
hasAuthorize,
|
|
560
|
+
authorize,
|
|
561
|
+
execute,
|
|
562
|
+
inputChecker,
|
|
563
|
+
outputChecker,
|
|
564
|
+
coercions,
|
|
565
|
+
logger,
|
|
566
|
+
errorBuilder,
|
|
567
|
+
cachedDb
|
|
568
|
+
};
|
|
490
569
|
}
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
570
|
+
async function executeCompiledRoute(plan, elysiaCtx) {
|
|
571
|
+
const { params, body, query, headers, request, set } = elysiaCtx;
|
|
572
|
+
const seq = (++_srvSeq).toString(36);
|
|
573
|
+
const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
|
|
574
|
+
const requestId = headers && headers["x-request-id"] || `req_${seq}`;
|
|
575
|
+
if (set?.headers) {
|
|
576
|
+
set.headers["x-trace-id"] = traceId;
|
|
577
|
+
set.headers["x-request-id"] = requestId;
|
|
578
|
+
}
|
|
579
|
+
let input;
|
|
580
|
+
if (plan.hasInput) {
|
|
581
|
+
let coercedQuery = query;
|
|
582
|
+
if (query && plan.coercions && plan.coercions.length > 0) {
|
|
583
|
+
coercedQuery = { ...query };
|
|
584
|
+
for (let i = 0; i < plan.coercions.length; i++) {
|
|
585
|
+
const c = plan.coercions[i];
|
|
586
|
+
const val = query[c.key];
|
|
587
|
+
if (val !== void 0) {
|
|
588
|
+
if (c.isNumber) {
|
|
589
|
+
const num = Number(val);
|
|
590
|
+
if (!isNaN(num)) coercedQuery[c.key] = num;
|
|
591
|
+
} else if (c.isBoolean) {
|
|
592
|
+
if (val === "true" || val === "1") coercedQuery[c.key] = true;
|
|
593
|
+
else if (val === "false" || val === "0") coercedQuery[c.key] = false;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const hasP = isNonEmpty$1(params);
|
|
599
|
+
const hasB = isNonEmpty$1(body);
|
|
600
|
+
const hasQ = isNonEmpty$1(coercedQuery);
|
|
601
|
+
if (plan.isGetLike) {
|
|
602
|
+
if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
603
|
+
else if (hasP && !hasQ && !hasB) input = params;
|
|
604
|
+
else if (hasB && !hasP && !hasQ) input = body;
|
|
605
|
+
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, params, body);
|
|
606
|
+
} else if (hasB && !hasP && !hasQ) input = body;
|
|
607
|
+
else if (hasP && !hasB && !hasQ) input = params;
|
|
608
|
+
else if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
609
|
+
else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
|
|
610
|
+
}
|
|
611
|
+
const ctx = {
|
|
612
|
+
request: request instanceof Request ? request : DEFAULT_REQUEST$2,
|
|
613
|
+
traceId,
|
|
614
|
+
requestId,
|
|
615
|
+
db: plan.cachedDb ?? plan.service.getDb(),
|
|
616
|
+
logger: plan.logger,
|
|
617
|
+
services: EMPTY_SERVICES$2,
|
|
618
|
+
metadata: { headers },
|
|
619
|
+
_resolved: true
|
|
620
|
+
};
|
|
504
621
|
try {
|
|
505
|
-
|
|
506
|
-
|
|
622
|
+
if (plan.hasContextHook) {
|
|
623
|
+
const extra = plan.contextHook(ctx);
|
|
624
|
+
const resolved = extra instanceof Promise ? await extra : extra;
|
|
625
|
+
if (resolved) Object.assign(ctx, resolved);
|
|
626
|
+
}
|
|
627
|
+
if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
|
|
628
|
+
if (plan.hasInput && plan.inputChecker) {
|
|
629
|
+
if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
|
|
630
|
+
path: "",
|
|
631
|
+
message: "Input exceeds maximum nesting depth"
|
|
632
|
+
}]);
|
|
633
|
+
if (!plan.inputChecker.Check(input)) {
|
|
634
|
+
const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
|
|
635
|
+
path: err.path,
|
|
636
|
+
message: err.message,
|
|
637
|
+
value: err.value
|
|
638
|
+
}));
|
|
639
|
+
throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
if (plan.hasAuthorize) {
|
|
643
|
+
const authRes = plan.authorize({
|
|
644
|
+
ctx,
|
|
645
|
+
input,
|
|
646
|
+
user: ctx.user
|
|
647
|
+
});
|
|
648
|
+
if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${plan.actionName}'`, 403);
|
|
649
|
+
}
|
|
650
|
+
const execRes = plan.execute({
|
|
651
|
+
input,
|
|
652
|
+
ctx,
|
|
653
|
+
error: plan.errorBuilder
|
|
654
|
+
});
|
|
655
|
+
const result = execRes instanceof Promise ? await execRes : execRes;
|
|
656
|
+
if (plan.outputChecker) {
|
|
657
|
+
if (!plan.outputChecker.Check(result)) {
|
|
658
|
+
const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
|
|
659
|
+
path: err.path,
|
|
660
|
+
message: err.message,
|
|
661
|
+
value: err.value
|
|
662
|
+
}));
|
|
663
|
+
throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return result;
|
|
507
667
|
} catch (err) {
|
|
508
|
-
|
|
668
|
+
if (err instanceof ValidationError || err instanceof ActionExecutionError) {
|
|
669
|
+
set.status = err.status || 400;
|
|
670
|
+
return err.toJSON();
|
|
671
|
+
}
|
|
672
|
+
set.status = 500;
|
|
673
|
+
return {
|
|
674
|
+
name: "InternalServerError",
|
|
675
|
+
message: err.message || "An unexpected error occurred",
|
|
676
|
+
status: 500
|
|
677
|
+
};
|
|
509
678
|
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
const db = config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client);
|
|
515
|
-
if (!db.$client) db.$client = client;
|
|
516
|
-
return db;
|
|
679
|
+
}
|
|
680
|
+
function createActionHandler(service, action, routePath, method) {
|
|
681
|
+
const plan = compileRoutePlan(service, action, routePath, method);
|
|
682
|
+
return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
|
|
517
683
|
}
|
|
518
684
|
//#endregion
|
|
519
|
-
//#region src/
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
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
|
+
//#region src/compiler/emit.ts
|
|
787
|
+
/** Emits framework code only. User callbacks remain closures bound separately. */
|
|
788
|
+
function emitHandlerFactory(route) {
|
|
789
|
+
const name = JSON.stringify(route.action);
|
|
790
|
+
const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
|
|
791
|
+
const input = ["let input;"];
|
|
792
|
+
if (route.input) {
|
|
793
|
+
input.push("let coercedQuery = query;");
|
|
794
|
+
if (route.coercions.length) {
|
|
795
|
+
input.push("if (query) {", "coercedQuery = { ...query };");
|
|
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;`);
|
|
801
|
+
}
|
|
802
|
+
input.push("}");
|
|
803
|
+
}
|
|
804
|
+
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
|
|
805
|
+
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
806
|
+
}
|
|
807
|
+
const asyncStages = route.context || route.authorize;
|
|
808
|
+
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");` : "";
|
|
810
|
+
const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : "";
|
|
811
|
+
const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
|
|
812
|
+
const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
|
|
813
|
+
if (isThenable(result)) return Promise.resolve(result).then(value => {
|
|
814
|
+
${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
|
|
815
|
+
return value;
|
|
816
|
+
}).catch(err => mapError(err, set));
|
|
817
|
+
${output}
|
|
818
|
+
return result;`;
|
|
819
|
+
return `function bindAction(binding, runtime) {
|
|
820
|
+
const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
|
|
821
|
+
const { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;
|
|
822
|
+
return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
|
|
823
|
+
const seq = nextSequence();
|
|
824
|
+
const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
|
|
825
|
+
const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
|
|
826
|
+
if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
|
|
827
|
+
${input.join("\n")}
|
|
828
|
+
const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
|
|
829
|
+
db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
|
|
830
|
+
try {
|
|
831
|
+
${context}
|
|
832
|
+
${validation}
|
|
833
|
+
${authorization}
|
|
834
|
+
${execute}
|
|
835
|
+
} catch (err) { return mapError(err, set); }
|
|
836
|
+
};
|
|
837
|
+
}`;
|
|
838
|
+
}
|
|
839
|
+
//#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
|
|
541
863
|
}));
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
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
|
+
//#region src/app-entry.ts
|
|
892
|
+
function isBrickApp(app) {
|
|
893
|
+
if (!app || typeof app !== "object") return false;
|
|
894
|
+
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";
|
|
895
|
+
}
|
|
896
|
+
function requireBrickApp(app) {
|
|
897
|
+
if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
898
|
+
if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
|
|
899
|
+
return app;
|
|
900
|
+
}
|
|
901
|
+
//#endregion
|
|
902
|
+
//#region src/compiler.ts
|
|
903
|
+
const buildBindings = /* @__PURE__ */ new Map();
|
|
904
|
+
function applicationKey(services, prefix = "/api") {
|
|
905
|
+
return JSON.stringify([prefix, services.map((service) => service.name)]);
|
|
906
|
+
}
|
|
907
|
+
/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
|
|
908
|
+
async function loadCompiledBrickApp(load, ir, bind) {
|
|
909
|
+
const key = JSON.stringify([ir.prefix, ir.services]);
|
|
910
|
+
if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
|
|
911
|
+
buildBindings.set(key, bind);
|
|
912
|
+
try {
|
|
913
|
+
const app = requireBrickApp((await load()).default);
|
|
914
|
+
if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
|
|
915
|
+
return app;
|
|
916
|
+
} finally {
|
|
917
|
+
buildBindings.delete(key);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
function bindAnalyzed(ir, bindings, factories) {
|
|
921
|
+
if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
|
|
922
|
+
const routes = ir.routes.map((route, index) => {
|
|
923
|
+
const { service, action } = bindings[index];
|
|
924
|
+
const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
|
|
925
|
+
const handler = factories[index](plan, compilerRuntime);
|
|
926
|
+
return Object.freeze({
|
|
927
|
+
ir: route,
|
|
928
|
+
handler
|
|
929
|
+
});
|
|
930
|
+
});
|
|
931
|
+
return Object.freeze({
|
|
932
|
+
ir: freezeIR(ir),
|
|
933
|
+
routes: Object.freeze(routes)
|
|
545
934
|
});
|
|
546
935
|
}
|
|
936
|
+
/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
|
|
937
|
+
function compileBrickApplication(options) {
|
|
938
|
+
const bind = buildBindings.get(applicationKey(options.services, options.prefix));
|
|
939
|
+
if (bind && options.mode !== "generic") return bind(options.services);
|
|
940
|
+
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((route) => new Function(`return (${emitHandlerFactory(route)});`)());
|
|
942
|
+
if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
|
|
943
|
+
return bindAnalyzed(ir, bindings, factories);
|
|
944
|
+
}
|
|
945
|
+
/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
|
|
946
|
+
function bindCompiledApplication(ir, services, factories) {
|
|
947
|
+
if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
|
|
948
|
+
const analyzed = analyzeApplication(services, ir.prefix);
|
|
949
|
+
if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
|
|
950
|
+
for (const service of services) service.prepareContributions();
|
|
951
|
+
return bindAnalyzed(ir, analyzed.bindings, factories);
|
|
952
|
+
}
|
|
953
|
+
//#endregion
|
|
954
|
+
//#region src/openapi.ts
|
|
955
|
+
function generateOpenApiSpec(options = {}) {
|
|
956
|
+
const title = options.title ?? "Brick-TS API Mesh";
|
|
957
|
+
const version = options.version ?? "1.0.0";
|
|
958
|
+
const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
|
|
959
|
+
const prefix = options.prefix ?? "/api";
|
|
960
|
+
const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
|
|
961
|
+
const paths = {};
|
|
962
|
+
const tagsSet = /* @__PURE__ */ new Set();
|
|
963
|
+
let hasAnyAuthorizedAction = false;
|
|
964
|
+
for (const service of services) {
|
|
965
|
+
tagsSet.add(service.name);
|
|
966
|
+
for (const action of service.listActions()) {
|
|
967
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
968
|
+
if (pluginRoute === false) continue;
|
|
969
|
+
const routePath = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
970
|
+
const method = (pluginRoute?.method ?? action.config.method ?? "POST").toLowerCase();
|
|
971
|
+
const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
|
|
972
|
+
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
973
|
+
if (!paths[actionPath]) paths[actionPath] = {};
|
|
974
|
+
if (paths[actionPath][method]) continue;
|
|
975
|
+
const hasAuth = Boolean(action.config.authorize);
|
|
976
|
+
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
977
|
+
const responses = {};
|
|
978
|
+
if (action.config.output) responses["200"] = {
|
|
979
|
+
description: "Successful response",
|
|
980
|
+
content: { "application/json": { schema: action.config.output } }
|
|
981
|
+
};
|
|
982
|
+
else responses["200"] = { description: "Successful response" };
|
|
983
|
+
if (action.config.input) responses["400"] = {
|
|
984
|
+
description: "Validation error",
|
|
985
|
+
content: { "application/json": { schema: {
|
|
986
|
+
type: "object",
|
|
987
|
+
properties: {
|
|
988
|
+
name: { type: "string" },
|
|
989
|
+
message: { type: "string" },
|
|
990
|
+
status: { type: "integer" },
|
|
991
|
+
errors: {
|
|
992
|
+
type: "array",
|
|
993
|
+
items: {
|
|
994
|
+
type: "object",
|
|
995
|
+
properties: {
|
|
996
|
+
path: { type: "string" },
|
|
997
|
+
message: { type: "string" }
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
} } }
|
|
1003
|
+
};
|
|
1004
|
+
if (hasAuth) responses["403"] = { description: "Access denied / Unauthorized" };
|
|
1005
|
+
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1006
|
+
const def = errorDef;
|
|
1007
|
+
const status = String(def.status || 400);
|
|
1008
|
+
responses[status] = {
|
|
1009
|
+
description: def.message || code,
|
|
1010
|
+
content: { "application/json": { schema: {
|
|
1011
|
+
type: "object",
|
|
1012
|
+
properties: {
|
|
1013
|
+
name: {
|
|
1014
|
+
type: "string",
|
|
1015
|
+
example: "ActionExecutionError"
|
|
1016
|
+
},
|
|
1017
|
+
code: {
|
|
1018
|
+
type: "string",
|
|
1019
|
+
example: code
|
|
1020
|
+
},
|
|
1021
|
+
message: {
|
|
1022
|
+
type: "string",
|
|
1023
|
+
example: def.message
|
|
1024
|
+
},
|
|
1025
|
+
status: {
|
|
1026
|
+
type: "integer",
|
|
1027
|
+
example: def.status || 400
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
} } }
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
responses["500"] = { description: "Internal server error" };
|
|
1034
|
+
const operation = {
|
|
1035
|
+
operationId: `${service.name}_${action.name}_${method}`,
|
|
1036
|
+
summary: `${service.name}.${action.name}`,
|
|
1037
|
+
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1038
|
+
tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
|
|
1039
|
+
responses
|
|
1040
|
+
};
|
|
1041
|
+
const inputSchema = action.config.input;
|
|
1042
|
+
const properties = inputSchema?.properties ?? {};
|
|
1043
|
+
const parameters = [...new Set(pathParams)].map((key) => ({
|
|
1044
|
+
name: key,
|
|
1045
|
+
in: "path",
|
|
1046
|
+
required: true,
|
|
1047
|
+
schema: properties[key] ?? { type: "string" }
|
|
1048
|
+
}));
|
|
1049
|
+
if (method === "get" || method === "delete") for (const [key, schema] of Object.entries(properties)) {
|
|
1050
|
+
if (pathParams.includes(key)) continue;
|
|
1051
|
+
parameters.push({
|
|
1052
|
+
name: key,
|
|
1053
|
+
in: "query",
|
|
1054
|
+
required: inputSchema?.required?.includes(key) ?? false,
|
|
1055
|
+
schema
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
else if (inputSchema) operation.requestBody = {
|
|
1059
|
+
required: true,
|
|
1060
|
+
content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
|
|
1061
|
+
...inputSchema,
|
|
1062
|
+
properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
|
|
1063
|
+
required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
|
|
1064
|
+
} : inputSchema } }
|
|
1065
|
+
};
|
|
1066
|
+
if (parameters.length) operation.parameters = parameters;
|
|
1067
|
+
if (hasAuth) operation.security = [{ bearerAuth: [] }];
|
|
1068
|
+
paths[actionPath][method] = operation;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
const spec = {
|
|
1072
|
+
openapi: "3.1.0",
|
|
1073
|
+
info: {
|
|
1074
|
+
title,
|
|
1075
|
+
version,
|
|
1076
|
+
description
|
|
1077
|
+
},
|
|
1078
|
+
paths,
|
|
1079
|
+
tags: Array.from(tagsSet).map((name) => ({
|
|
1080
|
+
name,
|
|
1081
|
+
description: `Actions exposed by '${name}' service`
|
|
1082
|
+
}))
|
|
1083
|
+
};
|
|
1084
|
+
if (hasAnyAuthorizedAction) spec.components = { securitySchemes: { bearerAuth: {
|
|
1085
|
+
type: "http",
|
|
1086
|
+
scheme: "bearer",
|
|
1087
|
+
bearerFormat: "JWT",
|
|
1088
|
+
description: "Enter your Bearer authentication token"
|
|
1089
|
+
} } };
|
|
1090
|
+
return spec;
|
|
1091
|
+
}
|
|
547
1092
|
//#endregion
|
|
548
1093
|
//#region src/secrets.ts
|
|
549
1094
|
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
@@ -635,55 +1180,516 @@ var SecretRef = class {
|
|
|
635
1180
|
isSet(source = envSource) {
|
|
636
1181
|
return this.resolveRaw(source) !== void 0;
|
|
637
1182
|
}
|
|
638
|
-
};
|
|
639
|
-
/**
|
|
640
|
-
* Declare a secret. Idempotent: re-declaring the same name returns the
|
|
641
|
-
* original ref (first declaration wins) so module re-evaluation is safe.
|
|
642
|
-
*/
|
|
643
|
-
function secret(name, options = {}) {
|
|
644
|
-
const existing = registry.get(name);
|
|
645
|
-
if (existing) return existing;
|
|
646
|
-
const ref = new SecretRef(name, options);
|
|
647
|
-
registry.set(name, ref);
|
|
648
|
-
return ref;
|
|
1183
|
+
};
|
|
1184
|
+
/**
|
|
1185
|
+
* Declare a secret. Idempotent: re-declaring the same name returns the
|
|
1186
|
+
* original ref (first declaration wins) so module re-evaluation is safe.
|
|
1187
|
+
*/
|
|
1188
|
+
function secret(name, options = {}) {
|
|
1189
|
+
const existing = registry.get(name);
|
|
1190
|
+
if (existing) return existing;
|
|
1191
|
+
const ref = new SecretRef(name, options);
|
|
1192
|
+
registry.set(name, ref);
|
|
1193
|
+
return ref;
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Validate every registered secret at boot. Throws a single error listing
|
|
1197
|
+
* all missing required secrets. Returns the resolved values.
|
|
1198
|
+
*/
|
|
1199
|
+
function resolveSecrets(opts = {}) {
|
|
1200
|
+
const source = opts.source ?? envSource;
|
|
1201
|
+
const missing = [];
|
|
1202
|
+
const resolved = {};
|
|
1203
|
+
for (const ref of registry.values()) {
|
|
1204
|
+
const v = ref.value(source);
|
|
1205
|
+
if (v === void 0) missing.push(ref.name);
|
|
1206
|
+
else resolved[ref.name] = v;
|
|
1207
|
+
}
|
|
1208
|
+
if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
|
|
1209
|
+
return resolved;
|
|
1210
|
+
}
|
|
1211
|
+
/** Metadata for introspection (values never exposed — future dashboard use). */
|
|
1212
|
+
function listSecrets(opts = {}) {
|
|
1213
|
+
const source = opts.source ?? envSource;
|
|
1214
|
+
return [...registry.values()].map((ref) => ({
|
|
1215
|
+
hasDefault: ref.hasDefault,
|
|
1216
|
+
isSet: ref.isSet(source),
|
|
1217
|
+
name: ref.name
|
|
1218
|
+
}));
|
|
1219
|
+
}
|
|
1220
|
+
/** Test/session override for one secret (`undefined` clears the override). */
|
|
1221
|
+
function overrideSecret(name, value) {
|
|
1222
|
+
overrides.set(name, value);
|
|
1223
|
+
}
|
|
1224
|
+
/** Bulk overrides (test/session scoped). */
|
|
1225
|
+
function overrideSecrets(values) {
|
|
1226
|
+
for (const [name, value] of Object.entries(values)) overrides.set(name, value);
|
|
1227
|
+
}
|
|
1228
|
+
/** Clear registry and overrides. Test-only. */
|
|
1229
|
+
function resetSecrets() {
|
|
1230
|
+
registry.clear();
|
|
1231
|
+
overrides.clear();
|
|
1232
|
+
}
|
|
1233
|
+
//#endregion
|
|
1234
|
+
//#region src/request-logger.ts
|
|
1235
|
+
function formatLog(method, path, status, elapsedMs) {
|
|
1236
|
+
return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError
|
|
1240
|
+
* while `set.status` may still hold the 200 default when onError runs).
|
|
1241
|
+
*/
|
|
1242
|
+
function thrownStatus(error) {
|
|
1243
|
+
if (typeof error === "object" && error !== null && "status" in error) {
|
|
1244
|
+
const status = error.status;
|
|
1245
|
+
if (typeof status === "number") return status;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
|
|
1250
|
+
* Timing is tracked per-Request via a WeakMap. The onError hook only logs and
|
|
1251
|
+
* returns undefined so existing error mapping is preserved. Logging only —
|
|
1252
|
+
* no CORS headers are set here.
|
|
1253
|
+
*
|
|
1254
|
+
* Hooks are registered with the "global" scope so they propagate to the
|
|
1255
|
+
* parent app when mounted via `app.use(...)` — Elysia scopes plain instance
|
|
1256
|
+
* hooks to the plugin's own routes. Timing is captured in beforeHandle
|
|
1257
|
+
* because request hooks are not propagated from a
|
|
1258
|
+
* used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
|
|
1259
|
+
*/
|
|
1260
|
+
function requestLoggingPlugin(opts = {}) {
|
|
1261
|
+
const plugin = new Elysia();
|
|
1262
|
+
if (!(opts.enabled ?? true)) return plugin;
|
|
1263
|
+
const logger = opts.logger ?? console.log;
|
|
1264
|
+
const startedAt = /* @__PURE__ */ new WeakMap();
|
|
1265
|
+
const markStarted = ({ request }) => {
|
|
1266
|
+
startedAt.set(request, Date.now());
|
|
1267
|
+
};
|
|
1268
|
+
const logSuccess = ({ request, set }) => {
|
|
1269
|
+
const start = startedAt.get(request) ?? Date.now();
|
|
1270
|
+
const path = new URL(request.url).pathname;
|
|
1271
|
+
logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
|
|
1272
|
+
};
|
|
1273
|
+
const logError = ({ request, set, error }) => {
|
|
1274
|
+
if (request) {
|
|
1275
|
+
const start = startedAt.get(request) ?? Date.now();
|
|
1276
|
+
const path = new URL(request.url).pathname;
|
|
1277
|
+
const status = thrownStatus(error) ?? set.status ?? 500;
|
|
1278
|
+
logger(formatLog(request.method, path, status, Date.now() - start));
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
plugin.beforeHandle("global", markStarted);
|
|
1282
|
+
plugin.afterHandle("global", logSuccess);
|
|
1283
|
+
plugin.error("global", logError);
|
|
1284
|
+
return plugin;
|
|
1285
|
+
}
|
|
1286
|
+
//#endregion
|
|
1287
|
+
//#region src/docs.ts
|
|
1288
|
+
/** Renders the Scalar API reference page for the given OpenAPI URL. */
|
|
1289
|
+
function scalarDocsHTML(specUrl, title) {
|
|
1290
|
+
return `<!doctype html>
|
|
1291
|
+
<html>
|
|
1292
|
+
<head>
|
|
1293
|
+
<title>${title} — API Reference</title>
|
|
1294
|
+
<meta charset="utf-8" />
|
|
1295
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
1296
|
+
<link rel="icon" type="image/svg+xml" href="https://scalar.com/favicon.svg" />
|
|
1297
|
+
<style>
|
|
1298
|
+
body { margin: 0; padding: 0; height: 100vh; }
|
|
1299
|
+
</style>
|
|
1300
|
+
</head>
|
|
1301
|
+
<body>
|
|
1302
|
+
<script
|
|
1303
|
+
id="api-reference"
|
|
1304
|
+
data-url="${specUrl}"
|
|
1305
|
+
data-configuration='{"theme": "purple", "layout": "modern"}'
|
|
1306
|
+
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference">
|
|
1307
|
+
<\/script>
|
|
1308
|
+
</body>
|
|
1309
|
+
</html>`;
|
|
1310
|
+
}
|
|
1311
|
+
/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
|
|
1312
|
+
function referencePlugin(opts = {}) {
|
|
1313
|
+
const path = opts.path ?? "/reference";
|
|
1314
|
+
const title = opts.title ?? "Brick-TS API Mesh";
|
|
1315
|
+
const specUrl = opts.specUrl ?? "/openapi.json";
|
|
1316
|
+
const plugin = new Elysia();
|
|
1317
|
+
plugin.get(path, ({ set }) => {
|
|
1318
|
+
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
1319
|
+
return scalarDocsHTML(specUrl, title);
|
|
1320
|
+
});
|
|
1321
|
+
return plugin;
|
|
1322
|
+
}
|
|
1323
|
+
/** Mounts the Scalar reference route onto an existing app. */
|
|
1324
|
+
function registerReferenceRoute(app, opts = {}) {
|
|
1325
|
+
return app.use(referencePlugin(opts));
|
|
1326
|
+
}
|
|
1327
|
+
/** Renders the Swagger UI page. */
|
|
1328
|
+
function swaggerDocsHTML(specUrl, title) {
|
|
1329
|
+
return `<!DOCTYPE html>
|
|
1330
|
+
<html lang="en">
|
|
1331
|
+
<head>
|
|
1332
|
+
<meta charset="UTF-8">
|
|
1333
|
+
<title>${title} — Swagger UI</title>
|
|
1334
|
+
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
|
|
1335
|
+
<style>
|
|
1336
|
+
html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }
|
|
1337
|
+
*, *:before, *:after { box-sizing: inherit; }
|
|
1338
|
+
body { margin:0; background: #fafafa; }
|
|
1339
|
+
</style>
|
|
1340
|
+
</head>
|
|
1341
|
+
<body>
|
|
1342
|
+
<div id="swagger-ui"></div>
|
|
1343
|
+
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" charset="UTF-8"><\/script>
|
|
1344
|
+
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" charset="UTF-8"><\/script>
|
|
1345
|
+
<script>
|
|
1346
|
+
window.onload = function() {
|
|
1347
|
+
SwaggerUIBundle({
|
|
1348
|
+
url: "${specUrl}",
|
|
1349
|
+
dom_id: '#swagger-ui',
|
|
1350
|
+
deepLinking: true,
|
|
1351
|
+
presets: [
|
|
1352
|
+
SwaggerUIBundle.presets.apis,
|
|
1353
|
+
SwaggerUIStandalonePreset
|
|
1354
|
+
],
|
|
1355
|
+
plugins: [
|
|
1356
|
+
SwaggerUIBundle.plugins.DownloadUrl
|
|
1357
|
+
],
|
|
1358
|
+
layout: "StandaloneLayout"
|
|
1359
|
+
});
|
|
1360
|
+
};
|
|
1361
|
+
<\/script>
|
|
1362
|
+
</body>
|
|
1363
|
+
</html>`;
|
|
1364
|
+
}
|
|
1365
|
+
//#endregion
|
|
1366
|
+
//#region src/endpoints.ts
|
|
1367
|
+
/** Resolve the db for an endpoint: explicit service first, else first service holding one. */
|
|
1368
|
+
function resolveEndpointDb(service, services) {
|
|
1369
|
+
if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb() ?? void 0;
|
|
1370
|
+
for (const svc of services) {
|
|
1371
|
+
const db = svc.getDb();
|
|
1372
|
+
if (db) return db;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
|
|
1376
|
+
function createEndpointHandler(def, services) {
|
|
1377
|
+
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)}`;
|
|
1380
|
+
if (set?.headers) {
|
|
1381
|
+
set.headers["x-trace-id"] = traceId;
|
|
1382
|
+
set.headers["x-request-id"] = requestId;
|
|
1383
|
+
}
|
|
1384
|
+
const tag = `endpoint:${def.method} ${def.path}`;
|
|
1385
|
+
const ctx = {
|
|
1386
|
+
body,
|
|
1387
|
+
db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
|
|
1388
|
+
headers: headers ?? {},
|
|
1389
|
+
logger: {
|
|
1390
|
+
info: (...args) => console.log(`[${tag}]`, ...args),
|
|
1391
|
+
warn: (...args) => console.warn(`[${tag}]`, ...args),
|
|
1392
|
+
error: (...args) => console.error(`[${tag}]`, ...args),
|
|
1393
|
+
debug: (...args) => console.debug(`[${tag}]`, ...args)
|
|
1394
|
+
},
|
|
1395
|
+
params: params ?? {},
|
|
1396
|
+
query: query ?? {},
|
|
1397
|
+
request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
|
|
1398
|
+
headers: new Headers(headers ?? {}),
|
|
1399
|
+
method: def.method
|
|
1400
|
+
}),
|
|
1401
|
+
requestId,
|
|
1402
|
+
set,
|
|
1403
|
+
traceId
|
|
1404
|
+
};
|
|
1405
|
+
try {
|
|
1406
|
+
return await def.handler(ctx);
|
|
1407
|
+
} catch (err) {
|
|
1408
|
+
if (err instanceof ValidationError) {
|
|
1409
|
+
set.status = err.status || 400;
|
|
1410
|
+
return err.toJSON();
|
|
1411
|
+
}
|
|
1412
|
+
if (err instanceof ActionExecutionError) {
|
|
1413
|
+
set.status = err.status || 400;
|
|
1414
|
+
return err.toJSON();
|
|
1415
|
+
}
|
|
1416
|
+
if (typeof err?.status === "number") {
|
|
1417
|
+
set.status = err.status;
|
|
1418
|
+
return {
|
|
1419
|
+
message: err.message || "Endpoint error",
|
|
1420
|
+
status: err.status
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
set.status = 500;
|
|
1424
|
+
return {
|
|
1425
|
+
message: err?.message || "An unexpected error occurred",
|
|
1426
|
+
status: 500
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
/** `/p/:slug` → `/p/{slug}` for OpenAPI. */
|
|
1432
|
+
function toOpenApiPath(elysiaPath) {
|
|
1433
|
+
return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
1434
|
+
}
|
|
1435
|
+
/** Parameter names (`:slug`) extracted for the OpenAPI path item. */
|
|
1436
|
+
function pathParamNames(elysiaPath) {
|
|
1437
|
+
return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
|
|
1438
|
+
}
|
|
1439
|
+
/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
|
|
1440
|
+
function endpointPaths(defs) {
|
|
1441
|
+
const paths = {};
|
|
1442
|
+
for (const def of defs) {
|
|
1443
|
+
const openApiPath = toOpenApiPath(def.path);
|
|
1444
|
+
if (!paths[openApiPath]) paths[openApiPath] = {};
|
|
1445
|
+
const params = pathParamNames(def.path).map((name) => ({
|
|
1446
|
+
in: "path",
|
|
1447
|
+
name,
|
|
1448
|
+
required: true,
|
|
1449
|
+
schema: { type: "string" }
|
|
1450
|
+
}));
|
|
1451
|
+
paths[openApiPath][def.method.toLowerCase()] = {
|
|
1452
|
+
...def.summary ? { summary: def.summary } : {},
|
|
1453
|
+
...def.description ? { description: def.description } : {},
|
|
1454
|
+
...def.tags ? { tags: def.tags } : {},
|
|
1455
|
+
...params.length > 0 ? { parameters: params } : {},
|
|
1456
|
+
responses: { 200: { description: "Successful response" } }
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
return paths;
|
|
1460
|
+
}
|
|
1461
|
+
//#endregion
|
|
1462
|
+
//#region src/server.ts
|
|
1463
|
+
function brick(options = {}) {
|
|
1464
|
+
const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
|
|
1465
|
+
const title = options.title ?? "Brick-TS API Mesh";
|
|
1466
|
+
const version = options.version ?? "1.0.0";
|
|
1467
|
+
const compiled = options.compiler !== false;
|
|
1468
|
+
const enableDocs = options.docs ?? true;
|
|
1469
|
+
const openApiPath = options.openApiPath ?? "/openapi.json";
|
|
1470
|
+
const docsPath = options.docsPath ?? "/docs";
|
|
1471
|
+
const swaggerPath = options.swaggerPath ?? "/swagger";
|
|
1472
|
+
const app = new Elysia();
|
|
1473
|
+
if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
|
|
1474
|
+
app.get("/_health", () => ({
|
|
1475
|
+
status: "ok",
|
|
1476
|
+
uptime: process.uptime(),
|
|
1477
|
+
timestamp: Date.now()
|
|
1478
|
+
}));
|
|
1479
|
+
app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(), () => {
|
|
1480
|
+
const registry = getGlobalRegistry();
|
|
1481
|
+
return [registry, registry.revision];
|
|
1482
|
+
}) : () => getGlobalRegistry().exportArchitecture());
|
|
1483
|
+
const requestLogging = options.requestLogging ?? true;
|
|
1484
|
+
if (requestLogging !== false) {
|
|
1485
|
+
const pluginOpts = requestLogging === true ? {} : requestLogging;
|
|
1486
|
+
if (pluginOpts.enabled !== false) app.use(requestLoggingPlugin(pluginOpts));
|
|
1487
|
+
}
|
|
1488
|
+
const reference = options.reference ?? false;
|
|
1489
|
+
if (reference !== false) {
|
|
1490
|
+
const refOpts = reference === true ? {} : reference;
|
|
1491
|
+
const settings = {
|
|
1492
|
+
path: refOpts.path ?? "/reference",
|
|
1493
|
+
title: refOpts.title ?? title,
|
|
1494
|
+
specUrl: refOpts.specUrl ?? openApiPath
|
|
1495
|
+
};
|
|
1496
|
+
if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
|
|
1497
|
+
else registerReferenceRoute(app, settings);
|
|
1498
|
+
}
|
|
1499
|
+
const services = options.services ?? getGlobalRegistry().list();
|
|
1500
|
+
for (const service of services) if (typeof service.build === "function") service.build();
|
|
1501
|
+
const endpointDefs = [];
|
|
1502
|
+
let endpointRevision = 0;
|
|
1503
|
+
if (enableDocs) {
|
|
1504
|
+
const buildSpec = () => {
|
|
1505
|
+
const spec = generateOpenApiSpec({
|
|
1506
|
+
title,
|
|
1507
|
+
version,
|
|
1508
|
+
description: options.description,
|
|
1509
|
+
prefix,
|
|
1510
|
+
services
|
|
1511
|
+
});
|
|
1512
|
+
const paths = { ...spec.paths };
|
|
1513
|
+
for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
|
|
1514
|
+
...paths[path],
|
|
1515
|
+
...operations
|
|
1516
|
+
};
|
|
1517
|
+
return {
|
|
1518
|
+
...spec,
|
|
1519
|
+
paths
|
|
1520
|
+
};
|
|
1521
|
+
};
|
|
1522
|
+
app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
|
|
1523
|
+
if (compiled) {
|
|
1524
|
+
app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
|
|
1525
|
+
app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
|
|
1526
|
+
} else {
|
|
1527
|
+
app.get(docsPath, ({ set }) => {
|
|
1528
|
+
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
1529
|
+
return scalarDocsHTML(openApiPath, title);
|
|
1530
|
+
});
|
|
1531
|
+
app.get(swaggerPath, ({ set }) => {
|
|
1532
|
+
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
1533
|
+
return swaggerDocsHTML(openApiPath, title);
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
const registeredRoutes = /* @__PURE__ */ new Map();
|
|
1538
|
+
const routeKey = (method, path) => `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
1539
|
+
registeredRoutes.set(routeKey("GET", "/_health"), false);
|
|
1540
|
+
registeredRoutes.set(routeKey("GET", "/_brick/services"), false);
|
|
1541
|
+
if (enableDocs) for (const path of [
|
|
1542
|
+
openApiPath,
|
|
1543
|
+
docsPath,
|
|
1544
|
+
swaggerPath
|
|
1545
|
+
]) registeredRoutes.set(routeKey("GET", path), false);
|
|
1546
|
+
if (reference !== false) registeredRoutes.set(routeKey("GET", reference === true ? "/reference" : reference.path ?? "/reference"), false);
|
|
1547
|
+
const mountRoute = (method, path, handler, plugin = false) => {
|
|
1548
|
+
const key = routeKey(method, path);
|
|
1549
|
+
if (registeredRoutes.has(key)) {
|
|
1550
|
+
if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
switch (method) {
|
|
1554
|
+
case "GET":
|
|
1555
|
+
app.get(path, handler);
|
|
1556
|
+
break;
|
|
1557
|
+
case "POST":
|
|
1558
|
+
app.post(path, handler);
|
|
1559
|
+
break;
|
|
1560
|
+
case "PUT":
|
|
1561
|
+
app.put(path, handler);
|
|
1562
|
+
break;
|
|
1563
|
+
case "PATCH":
|
|
1564
|
+
app.patch(path, handler);
|
|
1565
|
+
break;
|
|
1566
|
+
case "DELETE": app.delete(path, handler);
|
|
1567
|
+
}
|
|
1568
|
+
registeredRoutes.set(key, plugin);
|
|
1569
|
+
};
|
|
1570
|
+
const mountEndpoint = (def, plugin = false) => {
|
|
1571
|
+
mountRoute(def.method, def.path, createEndpointHandler(def, services), plugin);
|
|
1572
|
+
endpointDefs.push(def);
|
|
1573
|
+
endpointRevision++;
|
|
1574
|
+
};
|
|
1575
|
+
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
1576
|
+
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
1577
|
+
const brickApp = app;
|
|
1578
|
+
Object.defineProperty(brickApp, "definition", { value: Object.freeze({
|
|
1579
|
+
services: Object.freeze([...services]),
|
|
1580
|
+
prefix
|
|
1581
|
+
}) });
|
|
1582
|
+
brickApp.endpoint = (def) => {
|
|
1583
|
+
mountEndpoint(def);
|
|
1584
|
+
};
|
|
1585
|
+
brickApp.listEndpoints = () => [...endpointDefs];
|
|
1586
|
+
const compilation = options.compilation ?? compileBrickApplication({
|
|
1587
|
+
services,
|
|
1588
|
+
prefix,
|
|
1589
|
+
mode: options.compiler === false ? "generic" : "specialized"
|
|
1590
|
+
});
|
|
1591
|
+
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");
|
|
1592
|
+
for (const route of compilation.routes) {
|
|
1593
|
+
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) => {
|
|
1595
|
+
const result = route.handler(context);
|
|
1596
|
+
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
1597
|
+
}, getPluginActionRoute(action, prefix) !== void 0);
|
|
1598
|
+
}
|
|
1599
|
+
return brickApp;
|
|
1600
|
+
}
|
|
1601
|
+
function jsonActionResult(value) {
|
|
1602
|
+
return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
|
|
1603
|
+
}
|
|
1604
|
+
function htmlResponse(html) {
|
|
1605
|
+
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
1606
|
+
}
|
|
1607
|
+
/** Reuse serialized JSON, without sharing a mutable response body between requests. */
|
|
1608
|
+
function cachedJsonRoute(build, revision) {
|
|
1609
|
+
let [owner, version] = revision();
|
|
1610
|
+
let json = JSON.stringify(build());
|
|
1611
|
+
return ({ set }) => {
|
|
1612
|
+
const [currentOwner, currentVersion] = revision();
|
|
1613
|
+
if (currentOwner !== owner || currentVersion !== version) {
|
|
1614
|
+
json = JSON.stringify(build());
|
|
1615
|
+
owner = currentOwner;
|
|
1616
|
+
version = currentVersion;
|
|
1617
|
+
}
|
|
1618
|
+
set.headers["content-type"] = "application/json;charset=utf-8";
|
|
1619
|
+
return json;
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
//#endregion
|
|
1623
|
+
//#region src/tool.ts
|
|
1624
|
+
function defineTool(config) {
|
|
1625
|
+
if (config.input && config.input.type !== "object") throw new Error(`Tool '${config.name}' input must be an object schema`);
|
|
1626
|
+
const tool = defineAction(config);
|
|
1627
|
+
Object.defineProperty(tool, "kind", { value: "tool" });
|
|
1628
|
+
return tool;
|
|
1629
|
+
}
|
|
1630
|
+
function isTool(value) {
|
|
1631
|
+
return typeof value === "function" && value.kind === "tool";
|
|
1632
|
+
}
|
|
1633
|
+
//#endregion
|
|
1634
|
+
//#region src/db/load.ts
|
|
1635
|
+
function loadDriver(id) {
|
|
1636
|
+
return (globalThis.require ?? createRequire(import.meta.url))(id);
|
|
649
1637
|
}
|
|
1638
|
+
//#endregion
|
|
1639
|
+
//#region src/db/sqlite.ts
|
|
650
1640
|
/**
|
|
651
|
-
*
|
|
652
|
-
*
|
|
1641
|
+
* Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
|
|
1642
|
+
* and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
|
|
1643
|
+
*
|
|
1644
|
+
* Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
|
|
1645
|
+
* other runtimes (e.g. Node) stays safe until this function is actually
|
|
1646
|
+
* called.
|
|
653
1647
|
*/
|
|
654
|
-
function
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
1648
|
+
function createSQLiteDatabase(config = {}) {
|
|
1649
|
+
let Database;
|
|
1650
|
+
let drizzle;
|
|
1651
|
+
try {
|
|
1652
|
+
({Database} = loadDriver("bun:sqlite"));
|
|
1653
|
+
({drizzle} = __require("drizzle-orm/bun-sqlite"));
|
|
1654
|
+
} catch (err) {
|
|
1655
|
+
throw new Error(`[Brick-TS DB] SQLite engine requires the Bun runtime ('bun:sqlite' is unavailable here). Original error: ${err?.message ?? err}`);
|
|
662
1656
|
}
|
|
663
|
-
|
|
664
|
-
|
|
1657
|
+
const filePath = config.filename ?? config.path ?? ":memory:";
|
|
1658
|
+
const client = config.client ?? new Database(filePath);
|
|
1659
|
+
if (config.foreignKeys !== false) client.run("PRAGMA foreign_keys = ON;");
|
|
1660
|
+
if (config.wal !== false && filePath !== ":memory:") client.run("PRAGMA journal_mode = WAL;");
|
|
1661
|
+
const db = config.schema ? drizzle(client, { schema: config.schema }) : drizzle(client);
|
|
1662
|
+
if (!db.$client) db.$client = client;
|
|
1663
|
+
return db;
|
|
665
1664
|
}
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
1665
|
+
//#endregion
|
|
1666
|
+
//#region src/db/postgres.ts
|
|
1667
|
+
/**
|
|
1668
|
+
* Creates a PostgreSQL Drizzle instance using postgres-js.
|
|
1669
|
+
* Static imports (both are hard dependencies in package.json) so bundlers
|
|
1670
|
+
* (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
|
|
1671
|
+
* `sqlite.ts` since it only exists under Bun.
|
|
1672
|
+
*/
|
|
1673
|
+
function createPostgresDatabase(config = {}) {
|
|
1674
|
+
const connectionUrl = config.url ?? config.connectionString ?? (typeof process !== "undefined" ? process.env?.DATABASE_URL : void 0);
|
|
1675
|
+
const client = config.client ?? (connectionUrl ? postgres(connectionUrl, {
|
|
1676
|
+
max: config.max,
|
|
1677
|
+
prepare: config.prepare,
|
|
1678
|
+
ssl: config.ssl
|
|
1679
|
+
}) : postgres({
|
|
1680
|
+
host: config.host ?? "localhost",
|
|
1681
|
+
port: config.port ?? 5432,
|
|
1682
|
+
user: config.user,
|
|
1683
|
+
password: config.password,
|
|
1684
|
+
database: config.database,
|
|
1685
|
+
max: config.max,
|
|
1686
|
+
prepare: config.prepare,
|
|
1687
|
+
ssl: config.ssl
|
|
673
1688
|
}));
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
}
|
|
679
|
-
/** Bulk overrides (test/session scoped). */
|
|
680
|
-
function overrideSecrets(values) {
|
|
681
|
-
for (const [name, value] of Object.entries(values)) overrides.set(name, value);
|
|
682
|
-
}
|
|
683
|
-
/** Clear registry and overrides. Test-only. */
|
|
684
|
-
function resetSecrets() {
|
|
685
|
-
registry.clear();
|
|
686
|
-
overrides.clear();
|
|
1689
|
+
return drizzle(client, {
|
|
1690
|
+
schema: config.schema,
|
|
1691
|
+
...config.schemaName ? { schemaFilter: [config.schemaName] } : {}
|
|
1692
|
+
});
|
|
687
1693
|
}
|
|
688
1694
|
//#endregion
|
|
689
1695
|
//#region src/db/define.ts
|
|
@@ -1230,145 +2236,6 @@ function createServiceProxy(serviceName, options = {}) {
|
|
|
1230
2236
|
} });
|
|
1231
2237
|
}
|
|
1232
2238
|
//#endregion
|
|
1233
|
-
//#region src/openapi.ts
|
|
1234
|
-
function generateOpenApiSpec(options = {}) {
|
|
1235
|
-
const title = options.title ?? "Brick-TS API Mesh";
|
|
1236
|
-
const version = options.version ?? "1.0.0";
|
|
1237
|
-
const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
|
|
1238
|
-
const prefix = options.prefix ?? "/api";
|
|
1239
|
-
const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
|
|
1240
|
-
const paths = {};
|
|
1241
|
-
const tagsSet = /* @__PURE__ */ new Set();
|
|
1242
|
-
let hasAnyAuthorizedAction = false;
|
|
1243
|
-
for (const service of services) {
|
|
1244
|
-
tagsSet.add(service.name);
|
|
1245
|
-
for (const action of service.listActions()) {
|
|
1246
|
-
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
1247
|
-
if (pluginRoute === false) continue;
|
|
1248
|
-
const routePath = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
1249
|
-
const method = (pluginRoute?.method ?? action.config.method ?? "POST").toLowerCase();
|
|
1250
|
-
const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
|
|
1251
|
-
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
1252
|
-
if (!paths[actionPath]) paths[actionPath] = {};
|
|
1253
|
-
if (paths[actionPath][method]) continue;
|
|
1254
|
-
const hasAuth = Boolean(action.config.authorize);
|
|
1255
|
-
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
1256
|
-
const responses = {};
|
|
1257
|
-
if (action.config.output) responses["200"] = {
|
|
1258
|
-
description: "Successful response",
|
|
1259
|
-
content: { "application/json": { schema: action.config.output } }
|
|
1260
|
-
};
|
|
1261
|
-
else responses["200"] = { description: "Successful response" };
|
|
1262
|
-
if (action.config.input) responses["400"] = {
|
|
1263
|
-
description: "Validation error",
|
|
1264
|
-
content: { "application/json": { schema: {
|
|
1265
|
-
type: "object",
|
|
1266
|
-
properties: {
|
|
1267
|
-
name: { type: "string" },
|
|
1268
|
-
message: { type: "string" },
|
|
1269
|
-
status: { type: "integer" },
|
|
1270
|
-
errors: {
|
|
1271
|
-
type: "array",
|
|
1272
|
-
items: {
|
|
1273
|
-
type: "object",
|
|
1274
|
-
properties: {
|
|
1275
|
-
path: { type: "string" },
|
|
1276
|
-
message: { type: "string" }
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
}
|
|
1281
|
-
} } }
|
|
1282
|
-
};
|
|
1283
|
-
if (hasAuth) responses["403"] = { description: "Access denied / Unauthorized" };
|
|
1284
|
-
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1285
|
-
const def = errorDef;
|
|
1286
|
-
const status = String(def.status || 400);
|
|
1287
|
-
responses[status] = {
|
|
1288
|
-
description: def.message || code,
|
|
1289
|
-
content: { "application/json": { schema: {
|
|
1290
|
-
type: "object",
|
|
1291
|
-
properties: {
|
|
1292
|
-
name: {
|
|
1293
|
-
type: "string",
|
|
1294
|
-
example: "ActionExecutionError"
|
|
1295
|
-
},
|
|
1296
|
-
code: {
|
|
1297
|
-
type: "string",
|
|
1298
|
-
example: code
|
|
1299
|
-
},
|
|
1300
|
-
message: {
|
|
1301
|
-
type: "string",
|
|
1302
|
-
example: def.message
|
|
1303
|
-
},
|
|
1304
|
-
status: {
|
|
1305
|
-
type: "integer",
|
|
1306
|
-
example: def.status || 400
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
|
-
} } }
|
|
1310
|
-
};
|
|
1311
|
-
}
|
|
1312
|
-
responses["500"] = { description: "Internal server error" };
|
|
1313
|
-
const operation = {
|
|
1314
|
-
operationId: `${service.name}_${action.name}_${method}`,
|
|
1315
|
-
summary: `${service.name}.${action.name}`,
|
|
1316
|
-
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1317
|
-
tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
|
|
1318
|
-
responses
|
|
1319
|
-
};
|
|
1320
|
-
const inputSchema = action.config.input;
|
|
1321
|
-
const properties = inputSchema?.properties ?? {};
|
|
1322
|
-
const parameters = [...new Set(pathParams)].map((key) => ({
|
|
1323
|
-
name: key,
|
|
1324
|
-
in: "path",
|
|
1325
|
-
required: true,
|
|
1326
|
-
schema: properties[key] ?? { type: "string" }
|
|
1327
|
-
}));
|
|
1328
|
-
if (method === "get" || method === "delete") for (const [key, schema] of Object.entries(properties)) {
|
|
1329
|
-
if (pathParams.includes(key)) continue;
|
|
1330
|
-
parameters.push({
|
|
1331
|
-
name: key,
|
|
1332
|
-
in: "query",
|
|
1333
|
-
required: inputSchema?.required?.includes(key) ?? false,
|
|
1334
|
-
schema
|
|
1335
|
-
});
|
|
1336
|
-
}
|
|
1337
|
-
else if (inputSchema) operation.requestBody = {
|
|
1338
|
-
required: true,
|
|
1339
|
-
content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
|
|
1340
|
-
...inputSchema,
|
|
1341
|
-
properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
|
|
1342
|
-
required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
|
|
1343
|
-
} : inputSchema } }
|
|
1344
|
-
};
|
|
1345
|
-
if (parameters.length) operation.parameters = parameters;
|
|
1346
|
-
if (hasAuth) operation.security = [{ bearerAuth: [] }];
|
|
1347
|
-
paths[actionPath][method] = operation;
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
|
-
const spec = {
|
|
1351
|
-
openapi: "3.1.0",
|
|
1352
|
-
info: {
|
|
1353
|
-
title,
|
|
1354
|
-
version,
|
|
1355
|
-
description
|
|
1356
|
-
},
|
|
1357
|
-
paths,
|
|
1358
|
-
tags: Array.from(tagsSet).map((name) => ({
|
|
1359
|
-
name,
|
|
1360
|
-
description: `Actions exposed by '${name}' service`
|
|
1361
|
-
}))
|
|
1362
|
-
};
|
|
1363
|
-
if (hasAnyAuthorizedAction) spec.components = { securitySchemes: { bearerAuth: {
|
|
1364
|
-
type: "http",
|
|
1365
|
-
scheme: "bearer",
|
|
1366
|
-
bearerFormat: "JWT",
|
|
1367
|
-
description: "Enter your Bearer authentication token"
|
|
1368
|
-
} } };
|
|
1369
|
-
return spec;
|
|
1370
|
-
}
|
|
1371
|
-
//#endregion
|
|
1372
2239
|
//#region src/mcp.ts
|
|
1373
2240
|
var UnknownToolError = class extends Error {
|
|
1374
2241
|
constructor(name) {
|
|
@@ -1490,6 +2357,6 @@ function createMcpHandler(options) {
|
|
|
1490
2357
|
};
|
|
1491
2358
|
}
|
|
1492
2359
|
//#endregion
|
|
1493
|
-
export { ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, Type as t, UnknownToolError, ValidationError, and, asc, attachDatabase, blob, buildErrorHelpers, buildFtsMatchQuery, createBrickClient, createDatabase, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, relations, resetGlobalRegistry, resetSecrets, resolveSecrets, secret, sql, sqliteTable, syncSchema, text, uniqueIndex, validateWithSchema };
|
|
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 };
|
|
1494
2361
|
|
|
1495
2362
|
//# sourceMappingURL=index.js.map
|