@brickkit/core 0.12.0 → 0.13.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/chunks/client.d.ts +54 -13
- package/dist/chunks/client.js +382 -91
- package/dist/chunks/client.js.map +1 -1
- package/dist/chunks/server.d.ts +444 -0
- package/dist/chunks/server.js +1138 -1744
- package/dist/chunks/server.js.map +1 -1
- package/dist/chunks/types.d.ts +434 -630
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/index.d.ts +766 -5
- package/dist/index.js +532 -302
- package/dist/index.js.map +1 -1
- package/dist/tanstack-query.js.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -3
- package/dist/testing.js.map +1 -1
- package/dist/workflow.d.ts +74 -2
- package/package.json +2 -1
- package/dist/chunks/index.d.ts +0 -1106
- package/dist/chunks/workflow.d.ts +0 -74
package/dist/chunks/server.js
CHANGED
|
@@ -1,302 +1,33 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import "../workflow.js";
|
|
1
|
+
import { A as byteLength, B as splitSeq, C as SOCKET_BUFFER_BYTES, D as SOCKET_PROTOCOL, E as SOCKET_MAX_BYTES, F as isSocketRoom, G as DuplicateNameError, H as GLOBAL_SYMBOL, I as isSocketSeq, K as ValidationError, L as replayFrame, M as encodeFrame, N as isControlEvent, O as SOCKET_TOKEN_PROTOCOL, P as isSocketEnvelope, R as replayHeadroom, S as actionMeta, T as SOCKET_CONTROL, U as SPAN, V as ATTR, W as ActionExecutionError, _ as pathParamNames, b as toOpenApiPath, c as DEFAULT_PREFIX, d as getActionRoute, g as ownerPath, h as joinRoute, k as STANDARD_ERRORS, l as actionOwners, m as isReadLike, p as inputSource, s as serializeSocketSchema, u as checkSegments, v as pluginRoutePath, w as SOCKET_CLOSE, x as kebabCase, y as routeKey, z as signSeq } from "./client.js";
|
|
3
2
|
import { createRequire } from "node:module";
|
|
4
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
3
|
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
6
4
|
import { Type, Type as t } from "@sinclair/typebox";
|
|
7
5
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
8
6
|
import { formatWithOptions } from "node:util";
|
|
7
|
+
import { join, resolve } from "node:path";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
import { and, asc, eq, inArray, lt, lte, or, sql } from "drizzle-orm";
|
|
10
|
+
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
11
|
+
import { bigserial, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
|
|
9
12
|
import { existsSync, readFileSync } from "node:fs";
|
|
10
|
-
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
11
|
-
import { Value } from "@sinclair/typebox/value";
|
|
12
|
-
import { and, asc, eq, getTableName, inArray, lt, lte, or, sql } from "drizzle-orm";
|
|
13
|
-
import { index, integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
14
|
-
import { bigserial, boolean, doublePrecision, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
|
|
15
13
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
16
14
|
import { Elysia } from "elysia";
|
|
17
15
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
18
16
|
import { websocket } from "elysia/websocket";
|
|
19
|
-
// src/
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return path;
|
|
29
|
-
}
|
|
30
|
-
/** Joins a path relative to its owner. `/` is the owner's own route. */
|
|
31
|
-
function joinRoute(base, path) {
|
|
32
|
-
return `${base}${path === "/" ? "" : path}` || "/";
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Where an action is served over HTTP: its method and its path under the owner
|
|
36
|
-
* tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource
|
|
37
|
-
* action's `${prefix}/${service}/${resource}[/:id]/${action}`).
|
|
38
|
-
*
|
|
39
|
-
* @param action - An action registered on a service.
|
|
40
|
-
* @param prefix - The application's route prefix (default `/api`).
|
|
41
|
-
* @returns `false` when a plugin switched the route off, otherwise the route.
|
|
42
|
-
*/
|
|
43
|
-
function getActionRoute(action, prefix = "/api") {
|
|
44
|
-
const plugin = getPluginActionRoute(action, prefix);
|
|
45
|
-
if (plugin === false) return false;
|
|
46
|
-
if (plugin) return {
|
|
47
|
-
method: plugin.method,
|
|
48
|
-
path: plugin.path
|
|
49
|
-
};
|
|
50
|
-
const service = action.serviceName ?? "";
|
|
51
|
-
const method = action.config.method ?? "POST";
|
|
52
|
-
const { resourceAction } = action;
|
|
53
|
-
if (resourceAction) {
|
|
54
|
-
const base = ownerPath(prefix, service, resourceAction.resource);
|
|
55
|
-
return {
|
|
56
|
-
method,
|
|
57
|
-
path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}${resourceAction.record ? "/:id" : ""}/${kebabCase(resourceAction.name)}`
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
const base = ownerPath(prefix, service);
|
|
61
|
-
return {
|
|
62
|
-
method,
|
|
63
|
-
path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}/${kebabCase(action.name)}`
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
// src/compiler/ir.ts
|
|
67
|
-
function freezeIR(value) {
|
|
68
|
-
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
69
|
-
for (const child of Object.values(value)) freezeIR(child);
|
|
70
|
-
Object.freeze(value);
|
|
71
|
-
}
|
|
72
|
-
return value;
|
|
73
|
-
}
|
|
74
|
-
function schemaSnapshot(schema) {
|
|
75
|
-
return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
|
|
76
|
-
}
|
|
77
|
-
function analyzeApplication(services, prefix = "/api") {
|
|
78
|
-
for (const service of services) service.build();
|
|
79
|
-
return analyzeDeclaredApplication(services, prefix);
|
|
80
|
-
}
|
|
81
|
-
/** Inspect current declarations without closing service/plugin setup. */
|
|
82
|
-
function analyzeDeclaredApplication(services, prefix = "/api") {
|
|
83
|
-
if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
|
|
84
|
-
const names = /* @__PURE__ */ new Set();
|
|
85
|
-
for (const service of services) {
|
|
86
|
-
if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
|
|
87
|
-
names.add(service.name);
|
|
88
|
-
}
|
|
89
|
-
const routes = [];
|
|
90
|
-
const bindings = [];
|
|
91
|
-
const registered = /* @__PURE__ */ new Map();
|
|
92
|
-
const diagnostics = [];
|
|
93
|
-
const add = (service, action, method, path, kind) => {
|
|
94
|
-
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
95
|
-
const plugin = getPluginActionRoute(action, prefix) !== void 0;
|
|
96
|
-
const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
97
|
-
const previous = registered.get(key);
|
|
98
|
-
if (previous) {
|
|
99
|
-
if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
100
|
-
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
|
|
101
|
-
return;
|
|
102
|
-
}
|
|
103
|
-
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
104
|
-
registered.set(key, {
|
|
105
|
-
name: `${service.name}.${action.name}`,
|
|
106
|
-
plugin
|
|
107
|
-
});
|
|
108
|
-
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");
|
|
109
|
-
const coercions = [];
|
|
110
|
-
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
111
|
-
key,
|
|
112
|
-
type: "number"
|
|
113
|
-
});
|
|
114
|
-
else if (prop.type === "boolean") coercions.push({
|
|
115
|
-
key,
|
|
116
|
-
type: "boolean"
|
|
117
|
-
});
|
|
118
|
-
else if (prop.type === "array") coercions.push({
|
|
119
|
-
key,
|
|
120
|
-
type: "array"
|
|
121
|
-
});
|
|
122
|
-
routes.push({
|
|
123
|
-
method,
|
|
124
|
-
path,
|
|
125
|
-
service: service.name,
|
|
126
|
-
action: action.name,
|
|
127
|
-
kind,
|
|
128
|
-
input: Boolean(action.config.input),
|
|
129
|
-
output: Boolean(action.config.output),
|
|
130
|
-
context: typeof service.options.context === "function",
|
|
131
|
-
authorize: typeof action.config.authorize === "function",
|
|
132
|
-
inputPrecedence: readLike ? [
|
|
133
|
-
"query",
|
|
134
|
-
"params",
|
|
135
|
-
"body"
|
|
136
|
-
] : [
|
|
137
|
-
"params",
|
|
138
|
-
"body",
|
|
139
|
-
"query"
|
|
140
|
-
],
|
|
141
|
-
coercions,
|
|
142
|
-
inputSchema: schemaSnapshot(action.config.input),
|
|
143
|
-
outputSchema: schemaSnapshot(action.config.output)
|
|
144
|
-
});
|
|
145
|
-
bindings.push({
|
|
146
|
-
service,
|
|
147
|
-
action
|
|
148
|
-
});
|
|
149
|
-
};
|
|
150
|
-
for (const service of services) {
|
|
151
|
-
checkSegments(service);
|
|
152
|
-
for (const action of service.listActions()) {
|
|
153
|
-
const route = getActionRoute(action, prefix);
|
|
154
|
-
if (route === false) continue;
|
|
155
|
-
add(service, action, route.method, route.path, "action");
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
|
|
159
|
-
service: service.name,
|
|
160
|
-
name: contribution.name,
|
|
161
|
-
metadata: schemaSnapshot(contribution.describe?.())
|
|
162
|
-
})));
|
|
163
|
-
return {
|
|
164
|
-
ir: freezeIR({
|
|
165
|
-
version: 1,
|
|
166
|
-
target: "bun-elysia",
|
|
167
|
-
prefix,
|
|
168
|
-
services: [...names],
|
|
169
|
-
routes,
|
|
170
|
-
preparations,
|
|
171
|
-
diagnostics
|
|
172
|
-
}),
|
|
173
|
-
bindings
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
/** A service action, resource, and socket own the URL segment after the service. */
|
|
177
|
-
function checkSegments(service) {
|
|
178
|
-
const owners = /* @__PURE__ */ new Map();
|
|
179
|
-
const claim = (segment, owner) => {
|
|
180
|
-
const previous = owners.get(segment);
|
|
181
|
-
if (previous) throw new Error(`Brick: duplicate name "${segment}" in service "${service.name}": ${previous} and ${owner} share the URL segment`);
|
|
182
|
-
owners.set(segment, owner);
|
|
183
|
-
};
|
|
184
|
-
for (const resource of service.listResources()) claim(kebabCase(resource.name), `resource "${resource.name}"`);
|
|
185
|
-
for (const socket of service.listSockets()) if (socket.schema.path === void 0) claim(kebabCase(socket.schema.name), `socket "${socket.schema.name}"`);
|
|
186
|
-
for (const action of service.listActions()) if (action.config.path === void 0 && !action.resourceAction && getPluginActionRoute(action) === void 0) claim(kebabCase(action.name), `action "${action.name}"`);
|
|
187
|
-
}
|
|
188
|
-
// src/registry.ts
|
|
189
|
-
const brickRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
190
|
-
/**
|
|
191
|
-
* The first `file:line` outside Brick on the current stack: where a name is
|
|
192
|
-
* being defined. Best-effort: `undefined` when there is no stack.
|
|
193
|
-
*/
|
|
194
|
-
function definitionSite() {
|
|
195
|
-
const limit = Error.stackTraceLimit;
|
|
196
|
-
Error.stackTraceLimit = 50;
|
|
197
|
-
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
198
|
-
Error.stackTraceLimit = limit;
|
|
199
|
-
for (const line of stack?.split("\n").slice(1) ?? []) {
|
|
200
|
-
const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
|
|
201
|
-
if (!match) continue;
|
|
202
|
-
const [, file, row] = match;
|
|
203
|
-
if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
|
|
204
|
-
return `${file}:${row}`;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
/**
|
|
208
|
-
* Records where `name` is defined. The same file defining it again (a dev
|
|
209
|
-
* reload) replaces the old definition.
|
|
210
|
-
*
|
|
211
|
-
* @throws When a different file already defined `name`.
|
|
212
|
-
*/
|
|
213
|
-
function claimName(sites, label, name, site) {
|
|
214
|
-
const file = (at) => at?.replace(/:\d+$/, "");
|
|
215
|
-
if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new Error(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
|
|
216
|
-
sites.set(name, site);
|
|
217
|
-
}
|
|
218
|
-
var ServiceRegistry = class {
|
|
219
|
-
_revision = 0;
|
|
220
|
-
/** Definition revision for invalidating serialized architecture snapshots. */
|
|
221
|
-
get revision() {
|
|
222
|
-
return this._revision;
|
|
223
|
-
}
|
|
224
|
-
touch() {
|
|
225
|
-
this._revision++;
|
|
226
|
-
}
|
|
227
|
-
services = /* @__PURE__ */ new Map();
|
|
228
|
-
sites = /* @__PURE__ */ new Map();
|
|
229
|
-
routes = /* @__PURE__ */ new Map();
|
|
230
|
-
/** Remember the actual registered routes for subsequent registry exports. */
|
|
231
|
-
setApplicationRoutes(application) {
|
|
232
|
-
for (const service of application.services) this.routes.set(service, application.routes.filter((route) => route.service === service.name));
|
|
233
|
-
this.touch();
|
|
234
|
-
}
|
|
235
|
-
/** @throws When a different file already registered a service with this name. */
|
|
236
|
-
register(service, site = definitionSite()) {
|
|
237
|
-
claimName(this.sites, `service "${service.name}"`, service.name, site);
|
|
238
|
-
const previous = this.services.get(service.name);
|
|
239
|
-
if (previous) this.routes.delete(previous);
|
|
240
|
-
this.services.set(service.name, service);
|
|
241
|
-
this.touch();
|
|
242
|
-
}
|
|
243
|
-
get(name) {
|
|
244
|
-
return this.services.get(name);
|
|
245
|
-
}
|
|
246
|
-
has(name) {
|
|
247
|
-
return this.services.has(name);
|
|
248
|
-
}
|
|
249
|
-
list() {
|
|
250
|
-
return Array.from(this.services.values());
|
|
251
|
-
}
|
|
252
|
-
clear() {
|
|
253
|
-
this.services.clear();
|
|
254
|
-
this.sites.clear();
|
|
255
|
-
this.routes.clear();
|
|
256
|
-
this.touch();
|
|
257
|
-
}
|
|
258
|
-
exportArchitecture(application) {
|
|
259
|
-
return {
|
|
260
|
-
version: "1.0.0",
|
|
261
|
-
...application?.events ? { events: application.events } : {},
|
|
262
|
-
...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
|
|
263
|
-
services: (application?.services ?? this.list()).map((service) => {
|
|
264
|
-
const routes = application ? application.routes.filter((route) => route.service === service.name) : this.routes.get(service) ?? analyzeDeclaredApplication([service]).ir.routes;
|
|
265
|
-
const byAction = new Map(routes.map((route) => [route.action, route]));
|
|
266
|
-
const schema = service.introspect();
|
|
267
|
-
return {
|
|
268
|
-
...schema,
|
|
269
|
-
...application?.sockets ? { sockets: application.sockets.filter((socket) => socket.service === service.name) } : {},
|
|
270
|
-
actions: schema.actions.map((action) => {
|
|
271
|
-
const route = byAction.get(action.name);
|
|
272
|
-
return route ? {
|
|
273
|
-
...action,
|
|
274
|
-
method: route.method,
|
|
275
|
-
path: route.path
|
|
276
|
-
} : action;
|
|
277
|
-
})
|
|
278
|
-
};
|
|
279
|
-
})
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
};
|
|
283
|
-
let globalRegistry = new ServiceRegistry();
|
|
284
|
-
/**
|
|
285
|
-
* The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
|
|
286
|
-
* generator, `useService`, and the dashboard find services by name.
|
|
287
|
-
*
|
|
288
|
-
* @returns The current global registry.
|
|
289
|
-
*/
|
|
290
|
-
function getGlobalRegistry() {
|
|
291
|
-
return globalRegistry;
|
|
292
|
-
}
|
|
17
|
+
// src/plugin-types.ts
|
|
18
|
+
/** Where a plugin route mounts: under the app prefix, its service, or its resource. */
|
|
19
|
+
const PLUGIN_ROUTE_SCOPES = [
|
|
20
|
+
"app",
|
|
21
|
+
"service",
|
|
22
|
+
"resource"
|
|
23
|
+
];
|
|
24
|
+
/** Which host a plugin descriptor installs on. Process-global, so descriptors survive a second core copy. */
|
|
25
|
+
const PLUGIN_KIND = Symbol.for("brickkit.plugin.kind");
|
|
293
26
|
/**
|
|
294
|
-
*
|
|
295
|
-
*
|
|
27
|
+
* The setup context's slot where a `definePlugin` setup hands over what to do
|
|
28
|
+
* once its install succeeds; a failed install drops it.
|
|
296
29
|
*/
|
|
297
|
-
|
|
298
|
-
globalRegistry = new ServiceRegistry();
|
|
299
|
-
}
|
|
30
|
+
const PLUGIN_COMMIT = Symbol.for("brickkit.plugin.commit");
|
|
300
31
|
// src/telemetry.ts
|
|
301
32
|
const INSTRUMENTATION_SCOPE = "@brickkit/core";
|
|
302
33
|
const MAX_TEXT_LENGTH = 500;
|
|
@@ -356,10 +87,10 @@ function traceRoute(route, handler) {
|
|
|
356
87
|
*/
|
|
357
88
|
function traceHttpRequest(request, method, route, fn) {
|
|
358
89
|
const attributes = {
|
|
359
|
-
|
|
360
|
-
|
|
90
|
+
[ATTR.httpMethod]: method,
|
|
91
|
+
[ATTR.httpRoute]: route
|
|
361
92
|
};
|
|
362
|
-
if (request.request) attributes[
|
|
93
|
+
if (request.request) attributes[ATTR.urlPath] = new URL(request.request.url).pathname;
|
|
363
94
|
const headers = request.headers ?? {};
|
|
364
95
|
const parent = propagation.extract(context.active(), headers);
|
|
365
96
|
return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(`${method} ${route}`, {
|
|
@@ -373,9 +104,9 @@ function traceHttpRequest(request, method, route, fn) {
|
|
|
373
104
|
return settle(fn, (outcome) => {
|
|
374
105
|
const status = outcome.failed ? 500 : outcome.value instanceof Response ? outcome.value.status : responseStatus(request.set?.status);
|
|
375
106
|
if (outcome.failed) recordThrown(span, outcome.error);
|
|
376
|
-
span.setAttribute(
|
|
107
|
+
span.setAttribute(ATTR.httpStatus, status);
|
|
377
108
|
const traceId = headers["x-trace-id"];
|
|
378
|
-
if (traceId) span.setAttribute(
|
|
109
|
+
if (traceId) span.setAttribute(ATTR.traceId, traceId);
|
|
379
110
|
if (status >= 500) span.setStatus({
|
|
380
111
|
code: SpanStatusCode.ERROR,
|
|
381
112
|
message: `HTTP ${status}`
|
|
@@ -393,9 +124,9 @@ function recordFailure(error, failure) {
|
|
|
393
124
|
const span = trace.getActiveSpan();
|
|
394
125
|
if (!span) return;
|
|
395
126
|
span.setAttributes({
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
127
|
+
[ATTR.errorCode]: failure.code,
|
|
128
|
+
[ATTR.errorStatus]: failure.status,
|
|
129
|
+
[ATTR.errorMessage]: truncate(failure.message)
|
|
399
130
|
});
|
|
400
131
|
if (failure.status >= 500) recordThrown(span, error);
|
|
401
132
|
}
|
|
@@ -477,9 +208,9 @@ function statementName(sql) {
|
|
|
477
208
|
}
|
|
478
209
|
function statementAttributes(sql, system) {
|
|
479
210
|
return {
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
211
|
+
[ATTR.dbSystem]: system,
|
|
212
|
+
[ATTR.dbOperation]: operationOf(sql),
|
|
213
|
+
[ATTR.dbStatement]: truncate(sql, MAX_STATEMENT_LENGTH)
|
|
483
214
|
};
|
|
484
215
|
}
|
|
485
216
|
function operationOf(sql) {
|
|
@@ -630,9 +361,7 @@ function validateWithSchema(schema, value) {
|
|
|
630
361
|
* an export: the CLI and the app may each hold their own copy of this package,
|
|
631
362
|
* and nothing but a dashboard turns it on.
|
|
632
363
|
*/
|
|
633
|
-
const CAPTURE = Symbol.for(
|
|
634
|
-
/** The span event a log line becomes; the dashboard reads these. */
|
|
635
|
-
const LOG_EVENT = "log";
|
|
364
|
+
const CAPTURE = Symbol.for(GLOBAL_SYMBOL.logsCapture);
|
|
636
365
|
const MAX_MESSAGE_LENGTH = 4e3;
|
|
637
366
|
/**
|
|
638
367
|
* Logs one span keeps. OpenTelemetry keeps 128 events per span by default,
|
|
@@ -647,7 +376,6 @@ const logged = /* @__PURE__ */ new WeakMap();
|
|
|
647
376
|
* console output, which in a web page shows as stray characters.
|
|
648
377
|
*/
|
|
649
378
|
const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\))/g;
|
|
650
|
-
/** `text` without terminal formatting. */
|
|
651
379
|
function stripAnsi(text) {
|
|
652
380
|
return text.includes("\x1B") ? text.replace(ANSI, "") : text;
|
|
653
381
|
}
|
|
@@ -668,12 +396,12 @@ function record(span, level, args) {
|
|
|
668
396
|
const count = (logged.get(span) ?? 0) + 1;
|
|
669
397
|
logged.set(span, count);
|
|
670
398
|
if (count > MAX_LOGS_PER_SPAN) {
|
|
671
|
-
span.setAttribute(
|
|
399
|
+
span.setAttribute(ATTR.logsDropped, count - MAX_LOGS_PER_SPAN);
|
|
672
400
|
return;
|
|
673
401
|
}
|
|
674
|
-
span.addEvent(
|
|
675
|
-
|
|
676
|
-
|
|
402
|
+
span.addEvent(SPAN.logEvent, {
|
|
403
|
+
[ATTR.logLevel]: level,
|
|
404
|
+
[ATTR.logMessage]: render(args)
|
|
677
405
|
});
|
|
678
406
|
}
|
|
679
407
|
/**
|
|
@@ -686,7 +414,7 @@ function recordActive(level, args) {
|
|
|
686
414
|
record(span, level, args);
|
|
687
415
|
return true;
|
|
688
416
|
}
|
|
689
|
-
globalThis[Symbol.for(
|
|
417
|
+
globalThis[Symbol.for(GLOBAL_SYMBOL.logsRecord)] = recordActive;
|
|
690
418
|
/**
|
|
691
419
|
* A logger for actions, tools, and endpoints. While a dashboard is on, a line
|
|
692
420
|
* logged while a request is being traced becomes an event on the span that is
|
|
@@ -718,147 +446,332 @@ const DEFAULT_LOG_PREFIXES = {
|
|
|
718
446
|
error: "[ERROR]",
|
|
719
447
|
debug: "[DEBUG]"
|
|
720
448
|
};
|
|
721
|
-
// src/
|
|
449
|
+
// src/context.ts
|
|
450
|
+
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
451
|
+
const EMPTY = Object.freeze({});
|
|
722
452
|
const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
FORBIDDEN: {
|
|
736
|
-
status: 403,
|
|
737
|
-
message: "Forbidden"
|
|
738
|
-
},
|
|
739
|
-
NOT_FOUND: {
|
|
740
|
-
status: 404,
|
|
741
|
-
message: "Not Found"
|
|
742
|
-
},
|
|
743
|
-
CONFLICT: {
|
|
744
|
-
status: 409,
|
|
745
|
-
message: "Conflict"
|
|
746
|
-
},
|
|
747
|
-
INTERNAL_SERVER_ERROR: {
|
|
748
|
-
status: 500,
|
|
749
|
-
message: "Internal Server Error"
|
|
453
|
+
/** Random, so ids never repeat across restarts or processes. */
|
|
454
|
+
const newId = (kind) => `${kind}_${crypto.randomUUID()}`;
|
|
455
|
+
/**
|
|
456
|
+
* The trace and request ids of an HTTP request: the caller's `x-trace-id` and
|
|
457
|
+
* `x-request-id` headers, else fresh ones. Both are echoed on the response.
|
|
458
|
+
*/
|
|
459
|
+
function requestIds(headers, set) {
|
|
460
|
+
const traceId = headers?.["x-trace-id"] || newId("tr");
|
|
461
|
+
const requestId = headers?.["x-request-id"] || newId("req");
|
|
462
|
+
if (set?.headers) {
|
|
463
|
+
set.headers["x-trace-id"] = traceId;
|
|
464
|
+
set.headers["x-request-id"] = requestId;
|
|
750
465
|
}
|
|
751
|
-
};
|
|
752
|
-
function createDefaultContext(partial) {
|
|
753
|
-
if (partial?.[RESOLVED_SYMBOL]) return partial;
|
|
754
|
-
const seq = (++_defaultCtxSeq).toString(36);
|
|
755
466
|
return {
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
requestId: partial?.requestId || `req_${seq}`,
|
|
759
|
-
db: partial?.db,
|
|
760
|
-
user: partial?.user,
|
|
761
|
-
logger: partial?.logger || defaultLogger,
|
|
762
|
-
services: partial?.services || {},
|
|
763
|
-
metadata: partial?.metadata || {},
|
|
764
|
-
...partial,
|
|
765
|
-
[RESOLVED_SYMBOL]: true
|
|
467
|
+
traceId,
|
|
468
|
+
requestId
|
|
766
469
|
};
|
|
767
470
|
}
|
|
768
471
|
/**
|
|
769
|
-
* The
|
|
770
|
-
*
|
|
771
|
-
* codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
|
|
772
|
-
* `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
|
|
773
|
-
* them or replace one.
|
|
774
|
-
*
|
|
775
|
-
* @param errorsDef - The action's `errors`: for each code, its `message` and
|
|
776
|
-
* `status` (default 400).
|
|
777
|
-
* @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
|
|
778
|
-
* and always throw.
|
|
472
|
+
* The framework fields of an action context: what the caller gave, the rest
|
|
473
|
+
* defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.
|
|
779
474
|
*/
|
|
780
|
-
function
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
475
|
+
function baseContext(fields) {
|
|
476
|
+
return {
|
|
477
|
+
request: fields.request ?? DEFAULT_REQUEST,
|
|
478
|
+
db: fields.db,
|
|
479
|
+
logger: fields.logger ?? defaultLogger,
|
|
480
|
+
traceId: fields.traceId ?? newId("tr"),
|
|
481
|
+
requestId: fields.requestId ?? newId("req"),
|
|
482
|
+
services: fields.services ?? EMPTY,
|
|
483
|
+
metadata: fields.metadata ?? EMPTY,
|
|
484
|
+
deps: fields.deps ?? EMPTY
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function pickContextEnvelope(context) {
|
|
488
|
+
if (!context) return {};
|
|
489
|
+
const envelope = {};
|
|
490
|
+
if (context.caller !== void 0) envelope.caller = context.caller;
|
|
491
|
+
if (context.user !== void 0) envelope.user = context.user;
|
|
492
|
+
if (context.traceId !== void 0) envelope.traceId = context.traceId;
|
|
493
|
+
if (context.requestId !== void 0) envelope.requestId = context.requestId;
|
|
494
|
+
if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
|
|
495
|
+
return envelope;
|
|
797
496
|
}
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
Object.defineProperty(actionFn, "name", {
|
|
804
|
-
value: config.name,
|
|
805
|
-
configurable: true
|
|
806
|
-
});
|
|
807
|
-
actionFn.config = config;
|
|
808
|
-
actionFn.errorHelpers = errorHelpers;
|
|
809
|
-
actionFn.validateInput = (input) => {
|
|
810
|
-
return validateWithSchema(config.input, input);
|
|
811
|
-
};
|
|
812
|
-
actionFn.validateOutput = (output) => {
|
|
813
|
-
return validateWithSchema(actionFn.outputValidationSchema ?? config.output, output);
|
|
814
|
-
};
|
|
815
|
-
actionFn.run = async (input, ctx) => {
|
|
816
|
-
return actionFn.execute({
|
|
817
|
-
input,
|
|
818
|
-
ctx
|
|
819
|
-
});
|
|
820
|
-
};
|
|
821
|
-
actionFn.execute = async (params) => {
|
|
822
|
-
const boundService = actionFn.service;
|
|
823
|
-
const fullCtx = boundService?.resolveContext ? await boundService.resolveContext(params?.ctx) : createDefaultContext(params?.ctx);
|
|
824
|
-
try {
|
|
825
|
-
if (!fullCtx.db) {
|
|
826
|
-
const service = boundService ?? (actionFn.serviceName ? getGlobalRegistry().get(actionFn.serviceName) : void 0);
|
|
827
|
-
if (service?.getDb()) fullCtx.db = service.getDb();
|
|
828
|
-
}
|
|
829
|
-
if (config.input) {
|
|
830
|
-
const inputValidation = actionFn.validateInput(params?.input);
|
|
831
|
-
if (!inputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' input`, inputValidation.errors);
|
|
832
|
-
}
|
|
833
|
-
if (config.authorize) {
|
|
834
|
-
if (!await config.authorize({
|
|
835
|
-
user: fullCtx.user,
|
|
836
|
-
input: params?.input,
|
|
837
|
-
ctx: fullCtx
|
|
838
|
-
})) throw new ActionExecutionError(fullCtx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${config.name}'`, fullCtx.user == null ? 401 : 403);
|
|
839
|
-
}
|
|
840
|
-
const result = await config.execute({
|
|
841
|
-
input: params?.input,
|
|
842
|
-
ctx: fullCtx,
|
|
843
|
-
error: errorHelpers
|
|
844
|
-
});
|
|
845
|
-
if (actionFn.outputValidationSchema ?? config.output) {
|
|
846
|
-
const outputValidation = actionFn.validateOutput(result);
|
|
847
|
-
if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
|
|
848
|
-
}
|
|
849
|
-
return result;
|
|
850
|
-
} catch (err) {
|
|
851
|
-
throw normalizeActionError(err, fullCtx);
|
|
852
|
-
}
|
|
853
|
-
};
|
|
854
|
-
return actionFn;
|
|
497
|
+
// src/compiler/runtime.ts
|
|
498
|
+
function isNonEmpty(value) {
|
|
499
|
+
if (value == null) return false;
|
|
500
|
+
for (const _ in value) return true;
|
|
501
|
+
return false;
|
|
855
502
|
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
503
|
+
/** One source alone is the input as it is; several merge, later ones winning. */
|
|
504
|
+
function mergeInput(first, second, third) {
|
|
505
|
+
const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);
|
|
506
|
+
if (a && !b && !c) return first;
|
|
507
|
+
if (b && !a && !c) return second;
|
|
508
|
+
if (c && !a && !b) return third;
|
|
509
|
+
if (a || b || c) return Object.assign({}, first, second, third);
|
|
510
|
+
}
|
|
511
|
+
function coerceQueryValue(value, type, request, key) {
|
|
512
|
+
if (type === "number") {
|
|
513
|
+
const number = Number(value);
|
|
514
|
+
return Number.isNaN(number) ? value : number;
|
|
515
|
+
}
|
|
516
|
+
if (type === "array") {
|
|
517
|
+
const values = request ? new URL(request.url).searchParams.getAll(key) : [];
|
|
518
|
+
return values.length ? values : Array.isArray(value) ? value : [value];
|
|
519
|
+
}
|
|
520
|
+
if (value === "true" || value === "1") return true;
|
|
521
|
+
if (value === "false" || value === "0") return false;
|
|
522
|
+
return value;
|
|
523
|
+
}
|
|
524
|
+
/** The action's input from the path, query and body, coerced by its schema. */
|
|
525
|
+
function readInput(route, { params, body, query, request }) {
|
|
526
|
+
if (!route.input) return void 0;
|
|
527
|
+
let coercedQuery = query;
|
|
528
|
+
let coercedParams = params;
|
|
529
|
+
if (route.coercions.length) {
|
|
530
|
+
if (query) {
|
|
531
|
+
coercedQuery = { ...query };
|
|
532
|
+
for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
|
|
533
|
+
}
|
|
534
|
+
for (const { key, type } of route.coercions) {
|
|
535
|
+
if (type !== "number" || typeof params?.[key] !== "string") continue;
|
|
536
|
+
const value = Number(params[key]);
|
|
537
|
+
if (Number.isNaN(value)) continue;
|
|
538
|
+
if (coercedParams === params) coercedParams = { ...params };
|
|
539
|
+
coercedParams[key] = value;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const input = route.readLike ? mergeInput(coercedQuery, coercedParams, body) : mergeInput(coercedParams, body, coercedQuery);
|
|
543
|
+
return input === void 0 && route.inputSchema?.type === "object" ? {} : input;
|
|
544
|
+
}
|
|
545
|
+
const MAX_INPUT_DEPTH = 128;
|
|
546
|
+
function inputTooDeep(value) {
|
|
547
|
+
if (!value || typeof value !== "object") return false;
|
|
548
|
+
const stack = [{
|
|
549
|
+
node: value,
|
|
550
|
+
depth: 0
|
|
551
|
+
}];
|
|
552
|
+
while (stack.length > 0) {
|
|
553
|
+
const { node, depth } = stack.pop();
|
|
554
|
+
if (depth > MAX_INPUT_DEPTH) return true;
|
|
555
|
+
if (node && typeof node === "object") {
|
|
556
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
557
|
+
for (const child of children) if (child && typeof child === "object") stack.push({
|
|
558
|
+
node: child,
|
|
559
|
+
depth: depth + 1
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return false;
|
|
564
|
+
}
|
|
565
|
+
/** The error for input (400) or output (500) that fails its schema. */
|
|
566
|
+
function invalid(action, stage, errors) {
|
|
567
|
+
return new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
|
|
568
|
+
}
|
|
569
|
+
function validate(check, value, action, stage) {
|
|
570
|
+
if (check.Check(value)) return;
|
|
571
|
+
throw invalid(action, stage, Array.from(check.Errors(value)).map((err) => ({
|
|
572
|
+
path: err.path,
|
|
573
|
+
message: err.message,
|
|
574
|
+
value: err.value
|
|
575
|
+
})));
|
|
576
|
+
}
|
|
577
|
+
function validateInput(check, input, action, checkInput) {
|
|
578
|
+
const errors = checkInput?.(input);
|
|
579
|
+
if (errors) throw invalid(action, "input", errors);
|
|
580
|
+
if (inputTooDeep(input)) throw invalid(action, "input", [{
|
|
581
|
+
path: "",
|
|
582
|
+
message: "Input exceeds maximum nesting depth"
|
|
583
|
+
}]);
|
|
584
|
+
validate(check, input, action, "input");
|
|
585
|
+
}
|
|
586
|
+
/** A refused `authorize`: 401 without a user, 403 with one. */
|
|
587
|
+
function deny(action, user) {
|
|
588
|
+
throw new ActionExecutionError(user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${action}'`, user == null ? 401 : 403);
|
|
589
|
+
}
|
|
590
|
+
/** Runs `authorize`, if any, and denies the call when it refuses. */
|
|
591
|
+
async function authorizeCall(authorize, ctx, input, action) {
|
|
592
|
+
if (authorize && !await authorize({
|
|
593
|
+
ctx,
|
|
594
|
+
input,
|
|
595
|
+
user: ctx.user
|
|
596
|
+
})) deny(action, ctx.user);
|
|
597
|
+
}
|
|
598
|
+
/** The stage order of every call, over HTTP and in-process: check input → authorize → execute → check output. */
|
|
599
|
+
async function runStages(stages, input, ctx) {
|
|
600
|
+
stages.checkInput(input);
|
|
601
|
+
await authorizeCall(stages.authorize, ctx, input, stages.name);
|
|
602
|
+
return stages.checkOutput(await stages.execute({
|
|
603
|
+
input,
|
|
604
|
+
ctx,
|
|
605
|
+
error: stages.errorBuilder
|
|
606
|
+
}));
|
|
607
|
+
}
|
|
608
|
+
function mapError(err, set, options) {
|
|
609
|
+
const response = toErrorResponse(err, options);
|
|
610
|
+
set.status = response.status;
|
|
611
|
+
return response;
|
|
612
|
+
}
|
|
613
|
+
const isThenable = (value) => value != null && typeof value.then === "function";
|
|
614
|
+
/** The context of one HTTP request, with the trace and request id headers set. */
|
|
615
|
+
function requestContext(plan, { headers, request, set }) {
|
|
616
|
+
return baseContext({
|
|
617
|
+
...requestIds(headers, set),
|
|
618
|
+
request: request instanceof Request ? request : void 0,
|
|
619
|
+
db: plan.cachedDb ?? plan.service.getDb(),
|
|
620
|
+
logger: plan.logger,
|
|
621
|
+
metadata: { headers },
|
|
622
|
+
deps: plan.contextHook ? plan.service.deps : plan.deps ?? plan.service.deps
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
/** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */
|
|
626
|
+
function bindRoute(plan) {
|
|
627
|
+
const { route, execute, contextHook, authorize, inputChecker, outputChecker, checkInput, errorBuilder } = plan;
|
|
628
|
+
const name = route.action;
|
|
629
|
+
const stages = {
|
|
630
|
+
name,
|
|
631
|
+
checkInput: (input) => {
|
|
632
|
+
if (inputChecker) validateInput(inputChecker, input, name, checkInput);
|
|
633
|
+
},
|
|
634
|
+
authorize,
|
|
635
|
+
execute,
|
|
636
|
+
errorBuilder,
|
|
637
|
+
checkOutput: (result) => {
|
|
638
|
+
if (outputChecker) validate(outputChecker, result, name, "output");
|
|
639
|
+
return result;
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
if (contextHook || authorize) return async function brickAction(context) {
|
|
643
|
+
const input = readInput(route, context);
|
|
644
|
+
const ctx = requestContext(plan, context);
|
|
645
|
+
try {
|
|
646
|
+
if (contextHook) {
|
|
647
|
+
const extra = await contextHook(ctx);
|
|
648
|
+
if (extra) Object.assign(ctx, extra);
|
|
649
|
+
if (plan.deps) ctx.deps = plan.deps;
|
|
650
|
+
}
|
|
651
|
+
return await runStages(stages, input, ctx);
|
|
652
|
+
} catch (err) {
|
|
653
|
+
return mapError(err, context.set, ctx);
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
return function brickAction(context) {
|
|
657
|
+
const input = readInput(route, context);
|
|
658
|
+
const ctx = requestContext(plan, context);
|
|
659
|
+
try {
|
|
660
|
+
stages.checkInput(input);
|
|
661
|
+
const result = execute({
|
|
662
|
+
input,
|
|
663
|
+
ctx,
|
|
664
|
+
error: errorBuilder
|
|
665
|
+
});
|
|
666
|
+
if (isThenable(result)) return Promise.resolve(result).then(stages.checkOutput).catch((err) => mapError(err, context.set, ctx));
|
|
667
|
+
return stages.checkOutput(result);
|
|
668
|
+
} catch (err) {
|
|
669
|
+
return mapError(err, context.set, ctx);
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
/** What `bindCompiledApplication`'s handler factories receive. */
|
|
674
|
+
const compilerRuntime = Object.freeze({ bindRoute });
|
|
675
|
+
// src/action.ts
|
|
676
|
+
/**
|
|
677
|
+
* The `error` helpers an action receives: one function per error code that
|
|
678
|
+
* throws an `ActionExecutionError` with that code and status. The standard HTTP
|
|
679
|
+
* codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
|
|
680
|
+
* `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
|
|
681
|
+
* them or replace one.
|
|
682
|
+
*
|
|
683
|
+
* @param errorsDef - The action's `errors`: for each code, its `message` and
|
|
684
|
+
* `status` (default 400).
|
|
685
|
+
* @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
|
|
686
|
+
* and always throw.
|
|
687
|
+
*/
|
|
688
|
+
function buildErrorHelpers(errorsDef) {
|
|
689
|
+
const helpers = {};
|
|
690
|
+
for (const [code, def] of Object.entries({
|
|
691
|
+
...STANDARD_ERRORS,
|
|
692
|
+
...errorsDef
|
|
693
|
+
})) helpers[code] = (overrideMessage, details, options) => {
|
|
694
|
+
throw new ActionExecutionError(code, overrideMessage || def.message, def.status || 400, details, options);
|
|
695
|
+
};
|
|
696
|
+
return helpers;
|
|
697
|
+
}
|
|
698
|
+
/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */
|
|
699
|
+
function errorsOf(action) {
|
|
700
|
+
return action.config.errors ?? {};
|
|
701
|
+
}
|
|
702
|
+
function defineAction(config) {
|
|
703
|
+
const errorHelpers = buildErrorHelpers(config.errors);
|
|
704
|
+
const actionFn = (async (params) => {
|
|
705
|
+
return actionFn.execute(params);
|
|
706
|
+
});
|
|
707
|
+
Object.defineProperty(actionFn, "name", {
|
|
708
|
+
value: config.name,
|
|
709
|
+
configurable: true
|
|
710
|
+
});
|
|
711
|
+
actionFn.config = config;
|
|
712
|
+
actionFn.errorHelpers = errorHelpers;
|
|
713
|
+
actionFn.validateInput = (input) => {
|
|
714
|
+
const errors = actionMeta(actionFn).checkInput?.(input);
|
|
715
|
+
return errors ? {
|
|
716
|
+
success: false,
|
|
717
|
+
errors
|
|
718
|
+
} : validateWithSchema(config.input, input);
|
|
719
|
+
};
|
|
720
|
+
actionFn.validateOutput = (output) => validateWithSchema(actionMeta(actionFn).runtimeOutput ?? config.output, output);
|
|
721
|
+
actionFn.run = async (input, ctx) => {
|
|
722
|
+
return actionFn.execute({
|
|
723
|
+
input,
|
|
724
|
+
ctx
|
|
725
|
+
});
|
|
726
|
+
};
|
|
727
|
+
const stages = {
|
|
728
|
+
name: config.name,
|
|
729
|
+
checkInput: (input) => {
|
|
730
|
+
if (!config.input) return;
|
|
731
|
+
const checked = actionFn.validateInput(input);
|
|
732
|
+
if (!checked.success) throw invalid(config.name, "input", checked.errors);
|
|
733
|
+
},
|
|
734
|
+
authorize: config.authorize,
|
|
735
|
+
execute: config.execute,
|
|
736
|
+
errorBuilder: errorHelpers,
|
|
737
|
+
checkOutput: (result) => {
|
|
738
|
+
if (!(actionMeta(actionFn).runtimeOutput ?? config.output)) return result;
|
|
739
|
+
const checked = actionFn.validateOutput(result);
|
|
740
|
+
if (!checked.success) throw invalid(config.name, "output", checked.errors);
|
|
741
|
+
return result;
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
actionFn.execute = async (params) => {
|
|
745
|
+
const meta = actionMeta(actionFn);
|
|
746
|
+
const ctx = meta.service ? await meta.service.resolveContext(params?.ctx, meta.deps?.values) : {
|
|
747
|
+
...baseContext(params?.ctx ?? {}),
|
|
748
|
+
...params?.ctx
|
|
749
|
+
};
|
|
750
|
+
try {
|
|
751
|
+
return await runStages(stages, params?.input, ctx);
|
|
752
|
+
} catch (err) {
|
|
753
|
+
throw normalizeActionError(err, ctx);
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
return actionFn;
|
|
757
|
+
}
|
|
758
|
+
// src/http.ts
|
|
759
|
+
/** The HTTP methods an action, endpoint or plugin route can use. */
|
|
760
|
+
const HTTP_METHODS = [
|
|
761
|
+
"GET",
|
|
762
|
+
"POST",
|
|
763
|
+
"PUT",
|
|
764
|
+
"PATCH",
|
|
765
|
+
"DELETE"
|
|
766
|
+
];
|
|
767
|
+
// src/service-port.ts
|
|
768
|
+
/** The port of a service: every `Service` is a `ServicePort`. */
|
|
769
|
+
function portOf(service) {
|
|
770
|
+
return service;
|
|
771
|
+
}
|
|
772
|
+
// src/plugin.ts
|
|
773
|
+
/**
|
|
774
|
+
* Define a plugin that installs onto a service with `service.use(plugin)`. Its
|
|
862
775
|
* `setup` receives the service and a `routes` registrar for adding actions and
|
|
863
776
|
* raw HTTP endpoints, and returns the typed API that `service.use` hands back.
|
|
864
777
|
*
|
|
@@ -892,7 +805,7 @@ function defineServicePlugin(definition) {
|
|
|
892
805
|
return Object.freeze({
|
|
893
806
|
...definition,
|
|
894
807
|
routes: copyControls(definition.routes),
|
|
895
|
-
[
|
|
808
|
+
[PLUGIN_KIND]: "service"
|
|
896
809
|
});
|
|
897
810
|
}
|
|
898
811
|
/**
|
|
@@ -911,7 +824,7 @@ function defineResourcePlugin(definition) {
|
|
|
911
824
|
return Object.freeze({
|
|
912
825
|
...definition,
|
|
913
826
|
routes: copyControls(definition.routes),
|
|
914
|
-
[
|
|
827
|
+
[PLUGIN_KIND]: "resource"
|
|
915
828
|
});
|
|
916
829
|
}
|
|
917
830
|
function validateName(name) {
|
|
@@ -930,32 +843,34 @@ function copyControls(controls) {
|
|
|
930
843
|
continue;
|
|
931
844
|
}
|
|
932
845
|
if (value.path !== void 0) validatePath(value.path);
|
|
933
|
-
if (value.scope !== void 0 && !
|
|
934
|
-
"app",
|
|
935
|
-
"service",
|
|
936
|
-
"resource"
|
|
937
|
-
].includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
|
|
846
|
+
if (value.scope !== void 0 && !PLUGIN_ROUTE_SCOPES.includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
|
|
938
847
|
result[name] = Object.freeze({ ...value });
|
|
939
848
|
}
|
|
940
849
|
return Object.freeze(result);
|
|
941
850
|
}
|
|
942
851
|
const states = /* @__PURE__ */ new WeakMap();
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
852
|
+
/** Records the plugin state; the returned function puts all of it back (a failed install's rollback). */
|
|
853
|
+
function snapshotState(state) {
|
|
854
|
+
const copy = (maps) => new Map([...maps].map(([key, inner]) => [key, new Map(inner)]));
|
|
855
|
+
const saved = {
|
|
856
|
+
hosts: copy(state.hosts),
|
|
857
|
+
actions: new Map(state.actions),
|
|
858
|
+
endpoints: [...state.endpoints],
|
|
859
|
+
claims: copy(state.claims)
|
|
860
|
+
};
|
|
861
|
+
return () => {
|
|
862
|
+
for (const action of state.actions.keys()) if (!saved.actions.has(action)) delete actionMeta(action).route;
|
|
863
|
+
Object.assign(state, saved);
|
|
864
|
+
};
|
|
865
|
+
}
|
|
952
866
|
function stateOf(service) {
|
|
953
867
|
let state = states.get(service);
|
|
954
868
|
if (!state) {
|
|
955
869
|
state = {
|
|
956
870
|
hosts: /* @__PURE__ */ new Map(),
|
|
957
871
|
actions: /* @__PURE__ */ new Map(),
|
|
958
|
-
endpoints: []
|
|
872
|
+
endpoints: [],
|
|
873
|
+
claims: /* @__PURE__ */ new Map()
|
|
959
874
|
};
|
|
960
875
|
states.set(service, state);
|
|
961
876
|
}
|
|
@@ -964,32 +879,6 @@ function stateOf(service) {
|
|
|
964
879
|
function isInstallingPlugin(service) {
|
|
965
880
|
return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
|
|
966
881
|
}
|
|
967
|
-
function pathOf(binding, prefix) {
|
|
968
|
-
return joinRoute(binding.scope === "app" ? ownerPath(prefix) : ownerPath(prefix, binding.service.name, binding.scope === "resource" ? binding.resource.name : void 0), binding.path);
|
|
969
|
-
}
|
|
970
|
-
/**
|
|
971
|
-
* Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
|
|
972
|
-
* compiler, and the typed client.
|
|
973
|
-
*
|
|
974
|
-
* @param action - An action.
|
|
975
|
-
* @param prefix - The application's route prefix (default `/api`).
|
|
976
|
-
* @returns `undefined` when no plugin bound the action (it uses its own route),
|
|
977
|
-
* `false` when the plugin's route was switched off, otherwise the route's
|
|
978
|
-
* `path`, `method`, the `clientPath` the typed client uses, and the owning
|
|
979
|
-
* `plugin` and `resource`.
|
|
980
|
-
*/
|
|
981
|
-
function getPluginActionRoute(action, prefix = "/api") {
|
|
982
|
-
const binding = action[actionBindingKey] ?? actionBindings.get(action);
|
|
983
|
-
if (!binding) return void 0;
|
|
984
|
-
if (!binding.enabled) return false;
|
|
985
|
-
return {
|
|
986
|
-
path: pathOf(binding, prefix),
|
|
987
|
-
method: binding.method,
|
|
988
|
-
clientPath: binding.clientPath,
|
|
989
|
-
plugin: binding.plugin,
|
|
990
|
-
resource: binding.resource?.name
|
|
991
|
-
};
|
|
992
|
-
}
|
|
993
882
|
/**
|
|
994
883
|
* The raw HTTP endpoints plugins registered on a service, ready to mount on the
|
|
995
884
|
* application. Each handler resolves the service's context before it runs.
|
|
@@ -999,9 +888,9 @@ function getPluginActionRoute(action, prefix = "/api") {
|
|
|
999
888
|
* @returns The enabled endpoints: `path`, `method`, `handler`, and the
|
|
1000
889
|
* `summary`, `description`, and `tags` for OpenAPI.
|
|
1001
890
|
*/
|
|
1002
|
-
function getPluginEndpoints(service, prefix =
|
|
891
|
+
function getPluginEndpoints(service, prefix = DEFAULT_PREFIX) {
|
|
1003
892
|
return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
|
|
1004
|
-
path:
|
|
893
|
+
path: pluginRoutePath(binding, prefix),
|
|
1005
894
|
method: binding.method,
|
|
1006
895
|
service,
|
|
1007
896
|
plugin: binding.plugin,
|
|
@@ -1014,10 +903,14 @@ function getPluginEndpoints(service, prefix = "/api") {
|
|
|
1014
903
|
})
|
|
1015
904
|
}));
|
|
1016
905
|
}
|
|
906
|
+
/** The plugin that claimed `segment` under `resource`, if one did. */
|
|
907
|
+
function segmentClaimant(service, resource, segment) {
|
|
908
|
+
return states.get(service)?.claims.get(resource)?.get(segment);
|
|
909
|
+
}
|
|
1017
910
|
/** Descriptor identity is scoped to the service or resource installation host. */
|
|
1018
911
|
function installPlugin(service, resource, descriptor) {
|
|
1019
912
|
if (service.isBuilt) throw new Error("Plugins must be installed before service build");
|
|
1020
|
-
if (descriptor[
|
|
913
|
+
if (descriptor[PLUGIN_KIND] !== (resource ? "resource" : "service") && descriptor[PLUGIN_KIND] !== "plugin") throw new Error("Plugin does not support this installation host");
|
|
1021
914
|
const state = stateOf(service);
|
|
1022
915
|
const host = resource ?? service;
|
|
1023
916
|
const existing = state.hosts.get(host)?.get(descriptor.name);
|
|
@@ -1026,17 +919,8 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1026
919
|
if (existing.descriptor !== descriptor) throw new Error(`Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`);
|
|
1027
920
|
return resource ?? existing.api;
|
|
1028
921
|
}
|
|
1029
|
-
const
|
|
1030
|
-
|
|
1031
|
-
tools: new Map(service.tools),
|
|
1032
|
-
tables: new Map(service.tables),
|
|
1033
|
-
resources: new Map(service.resources),
|
|
1034
|
-
preparations: new Map(service.preparations),
|
|
1035
|
-
hosts: new Map([...state.hosts].map(([key, installations]) => [key, new Map(installations)])),
|
|
1036
|
-
bindings: new Map(state.actions),
|
|
1037
|
-
endpoints: [...state.endpoints],
|
|
1038
|
-
properties: new Map([...service.resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]))
|
|
1039
|
-
};
|
|
922
|
+
const restoreService = portOf(service).snapshot();
|
|
923
|
+
const restoreState = snapshotState(state);
|
|
1040
924
|
const installations = state.hosts.get(host) ?? /* @__PURE__ */ new Map();
|
|
1041
925
|
state.hosts.set(host, installations);
|
|
1042
926
|
installations.set(descriptor.name, {
|
|
@@ -1044,34 +928,39 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1044
928
|
status: "installing"
|
|
1045
929
|
});
|
|
1046
930
|
const names = /* @__PURE__ */ new Set();
|
|
931
|
+
const commits = [];
|
|
1047
932
|
const ownedActions = /* @__PURE__ */ new Set();
|
|
1048
933
|
let active = true;
|
|
934
|
+
const claim = (segment) => {
|
|
935
|
+
if (!resource) throw new Error("Only resource plugins claim URL segments");
|
|
936
|
+
const claims = state.claims.get(resource) ?? /* @__PURE__ */ new Map();
|
|
937
|
+
state.claims.set(resource, claims);
|
|
938
|
+
if (claims.has(segment)) return;
|
|
939
|
+
const taken = service.listActions().find((action) => {
|
|
940
|
+
const info = actionMeta(action).resourceAction;
|
|
941
|
+
return info?.resource === resource.name && kebabCase(info.name) === segment;
|
|
942
|
+
});
|
|
943
|
+
if (taken) throw new DuplicateNameError(`Brick: duplicate name "${taken.name}" in service "${service.name}": "${segment}" is a ${descriptor.name} route`);
|
|
944
|
+
claims.set(segment, descriptor.name);
|
|
945
|
+
};
|
|
1049
946
|
const bindingFor = (config) => {
|
|
1050
947
|
if (!active || service.isBuilt) throw new Error("Plugin routes can only be registered during setup");
|
|
1051
948
|
validateName(config.name);
|
|
1052
949
|
validatePath(config.path);
|
|
1053
|
-
if (names.has(config.name)) throw new
|
|
950
|
+
if (names.has(config.name)) throw new DuplicateNameError(`Duplicate plugin route name '${config.name}'`);
|
|
1054
951
|
names.add(config.name);
|
|
1055
952
|
const control = descriptor.routes === false ? false : descriptor.routes?.[config.name];
|
|
1056
953
|
const scope = control && control.scope || config.scope || (resource ? "resource" : "service");
|
|
1057
954
|
if (scope === "resource" && !resource) throw new Error("Service plugin routes cannot use resource scope");
|
|
1058
|
-
if (!
|
|
1059
|
-
|
|
1060
|
-
"service",
|
|
1061
|
-
"resource"
|
|
1062
|
-
].includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
|
|
1063
|
-
if (![
|
|
1064
|
-
"GET",
|
|
1065
|
-
"POST",
|
|
1066
|
-
"PUT",
|
|
1067
|
-
"PATCH",
|
|
1068
|
-
"DELETE"
|
|
1069
|
-
].includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
|
|
955
|
+
if (!PLUGIN_ROUTE_SCOPES.includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
|
|
956
|
+
if (!HTTP_METHODS.includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
|
|
1070
957
|
const path = control && control.path || config.path;
|
|
1071
958
|
validatePath(path);
|
|
959
|
+
const segment = path.split("/")[1];
|
|
960
|
+
if (scope === "resource" && segment && !segment.startsWith(":")) claim(segment);
|
|
1072
961
|
return {
|
|
1073
|
-
service,
|
|
1074
|
-
resource,
|
|
962
|
+
service: service.name,
|
|
963
|
+
resource: resource?.name,
|
|
1075
964
|
plugin: descriptor.name,
|
|
1076
965
|
path,
|
|
1077
966
|
method: config.method,
|
|
@@ -1082,21 +971,22 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1082
971
|
const routes = {
|
|
1083
972
|
action(config) {
|
|
1084
973
|
const binding = bindingFor(config);
|
|
1085
|
-
for (const
|
|
974
|
+
for (const name of pathParamNames(binding.path)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, name)) throw new Error(`Plugin action path parameter '${name}' must be declared in its input schema`);
|
|
1086
975
|
const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
|
|
1087
|
-
if (service.
|
|
1088
|
-
const { scope: _scope, ...actionConfig } = config;
|
|
976
|
+
if (service.getAction(name)) throw new DuplicateNameError(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
|
|
977
|
+
const { scope: _scope, runtimeOutput, checkInput, ...actionConfig } = config;
|
|
1089
978
|
const action = defineAction({
|
|
1090
979
|
...actionConfig,
|
|
1091
980
|
name
|
|
1092
981
|
});
|
|
1093
|
-
action
|
|
1094
|
-
|
|
982
|
+
Object.assign(actionMeta(action), {
|
|
983
|
+
route: binding,
|
|
984
|
+
runtimeOutput,
|
|
985
|
+
checkInput
|
|
986
|
+
});
|
|
1095
987
|
service.action(action);
|
|
1096
988
|
ownedActions.add(action);
|
|
1097
989
|
state.actions.set(action, binding);
|
|
1098
|
-
actionBindings.set(action, binding);
|
|
1099
|
-
action[actionBindingKey] = binding;
|
|
1100
990
|
return action;
|
|
1101
991
|
},
|
|
1102
992
|
endpoint(config) {
|
|
@@ -1108,17 +998,17 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1108
998
|
description: config.description,
|
|
1109
999
|
tags: config.tags
|
|
1110
1000
|
});
|
|
1111
|
-
}
|
|
1001
|
+
},
|
|
1002
|
+
claim
|
|
1112
1003
|
};
|
|
1113
1004
|
try {
|
|
1114
|
-
const
|
|
1005
|
+
const context = {
|
|
1115
1006
|
service,
|
|
1116
|
-
resource,
|
|
1117
|
-
routes
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
});
|
|
1007
|
+
...resource ? { resource } : {},
|
|
1008
|
+
routes,
|
|
1009
|
+
[PLUGIN_COMMIT]: (commit) => commits.push(commit)
|
|
1010
|
+
};
|
|
1011
|
+
const api = resource ? descriptor.setup(context) : descriptor.setup(context);
|
|
1122
1012
|
if (api && typeof api === "object" && "then" in api) throw new Error("Plugin setup must be synchronous");
|
|
1123
1013
|
if (descriptor.routes && Object.keys(descriptor.routes).some((name) => !names.has(name))) throw new Error(`Plugin '${descriptor.name}' has an override for an unknown route`);
|
|
1124
1014
|
const walk = (value, path, ancestors) => {
|
|
@@ -1152,36 +1042,16 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1152
1042
|
status: "installed",
|
|
1153
1043
|
api
|
|
1154
1044
|
});
|
|
1155
|
-
|
|
1156
|
-
getGlobalRegistry().touch();
|
|
1045
|
+
for (const commit of commits) commit();
|
|
1157
1046
|
return resource ?? api;
|
|
1158
1047
|
} catch (error) {
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
actionBindings.delete(action);
|
|
1162
|
-
delete action[actionBindingKey];
|
|
1163
|
-
}
|
|
1164
|
-
restoreMap(service.actions, snapshots.actions);
|
|
1165
|
-
restoreMap(service.tools, snapshots.tools);
|
|
1166
|
-
restoreMap(service.tables, snapshots.tables);
|
|
1167
|
-
restoreMap(service.resources, snapshots.resources);
|
|
1168
|
-
restoreMap(service.preparations, snapshots.preparations);
|
|
1169
|
-
state.hosts = snapshots.hosts;
|
|
1170
|
-
state.actions = snapshots.bindings;
|
|
1171
|
-
state.endpoints = snapshots.endpoints;
|
|
1172
|
-
for (const [item, properties] of snapshots.properties) {
|
|
1173
|
-
for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);
|
|
1174
|
-
Object.defineProperties(item, properties);
|
|
1175
|
-
}
|
|
1176
|
-
getGlobalRegistry().touch();
|
|
1048
|
+
restoreService();
|
|
1049
|
+
restoreState();
|
|
1177
1050
|
throw error;
|
|
1178
1051
|
} finally {
|
|
1179
1052
|
active = false;
|
|
1180
1053
|
}
|
|
1181
1054
|
}
|
|
1182
|
-
function finish(descriptor, installed) {
|
|
1183
|
-
descriptor[pluginFinish]?.(installed);
|
|
1184
|
-
}
|
|
1185
1055
|
/** Whether a plugin named `name` is installed on `host` (the service or a resource). */
|
|
1186
1056
|
function hasPlugin(service, host, name) {
|
|
1187
1057
|
return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
|
|
@@ -1190,10 +1060,6 @@ function hasPlugin(service, host, name) {
|
|
|
1190
1060
|
function installedPlugins(service) {
|
|
1191
1061
|
return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
|
|
1192
1062
|
}
|
|
1193
|
-
function restoreMap(target, snapshot) {
|
|
1194
|
-
target.clear();
|
|
1195
|
-
for (const [key, value] of snapshot) target.set(key, value);
|
|
1196
|
-
}
|
|
1197
1063
|
// src/deps.ts
|
|
1198
1064
|
/**
|
|
1199
1065
|
* Declare a dependency a service needs, without creating it. The app provides
|
|
@@ -1215,7 +1081,7 @@ function restoreMap(target, snapshot) {
|
|
|
1215
1081
|
function port() {
|
|
1216
1082
|
return Object.freeze({});
|
|
1217
1083
|
}
|
|
1218
|
-
/** Where a
|
|
1084
|
+
/** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */
|
|
1219
1085
|
const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
|
|
1220
1086
|
const running = new AsyncLocalStorage();
|
|
1221
1087
|
/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
|
|
@@ -1243,378 +1109,12 @@ function bindDeps(services, provided = {}) {
|
|
|
1243
1109
|
declared.add(name);
|
|
1244
1110
|
own[name] = provided[name];
|
|
1245
1111
|
}
|
|
1246
|
-
service.setDeps
|
|
1112
|
+
portOf(service).setDeps(Object.freeze(own));
|
|
1247
1113
|
}
|
|
1248
1114
|
for (const name of Object.keys(provided)) if (!declared.has(name)) throw new Error(`Brick: brick({ deps }) provides "${name}", but no service declares it (services: ${services.map((service) => service.name).join(", ") || "none"})`);
|
|
1249
1115
|
}
|
|
1250
|
-
// src/
|
|
1251
|
-
let runningVersion;
|
|
1252
|
-
/** The version of this @brickkit/core, read from its package.json; `""` when unknown. */
|
|
1253
|
-
function brickVersion() {
|
|
1254
|
-
if (runningVersion !== void 0) return runningVersion;
|
|
1255
|
-
for (const relative of ["../package.json", "../../package.json"]) try {
|
|
1256
|
-
const json = JSON.parse(readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8"));
|
|
1257
|
-
if (json.name === "@brickkit/core") return runningVersion = json.version;
|
|
1258
|
-
} catch {}
|
|
1259
|
-
return runningVersion = "";
|
|
1260
|
-
}
|
|
1261
|
-
function parseVersion(version) {
|
|
1262
|
-
const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[-+]/)[0].split(".").map(Number);
|
|
1263
|
-
return [
|
|
1264
|
-
major,
|
|
1265
|
-
minor,
|
|
1266
|
-
patch
|
|
1267
|
-
];
|
|
1268
|
-
}
|
|
1269
|
-
function compare(a, b) {
|
|
1270
|
-
return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
|
|
1271
|
-
}
|
|
1272
|
-
/**
|
|
1273
|
-
* Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,
|
|
1274
|
-
* `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.
|
|
1275
|
-
*/
|
|
1276
|
-
function satisfiesRange(version, range) {
|
|
1277
|
-
const current = parseVersion(version);
|
|
1278
|
-
return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
|
|
1279
|
-
const match = /^(\^|~|>=|<=|>|<|=)?v?([\dx*]+(?:\.[\dx*]+){0,2})?/i.exec(comparator);
|
|
1280
|
-
const operator = match?.[1] ?? "";
|
|
1281
|
-
const parts = (match?.[2] ?? "*").split(".");
|
|
1282
|
-
const wild = parts.findIndex((part) => /^[x*]$/i.test(part));
|
|
1283
|
-
const given = wild === -1 ? parts.length : wild;
|
|
1284
|
-
const low = parseVersion(parts.slice(0, given).join(".") || "0");
|
|
1285
|
-
if (given === 0) return true;
|
|
1286
|
-
const cmp = compare(current, low);
|
|
1287
|
-
if (operator === ">=") return cmp >= 0;
|
|
1288
|
-
if (operator === ">") return cmp > 0;
|
|
1289
|
-
if (operator === "<") return cmp < 0;
|
|
1290
|
-
if (operator === "<=") return cmp <= 0;
|
|
1291
|
-
let high;
|
|
1292
|
-
if (operator === "^") high = low[0] > 0 || given === 1 ? [
|
|
1293
|
-
low[0] + 1,
|
|
1294
|
-
0,
|
|
1295
|
-
0
|
|
1296
|
-
] : low[1] > 0 || given === 2 ? [
|
|
1297
|
-
0,
|
|
1298
|
-
low[1] + 1,
|
|
1299
|
-
0
|
|
1300
|
-
] : [
|
|
1301
|
-
0,
|
|
1302
|
-
0,
|
|
1303
|
-
low[2] + 1
|
|
1304
|
-
];
|
|
1305
|
-
else if (operator === "~" || given < 3) high = given === 1 ? [
|
|
1306
|
-
low[0] + 1,
|
|
1307
|
-
0,
|
|
1308
|
-
0
|
|
1309
|
-
] : [
|
|
1310
|
-
low[0],
|
|
1311
|
-
low[1] + 1,
|
|
1312
|
-
0
|
|
1313
|
-
];
|
|
1314
|
-
else return cmp === 0;
|
|
1315
|
-
return cmp >= 0 && compare(current, high) < 0;
|
|
1316
|
-
}));
|
|
1317
|
-
}
|
|
1318
|
-
const OWNER = Symbol.for("brickkit.plugin.owner");
|
|
1319
|
-
/** The plugin that owns a table, for tables a `definePlugin` contributed. */
|
|
1320
|
-
function pluginOwner(table) {
|
|
1321
|
-
return table && typeof table === "object" ? table[OWNER] : void 0;
|
|
1322
|
-
}
|
|
1323
|
-
const sqliteBuilders = {
|
|
1324
|
-
/** A table. Its name gets the plugin's prefix (`page_comments`). */
|
|
1325
|
-
table: (name, columns) => sqliteTable(name, columns),
|
|
1326
|
-
text: (name) => text(name),
|
|
1327
|
-
integer: (name) => integer(name, { mode: "number" }),
|
|
1328
|
-
real: (name) => real(name),
|
|
1329
|
-
boolean: (name) => integer(name, { mode: "boolean" }),
|
|
1330
|
-
/** A `Date`, stored as epoch milliseconds or `timestamptz`. */
|
|
1331
|
-
timestamp: (name) => integer(name, { mode: "timestamp_ms" }),
|
|
1332
|
-
json: (name) => text(name, { mode: "json" })
|
|
1333
|
-
};
|
|
1334
|
-
function builders(engine, tableName) {
|
|
1335
|
-
if (engine === "postgres") return {
|
|
1336
|
-
engine,
|
|
1337
|
-
table: (name, columns) => pgTable(tableName(name), columns),
|
|
1338
|
-
text: (name) => text$1(name),
|
|
1339
|
-
integer: (name) => integer$1(name),
|
|
1340
|
-
real: (name) => doublePrecision(name),
|
|
1341
|
-
boolean: (name) => boolean(name),
|
|
1342
|
-
timestamp: (name) => timestamp(name, {
|
|
1343
|
-
mode: "date",
|
|
1344
|
-
withTimezone: true
|
|
1345
|
-
}),
|
|
1346
|
-
json: (name) => jsonb(name)
|
|
1347
|
-
};
|
|
1348
|
-
return {
|
|
1349
|
-
...sqliteBuilders,
|
|
1350
|
-
engine,
|
|
1351
|
-
table: (name, columns) => sqliteTable(tableName(name), columns)
|
|
1352
|
-
};
|
|
1353
|
-
}
|
|
1354
|
-
/** Where `hooks.*` stores a plugin's hooks; `@brickkit/crud` runs them. */
|
|
1355
|
-
const HOST_HOOKS = Symbol.for("brickkit.plugin.hooks");
|
|
1356
|
-
const HOOK_NAMES = [
|
|
1357
|
-
"beforeCreate",
|
|
1358
|
-
"afterCreate",
|
|
1359
|
-
"beforeUpdate",
|
|
1360
|
-
"afterUpdate",
|
|
1361
|
-
"beforeDelete",
|
|
1362
|
-
"afterDelete",
|
|
1363
|
-
"afterCommit"
|
|
1364
|
-
];
|
|
1116
|
+
// src/plugin-app.ts
|
|
1365
1117
|
const INTERNALS = Symbol.for("brickkit.plugin.internals");
|
|
1366
|
-
let installCount = 0;
|
|
1367
|
-
const toWords = (name) => (name.split("/").pop() ?? name).replace(/^brick-/, "").replace(/-plugin$/, "").split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
1368
|
-
const snake = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
1369
|
-
/**
|
|
1370
|
-
* Define a plugin: a manifest Brick checks, plus the capabilities the plugin
|
|
1371
|
-
* brings. Install its instances with `resource.use()`, `service.use()` or
|
|
1372
|
-
* `brick({ plugins })`; scope comes from where it is installed.
|
|
1373
|
-
*
|
|
1374
|
-
* @param manifest - `name`, `brick` (semver range), `requires`, `options`
|
|
1375
|
-
* (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
|
|
1376
|
-
* parts, and a `dashboard` extension.
|
|
1377
|
-
* @returns A factory: `comments({ maxLength: 500 })` validates the options and
|
|
1378
|
-
* the Brick version and returns an instance to install.
|
|
1379
|
-
* @throws From the factory, when the running Brick is outside `brick` or an
|
|
1380
|
-
* option is invalid; when installed, when a required plugin is missing or the
|
|
1381
|
-
* host does not suit the plugin.
|
|
1382
|
-
* @example
|
|
1383
|
-
* export const audit = definePlugin({
|
|
1384
|
-
* name: "@acme/brick-audit",
|
|
1385
|
-
* brick: "^0.11.0",
|
|
1386
|
-
* requires: ["@brickkit/crud"],
|
|
1387
|
-
* options: t.Object({ table: t.String({ default: "audit" }) }),
|
|
1388
|
-
* tables: ({ table, text, timestamp }) => ({
|
|
1389
|
-
* log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
|
|
1390
|
-
* }),
|
|
1391
|
-
* resource: ({ tables, hooks }) => {
|
|
1392
|
-
* hooks.afterCreate(({ row, tx }) =>
|
|
1393
|
-
* tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
|
|
1394
|
-
* return {};
|
|
1395
|
-
* },
|
|
1396
|
-
* });
|
|
1397
|
-
*
|
|
1398
|
-
* page.use(audit());
|
|
1399
|
-
*/
|
|
1400
|
-
function definePlugin(manifest) {
|
|
1401
|
-
const { name } = manifest;
|
|
1402
|
-
if (!name || name.trim() !== name) throw new Error("Plugin names must be nonempty and have no surrounding whitespace");
|
|
1403
|
-
if (!manifest.resource && !manifest.service && !manifest.app) throw new Error(`Plugin "${name}" needs a resource, service or app part to install`);
|
|
1404
|
-
for (const key of Object.keys(manifest.events ?? {})) if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key)) throw new Error(`Event "${key}" of plugin "${name}" must be a plain name such as added`);
|
|
1405
|
-
const site = definitionSite()?.replace(/:\d+$/, "");
|
|
1406
|
-
const dashboard = manifest.dashboard === void 0 ? void 0 : manifest.dashboard.startsWith("file:") ? fileURLToPath(manifest.dashboard) : isAbsolute(manifest.dashboard) || !site ? resolve(manifest.dashboard) : resolve(dirname(site), manifest.dashboard);
|
|
1407
|
-
const info = Object.freeze({
|
|
1408
|
-
name,
|
|
1409
|
-
description: manifest.description,
|
|
1410
|
-
brick: manifest.brick,
|
|
1411
|
-
requires: Object.freeze([...manifest.requires ?? []]),
|
|
1412
|
-
options: manifest.options,
|
|
1413
|
-
secrets: Object.freeze(Object.values(manifest.secrets ?? {}).map((secret) => secret.name)),
|
|
1414
|
-
deps: Object.freeze(Object.keys(manifest.deps ?? {})),
|
|
1415
|
-
capabilities: Object.freeze([
|
|
1416
|
-
"tables",
|
|
1417
|
-
"events",
|
|
1418
|
-
"resource",
|
|
1419
|
-
"service",
|
|
1420
|
-
"app",
|
|
1421
|
-
"dashboard"
|
|
1422
|
-
].filter((key) => manifest[key] !== void 0))
|
|
1423
|
-
});
|
|
1424
|
-
const words = toWords(name);
|
|
1425
|
-
const eventSpace = words.map((word, index) => index ? word[0].toUpperCase() + word.slice(1) : word).join("");
|
|
1426
|
-
const tableSpace = snake(words.join("_"));
|
|
1427
|
-
if (!eventSpace) throw new Error(`Plugin "${name}" needs letters or digits in its name`);
|
|
1428
|
-
const factory = (input = {}, install = {}) => {
|
|
1429
|
-
const version = brickVersion();
|
|
1430
|
-
if (manifest.brick && version && !satisfiesRange(version, manifest.brick)) throw new Error(`${name} supports Brick ${manifest.brick}; this app runs ${version}`);
|
|
1431
|
-
const options = checkOptions(name, manifest.options, input);
|
|
1432
|
-
const deps = checkDeps(name, eventSpace, manifest.deps, install.deps);
|
|
1433
|
-
const secrets = manifest.secrets ?? {};
|
|
1434
|
-
const internals = {
|
|
1435
|
-
manifest,
|
|
1436
|
-
options,
|
|
1437
|
-
deps,
|
|
1438
|
-
install,
|
|
1439
|
-
dashboard,
|
|
1440
|
-
installs: []
|
|
1441
|
-
};
|
|
1442
|
-
const pending = [];
|
|
1443
|
-
const setup = (context) => {
|
|
1444
|
-
const { service, resource } = context;
|
|
1445
|
-
const host = resource ?? service;
|
|
1446
|
-
const where = resource ? `resource "${resource.name}"` : `service "${service.name}"`;
|
|
1447
|
-
const part = resource ? manifest.resource : manifest.service;
|
|
1448
|
-
if (!part) throw new Error(`${name} cannot be installed on a ${resource ? "resource" : "service"}; ${manifest.resource ? "use resource.use()" : manifest.service ? "use service.use()" : "add it to brick({ plugins })"}`);
|
|
1449
|
-
for (const required of manifest.requires ?? []) if (!hasPlugin(service, host, required)) throw new Error(`${name} requires ${required}, installed on ${where} before it`);
|
|
1450
|
-
let tables = {};
|
|
1451
|
-
if (manifest.tables) {
|
|
1452
|
-
const database = service.getDatabaseHandle?.();
|
|
1453
|
-
if (!database) throw new Error(`${name} owns tables, so service "${service.name}" needs a database`);
|
|
1454
|
-
const prefix = install.prefix ?? `${snake(resource?.name ?? service.name)}_`;
|
|
1455
|
-
tables = manifest.tables(builders(database.engine, (table) => install.prefix !== void 0 || table === tableSpace ? `${prefix}${table}` : `${prefix}${tableSpace}_${table}`));
|
|
1456
|
-
const taken = new Set([...service.tables.values(), ...Object.values(database.tables)].map((table) => getTableName(table)));
|
|
1457
|
-
for (const table of Object.values(tables)) {
|
|
1458
|
-
const tableName = getTableName(table);
|
|
1459
|
-
if (taken.has(tableName)) throw new Error(`${name} table "${tableName}" clashes with a table service "${service.name}" already has; install it with another prefix`);
|
|
1460
|
-
taken.add(tableName);
|
|
1461
|
-
Object.defineProperty(table, OWNER, { value: name });
|
|
1462
|
-
service.registerTable(table);
|
|
1463
|
-
}
|
|
1464
|
-
}
|
|
1465
|
-
const catalog = service.events;
|
|
1466
|
-
const events = {};
|
|
1467
|
-
for (const [key, schema] of Object.entries(manifest.events ?? {})) {
|
|
1468
|
-
const existing = catalog[`${eventSpace}.${key}`];
|
|
1469
|
-
if (existing && existing.plugin !== name) throw new Error(`${name} event "${eventSpace}.${key}" is already in the catalog of service "${service.name}"`);
|
|
1470
|
-
events[key] = existing ?? Object.freeze({
|
|
1471
|
-
name: `${service.name}.${eventSpace}.${key}`,
|
|
1472
|
-
service: service.name,
|
|
1473
|
-
schema,
|
|
1474
|
-
plugin: name
|
|
1475
|
-
});
|
|
1476
|
-
}
|
|
1477
|
-
const added = {};
|
|
1478
|
-
const hooks = Object.fromEntries(HOOK_NAMES.map((hook) => [hook, (fn) => {
|
|
1479
|
-
if (typeof fn !== "function") throw new Error(`${name}: hooks.${hook} needs a function`);
|
|
1480
|
-
(added[hook] ??= []).push((args) => fn({
|
|
1481
|
-
...args,
|
|
1482
|
-
ctx: {
|
|
1483
|
-
...args.ctx,
|
|
1484
|
-
deps
|
|
1485
|
-
}
|
|
1486
|
-
}));
|
|
1487
|
-
}]));
|
|
1488
|
-
const routes = {
|
|
1489
|
-
action: (config) => context.routes.action(config),
|
|
1490
|
-
endpoint: (config) => context.routes.endpoint({
|
|
1491
|
-
...config,
|
|
1492
|
-
handler: (args) => config.handler({
|
|
1493
|
-
...args,
|
|
1494
|
-
ctx: {
|
|
1495
|
-
...args.ctx,
|
|
1496
|
-
deps
|
|
1497
|
-
}
|
|
1498
|
-
})
|
|
1499
|
-
})
|
|
1500
|
-
};
|
|
1501
|
-
const before = /* @__PURE__ */ new Set([
|
|
1502
|
-
...service.actions.values(),
|
|
1503
|
-
...service.tools.values(),
|
|
1504
|
-
...service.listSockets()
|
|
1505
|
-
]);
|
|
1506
|
-
const started = bindings;
|
|
1507
|
-
const api = part({
|
|
1508
|
-
options,
|
|
1509
|
-
secrets,
|
|
1510
|
-
tables,
|
|
1511
|
-
events,
|
|
1512
|
-
deps,
|
|
1513
|
-
service,
|
|
1514
|
-
resource,
|
|
1515
|
-
routes,
|
|
1516
|
-
hooks
|
|
1517
|
-
});
|
|
1518
|
-
if (api && typeof api.then === "function") throw new Error("Plugin setup must be synchronous");
|
|
1519
|
-
for (const action of [...service.actions.values(), ...service.tools.values()]) if (!before.has(action)) bindPluginDeps(name, action, deps, started);
|
|
1520
|
-
for (const socket of service.listSockets()) if (!before.has(socket)) socket[PLUGIN_DEPS] ??= deps;
|
|
1521
|
-
pending.push(() => {
|
|
1522
|
-
const database = service.getDatabaseHandle?.();
|
|
1523
|
-
for (const table of Object.values(tables)) database?.addTable?.(getTableName(table), table);
|
|
1524
|
-
if (Object.keys(events).length) service.events = Object.freeze({
|
|
1525
|
-
...catalog,
|
|
1526
|
-
...Object.fromEntries(Object.entries(events).map(([key, ref]) => [`${eventSpace}.${key}`, ref]))
|
|
1527
|
-
});
|
|
1528
|
-
const store = host[HOST_HOOKS] ??= {};
|
|
1529
|
-
for (const [hook, fns] of Object.entries(added)) (store[hook] ??= []).push(...fns);
|
|
1530
|
-
internals.installs.push({
|
|
1531
|
-
scope: resource ? "resource" : "service",
|
|
1532
|
-
service: service.name,
|
|
1533
|
-
resource: resource?.name
|
|
1534
|
-
});
|
|
1535
|
-
internals.order ??= ++installCount;
|
|
1536
|
-
});
|
|
1537
|
-
return resource ? api ?? {} : api;
|
|
1538
|
-
};
|
|
1539
|
-
return Object.freeze({
|
|
1540
|
-
[Symbol.for("brickkit.plugin.kind")]: "plugin",
|
|
1541
|
-
name,
|
|
1542
|
-
info,
|
|
1543
|
-
setup,
|
|
1544
|
-
[INTERNALS]: internals,
|
|
1545
|
-
[pluginFinish]: (installed) => {
|
|
1546
|
-
const commit = pending.pop();
|
|
1547
|
-
if (installed) commit?.();
|
|
1548
|
-
}
|
|
1549
|
-
});
|
|
1550
|
-
};
|
|
1551
|
-
return Object.assign(factory, { info });
|
|
1552
|
-
}
|
|
1553
|
-
/** Counts bindings, so a setup can tell a nested install's from an earlier one's. */
|
|
1554
|
-
let bindings = 0;
|
|
1555
|
-
/**
|
|
1556
|
-
* Give an action's `execute` and `authorize` the plugin's deps as `ctx.deps`.
|
|
1557
|
-
* The config is changed in place: every way an action runs (HTTP, compiled
|
|
1558
|
-
* routes, `action.run`, RPC) reads `config.execute` from it. A nested
|
|
1559
|
-
* definePlugin binds its own actions first, so they keep its deps.
|
|
1560
|
-
*
|
|
1561
|
-
* @throws When the action is already bound to another install's deps: one
|
|
1562
|
-
* action object shared by two installs could only run with one of them.
|
|
1563
|
-
*/
|
|
1564
|
-
function bindPluginDeps(plugin, action, deps, started) {
|
|
1565
|
-
const config = action.config;
|
|
1566
|
-
if (!config) return;
|
|
1567
|
-
const bound = config[PLUGIN_DEPS];
|
|
1568
|
-
if (bound) {
|
|
1569
|
-
if (bound.deps === deps || bound.at > started) return;
|
|
1570
|
-
throw new Error(`${plugin}: action "${action.name}" is already bound to the deps of another install; create the action inside the setup so each install gets its own`);
|
|
1571
|
-
}
|
|
1572
|
-
config[PLUGIN_DEPS] = {
|
|
1573
|
-
deps,
|
|
1574
|
-
at: ++bindings
|
|
1575
|
-
};
|
|
1576
|
-
const { execute, authorize } = config;
|
|
1577
|
-
if (typeof execute === "function") config.execute = (args) => execute({
|
|
1578
|
-
...args,
|
|
1579
|
-
ctx: {
|
|
1580
|
-
...args.ctx,
|
|
1581
|
-
deps
|
|
1582
|
-
}
|
|
1583
|
-
});
|
|
1584
|
-
if (typeof authorize === "function") config.authorize = (args) => authorize({
|
|
1585
|
-
...args,
|
|
1586
|
-
ctx: {
|
|
1587
|
-
...args.ctx,
|
|
1588
|
-
deps
|
|
1589
|
-
}
|
|
1590
|
-
});
|
|
1591
|
-
}
|
|
1592
|
-
/** Check the deps passed at install against the ports the plugin declares. */
|
|
1593
|
-
function checkDeps(plugin, factory, ports, given = {}) {
|
|
1594
|
-
if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${plugin}: deps must be an object`);
|
|
1595
|
-
const declared = Object.keys(ports ?? {});
|
|
1596
|
-
const provided = given;
|
|
1597
|
-
const extra = Object.keys(provided).filter((key) => !declared.includes(key));
|
|
1598
|
-
if (extra.length) throw new Error(`${plugin} does not declare ${extra.map((key) => `deps.${key}`).join(", ")}; ${declared.length ? `it takes ${declared.join(", ")}` : "it takes no deps"}`);
|
|
1599
|
-
const missing = declared.filter((key) => provided[key] === void 0);
|
|
1600
|
-
if (missing.length) throw new Error(`${plugin} needs ${missing.map((key) => `deps.${key}`).join(", ")}; pass it when installing: ${factory}(options, { deps: { ${missing.join(", ")} } })`);
|
|
1601
|
-
return Object.freeze(Object.fromEntries(declared.map((key) => [key, provided[key]])));
|
|
1602
|
-
}
|
|
1603
|
-
function checkOptions(plugin, schema, input) {
|
|
1604
|
-
if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error(`${plugin}: options must be an object`);
|
|
1605
|
-
if (!schema) {
|
|
1606
|
-
if (Object.keys(input).length) throw new Error(`${plugin} takes no options`);
|
|
1607
|
-
return {};
|
|
1608
|
-
}
|
|
1609
|
-
const value = Value.Default(schema, structuredClone(input));
|
|
1610
|
-
const result = validateWithSchema(schema, value);
|
|
1611
|
-
if (!result.success) {
|
|
1612
|
-
const [first] = result.errors;
|
|
1613
|
-
const option = first.path.replace(/^\//, "").replaceAll("/", ".");
|
|
1614
|
-
throw new Error(`${plugin}: option ${option ? `"${option}"` : ""} ${first.message}`.replace(/\s+/g, " "));
|
|
1615
|
-
}
|
|
1616
|
-
return value;
|
|
1617
|
-
}
|
|
1618
1118
|
function isPluginInstance(value) {
|
|
1619
1119
|
return typeof value === "object" && value !== null && INTERNALS in value;
|
|
1620
1120
|
}
|
|
@@ -1676,17 +1176,10 @@ function setupAppPlugins(installedOnServices, appPlugins) {
|
|
|
1676
1176
|
middleware.push(handler);
|
|
1677
1177
|
},
|
|
1678
1178
|
listeners(...items) {
|
|
1679
|
-
listeners.push(...items.map((listener) => {
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
[PLUGIN_DEPS]: deps
|
|
1684
|
-
};
|
|
1685
|
-
return {
|
|
1686
|
-
...listener,
|
|
1687
|
-
run: (delivery) => runWithDeps(deps, () => run(delivery))
|
|
1688
|
-
};
|
|
1689
|
-
}));
|
|
1179
|
+
listeners.push(...items.map((listener) => ({
|
|
1180
|
+
...listener,
|
|
1181
|
+
[PLUGIN_DEPS]: deps
|
|
1182
|
+
})));
|
|
1690
1183
|
}
|
|
1691
1184
|
});
|
|
1692
1185
|
lifecycles.push({
|
|
@@ -1744,295 +1237,171 @@ function pluginLifecycle(lifecycles) {
|
|
|
1744
1237
|
}
|
|
1745
1238
|
};
|
|
1746
1239
|
}
|
|
1747
|
-
// src/
|
|
1748
|
-
const
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
const
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
}
|
|
1764
|
-
const MAX_INPUT_DEPTH = 128;
|
|
1765
|
-
function inputTooDeep(value) {
|
|
1766
|
-
if (!value || typeof value !== "object") return false;
|
|
1767
|
-
const stack = [{
|
|
1768
|
-
node: value,
|
|
1769
|
-
depth: 0
|
|
1770
|
-
}];
|
|
1771
|
-
while (stack.length > 0) {
|
|
1772
|
-
const { node, depth } = stack.pop();
|
|
1773
|
-
if (depth > MAX_INPUT_DEPTH) return true;
|
|
1774
|
-
if (node && typeof node === "object") {
|
|
1775
|
-
const children = Array.isArray(node) ? node : Object.values(node);
|
|
1776
|
-
for (const child of children) if (child && typeof child === "object") stack.push({
|
|
1777
|
-
node: child,
|
|
1778
|
-
depth: depth + 1
|
|
1779
|
-
});
|
|
1780
|
-
}
|
|
1240
|
+
// src/definition-site.ts
|
|
1241
|
+
const brickRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
1242
|
+
/**
|
|
1243
|
+
* The first `file:line` outside Brick on the current stack: where a name is
|
|
1244
|
+
* being defined. Best-effort: `undefined` when there is no stack.
|
|
1245
|
+
*/
|
|
1246
|
+
function definitionSite() {
|
|
1247
|
+
const limit = Error.stackTraceLimit;
|
|
1248
|
+
Error.stackTraceLimit = 50;
|
|
1249
|
+
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
1250
|
+
Error.stackTraceLimit = limit;
|
|
1251
|
+
for (const line of stack?.split("\n").slice(1) ?? []) {
|
|
1252
|
+
const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
|
|
1253
|
+
if (!match) continue;
|
|
1254
|
+
const [, file, row] = match;
|
|
1255
|
+
if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
|
|
1256
|
+
return `${file}:${row}`;
|
|
1781
1257
|
}
|
|
1782
|
-
return false;
|
|
1783
1258
|
}
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1259
|
+
/**
|
|
1260
|
+
* Records where `name` is defined. The same file defining it again (a dev
|
|
1261
|
+
* reload) replaces the old definition.
|
|
1262
|
+
*
|
|
1263
|
+
* @throws When a different file already defined `name`.
|
|
1264
|
+
*/
|
|
1265
|
+
function claimName(sites, label, name, site) {
|
|
1266
|
+
const file = (at) => at?.replace(/:\d+$/, "");
|
|
1267
|
+
if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new DuplicateNameError(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
|
|
1268
|
+
sites.set(name, site);
|
|
1790
1269
|
}
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
|
|
1270
|
+
// src/compiler/ir.ts
|
|
1271
|
+
function freezeIR(value) {
|
|
1272
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
1273
|
+
for (const child of Object.values(value)) freezeIR(child);
|
|
1274
|
+
Object.freeze(value);
|
|
1275
|
+
}
|
|
1276
|
+
return value;
|
|
1799
1277
|
}
|
|
1800
|
-
function
|
|
1801
|
-
|
|
1802
|
-
set.status = response.status;
|
|
1803
|
-
return response;
|
|
1278
|
+
function schemaSnapshot(schema) {
|
|
1279
|
+
return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
|
|
1804
1280
|
}
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
nextSequence: () => (++sequence).toString(36),
|
|
1809
|
-
mergeInput,
|
|
1810
|
-
checkDepth,
|
|
1811
|
-
validate,
|
|
1812
|
-
mapError,
|
|
1813
|
-
isThenable: (value) => value != null && typeof value.then === "function",
|
|
1814
|
-
deny: (action, user) => {
|
|
1815
|
-
throw new ActionExecutionError(user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${action}'`, user == null ? 401 : 403);
|
|
1816
|
-
}
|
|
1817
|
-
});
|
|
1818
|
-
// src/action-handler.ts
|
|
1819
|
-
let _srvSeq = 0;
|
|
1820
|
-
const EMPTY_SERVICES = Object.freeze({});
|
|
1821
|
-
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
1822
|
-
function isNonEmpty(obj) {
|
|
1823
|
-
if (obj == null) return false;
|
|
1824
|
-
for (const _ in obj) return true;
|
|
1825
|
-
return false;
|
|
1281
|
+
function analyzeApplication(services, prefix = DEFAULT_PREFIX) {
|
|
1282
|
+
for (const service of services) service.build();
|
|
1283
|
+
return analyzeDeclaredApplication(services, prefix);
|
|
1826
1284
|
}
|
|
1827
|
-
/**
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
isNumber: false,
|
|
1867
|
-
isBoolean: false,
|
|
1868
|
-
isArray: true
|
|
1869
|
-
});
|
|
1285
|
+
/** Inspect current declarations without closing service/plugin setup. */
|
|
1286
|
+
function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
|
|
1287
|
+
if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
|
|
1288
|
+
const names = /* @__PURE__ */ new Set();
|
|
1289
|
+
for (const service of services) {
|
|
1290
|
+
if (names.has(service.name)) throw new DuplicateNameError(`Brick compiler: duplicate service '${service.name}'`);
|
|
1291
|
+
names.add(service.name);
|
|
1292
|
+
}
|
|
1293
|
+
const routes = [];
|
|
1294
|
+
const bindings = [];
|
|
1295
|
+
const registered = /* @__PURE__ */ new Map();
|
|
1296
|
+
const diagnostics = [];
|
|
1297
|
+
const add = (service, action, method, path) => {
|
|
1298
|
+
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
1299
|
+
const route = describeRoute(service, action, method, path);
|
|
1300
|
+
const key = routeKey(method, path);
|
|
1301
|
+
const previous = registered.get(key);
|
|
1302
|
+
if (previous) {
|
|
1303
|
+
if (route.plugin || previous.plugin) throw new DuplicateNameError(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
1304
|
+
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
1308
|
+
registered.set(key, {
|
|
1309
|
+
name: `${service.name}.${action.name}`,
|
|
1310
|
+
plugin: Boolean(route.plugin)
|
|
1311
|
+
});
|
|
1312
|
+
routes.push(route);
|
|
1313
|
+
bindings.push({
|
|
1314
|
+
service,
|
|
1315
|
+
action
|
|
1316
|
+
});
|
|
1317
|
+
};
|
|
1318
|
+
for (const service of services) {
|
|
1319
|
+
checkSegments(service);
|
|
1320
|
+
for (const action of service.listActions()) {
|
|
1321
|
+
const route = getActionRoute(action, prefix);
|
|
1322
|
+
if (route === false) continue;
|
|
1323
|
+
add(service, action, route.method, route.path);
|
|
1870
1324
|
}
|
|
1871
|
-
if (list.length > 0) coercions = list;
|
|
1872
1325
|
}
|
|
1873
|
-
const
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1326
|
+
const preparations = services.flatMap((service) => portOf(service).listPreparations().map((contribution) => ({
|
|
1327
|
+
service: service.name,
|
|
1328
|
+
name: contribution.name,
|
|
1329
|
+
metadata: schemaSnapshot(contribution.describe?.())
|
|
1330
|
+
})));
|
|
1331
|
+
return {
|
|
1332
|
+
ir: freezeIR({
|
|
1333
|
+
version: 1,
|
|
1334
|
+
target: "bun-elysia",
|
|
1335
|
+
prefix,
|
|
1336
|
+
services: [...names],
|
|
1337
|
+
routes,
|
|
1338
|
+
preparations,
|
|
1339
|
+
diagnostics
|
|
1340
|
+
}),
|
|
1341
|
+
bindings
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
/** What the compiler records about one action route. */
|
|
1345
|
+
function describeRoute(service, action, method, path) {
|
|
1346
|
+
const coercions = [];
|
|
1347
|
+
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
1348
|
+
key,
|
|
1349
|
+
type: "number"
|
|
1350
|
+
});
|
|
1351
|
+
else if (prop.type === "boolean") coercions.push({
|
|
1352
|
+
key,
|
|
1353
|
+
type: "boolean"
|
|
1354
|
+
});
|
|
1355
|
+
else if (prop.type === "array") coercions.push({
|
|
1356
|
+
key,
|
|
1357
|
+
type: "array"
|
|
1358
|
+
});
|
|
1359
|
+
const plugin = actionMeta(action).route?.plugin;
|
|
1881
1360
|
return {
|
|
1882
|
-
service,
|
|
1883
|
-
action,
|
|
1884
|
-
actionName,
|
|
1885
|
-
serviceName,
|
|
1886
|
-
routePath,
|
|
1887
1361
|
method,
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1362
|
+
path,
|
|
1363
|
+
service: service.name,
|
|
1364
|
+
action: action.name,
|
|
1365
|
+
kind: "action",
|
|
1366
|
+
...plugin ? { plugin } : {},
|
|
1367
|
+
input: Boolean(action.config.input),
|
|
1368
|
+
output: Boolean(action.config.output),
|
|
1369
|
+
context: typeof service.options.context === "function",
|
|
1370
|
+
authorize: typeof action.config.authorize === "function",
|
|
1371
|
+
readLike: isReadLike(method, action.name),
|
|
1372
|
+
inputSource: inputSource(method),
|
|
1897
1373
|
coercions,
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
cachedDb
|
|
1374
|
+
inputSchema: schemaSnapshot(action.config.input),
|
|
1375
|
+
outputSchema: schemaSnapshot(action.config.output)
|
|
1901
1376
|
};
|
|
1902
1377
|
}
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
let input;
|
|
1923
|
-
if (plan.hasInput) {
|
|
1924
|
-
let coercedQuery = query;
|
|
1925
|
-
if (query && plan.coercions && plan.coercions.length > 0) {
|
|
1926
|
-
coercedQuery = { ...query };
|
|
1927
|
-
for (let i = 0; i < plan.coercions.length; i++) {
|
|
1928
|
-
const c = plan.coercions[i];
|
|
1929
|
-
const val = query[c.key];
|
|
1930
|
-
if (val !== void 0) {
|
|
1931
|
-
if (c.isNumber) {
|
|
1932
|
-
const num = Number(val);
|
|
1933
|
-
if (!isNaN(num)) coercedQuery[c.key] = num;
|
|
1934
|
-
} else if (c.isArray) {
|
|
1935
|
-
const values = request ? new URL(request.url).searchParams.getAll(c.key) : [];
|
|
1936
|
-
coercedQuery[c.key] = values.length ? values : Array.isArray(val) ? val : [val];
|
|
1937
|
-
} else if (c.isBoolean) {
|
|
1938
|
-
if (val === "true" || val === "1") coercedQuery[c.key] = true;
|
|
1939
|
-
else if (val === "false" || val === "0") coercedQuery[c.key] = false;
|
|
1940
|
-
}
|
|
1941
|
-
}
|
|
1942
|
-
}
|
|
1943
|
-
}
|
|
1944
|
-
let coercedParams = params;
|
|
1945
|
-
if (params && plan.coercions) for (const c of plan.coercions) {
|
|
1946
|
-
if (!c.isNumber || typeof params[c.key] !== "string") continue;
|
|
1947
|
-
const num = Number(params[c.key]);
|
|
1948
|
-
if (isNaN(num)) continue;
|
|
1949
|
-
if (coercedParams === params) coercedParams = { ...params };
|
|
1950
|
-
coercedParams[c.key] = num;
|
|
1951
|
-
}
|
|
1952
|
-
const hasP = isNonEmpty(coercedParams);
|
|
1953
|
-
const hasB = isNonEmpty(body);
|
|
1954
|
-
const hasQ = isNonEmpty(coercedQuery);
|
|
1955
|
-
if (plan.isGetLike) {
|
|
1956
|
-
if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
1957
|
-
else if (hasP && !hasQ && !hasB) input = coercedParams;
|
|
1958
|
-
else if (hasB && !hasP && !hasQ) input = body;
|
|
1959
|
-
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, coercedParams, body);
|
|
1960
|
-
} else if (hasB && !hasP && !hasQ) input = body;
|
|
1961
|
-
else if (hasP && !hasB && !hasQ) input = coercedParams;
|
|
1962
|
-
else if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
1963
|
-
else if (hasP || hasB || hasQ) input = Object.assign({}, coercedParams, body, coercedQuery);
|
|
1964
|
-
}
|
|
1965
|
-
const ctx = {
|
|
1966
|
-
request: request instanceof Request ? request : DEFAULT_REQUEST,
|
|
1967
|
-
traceId,
|
|
1968
|
-
requestId,
|
|
1969
|
-
db: plan.cachedDb ?? plan.service.getDb(),
|
|
1970
|
-
logger: plan.logger,
|
|
1971
|
-
services: EMPTY_SERVICES,
|
|
1972
|
-
deps: plan.service.deps ?? EMPTY_SERVICES,
|
|
1973
|
-
metadata: { headers },
|
|
1974
|
-
_resolved: true
|
|
1378
|
+
// src/action-handler.ts
|
|
1379
|
+
/** The plan of an analyzed route: its callbacks, validators and logger. */
|
|
1380
|
+
function planRoute(route, service, action) {
|
|
1381
|
+
const meta = actionMeta(action);
|
|
1382
|
+
const outputSchema = meta.runtimeOutput ?? action.config.output;
|
|
1383
|
+
return {
|
|
1384
|
+
route,
|
|
1385
|
+
service: portOf(service),
|
|
1386
|
+
action,
|
|
1387
|
+
execute: action.config.execute,
|
|
1388
|
+
authorize: action.config.authorize,
|
|
1389
|
+
contextHook: service.options.context,
|
|
1390
|
+
inputChecker: action.config.input ? getCompiledCheck(action.config.input) : void 0,
|
|
1391
|
+
outputChecker: outputSchema ? getCompiledCheck(outputSchema) : void 0,
|
|
1392
|
+
errorBuilder: action.errorHelpers,
|
|
1393
|
+
logger: createLogger(`[${service.name}:${action.name}]`),
|
|
1394
|
+
cachedDb: service.getDb(),
|
|
1395
|
+
checkInput: meta.checkInput,
|
|
1396
|
+
deps: meta.deps?.values
|
|
1975
1397
|
};
|
|
1976
|
-
try {
|
|
1977
|
-
if (plan.hasContextHook) {
|
|
1978
|
-
const extra = plan.contextHook(ctx);
|
|
1979
|
-
const resolved = extra instanceof Promise ? await extra : extra;
|
|
1980
|
-
if (resolved) Object.assign(ctx, resolved);
|
|
1981
|
-
}
|
|
1982
|
-
if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
|
|
1983
|
-
if (plan.hasInput && plan.inputChecker) {
|
|
1984
|
-
if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
|
|
1985
|
-
path: "",
|
|
1986
|
-
message: "Input exceeds maximum nesting depth"
|
|
1987
|
-
}]);
|
|
1988
|
-
if (!plan.inputChecker.Check(input)) {
|
|
1989
|
-
const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
|
|
1990
|
-
path: err.path,
|
|
1991
|
-
message: err.message,
|
|
1992
|
-
value: err.value
|
|
1993
|
-
}));
|
|
1994
|
-
throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
|
|
1995
|
-
}
|
|
1996
|
-
}
|
|
1997
|
-
if (plan.hasAuthorize) {
|
|
1998
|
-
const authRes = plan.authorize({
|
|
1999
|
-
ctx,
|
|
2000
|
-
input,
|
|
2001
|
-
user: ctx.user
|
|
2002
|
-
});
|
|
2003
|
-
if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError(ctx.user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${plan.actionName}'`, ctx.user == null ? 401 : 403);
|
|
2004
|
-
}
|
|
2005
|
-
const execRes = plan.execute({
|
|
2006
|
-
input,
|
|
2007
|
-
ctx,
|
|
2008
|
-
error: plan.errorBuilder
|
|
2009
|
-
});
|
|
2010
|
-
const result = execRes instanceof Promise ? await execRes : execRes;
|
|
2011
|
-
if (plan.outputChecker) {
|
|
2012
|
-
if (!plan.outputChecker.Check(result)) {
|
|
2013
|
-
const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
|
|
2014
|
-
path: err.path,
|
|
2015
|
-
message: err.message,
|
|
2016
|
-
value: err.value
|
|
2017
|
-
}));
|
|
2018
|
-
throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
|
|
2019
|
-
}
|
|
2020
|
-
}
|
|
2021
|
-
return result;
|
|
2022
|
-
} catch (err) {
|
|
2023
|
-
const response = toErrorResponse(err, {
|
|
2024
|
-
logger: ctx.logger,
|
|
2025
|
-
requestId
|
|
2026
|
-
});
|
|
2027
|
-
set.status = response.status;
|
|
2028
|
-
return response;
|
|
2029
|
-
}
|
|
2030
1398
|
}
|
|
2031
1399
|
/**
|
|
2032
|
-
* An Elysia handler for one action
|
|
2033
|
-
* `executeCompiledRoute` together. Use it to mount an action on your own
|
|
1400
|
+
* An Elysia handler for one action. Use it to mount an action on your own
|
|
2034
1401
|
* Elysia app; `brick()` does it for you.
|
|
2035
1402
|
*
|
|
1403
|
+
* @deprecated Serve actions with `brick()`, or bind every route at once with
|
|
1404
|
+
* `compileBrickApplication`.
|
|
2036
1405
|
* @param service - The service the action belongs to.
|
|
2037
1406
|
* @param action - The action.
|
|
2038
1407
|
* @param routePath - The route's path.
|
|
@@ -2040,209 +1409,164 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
2040
1409
|
* @returns A function from the Elysia context to the response.
|
|
2041
1410
|
*/
|
|
2042
1411
|
function createActionHandler(service, action, routePath, method) {
|
|
2043
|
-
|
|
2044
|
-
return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
|
|
1412
|
+
return bindRoute(planRoute(describeRoute(service, action, method ?? "POST", routePath), service, action));
|
|
2045
1413
|
}
|
|
2046
|
-
// src/
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
1414
|
+
// src/app-entry.ts
|
|
1415
|
+
/**
|
|
1416
|
+
* Whether a value is an application made by `brick()`. It checks for the
|
|
1417
|
+
* methods and `definition` a `BrickApp` has, so it also recognizes one built by
|
|
1418
|
+
* another copy of the package.
|
|
1419
|
+
*
|
|
1420
|
+
* @param app - Anything, such as the default export of an entry file.
|
|
1421
|
+
* @returns `true` for a `BrickApp`, narrowing its type.
|
|
1422
|
+
*/
|
|
1423
|
+
function isBrickApp(app) {
|
|
1424
|
+
if (!app || typeof app !== "object") return false;
|
|
1425
|
+
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";
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* Check that a module's default export is an application ready to be served,
|
|
1429
|
+
* for tools that load an entry file.
|
|
1430
|
+
*
|
|
1431
|
+
* @param app - The default export of an entry file.
|
|
1432
|
+
* @returns The app.
|
|
1433
|
+
* @throws When it is not a `BrickApp`, or it already called `.listen()`: the
|
|
1434
|
+
* entry must only build the app, and leave listening to the server bootstrap.
|
|
1435
|
+
*/
|
|
1436
|
+
function requireBrickApp(app) {
|
|
1437
|
+
if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
1438
|
+
if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
|
|
1439
|
+
return app;
|
|
1440
|
+
}
|
|
1441
|
+
// src/compiler.ts
|
|
1442
|
+
/** @throws When the services no longer analyze to `ir`, so the build is stale. */
|
|
1443
|
+
function analyzeMatching(services, ir) {
|
|
1444
|
+
const analyzed = analyzeApplication(services, ir.prefix);
|
|
1445
|
+
if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
|
|
1446
|
+
return analyzed;
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Build artifact bootstrap: import the app and check that its definitions
|
|
1450
|
+
* still match the IR `brick build` compiled.
|
|
1451
|
+
*
|
|
1452
|
+
* @throws When the app's definitions differ from `ir`.
|
|
1453
|
+
*/
|
|
1454
|
+
async function loadCompiledBrickApp(load, ir) {
|
|
1455
|
+
const app = requireBrickApp((await load()).default);
|
|
1456
|
+
analyzeMatching([...app.definition.services], ir);
|
|
1457
|
+
return app;
|
|
1458
|
+
}
|
|
1459
|
+
function bindAnalyzed(ir, bindings, bind = bindRoute) {
|
|
1460
|
+
const routes = ir.routes.map((route, index) => {
|
|
1461
|
+
const { service, action } = bindings[index];
|
|
1462
|
+
const plan = Object.freeze(planRoute(route, service, action));
|
|
1463
|
+
return Object.freeze({
|
|
1464
|
+
ir: route,
|
|
1465
|
+
handler: bind(plan, index)
|
|
1466
|
+
});
|
|
1467
|
+
});
|
|
1468
|
+
return Object.freeze({
|
|
1469
|
+
ir: freezeIR(ir),
|
|
1470
|
+
routes: Object.freeze(routes)
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
/** Startup compiler: analyzes once, then binds live callbacks. */
|
|
1474
|
+
function compileBrickApplication(options) {
|
|
1475
|
+
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
1476
|
+
if (options.mode !== "generic") for (const service of options.services) portOf(service).prepareContributions();
|
|
1477
|
+
return bindAnalyzed(ir, bindings);
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Build artifact binder: consumes emitted functions, with no runtime handler code generation.
|
|
1481
|
+
*
|
|
1482
|
+
* @deprecated `brick build` no longer emits handler factories; built servers
|
|
1483
|
+
* use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as
|
|
1484
|
+
* `brick({ compilation })` instead.
|
|
1485
|
+
*/
|
|
1486
|
+
function bindCompiledApplication(ir, services, factories) {
|
|
1487
|
+
if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
|
|
1488
|
+
const analyzed = analyzeMatching(services, ir);
|
|
1489
|
+
if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
|
|
1490
|
+
for (const service of services) portOf(service).prepareContributions();
|
|
1491
|
+
return bindAnalyzed(ir, analyzed.bindings, (plan, index) => factories[index](plan, compilerRuntime));
|
|
1492
|
+
}
|
|
1493
|
+
// src/registry.ts
|
|
1494
|
+
var ServiceRegistry = class {
|
|
1495
|
+
_revision = 0;
|
|
1496
|
+
/** Definition revision for invalidating serialized architecture snapshots. */
|
|
1497
|
+
get revision() {
|
|
1498
|
+
return this._revision;
|
|
2051
1499
|
}
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
return values.length ? values : Array.isArray(value) ? value : [value];
|
|
1500
|
+
touch() {
|
|
1501
|
+
this._revision++;
|
|
2055
1502
|
}
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
1503
|
+
services = /* @__PURE__ */ new Map();
|
|
1504
|
+
sites = /* @__PURE__ */ new Map();
|
|
1505
|
+
/** @throws When a different file already registered a service with this name. */
|
|
1506
|
+
register(service, site = definitionSite()) {
|
|
1507
|
+
claimName(this.sites, `service "${service.name}"`, service.name, site);
|
|
1508
|
+
this.services.set(service.name, service);
|
|
1509
|
+
this.touch();
|
|
2059
1510
|
}
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
let input = readLike ? runtime.mergeInput(coercedQuery, coercedParams, body) : runtime.mergeInput(coercedParams, body, coercedQuery);
|
|
2083
|
-
if (objectInput) input ??= {};
|
|
2084
|
-
return input;
|
|
2085
|
-
} : () => void 0;
|
|
2086
|
-
const validateInput = (input) => {
|
|
2087
|
-
if (inputChecker) {
|
|
2088
|
-
runtime.checkDepth(input, route.action);
|
|
2089
|
-
runtime.validate(inputChecker, input, route.action, "input");
|
|
2090
|
-
}
|
|
2091
|
-
};
|
|
2092
|
-
const validateOutput = (result) => {
|
|
2093
|
-
if (route.output && outputChecker) runtime.validate(outputChecker, result, route.action, "output");
|
|
2094
|
-
return result;
|
|
2095
|
-
};
|
|
2096
|
-
const createContext = ({ headers, request, set }) => {
|
|
2097
|
-
const seq = runtime.nextSequence();
|
|
2098
|
-
const traceId = headers?.["x-trace-id"] || "tr_" + seq;
|
|
2099
|
-
const requestId = headers?.["x-request-id"] || "req_" + seq;
|
|
2100
|
-
if (set?.headers) {
|
|
2101
|
-
set.headers["x-trace-id"] = traceId;
|
|
2102
|
-
set.headers["x-request-id"] = requestId;
|
|
2103
|
-
}
|
|
2104
|
-
return {
|
|
2105
|
-
request: request instanceof Request ? request : runtime.defaultRequest,
|
|
2106
|
-
traceId,
|
|
2107
|
-
requestId,
|
|
2108
|
-
db: cachedDb ?? service.getDb(),
|
|
2109
|
-
logger,
|
|
2110
|
-
services: runtime.emptyServices,
|
|
2111
|
-
deps: service.deps ?? runtime.emptyServices,
|
|
2112
|
-
metadata: { headers },
|
|
2113
|
-
_resolved: true
|
|
2114
|
-
};
|
|
2115
|
-
};
|
|
2116
|
-
if (contextHook || authorize) return async function brickAction(context) {
|
|
2117
|
-
const input = readInput(context);
|
|
2118
|
-
const ctx = createContext(context);
|
|
2119
|
-
try {
|
|
2120
|
-
if (contextHook) {
|
|
2121
|
-
const extra = await contextHook(ctx);
|
|
2122
|
-
if (extra) Object.assign(ctx, extra);
|
|
2123
|
-
}
|
|
2124
|
-
validateInput(input);
|
|
2125
|
-
if (authorize && !await authorize({
|
|
2126
|
-
ctx,
|
|
2127
|
-
input,
|
|
2128
|
-
user: ctx.user
|
|
2129
|
-
})) runtime.deny(route.action, ctx.user);
|
|
2130
|
-
return validateOutput(await execute({
|
|
2131
|
-
input,
|
|
2132
|
-
ctx,
|
|
2133
|
-
error: errorBuilder
|
|
1511
|
+
get(name) {
|
|
1512
|
+
return this.services.get(name);
|
|
1513
|
+
}
|
|
1514
|
+
has(name) {
|
|
1515
|
+
return this.services.has(name);
|
|
1516
|
+
}
|
|
1517
|
+
list() {
|
|
1518
|
+
return Array.from(this.services.values());
|
|
1519
|
+
}
|
|
1520
|
+
/**
|
|
1521
|
+
* The architecture of an app (`app.definition`): its mounted routes. Without
|
|
1522
|
+
* one, every registered service with its default routes under `/api`.
|
|
1523
|
+
*/
|
|
1524
|
+
exportArchitecture(application) {
|
|
1525
|
+
return {
|
|
1526
|
+
version: "1.0.0",
|
|
1527
|
+
...application?.events ? { events: application.events } : {},
|
|
1528
|
+
...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
|
|
1529
|
+
services: (application?.services ?? this.list()).map((service) => {
|
|
1530
|
+
const byAction = new Map(application ? application.routes.filter((route) => route.service === service.name).map((route) => [route.action, route]) : service.listActions().flatMap((action) => {
|
|
1531
|
+
const route = getActionRoute(action);
|
|
1532
|
+
return route ? [[action.name, route]] : [];
|
|
2134
1533
|
}));
|
|
2135
|
-
|
|
2136
|
-
return
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
}
|
|
2154
|
-
};
|
|
2155
|
-
};
|
|
2156
|
-
}
|
|
2157
|
-
// src/app-entry.ts
|
|
1534
|
+
const schema = service.introspect();
|
|
1535
|
+
return {
|
|
1536
|
+
...schema,
|
|
1537
|
+
...application?.sockets ? { sockets: application.sockets.filter((socket) => socket.service === service.name) } : {},
|
|
1538
|
+
actions: schema.actions.map((action) => {
|
|
1539
|
+
const route = byAction.get(action.name);
|
|
1540
|
+
return route ? {
|
|
1541
|
+
...action,
|
|
1542
|
+
method: route.method,
|
|
1543
|
+
path: route.path
|
|
1544
|
+
} : action;
|
|
1545
|
+
})
|
|
1546
|
+
};
|
|
1547
|
+
})
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1551
|
+
let globalRegistry = new ServiceRegistry();
|
|
2158
1552
|
/**
|
|
2159
|
-
*
|
|
2160
|
-
*
|
|
2161
|
-
* another copy of the package.
|
|
1553
|
+
* The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
|
|
1554
|
+
* generator, `useService`, and the dashboard find services by name.
|
|
2162
1555
|
*
|
|
2163
|
-
* @
|
|
2164
|
-
* @returns `true` for a `BrickApp`, narrowing its type.
|
|
1556
|
+
* @returns The current global registry.
|
|
2165
1557
|
*/
|
|
2166
|
-
function
|
|
2167
|
-
|
|
2168
|
-
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";
|
|
1558
|
+
function getGlobalRegistry() {
|
|
1559
|
+
return globalRegistry;
|
|
2169
1560
|
}
|
|
2170
1561
|
/**
|
|
2171
|
-
*
|
|
2172
|
-
*
|
|
2173
|
-
*
|
|
2174
|
-
* @param app - The default export of an entry file.
|
|
2175
|
-
* @returns The app.
|
|
2176
|
-
* @throws When it is not a `BrickApp`, or it already called `.listen()`: the
|
|
2177
|
-
* entry must only build the app, and leave listening to the server bootstrap.
|
|
1562
|
+
* Start over with an empty global registry. For tests, which define the same
|
|
1563
|
+
* services again in each case; an application never needs it.
|
|
2178
1564
|
*/
|
|
2179
|
-
function
|
|
2180
|
-
|
|
2181
|
-
if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
|
|
2182
|
-
return app;
|
|
2183
|
-
}
|
|
2184
|
-
// src/compiler.ts
|
|
2185
|
-
const buildBindings = /* @__PURE__ */ new Map();
|
|
2186
|
-
function applicationKey(services, prefix = "/api") {
|
|
2187
|
-
return JSON.stringify([prefix, services.map((service) => service.name)]);
|
|
2188
|
-
}
|
|
2189
|
-
/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
|
|
2190
|
-
async function loadCompiledBrickApp(load, ir, bind) {
|
|
2191
|
-
const key = JSON.stringify([ir.prefix, ir.services]);
|
|
2192
|
-
if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
|
|
2193
|
-
buildBindings.set(key, bind);
|
|
2194
|
-
try {
|
|
2195
|
-
const app = requireBrickApp((await load()).default);
|
|
2196
|
-
if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
|
|
2197
|
-
return app;
|
|
2198
|
-
} finally {
|
|
2199
|
-
buildBindings.delete(key);
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
2202
|
-
function bindAnalyzed(ir, bindings, factories) {
|
|
2203
|
-
if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
|
|
2204
|
-
const routes = ir.routes.map((route, index) => {
|
|
2205
|
-
const { service, action } = bindings[index];
|
|
2206
|
-
const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
|
|
2207
|
-
const handler = factories[index](plan, compilerRuntime);
|
|
2208
|
-
return Object.freeze({
|
|
2209
|
-
ir: route,
|
|
2210
|
-
handler
|
|
2211
|
-
});
|
|
2212
|
-
});
|
|
2213
|
-
return Object.freeze({
|
|
2214
|
-
ir: freezeIR(ir),
|
|
2215
|
-
routes: Object.freeze(routes)
|
|
2216
|
-
});
|
|
2217
|
-
}
|
|
2218
|
-
/** Startup compiler: analyzes once, then binds live callbacks. */
|
|
2219
|
-
function compileBrickApplication(options) {
|
|
2220
|
-
const bind = buildBindings.get(applicationKey(options.services, options.prefix));
|
|
2221
|
-
if (bind && options.mode !== "generic") return bind(options.services);
|
|
2222
|
-
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
2223
|
-
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map(createHandlerFactory);
|
|
2224
|
-
if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
|
|
2225
|
-
return bindAnalyzed(ir, bindings, factories);
|
|
2226
|
-
}
|
|
2227
|
-
/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
|
|
2228
|
-
function bindCompiledApplication(ir, services, factories) {
|
|
2229
|
-
if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
|
|
2230
|
-
const analyzed = analyzeApplication(services, ir.prefix);
|
|
2231
|
-
if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
|
|
2232
|
-
for (const service of services) service.prepareContributions();
|
|
2233
|
-
return bindAnalyzed(ir, analyzed.bindings, factories);
|
|
1565
|
+
function resetGlobalRegistry() {
|
|
1566
|
+
globalRegistry = new ServiceRegistry();
|
|
2234
1567
|
}
|
|
2235
1568
|
// src/access.ts
|
|
2236
1569
|
/**
|
|
2237
|
-
* Cross-copy access metadata protocol. CRUD enforces its access policy
|
|
2238
|
-
* inside `execute`, so `config.authorize` is absent and introspection
|
|
2239
|
-
* can't see it. The plugin stamps each action under this process-global
|
|
2240
|
-
* symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
|
|
2241
|
-
* the binding survives a second copy of core (bundler SSR, Vitest),
|
|
2242
|
-
* same as the plugin action-binding key.
|
|
2243
|
-
*/
|
|
2244
|
-
const ACTION_ACCESS_KEY = Symbol.for("brickkit.action.access");
|
|
2245
|
-
/**
|
|
2246
1570
|
* Record how an action is protected, for tools that cannot read it from the
|
|
2247
1571
|
* configuration: plugins such as `crud` enforce access inside `execute`, so the
|
|
2248
1572
|
* action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
|
|
@@ -2253,7 +1577,7 @@ const ACTION_ACCESS_KEY = Symbol.for("brickkit.action.access");
|
|
|
2253
1577
|
* and the resulting policy.
|
|
2254
1578
|
*/
|
|
2255
1579
|
function setActionAccess(action, info) {
|
|
2256
|
-
action
|
|
1580
|
+
actionMeta(action).access = {
|
|
2257
1581
|
hasAuthorize: info.hasAuthorize,
|
|
2258
1582
|
hasScope: info.hasScope,
|
|
2259
1583
|
policy: info.policy
|
|
@@ -2270,8 +1594,8 @@ function setActionAccess(action, info) {
|
|
|
2270
1594
|
* @returns `hasAuthorize`, `hasScope`, and `policy`.
|
|
2271
1595
|
*/
|
|
2272
1596
|
function getActionAccess(action) {
|
|
2273
|
-
const meta = action
|
|
2274
|
-
const configAuthorize =
|
|
1597
|
+
const meta = actionMeta(action).access;
|
|
1598
|
+
const configAuthorize = typeof action.config?.authorize === "function";
|
|
2275
1599
|
if (!meta) return {
|
|
2276
1600
|
hasAuthorize: configAuthorize,
|
|
2277
1601
|
hasScope: false,
|
|
@@ -2290,6 +1614,12 @@ function getActionAccess(action) {
|
|
|
2290
1614
|
};
|
|
2291
1615
|
}
|
|
2292
1616
|
// src/openapi.ts
|
|
1617
|
+
/** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */
|
|
1618
|
+
const OPENAPI_DEFAULTS = Object.freeze({
|
|
1619
|
+
title: "Brick-TS API Mesh",
|
|
1620
|
+
version: "1.0.0",
|
|
1621
|
+
path: "/openapi.json"
|
|
1622
|
+
});
|
|
2293
1623
|
function isAnchor(node) {
|
|
2294
1624
|
return typeof node === "object" && node !== null && typeof node.$id === "string";
|
|
2295
1625
|
}
|
|
@@ -2309,7 +1639,6 @@ function toComponentKey(id) {
|
|
|
2309
1639
|
*/
|
|
2310
1640
|
function hoistAnchoredSchemas(spec) {
|
|
2311
1641
|
const anchored = /* @__PURE__ */ new Map();
|
|
2312
|
-
const conflicts = [];
|
|
2313
1642
|
const collect = (node) => {
|
|
2314
1643
|
if (Array.isArray(node)) return node.map(collect);
|
|
2315
1644
|
if (typeof node !== "object" || node === null) return node;
|
|
@@ -2317,9 +1646,7 @@ function hoistAnchoredSchemas(spec) {
|
|
|
2317
1646
|
const id = node.$id;
|
|
2318
1647
|
const { $id: _dropped, ...rest } = node;
|
|
2319
1648
|
const collected = collect(rest);
|
|
2320
|
-
if (anchored.has(id))
|
|
2321
|
-
if (JSON.stringify(anchored.get(id)) !== JSON.stringify(collected)) conflicts.push(id);
|
|
2322
|
-
} else anchored.set(id, collected);
|
|
1649
|
+
if (!anchored.has(id)) anchored.set(id, collected);
|
|
2323
1650
|
return { $ref: `#/components/schemas/${toComponentKey(id)}` };
|
|
2324
1651
|
}
|
|
2325
1652
|
for (const key of Object.keys(node)) node[key] = collect(node[key]);
|
|
@@ -2339,7 +1666,6 @@ function hoistAnchoredSchemas(spec) {
|
|
|
2339
1666
|
const schemas = components.schemas ??= {};
|
|
2340
1667
|
for (const [id, schema] of anchored) schemas[toComponentKey(id)] = schema;
|
|
2341
1668
|
rewrite(spec);
|
|
2342
|
-
return [...anchored.keys()];
|
|
2343
1669
|
}
|
|
2344
1670
|
/**
|
|
2345
1671
|
* Build the OpenAPI 3.1 document for the services: one path per action route,
|
|
@@ -2352,31 +1678,31 @@ function hoistAnchoredSchemas(spec) {
|
|
|
2352
1678
|
* document to a file or feed another tool.
|
|
2353
1679
|
*
|
|
2354
1680
|
* @param options - `title`, `version`, and `description` for the `info` block,
|
|
2355
|
-
* `prefix` (default `/api`), and the `services`
|
|
2356
|
-
*
|
|
1681
|
+
* `prefix` (default `/api`), and the `services` to describe (the global
|
|
1682
|
+
* registry's by default).
|
|
2357
1683
|
* @returns The document as a plain object.
|
|
2358
1684
|
*/
|
|
2359
1685
|
function generateOpenApiSpec(options = {}) {
|
|
2360
|
-
const title = options.title ??
|
|
2361
|
-
const version = options.version ??
|
|
1686
|
+
const title = options.title ?? OPENAPI_DEFAULTS.title;
|
|
1687
|
+
const version = options.version ?? OPENAPI_DEFAULTS.version;
|
|
2362
1688
|
const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
|
|
2363
1689
|
const prefix = options.prefix ?? "/api";
|
|
2364
|
-
const services = options.services ??
|
|
1690
|
+
const services = options.services ?? getGlobalRegistry().list();
|
|
2365
1691
|
const paths = {};
|
|
2366
1692
|
const tags = /* @__PURE__ */ new Map();
|
|
2367
1693
|
let hasAnyAuthorizedAction = false;
|
|
1694
|
+
const { ir, bindings } = analyzeDeclaredApplication([...services], prefix);
|
|
2368
1695
|
for (const service of services) {
|
|
2369
1696
|
tags.set(service.name, `Actions exposed by '${service.name}' service`);
|
|
2370
|
-
for (const
|
|
2371
|
-
|
|
2372
|
-
|
|
1697
|
+
for (const [index, route] of ir.routes.entries()) {
|
|
1698
|
+
if (route.service !== service.name) continue;
|
|
1699
|
+
const { action } = bindings[index];
|
|
2373
1700
|
const routePath = route.path;
|
|
2374
1701
|
const method = route.method.toLowerCase();
|
|
2375
|
-
const pathParams =
|
|
2376
|
-
const actionPath = routePath
|
|
1702
|
+
const pathParams = pathParamNames(routePath);
|
|
1703
|
+
const actionPath = toOpenApiPath(routePath);
|
|
2377
1704
|
if (!paths[actionPath]) paths[actionPath] = {};
|
|
2378
|
-
|
|
2379
|
-
const resource = action.resource;
|
|
1705
|
+
const { plugin, resource } = actionOwners(action);
|
|
2380
1706
|
const group = resource ? `${service.name} · ${resource}` : service.name;
|
|
2381
1707
|
if (resource) tags.set(group, `Routes of resource '${resource}' in service '${service.name}'`);
|
|
2382
1708
|
const hasAuth = getActionAccess(action).hasAuthorize;
|
|
@@ -2425,8 +1751,8 @@ function generateOpenApiSpec(options = {}) {
|
|
|
2425
1751
|
summary: `${service.name}.${action.name}`,
|
|
2426
1752
|
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
2427
1753
|
tags: [.../* @__PURE__ */ new Set([group, ...action.config.tags ?? []])],
|
|
2428
|
-
...
|
|
2429
|
-
...
|
|
1754
|
+
...plugin ? { "x-brick-plugin": plugin } : {},
|
|
1755
|
+
...resource ? { "x-brick-resource": resource } : {},
|
|
2430
1756
|
responses
|
|
2431
1757
|
};
|
|
2432
1758
|
const inputSchema = action.config.input;
|
|
@@ -2437,7 +1763,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
2437
1763
|
required: true,
|
|
2438
1764
|
schema: properties[key] ?? { type: "string" }
|
|
2439
1765
|
}));
|
|
2440
|
-
if (
|
|
1766
|
+
if (route.inputSource === "query") for (const [key, schema] of Object.entries(properties)) {
|
|
2441
1767
|
if (pathParams.includes(key)) continue;
|
|
2442
1768
|
parameters.push({
|
|
2443
1769
|
name: key,
|
|
@@ -2519,10 +1845,32 @@ function generateOpenApiSpec(options = {}) {
|
|
|
2519
1845
|
return document;
|
|
2520
1846
|
}
|
|
2521
1847
|
// src/secrets.ts
|
|
1848
|
+
/**
|
|
1849
|
+
* Type-safe secrets & environment variables.
|
|
1850
|
+
*
|
|
1851
|
+
* Declare each secret once at module scope instead of scattering untyped
|
|
1852
|
+
* `process.env.FOO` reads:
|
|
1853
|
+
*
|
|
1854
|
+
* const port = defineSecret("PORT").default("3333").transform(Number).require();
|
|
1855
|
+
* const baseUrl = defineSecret("BASE_URL").url().require();
|
|
1856
|
+
* const key = defineSecret("STRIPE_KEY").validate((v) =>
|
|
1857
|
+
* v.startsWith("sk_") || "must start with sk_"
|
|
1858
|
+
* ).require();
|
|
1859
|
+
*
|
|
1860
|
+
* Values resolve from the environment (Bun populates `process.env` from
|
|
1861
|
+
* `.env` locally; in prod the same env source applies — a future
|
|
1862
|
+
* `SecretSource` such as AWS can slot in without touching call sites).
|
|
1863
|
+
*
|
|
1864
|
+
* Resolution order per secret: test/session override → source (`process.env`
|
|
1865
|
+
* by default) → declared `default`. `resolveSecrets()` validates every
|
|
1866
|
+
* registered secret at boot and throws listing all missing required ones.
|
|
1867
|
+
*/
|
|
2522
1868
|
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
2523
1869
|
const envSource = { get: (name) => process.env[name] };
|
|
2524
1870
|
const registry = /* @__PURE__ */ new Map();
|
|
2525
1871
|
const overrides = /* @__PURE__ */ new Map();
|
|
1872
|
+
/** Where each secret was first declared. */
|
|
1873
|
+
const sites = /* @__PURE__ */ new Map();
|
|
2526
1874
|
var SecretRef = class {
|
|
2527
1875
|
name;
|
|
2528
1876
|
options;
|
|
@@ -2566,11 +1914,7 @@ var SecretRef = class {
|
|
|
2566
1914
|
return this;
|
|
2567
1915
|
}
|
|
2568
1916
|
resolveRaw(source) {
|
|
2569
|
-
|
|
2570
|
-
const v = overrides.get(this.name);
|
|
2571
|
-
if (v !== void 0) return v;
|
|
2572
|
-
}
|
|
2573
|
-
return source.get(this.name) ?? this.options.default;
|
|
1917
|
+
return overrides.get(this.name) ?? source.get(this.name) ?? this.options.default;
|
|
2574
1918
|
}
|
|
2575
1919
|
coerce(raw) {
|
|
2576
1920
|
let value;
|
|
@@ -2610,12 +1954,22 @@ var SecretRef = class {
|
|
|
2610
1954
|
}
|
|
2611
1955
|
};
|
|
2612
1956
|
/**
|
|
2613
|
-
* Declare a secret.
|
|
2614
|
-
*
|
|
1957
|
+
* Declare a secret. Calling it again for the name returns the same ref. From
|
|
1958
|
+
* the same line (a module evaluated again) it starts the declaration over, so
|
|
1959
|
+
* its builder calls replace the earlier ones instead of adding to them.
|
|
2615
1960
|
*/
|
|
2616
1961
|
function defineSecret(name, options = {}) {
|
|
1962
|
+
const site = definitionSite();
|
|
2617
1963
|
const existing = registry.get(name);
|
|
2618
|
-
if (existing)
|
|
1964
|
+
if (existing) {
|
|
1965
|
+
if (site !== void 0 && sites.get(name) === site) {
|
|
1966
|
+
existing.options = options;
|
|
1967
|
+
existing["validators"] = [];
|
|
1968
|
+
existing["transformFn"] = void 0;
|
|
1969
|
+
}
|
|
1970
|
+
return existing;
|
|
1971
|
+
}
|
|
1972
|
+
sites.set(name, site);
|
|
2619
1973
|
const ref = new SecretRef(name, options);
|
|
2620
1974
|
registry.set(name, ref);
|
|
2621
1975
|
return ref;
|
|
@@ -2647,16 +2001,14 @@ function listSecrets(opts = {}) {
|
|
|
2647
2001
|
}
|
|
2648
2002
|
/** Test/session override for one secret (`undefined` clears the override). */
|
|
2649
2003
|
function overrideSecret(name, value) {
|
|
2650
|
-
overrides.
|
|
2651
|
-
|
|
2652
|
-
/** Bulk overrides (test/session scoped). */
|
|
2653
|
-
function overrideSecrets(values) {
|
|
2654
|
-
for (const [name, value] of Object.entries(values)) overrides.set(name, value);
|
|
2004
|
+
if (value === void 0) overrides.delete(name);
|
|
2005
|
+
else overrides.set(name, value);
|
|
2655
2006
|
}
|
|
2656
2007
|
/** Clear registry and overrides. Test-only. */
|
|
2657
2008
|
function resetSecrets() {
|
|
2658
2009
|
registry.clear();
|
|
2659
2010
|
overrides.clear();
|
|
2011
|
+
sites.clear();
|
|
2660
2012
|
}
|
|
2661
2013
|
// src/request-logger.ts
|
|
2662
2014
|
function formatLog(method, path, status, elapsedMs) {
|
|
@@ -2675,8 +2027,7 @@ function thrownStatus(error) {
|
|
|
2675
2027
|
/**
|
|
2676
2028
|
* Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
|
|
2677
2029
|
* Timing is tracked per-Request via a WeakMap. The onError hook only logs and
|
|
2678
|
-
* returns undefined so existing error mapping is preserved.
|
|
2679
|
-
* no CORS headers are set here.
|
|
2030
|
+
* returns undefined so existing error mapping is preserved.
|
|
2680
2031
|
*
|
|
2681
2032
|
* Hooks are registered with the "global" scope so they propagate to the
|
|
2682
2033
|
* parent app when mounted via `app.use(...)` — Elysia scopes plain instance
|
|
@@ -2734,11 +2085,15 @@ function scalarDocsHTML(specUrl, title) {
|
|
|
2734
2085
|
</body>
|
|
2735
2086
|
</html>`;
|
|
2736
2087
|
}
|
|
2737
|
-
/**
|
|
2088
|
+
/**
|
|
2089
|
+
* Standalone Elysia plugin serving GET <path> with the Scalar HTML page.
|
|
2090
|
+
*
|
|
2091
|
+
* @deprecated Use `brick({ reference: true })` or `reference: { path }`.
|
|
2092
|
+
*/
|
|
2738
2093
|
function referencePlugin(opts = {}) {
|
|
2739
2094
|
const path = opts.path ?? "/reference";
|
|
2740
|
-
const title = opts.title ??
|
|
2741
|
-
const specUrl = opts.specUrl ??
|
|
2095
|
+
const title = opts.title ?? OPENAPI_DEFAULTS.title;
|
|
2096
|
+
const specUrl = opts.specUrl ?? OPENAPI_DEFAULTS.path;
|
|
2742
2097
|
const plugin = new Elysia();
|
|
2743
2098
|
plugin.get(path, ({ set }) => {
|
|
2744
2099
|
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
@@ -2746,7 +2101,11 @@ function referencePlugin(opts = {}) {
|
|
|
2746
2101
|
});
|
|
2747
2102
|
return plugin;
|
|
2748
2103
|
}
|
|
2749
|
-
/**
|
|
2104
|
+
/**
|
|
2105
|
+
* Mounts the Scalar reference route onto an existing app.
|
|
2106
|
+
*
|
|
2107
|
+
* @deprecated Use `brick({ reference: true })` or `reference: { path }`.
|
|
2108
|
+
*/
|
|
2750
2109
|
function registerReferenceRoute(app, opts = {}) {
|
|
2751
2110
|
return app.use(referencePlugin(opts));
|
|
2752
2111
|
}
|
|
@@ -2825,7 +2184,7 @@ function normalizeDashboard(options) {
|
|
|
2825
2184
|
// src/endpoints.ts
|
|
2826
2185
|
/** Resolve the db for an endpoint: explicit service first, else first service holding one. */
|
|
2827
2186
|
function resolveEndpointDb(service, services) {
|
|
2828
|
-
if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb()
|
|
2187
|
+
if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb();
|
|
2829
2188
|
for (const svc of services) {
|
|
2830
2189
|
const db = svc.getDb();
|
|
2831
2190
|
if (db) return db;
|
|
@@ -2835,12 +2194,7 @@ function resolveEndpointDb(service, services) {
|
|
|
2835
2194
|
function createEndpointHandler(def, services) {
|
|
2836
2195
|
const logger = createLogger(`[${`endpoint:${def.method} ${def.path}`}]`);
|
|
2837
2196
|
return async ({ params, body, query, headers, request, set }) => {
|
|
2838
|
-
const traceId = headers
|
|
2839
|
-
const requestId = headers?.["x-request-id"] || `req_${crypto.randomUUID()}`;
|
|
2840
|
-
if (set?.headers) {
|
|
2841
|
-
set.headers["x-trace-id"] = traceId;
|
|
2842
|
-
set.headers["x-request-id"] = requestId;
|
|
2843
|
-
}
|
|
2197
|
+
const { traceId, requestId } = requestIds(headers, set);
|
|
2844
2198
|
const ctx = {
|
|
2845
2199
|
body,
|
|
2846
2200
|
db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
|
|
@@ -2868,14 +2222,6 @@ function createEndpointHandler(def, services) {
|
|
|
2868
2222
|
}
|
|
2869
2223
|
};
|
|
2870
2224
|
}
|
|
2871
|
-
/** `/p/:slug` → `/p/{slug}` for OpenAPI. */
|
|
2872
|
-
function toOpenApiPath(elysiaPath) {
|
|
2873
|
-
return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
2874
|
-
}
|
|
2875
|
-
/** Parameter names (`:slug`) extracted for the OpenAPI path item. */
|
|
2876
|
-
function pathParamNames(elysiaPath) {
|
|
2877
|
-
return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
|
|
2878
|
-
}
|
|
2879
2225
|
/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
|
|
2880
2226
|
function endpointPaths(defs) {
|
|
2881
2227
|
const paths = {};
|
|
@@ -2899,8 +2245,32 @@ function endpointPaths(defs) {
|
|
|
2899
2245
|
}
|
|
2900
2246
|
return paths;
|
|
2901
2247
|
}
|
|
2248
|
+
// src/events/id.ts
|
|
2249
|
+
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
2250
|
+
function newEventId(now = Date.now()) {
|
|
2251
|
+
let time = "";
|
|
2252
|
+
let remaining = now;
|
|
2253
|
+
for (let index = 0; index < 10; index++) {
|
|
2254
|
+
time = ALPHABET[remaining % 32] + time;
|
|
2255
|
+
remaining = Math.floor(remaining / 32);
|
|
2256
|
+
}
|
|
2257
|
+
let random = "";
|
|
2258
|
+
for (const byte of crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))) random += ALPHABET[byte % 32];
|
|
2259
|
+
return `evt_${time}${random}`;
|
|
2260
|
+
}
|
|
2261
|
+
/**
|
|
2262
|
+
* A delivery's id: `<event id>:<listener>`, which is why a listener name cannot
|
|
2263
|
+
* contain `:`.
|
|
2264
|
+
*/
|
|
2265
|
+
const deliveryId = (eventId, listener) => `${eventId}:${listener}`;
|
|
2902
2266
|
// src/events/outbox.ts
|
|
2903
2267
|
const OUTBOX = Symbol.for("brick.outbox");
|
|
2268
|
+
const OUTBOX_STATUSES = [
|
|
2269
|
+
"pending",
|
|
2270
|
+
"claimed",
|
|
2271
|
+
"delivered",
|
|
2272
|
+
"dead"
|
|
2273
|
+
];
|
|
2904
2274
|
function sqliteOutbox(name) {
|
|
2905
2275
|
const timestampMs = (column) => integer(column, { mode: "timestamp_ms" });
|
|
2906
2276
|
return sqliteTable(name, {
|
|
@@ -2956,6 +2326,36 @@ function outboxTable(engine, options = {}) {
|
|
|
2956
2326
|
function isOutboxTable(value) {
|
|
2957
2327
|
return typeof value === "object" && value !== null && OUTBOX in value;
|
|
2958
2328
|
}
|
|
2329
|
+
/** The rows that record an event: one per listener, due now. */
|
|
2330
|
+
function outboxRows(event, listeners) {
|
|
2331
|
+
return listeners.map((listener) => ({
|
|
2332
|
+
id: deliveryId(event.id, listener),
|
|
2333
|
+
eventId: event.id,
|
|
2334
|
+
listener,
|
|
2335
|
+
name: event.name,
|
|
2336
|
+
payload: event.payload,
|
|
2337
|
+
traceId: event.traceId ?? null,
|
|
2338
|
+
source: event.source ?? null,
|
|
2339
|
+
occurredAt: event.occurredAt,
|
|
2340
|
+
status: "pending",
|
|
2341
|
+
attempts: 0,
|
|
2342
|
+
availableAt: event.occurredAt
|
|
2343
|
+
}));
|
|
2344
|
+
}
|
|
2345
|
+
/** The delivery a row of `outboxRows` is. */
|
|
2346
|
+
function deliveryOf(row) {
|
|
2347
|
+
return {
|
|
2348
|
+
id: row.eventId,
|
|
2349
|
+
name: row.name,
|
|
2350
|
+
payload: row.payload,
|
|
2351
|
+
occurredAt: row.occurredAt.toISOString(),
|
|
2352
|
+
...row.traceId ? { traceId: row.traceId } : {},
|
|
2353
|
+
...row.source ? { source: row.source } : {},
|
|
2354
|
+
listener: row.listener,
|
|
2355
|
+
deliveryId: row.id,
|
|
2356
|
+
attempt: row.attempts
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2959
2359
|
function outboxEngine(table) {
|
|
2960
2360
|
return table[OUTBOX].engine;
|
|
2961
2361
|
}
|
|
@@ -3084,7 +2484,7 @@ async function onTransactionCommit(db, fn) {
|
|
|
3084
2484
|
else await fn();
|
|
3085
2485
|
}
|
|
3086
2486
|
// src/events/dispatcher.ts
|
|
3087
|
-
function resolveDispatchOptions(options
|
|
2487
|
+
function resolveDispatchOptions(options) {
|
|
3088
2488
|
return {
|
|
3089
2489
|
timer: options.timer ?? true,
|
|
3090
2490
|
intervalMs: options.intervalMs ?? 1e3,
|
|
@@ -3096,8 +2496,10 @@ function resolveDispatchOptions(options = {}) {
|
|
|
3096
2496
|
};
|
|
3097
2497
|
}
|
|
3098
2498
|
const PURGE_INTERVAL_MS = 6e4;
|
|
3099
|
-
/**
|
|
3100
|
-
|
|
2499
|
+
/** Listeners whose `retry` threw, logged once each. */
|
|
2500
|
+
const brokenRetry = /* @__PURE__ */ new WeakSet();
|
|
2501
|
+
/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry", and is logged once. */
|
|
2502
|
+
function decideRetry(name, listener, error) {
|
|
3101
2503
|
if (!listener.retry) return "retry";
|
|
3102
2504
|
try {
|
|
3103
2505
|
return listener.retry(error instanceof ActionExecutionError && listener.errors?.[error.code] ? {
|
|
@@ -3109,7 +2511,11 @@ function decideRetry(listener, error) {
|
|
|
3109
2511
|
message: error instanceof Error ? error.message : String(error),
|
|
3110
2512
|
cause: error
|
|
3111
2513
|
});
|
|
3112
|
-
} catch {
|
|
2514
|
+
} catch (thrown) {
|
|
2515
|
+
if (!brokenRetry.has(listener)) {
|
|
2516
|
+
brokenRetry.add(listener);
|
|
2517
|
+
console.error(`[Brick-TS events] Listener '${name}': its retry() threw, so the failure is retried. Later throws are not logged.`, thrown);
|
|
2518
|
+
}
|
|
3113
2519
|
return "retry";
|
|
3114
2520
|
}
|
|
3115
2521
|
}
|
|
@@ -3131,25 +2537,19 @@ var Dispatcher = class {
|
|
|
3131
2537
|
db;
|
|
3132
2538
|
table;
|
|
3133
2539
|
listeners;
|
|
3134
|
-
onError;
|
|
3135
2540
|
engine;
|
|
3136
2541
|
options;
|
|
3137
2542
|
inFlight = /* @__PURE__ */ new Set();
|
|
3138
2543
|
timer;
|
|
3139
2544
|
tickQueue;
|
|
3140
2545
|
lastPurge = 0;
|
|
3141
|
-
constructor(db, table, listeners, options = {}
|
|
2546
|
+
constructor(db, table, listeners, options = {}) {
|
|
3142
2547
|
this.db = db;
|
|
3143
2548
|
this.table = table;
|
|
3144
2549
|
this.listeners = listeners;
|
|
3145
|
-
this.onError = onError;
|
|
3146
2550
|
this.engine = outboxEngine(table);
|
|
3147
2551
|
this.options = resolveDispatchOptions(options);
|
|
3148
2552
|
}
|
|
3149
|
-
/** Whether the dispatcher is looking for work on a timer. */
|
|
3150
|
-
get running() {
|
|
3151
|
-
return this.timer !== void 0;
|
|
3152
|
-
}
|
|
3153
2553
|
/** Start looking for due deliveries on a timer. Does nothing if it already is. */
|
|
3154
2554
|
start() {
|
|
3155
2555
|
if (this.timer || !this.options.timer) return;
|
|
@@ -3157,9 +2557,7 @@ var Dispatcher = class {
|
|
|
3157
2557
|
this.timer.unref?.();
|
|
3158
2558
|
this.tick();
|
|
3159
2559
|
}
|
|
3160
|
-
/**
|
|
3161
|
-
* Stop the timer and wait for the deliveries that are running to finish.
|
|
3162
|
-
*/
|
|
2560
|
+
/** Stop the timer and wait for the deliveries that are running to finish. */
|
|
3163
2561
|
async stop() {
|
|
3164
2562
|
if (this.timer) clearInterval(this.timer);
|
|
3165
2563
|
this.timer = void 0;
|
|
@@ -3171,12 +2569,7 @@ var Dispatcher = class {
|
|
|
3171
2569
|
if (!this.timer) return;
|
|
3172
2570
|
setTimeout(() => void this.tick(), 0).unref?.();
|
|
3173
2571
|
}
|
|
3174
|
-
/**
|
|
3175
|
-
* Claim what is due and run it, once. Used by the timer, and by tests and
|
|
3176
|
-
* workers that drive delivery themselves.
|
|
3177
|
-
*
|
|
3178
|
-
* @returns How many deliveries it started.
|
|
3179
|
-
*/
|
|
2572
|
+
/** Claim what is due and run it, once. @returns How many deliveries it started. */
|
|
3180
2573
|
tick() {
|
|
3181
2574
|
this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(() => this.claimAndRun(), () => this.claimAndRun());
|
|
3182
2575
|
return this.tickQueue;
|
|
@@ -3196,21 +2589,13 @@ var Dispatcher = class {
|
|
|
3196
2589
|
total += started;
|
|
3197
2590
|
}
|
|
3198
2591
|
}
|
|
3199
|
-
/**
|
|
3200
|
-
* How many rows are in each state.
|
|
3201
|
-
*/
|
|
3202
2592
|
async counts() {
|
|
3203
2593
|
const t = this.table;
|
|
3204
2594
|
const rows = await this.db.select({
|
|
3205
2595
|
status: t.status,
|
|
3206
2596
|
count: sql`count(*)`
|
|
3207
2597
|
}).from(t).groupBy(t.status);
|
|
3208
|
-
const counts =
|
|
3209
|
-
pending: 0,
|
|
3210
|
-
claimed: 0,
|
|
3211
|
-
delivered: 0,
|
|
3212
|
-
dead: 0
|
|
3213
|
-
};
|
|
2598
|
+
const counts = Object.fromEntries(OUTBOX_STATUSES.map((status) => [status, 0]));
|
|
3214
2599
|
for (const row of rows) counts[row.status] = Number(row.count);
|
|
3215
2600
|
return counts;
|
|
3216
2601
|
}
|
|
@@ -3244,7 +2629,7 @@ var Dispatcher = class {
|
|
|
3244
2629
|
await this.purgeDelivered();
|
|
3245
2630
|
return rows.length;
|
|
3246
2631
|
} catch (error) {
|
|
3247
|
-
this.
|
|
2632
|
+
this.logError(error);
|
|
3248
2633
|
return 0;
|
|
3249
2634
|
}
|
|
3250
2635
|
}
|
|
@@ -3276,21 +2661,10 @@ var Dispatcher = class {
|
|
|
3276
2661
|
await this.park(row, `No listener named '${row.listener}' is registered`);
|
|
3277
2662
|
return;
|
|
3278
2663
|
}
|
|
3279
|
-
const delivery = {
|
|
3280
|
-
id: row.eventId,
|
|
3281
|
-
name: row.name,
|
|
3282
|
-
payload: row.payload,
|
|
3283
|
-
occurredAt: row.occurredAt.toISOString(),
|
|
3284
|
-
...row.traceId ? { traceId: row.traceId } : {},
|
|
3285
|
-
...row.source ? { source: row.source } : {},
|
|
3286
|
-
listener: row.listener,
|
|
3287
|
-
deliveryId: row.id,
|
|
3288
|
-
attempt: row.attempts
|
|
3289
|
-
};
|
|
3290
2664
|
try {
|
|
3291
|
-
await listener.run(
|
|
2665
|
+
await listener.run(deliveryOf(row));
|
|
3292
2666
|
} catch (error) {
|
|
3293
|
-
await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(listener, error));
|
|
2667
|
+
await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(row.listener, listener, error));
|
|
3294
2668
|
return;
|
|
3295
2669
|
}
|
|
3296
2670
|
await this.markDelivered(row);
|
|
@@ -3305,10 +2679,10 @@ var Dispatcher = class {
|
|
|
3305
2679
|
lastError: null
|
|
3306
2680
|
}).where(eq(t.seq, row.seq));
|
|
3307
2681
|
} catch (error) {
|
|
3308
|
-
this.
|
|
2682
|
+
this.logError(error);
|
|
3309
2683
|
}
|
|
3310
2684
|
}
|
|
3311
|
-
async fail(row, error, maxAttempts, decision
|
|
2685
|
+
async fail(row, error, maxAttempts, decision) {
|
|
3312
2686
|
const message = error instanceof Error ? error.message : String(error);
|
|
3313
2687
|
if (decision === "dead" || row.attempts >= maxAttempts) {
|
|
3314
2688
|
await this.park(row, message);
|
|
@@ -3323,7 +2697,7 @@ var Dispatcher = class {
|
|
|
3323
2697
|
availableAt: new Date(Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs))
|
|
3324
2698
|
}).where(eq(t.seq, row.seq));
|
|
3325
2699
|
} catch (writeError) {
|
|
3326
|
-
this.
|
|
2700
|
+
this.logError(writeError);
|
|
3327
2701
|
}
|
|
3328
2702
|
}
|
|
3329
2703
|
async park(row, message) {
|
|
@@ -3335,9 +2709,12 @@ var Dispatcher = class {
|
|
|
3335
2709
|
claimedAt: null
|
|
3336
2710
|
}).where(eq(t.seq, row.seq));
|
|
3337
2711
|
} catch (error) {
|
|
3338
|
-
this.
|
|
2712
|
+
this.logError(error);
|
|
3339
2713
|
}
|
|
3340
2714
|
}
|
|
2715
|
+
logError(error) {
|
|
2716
|
+
console.error("[Brick-TS events]", error);
|
|
2717
|
+
}
|
|
3341
2718
|
async purgeDelivered() {
|
|
3342
2719
|
const keep = this.options.retainDeliveredMs;
|
|
3343
2720
|
const now = Date.now();
|
|
@@ -3347,26 +2724,114 @@ var Dispatcher = class {
|
|
|
3347
2724
|
await this.db.delete(t).where(and(eq(t.status, "delivered"), lt(t.deliveredAt, new Date(now - keep))));
|
|
3348
2725
|
}
|
|
3349
2726
|
};
|
|
3350
|
-
// src/events/
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
2727
|
+
// src/events/catalog.ts
|
|
2728
|
+
function isEventRef(value) {
|
|
2729
|
+
return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.service === "string" && typeof value.schema === "object";
|
|
2730
|
+
}
|
|
2731
|
+
/** Build `service.events` from its catalog. */
|
|
2732
|
+
function eventRefs(service, catalog) {
|
|
2733
|
+
const refs = Object.create(null);
|
|
2734
|
+
for (const [key, schema] of Object.entries(catalog ?? {})) {
|
|
2735
|
+
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key)) throw new Error(`Event "${key}" in service "${service}" must be a plain name such as shipped or itemAdded`);
|
|
2736
|
+
if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
|
|
2737
|
+
refs[key] = Object.freeze({
|
|
2738
|
+
name: `${service}.${key}`,
|
|
2739
|
+
service,
|
|
2740
|
+
schema
|
|
2741
|
+
});
|
|
3358
2742
|
}
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
2743
|
+
return Object.freeze(refs);
|
|
2744
|
+
}
|
|
2745
|
+
/** @throws When the payload does not match the event's schema. */
|
|
2746
|
+
function checkPayload(ref, payload) {
|
|
2747
|
+
const result = validateWithSchema(ref.schema, payload);
|
|
2748
|
+
if (!result.success) throw new Error(`Event "${ref.name}" payload does not match its schema: ${result.errors.map((error) => `${error.path || "/"} ${error.message}`).join("; ")}`);
|
|
2749
|
+
}
|
|
2750
|
+
/** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
|
|
2751
|
+
const CRUD_EVENT_OPERATIONS = [
|
|
2752
|
+
"create",
|
|
2753
|
+
"update",
|
|
2754
|
+
"delete"
|
|
2755
|
+
];
|
|
2756
|
+
/** The event a CRUD write records: `<resource>.<operation>`. */
|
|
2757
|
+
const crudEventName = (resource, operation) => `${resource}.${operation}`;
|
|
2758
|
+
/** The `source` of a resource's events: `<service>.<resource>`. */
|
|
2759
|
+
const crudEventSource = (service, resource) => `${service}.${resource}`;
|
|
2760
|
+
/** Whether `name` is the CRUD event of one of `resources`. */
|
|
2761
|
+
function isCrudEvent(name, resources) {
|
|
2762
|
+
const dot = name.indexOf(".");
|
|
2763
|
+
return dot > 0 && CRUD_EVENT_OPERATIONS.includes(name.slice(dot + 1)) && resources.includes(name.slice(0, dot));
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* Check an event against the catalog of the service recording it. Without a
|
|
2767
|
+
* catalog any name goes. With one, the name must be `<service>.<event>` from it
|
|
2768
|
+
* (the payload is checked against its schema) or a CRUD event of one of the
|
|
2769
|
+
* service's resources (`<resource>.create|update|delete`).
|
|
2770
|
+
*
|
|
2771
|
+
* @throws When the name is not declared or the payload does not match.
|
|
2772
|
+
*/
|
|
2773
|
+
function checkEvent(service, name, payload) {
|
|
2774
|
+
const prefix = `${service.name}.`;
|
|
2775
|
+
const ref = name.startsWith(prefix) ? service.events[name.slice(prefix.length)] : void 0;
|
|
2776
|
+
if (ref) return checkPayload(ref, payload);
|
|
2777
|
+
if (!service.hasCatalog) return;
|
|
2778
|
+
if (isCrudEvent(name, service.listResources().map((r) => r.name))) return;
|
|
2779
|
+
throw new Error(`Event "${name}" is not in the event catalog of service "${service.name}" (declared: ${Object.values(service.events).map((ref) => ref.name).join(", ") || "none"})`);
|
|
2780
|
+
}
|
|
2781
|
+
// src/events/listener.ts
|
|
2782
|
+
function defineListener(config) {
|
|
2783
|
+
const on = (Array.isArray(config.on) ? config.on : [config.on]).map((item) => isEventRef(item) ? item.name : item);
|
|
2784
|
+
validateListener({
|
|
2785
|
+
...config,
|
|
2786
|
+
on
|
|
2787
|
+
});
|
|
2788
|
+
const helpers = buildErrorHelpers(config.errors);
|
|
2789
|
+
return Object.freeze({
|
|
2790
|
+
name: config.name,
|
|
2791
|
+
on: Object.freeze(on),
|
|
2792
|
+
...config.run !== void 0 ? { run: ((delivery) => config.run(delivery, { error: helpers })) } : {},
|
|
2793
|
+
...config.errors ? { errors: config.errors } : {},
|
|
2794
|
+
...config.retry ? { retry: config.retry } : {},
|
|
2795
|
+
...config.workflow !== void 0 ? { workflow: config.workflow } : {},
|
|
2796
|
+
...config.maxAttempts !== void 0 ? { maxAttempts: config.maxAttempts } : {}
|
|
2797
|
+
});
|
|
3362
2798
|
}
|
|
2799
|
+
/**
|
|
2800
|
+
* @throws When the name is empty or contains `:`, `on` is empty, `maxAttempts`
|
|
2801
|
+
* is not a positive integer, or the listener has both or neither of `run` and
|
|
2802
|
+
* `workflow`.
|
|
2803
|
+
*/
|
|
2804
|
+
function validateListener(listener) {
|
|
2805
|
+
const { name, on, maxAttempts, run, workflow } = listener;
|
|
2806
|
+
if (typeof name !== "string" || !name) throw new Error("An event listener needs a name");
|
|
2807
|
+
if (name.includes(":")) throw new Error(`Event listener name '${name}' must not contain ':'`);
|
|
2808
|
+
if (!Array.isArray(on) || !on.length || on.some((pattern) => !pattern || typeof pattern !== "string")) throw new Error(`Event listener '${name}' listens for nothing`);
|
|
2809
|
+
if (maxAttempts !== void 0 && (!Number.isInteger(maxAttempts) || maxAttempts < 1)) throw new Error(`Event listener '${name}': maxAttempts must be a positive integer`);
|
|
2810
|
+
if (run !== void 0 && workflow !== void 0) throw new Error(`Event listener '${name}' has both run and workflow; give it one`);
|
|
2811
|
+
if (run === void 0 && workflow === void 0) throw new Error(`Event listener '${name}' needs a run handler or a workflow`);
|
|
2812
|
+
if (run !== void 0 && typeof run !== "function") throw new Error(`Event listener '${name}': run must be a function`);
|
|
2813
|
+
if (workflow !== void 0 && typeof workflow !== "function") throw new Error(`Event listener '${name}': workflow must be a function marked "use workflow"`);
|
|
2814
|
+
}
|
|
2815
|
+
/** The deps a plugin's listener runs with, set by the plugin install; `undefined` for the app's own. */
|
|
2816
|
+
const listenerDeps = (listener) => listener[PLUGIN_DEPS];
|
|
3363
2817
|
// src/events/workflows.ts
|
|
3364
|
-
/** `
|
|
3365
|
-
const
|
|
3366
|
-
|
|
2818
|
+
/** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */
|
|
2819
|
+
const WORKFLOW_BUNDLE = {
|
|
2820
|
+
dir: ".well-known/workflow/v1",
|
|
2821
|
+
flow: "flow.mjs",
|
|
2822
|
+
steps: "__step_registrations.mjs",
|
|
2823
|
+
webhook: "webhook.mjs",
|
|
2824
|
+
manifest: "manifest.json"
|
|
2825
|
+
};
|
|
2826
|
+
/** From the Workflow SDK: the queue a workflow run goes to (`getQueueTopicPrefix("workflow")` in `@workflow/world`), and the header a world names it in. */
|
|
2827
|
+
const WORKFLOW_QUEUE = {
|
|
2828
|
+
prefix: "__wkf_workflow_",
|
|
2829
|
+
header: "x-vqs-queue-name"
|
|
2830
|
+
};
|
|
3367
2831
|
const STOPPED = "The events were stopped, so workflows can no longer run";
|
|
2832
|
+
const NOT_BUILT = "brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.";
|
|
3368
2833
|
/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */
|
|
3369
|
-
const WEBHOOK_ROUTE =
|
|
2834
|
+
const WEBHOOK_ROUTE = `/${WORKFLOW_BUNDLE.dir}/webhook/*`;
|
|
3370
2835
|
/** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */
|
|
3371
2836
|
const STEP_REGISTRY = Symbol.for("@workflow/core//registeredSteps");
|
|
3372
2837
|
/**
|
|
@@ -3381,7 +2846,7 @@ function resolveWorkflowPaths(options = {}) {
|
|
|
3381
2846
|
const root = resolve(options.root ?? process.cwd());
|
|
3382
2847
|
return {
|
|
3383
2848
|
root,
|
|
3384
|
-
dir: join(root,
|
|
2849
|
+
dir: join(root, WORKFLOW_BUNDLE.dir)
|
|
3385
2850
|
};
|
|
3386
2851
|
}
|
|
3387
2852
|
/**
|
|
@@ -3418,16 +2883,15 @@ var WorkflowRuntime = class {
|
|
|
3418
2883
|
*
|
|
3419
2884
|
* @param listener - The workflow listener the delivery is for.
|
|
3420
2885
|
* @param delivery - The delivery.
|
|
3421
|
-
* @returns The run id.
|
|
3422
2886
|
*/
|
|
3423
2887
|
async startRun(listener, delivery) {
|
|
3424
2888
|
const sdk = await this.ensure();
|
|
3425
2889
|
const { attempt: _attempt, ...event } = delivery;
|
|
3426
|
-
|
|
2890
|
+
await sdk.start(listener.workflow, [event], {
|
|
3427
2891
|
world: this.world,
|
|
3428
2892
|
runKey: delivery.deliveryId,
|
|
3429
2893
|
runKeyTime: Date.parse(delivery.occurredAt)
|
|
3430
|
-
})
|
|
2894
|
+
});
|
|
3431
2895
|
}
|
|
3432
2896
|
/**
|
|
3433
2897
|
* Answer a request to a webhook a workflow created with `createWebhook`, by
|
|
@@ -3440,8 +2904,8 @@ var WorkflowRuntime = class {
|
|
|
3440
2904
|
*/
|
|
3441
2905
|
async handleWebhook(request) {
|
|
3442
2906
|
await this.connect();
|
|
3443
|
-
const file = join(this.dir,
|
|
3444
|
-
if (!existsSync(file)) throw new Error(`No webhook bundle at ${file}.
|
|
2907
|
+
const file = join(this.dir, WORKFLOW_BUNDLE.webhook);
|
|
2908
|
+
if (!existsSync(file)) throw new Error(`No webhook bundle at ${file}. ${NOT_BUILT}`);
|
|
3445
2909
|
const handler = (await import(pathToFileURL(file).href))[request.method];
|
|
3446
2910
|
if (typeof handler !== "function") return new Response(null, { status: 405 });
|
|
3447
2911
|
return handler(request);
|
|
@@ -3476,16 +2940,16 @@ var WorkflowRuntime = class {
|
|
|
3476
2940
|
async initialize() {
|
|
3477
2941
|
if (typeof this.world.createRunId !== "function") throw new Error("This world cannot name a run after its key, so an event delivered twice would start two runs. Use the world from @brickkit/redis-world or @brickkit/bullmq-world.");
|
|
3478
2942
|
const sdk = await this.connect();
|
|
3479
|
-
const flow = join(this.dir,
|
|
3480
|
-
if (!existsSync(flow)) throw new Error(`No workflow bundle at ${flow}.
|
|
2943
|
+
const flow = join(this.dir, WORKFLOW_BUNDLE.flow);
|
|
2944
|
+
if (!existsSync(flow)) throw new Error(`No workflow bundle at ${flow}. ${NOT_BUILT}`);
|
|
3481
2945
|
const manifest = this.readManifest();
|
|
3482
2946
|
const depsOf = this.checkListeners(manifest);
|
|
3483
2947
|
const bundle = await this.loadBundle(flow);
|
|
3484
2948
|
if (typeof bundle.POST !== "function") throw new Error(`${flow} does not export a POST handler`);
|
|
3485
2949
|
const post = bundle.POST;
|
|
3486
|
-
this.world.registerHandler?.(
|
|
3487
|
-
const queue = request.headers.get(
|
|
3488
|
-
return runWithDeps(depsOf.get(queue.slice(
|
|
2950
|
+
this.world.registerHandler?.(WORKFLOW_QUEUE.prefix, (request) => {
|
|
2951
|
+
const queue = request.headers.get(WORKFLOW_QUEUE.header) ?? "";
|
|
2952
|
+
return runWithDeps(depsOf.get(queue.slice(WORKFLOW_QUEUE.prefix.length)) ?? this.deps, () => post(request));
|
|
3489
2953
|
});
|
|
3490
2954
|
await this.world.start?.();
|
|
3491
2955
|
return sdk;
|
|
@@ -3523,7 +2987,7 @@ var WorkflowRuntime = class {
|
|
|
3523
2987
|
return bundle;
|
|
3524
2988
|
}
|
|
3525
2989
|
readManifest() {
|
|
3526
|
-
const path = join(this.dir,
|
|
2990
|
+
const path = join(this.dir, WORKFLOW_BUNDLE.manifest);
|
|
3527
2991
|
if (!existsSync(path)) return void 0;
|
|
3528
2992
|
return JSON.parse(readFileSync(path, "utf8"));
|
|
3529
2993
|
}
|
|
@@ -3545,7 +3009,7 @@ var WorkflowRuntime = class {
|
|
|
3545
3009
|
const id = listener.workflow?.workflowId;
|
|
3546
3010
|
if (typeof id !== "string") throw new Error(`The workflow of listener '${listener.name}' was not transformed. Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.`);
|
|
3547
3011
|
if (manifest && !known.has(id)) throw new Error(`The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`);
|
|
3548
|
-
const deps = listener
|
|
3012
|
+
const deps = listenerDeps(listener) ?? this.deps;
|
|
3549
3013
|
if ((depsOf.get(id) ?? deps) !== deps) throw new Error(`Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`);
|
|
3550
3014
|
depsOf.set(id, deps);
|
|
3551
3015
|
}
|
|
@@ -3558,9 +3022,9 @@ function matchesEvent(pattern, name) {
|
|
|
3558
3022
|
if (pattern.endsWith("*")) return name.startsWith(pattern.slice(0, -1));
|
|
3559
3023
|
return pattern === name;
|
|
3560
3024
|
}
|
|
3561
|
-
/** The
|
|
3562
|
-
const
|
|
3563
|
-
const startedHubs = globalThis[Symbol.for(
|
|
3025
|
+
/** The service of each database that records events, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */
|
|
3026
|
+
const recordingServices = /* @__PURE__ */ new WeakMap();
|
|
3027
|
+
const startedHubs = globalThis[Symbol.for(GLOBAL_SYMBOL.eventsStarted)] ??= /* @__PURE__ */ new Set();
|
|
3564
3028
|
/**
|
|
3565
3029
|
* Stop every events hub started in this process, by any copy of `@brickkit/core`,
|
|
3566
3030
|
* and wait for their deliveries. A hub that fails to stop does not cut the wait
|
|
@@ -3593,11 +3057,8 @@ var EventsHub = class {
|
|
|
3593
3057
|
constructor(options, deps = {}) {
|
|
3594
3058
|
this.deps = deps;
|
|
3595
3059
|
for (const listener of options.listeners ?? []) {
|
|
3596
|
-
|
|
3597
|
-
if (listener.name
|
|
3598
|
-
if (!listener.on?.length) throw new Error(`Event listener '${listener.name}' listens for nothing`);
|
|
3599
|
-
if (this.byName.has(listener.name)) throw new Error(`Duplicate event listener '${listener.name}'`);
|
|
3600
|
-
if (!listener.run === !listener.workflow) throw new Error(`Event listener '${listener.name}' needs exactly one of run and workflow`);
|
|
3060
|
+
validateListener(listener);
|
|
3061
|
+
if (this.byName.has(listener.name)) throw new DuplicateNameError(`Duplicate event listener '${listener.name}'`);
|
|
3601
3062
|
this.byName.set(listener.name, listener);
|
|
3602
3063
|
}
|
|
3603
3064
|
const workflowListeners = [...this.byName.values()].filter((listener) => listener.workflow);
|
|
@@ -3616,31 +3077,23 @@ var EventsHub = class {
|
|
|
3616
3077
|
* @returns The hub, for chaining.
|
|
3617
3078
|
*/
|
|
3618
3079
|
attach(services) {
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
const table = service.getOutbox?.();
|
|
3080
|
+
for (const service of services.map(portOf)) {
|
|
3081
|
+
const table = service.getOutbox();
|
|
3622
3082
|
if (!table) continue;
|
|
3623
|
-
attached++;
|
|
3624
3083
|
this.recorderNames.push(service.name);
|
|
3625
|
-
|
|
3626
|
-
service.setRecorder?.(bound);
|
|
3084
|
+
service.setRecorder(this.bind(table, (name, payload) => service.checkEvent(name, payload)));
|
|
3627
3085
|
const db = service.getDb();
|
|
3628
|
-
if (db && typeof db === "object")
|
|
3629
|
-
|
|
3630
|
-
if (attached === 0 && this.byName.size > 0) console.warn("[Brick-TS] events are configured, but no service database has an outbox table. Add outboxTable() to a database's tables so its writes can record events.");
|
|
3631
|
-
for (const service of services) {
|
|
3632
|
-
const table = service.getOutbox?.();
|
|
3633
|
-
if (table && !this.dispatchers.has(table)) this.dispatchers.set(table, new Dispatcher(service.getDb(), table, (name) => this.deliverable(name), this.dispatchOptions || {}));
|
|
3086
|
+
if (db && typeof db === "object") recordingServices.set(db, service);
|
|
3087
|
+
if (!this.dispatchers.has(table)) this.dispatchers.set(table, new Dispatcher(db, table, (name) => this.deliverable(name), this.dispatchOptions || {}));
|
|
3634
3088
|
}
|
|
3089
|
+
if (this.recorderNames.length === 0 && this.byName.size > 0) console.warn("[Brick-TS] events are configured, but no service database has an outbox table. Add outboxTable() to a database's tables so its writes can record events.");
|
|
3635
3090
|
return this;
|
|
3636
3091
|
}
|
|
3637
|
-
/** The listeners that want an event. */
|
|
3638
3092
|
matching(name) {
|
|
3639
3093
|
const found = [];
|
|
3640
3094
|
for (const listener of this.byName.values()) if (listener.on.some((pattern) => matchesEvent(pattern, name))) found.push(listener);
|
|
3641
3095
|
return found;
|
|
3642
3096
|
}
|
|
3643
|
-
/** The listeners and settings, as plain data. */
|
|
3644
3097
|
describe() {
|
|
3645
3098
|
return {
|
|
3646
3099
|
listeners: [...this.byName.values()].map((listener) => ({
|
|
@@ -3714,15 +3167,10 @@ var EventsHub = class {
|
|
|
3714
3167
|
}
|
|
3715
3168
|
/** How many rows are in each state, across the app's outbox tables. */
|
|
3716
3169
|
async counts() {
|
|
3717
|
-
const total =
|
|
3718
|
-
pending: 0,
|
|
3719
|
-
claimed: 0,
|
|
3720
|
-
delivered: 0,
|
|
3721
|
-
dead: 0
|
|
3722
|
-
};
|
|
3170
|
+
const total = Object.fromEntries(OUTBOX_STATUSES.map((status) => [status, 0]));
|
|
3723
3171
|
for (const dispatcher of this.dispatchers.values()) {
|
|
3724
3172
|
const counts = await dispatcher.counts();
|
|
3725
|
-
for (const status of
|
|
3173
|
+
for (const status of OUTBOX_STATUSES) total[status] += counts[status];
|
|
3726
3174
|
}
|
|
3727
3175
|
return total;
|
|
3728
3176
|
}
|
|
@@ -3742,19 +3190,13 @@ var EventsHub = class {
|
|
|
3742
3190
|
if (!listener) return void 0;
|
|
3743
3191
|
let found = this.deliverables.get(name);
|
|
3744
3192
|
if (!found) {
|
|
3745
|
-
const
|
|
3193
|
+
const { run, workflow, maxAttempts, errors, retry } = listener;
|
|
3194
|
+
const deps = listenerDeps(listener) ?? this.deps;
|
|
3746
3195
|
found = {
|
|
3747
|
-
...
|
|
3748
|
-
...
|
|
3749
|
-
...
|
|
3750
|
-
|
|
3751
|
-
run: async (delivery) => {
|
|
3752
|
-
await runtime.startRun(listener, delivery);
|
|
3753
|
-
}
|
|
3754
|
-
} : {
|
|
3755
|
-
...listener.maxAttempts !== void 0 ? { maxAttempts: listener.maxAttempts } : {},
|
|
3756
|
-
run: (delivery) => runWithDeps(this.deps, () => listener.run(delivery))
|
|
3757
|
-
}
|
|
3196
|
+
...errors ? { errors } : {},
|
|
3197
|
+
...retry ? { retry } : {},
|
|
3198
|
+
...maxAttempts !== void 0 ? { maxAttempts } : {},
|
|
3199
|
+
run: workflow ? (delivery) => this.runtime.startRun(listener, delivery) : (delivery) => runWithDeps(deps, () => run(delivery))
|
|
3758
3200
|
};
|
|
3759
3201
|
this.deliverables.set(name, found);
|
|
3760
3202
|
}
|
|
@@ -3769,21 +3211,13 @@ var EventsHub = class {
|
|
|
3769
3211
|
check(name, payload);
|
|
3770
3212
|
const listeners = this.matching(name);
|
|
3771
3213
|
if (!listeners.length) return false;
|
|
3772
|
-
|
|
3773
|
-
|
|
3774
|
-
await tx.insert(table).values(listeners.map((listener) => ({
|
|
3775
|
-
id: `${eventId}:${listener.name}`,
|
|
3776
|
-
eventId,
|
|
3777
|
-
listener: listener.name,
|
|
3214
|
+
await tx.insert(table).values(outboxRows({
|
|
3215
|
+
id: newEventId(),
|
|
3778
3216
|
name,
|
|
3779
3217
|
payload,
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
status: "pending",
|
|
3784
|
-
attempts: 0,
|
|
3785
|
-
availableAt: occurredAt
|
|
3786
|
-
})));
|
|
3218
|
+
occurredAt: /* @__PURE__ */ new Date(),
|
|
3219
|
+
...context
|
|
3220
|
+
}, listeners.map((listener) => listener.name)));
|
|
3787
3221
|
return true;
|
|
3788
3222
|
};
|
|
3789
3223
|
return {
|
|
@@ -3805,18 +3239,57 @@ var EventsHub = class {
|
|
|
3805
3239
|
};
|
|
3806
3240
|
}
|
|
3807
3241
|
};
|
|
3242
|
+
// src/cors.ts
|
|
3243
|
+
/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */
|
|
3244
|
+
function publicOrigin(request) {
|
|
3245
|
+
const forwarded = (name) => request.headers.get(name)?.split(",")[0]?.trim() || void 0;
|
|
3246
|
+
const url = new URL(request.url);
|
|
3247
|
+
const proto = forwarded("x-forwarded-proto");
|
|
3248
|
+
return `${proto ? `${proto}:` : url.protocol}//${forwarded("x-forwarded-host") ?? url.host}`;
|
|
3249
|
+
}
|
|
3250
|
+
const METHODS = "GET, POST, PUT, PATCH, DELETE";
|
|
3251
|
+
/**
|
|
3252
|
+
* A request hook that adds CORS headers for allowed origins and answers
|
|
3253
|
+
* preflights. An origin that doesn't match gets no `Access-Control-Allow-Origin`,
|
|
3254
|
+
* so the browser blocks it; origins are compared exactly and never reflected
|
|
3255
|
+
* unless the rule allows them.
|
|
3256
|
+
*/
|
|
3257
|
+
function corsHook(cors) {
|
|
3258
|
+
const { origin = true, credentials = false } = typeof cors === "object" && !Array.isArray(cors) ? cors : { origin: cors };
|
|
3259
|
+
const list = typeof origin === "string" ? [origin] : Array.isArray(origin) ? origin : void 0;
|
|
3260
|
+
if (list?.includes("*")) throw new Error("Brick: cors origin \"*\" is not supported. List the origins, or pass a predicate.");
|
|
3261
|
+
const allows = (from, request) => origin === true ? from === publicOrigin(request) : typeof origin === "function" ? origin(from, request) === true : list.includes(from);
|
|
3262
|
+
return ({ request, set }) => {
|
|
3263
|
+
const from = request.headers.get("origin");
|
|
3264
|
+
if (from === null) return;
|
|
3265
|
+
const headers = { vary: "Origin" };
|
|
3266
|
+
if (allows(from, request)) {
|
|
3267
|
+
headers["access-control-allow-origin"] = from;
|
|
3268
|
+
if (credentials) headers["access-control-allow-credentials"] = "true";
|
|
3269
|
+
}
|
|
3270
|
+
if (!(request.method === "OPTIONS" && request.headers.has("access-control-request-method"))) {
|
|
3271
|
+
Object.assign(set.headers, headers);
|
|
3272
|
+
return;
|
|
3273
|
+
}
|
|
3274
|
+
if (headers["access-control-allow-origin"]) {
|
|
3275
|
+
headers["access-control-allow-methods"] = METHODS;
|
|
3276
|
+
const requested = request.headers.get("access-control-request-headers");
|
|
3277
|
+
if (requested) headers["access-control-allow-headers"] = requested;
|
|
3278
|
+
}
|
|
3279
|
+
return new Response(null, {
|
|
3280
|
+
status: 204,
|
|
3281
|
+
headers
|
|
3282
|
+
});
|
|
3283
|
+
};
|
|
3284
|
+
}
|
|
3808
3285
|
// src/socket.ts
|
|
3809
3286
|
var SocketDenied = class extends Error {};
|
|
3810
|
-
const bytes = (value) => new TextEncoder().encode(value).byteLength;
|
|
3811
3287
|
/** Validates and serializes one output message, rechecking what survives JSON. */
|
|
3812
3288
|
function outputFrame(output, event, data) {
|
|
3813
3289
|
const schema = Object.hasOwn(output, event) ? output[event] : void 0;
|
|
3814
3290
|
if (!schema || !getCompiledCheck(schema).Check(data)) throw new Error("Invalid socket output");
|
|
3815
|
-
const frame =
|
|
3816
|
-
|
|
3817
|
-
data
|
|
3818
|
-
});
|
|
3819
|
-
if (bytes(frame) > 65536) throw new Error("Socket output too large");
|
|
3291
|
+
const frame = encodeFrame(event, data);
|
|
3292
|
+
if (byteLength(frame) > 65536) throw new Error("Socket output too large");
|
|
3820
3293
|
if (!getCompiledCheck(schema).Check(JSON.parse(frame).data)) throw new Error("Socket output is not JSON-compatible");
|
|
3821
3294
|
return frame;
|
|
3822
3295
|
}
|
|
@@ -3892,7 +3365,7 @@ function defineServiceSocket(service, config, resolve) {
|
|
|
3892
3365
|
const output = Object.freeze({ ...config.output });
|
|
3893
3366
|
const handlers = { ...config.handlers };
|
|
3894
3367
|
if (Object.keys(input).length !== Object.keys(handlers).length || Object.keys(input).some((key) => !Object.hasOwn(handlers, key) || typeof handlers[key] !== "function")) throw new Error("Every socket input event needs exactly one handler");
|
|
3895
|
-
if ([...Object.keys(input), ...Object.keys(output)].some(
|
|
3368
|
+
if ([...Object.keys(input), ...Object.keys(output)].some(isControlEvent)) throw new Error("Socket event names starting with $ are reserved");
|
|
3896
3369
|
const maxRooms = config.maxRooms ?? 100;
|
|
3897
3370
|
if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
|
|
3898
3371
|
const replay = config.replay && { ...config.replay };
|
|
@@ -3944,9 +3417,10 @@ function defineServiceSocket(service, config, resolve) {
|
|
|
3944
3417
|
handle: {
|
|
3945
3418
|
name: config.name,
|
|
3946
3419
|
emit(rooms, ...[event, payload, options]) {
|
|
3947
|
-
const
|
|
3420
|
+
const unique = [...new Set(typeof rooms === "string" ? [rooms] : rooms)];
|
|
3421
|
+
const topics = unique.map(topic);
|
|
3948
3422
|
const frame = outputFrame(output, event, payload);
|
|
3949
|
-
if (replay &&
|
|
3423
|
+
if (replay && unique.some((room) => byteLength(frame) + replayHeadroom(room) > 65536)) throw new Error("Socket output too large");
|
|
3950
3424
|
publish(topics.map((topic) => ({
|
|
3951
3425
|
type: "emit",
|
|
3952
3426
|
topic,
|
|
@@ -4011,26 +3485,18 @@ function defineServiceSocket(service, config, resolve) {
|
|
|
4011
3485
|
function socketPath(prefix, service, socket) {
|
|
4012
3486
|
return joinRoute(ownerPath(prefix, service), socket.schema.path ?? `/${kebabCase(socket.schema.name)}`);
|
|
4013
3487
|
}
|
|
4014
|
-
/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */
|
|
4015
|
-
function publicOrigin(request) {
|
|
4016
|
-
const forwarded = (name) => request.headers.get(name)?.split(",")[0]?.trim() || void 0;
|
|
4017
|
-
const url = new URL(request.url);
|
|
4018
|
-
const proto = forwarded("x-forwarded-proto");
|
|
4019
|
-
return `${proto ? `${proto}:` : url.protocol}//${forwarded("x-forwarded-host") ?? url.host}`;
|
|
4020
|
-
}
|
|
4021
|
-
const TOKEN_PROTOCOL = "brick.token.";
|
|
4022
3488
|
const protocols = (request) => (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((protocol) => protocol.trim()).filter(Boolean);
|
|
4023
3489
|
/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */
|
|
4024
3490
|
function tokenRequest(request) {
|
|
4025
3491
|
const offered = protocols(request);
|
|
4026
|
-
const token = offered.find((protocol) => protocol.startsWith(
|
|
3492
|
+
const token = offered.find((protocol) => protocol.startsWith(SOCKET_TOKEN_PROTOCOL))?.slice(SOCKET_TOKEN_PROTOCOL.length);
|
|
4027
3493
|
if (!token) return {
|
|
4028
3494
|
token: false,
|
|
4029
3495
|
request
|
|
4030
3496
|
};
|
|
4031
3497
|
const headers = new Headers(request.headers);
|
|
4032
3498
|
headers.set("authorization", `Bearer ${token}`);
|
|
4033
|
-
const rest = offered.filter((protocol) => !protocol.startsWith(
|
|
3499
|
+
const rest = offered.filter((protocol) => !protocol.startsWith(SOCKET_TOKEN_PROTOCOL));
|
|
4034
3500
|
if (rest.length) headers.set("sec-websocket-protocol", rest.join(", "));
|
|
4035
3501
|
else headers.delete("sec-websocket-protocol");
|
|
4036
3502
|
return {
|
|
@@ -4041,14 +3507,14 @@ function tokenRequest(request) {
|
|
|
4041
3507
|
})
|
|
4042
3508
|
};
|
|
4043
3509
|
}
|
|
4044
|
-
/**
|
|
3510
|
+
/** Each connection owns its queue and service session. */
|
|
4045
3511
|
function mountSockets(app, sockets, broker, secret) {
|
|
4046
3512
|
if (secret === "") throw new Error("Brick: sockets.secret can't be empty");
|
|
4047
3513
|
const key = secret ?? randomBytes(32);
|
|
4048
3514
|
const signature = (topic, seq) => createHmac("sha256", key).update(`${topic}\n${seq}`).digest("base64url").slice(0, 22);
|
|
4049
|
-
const sign = (topic, seq) =>
|
|
3515
|
+
const sign = (topic, seq) => signSeq(seq, signature(topic, seq));
|
|
4050
3516
|
const verify = (topic, signed) => {
|
|
4051
|
-
const [seq, sig] = signed
|
|
3517
|
+
const [seq, sig] = splitSeq(signed);
|
|
4052
3518
|
return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq))) ? seq : void 0;
|
|
4053
3519
|
};
|
|
4054
3520
|
if (sockets.some(({ definition }) => definition.replay) && !(broker.head && broker.history)) throw new Error("Brick: the socket broker does not support replay");
|
|
@@ -4070,10 +3536,7 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4070
3536
|
const roomOf = (topic) => topic.slice(definition.topicPrefix.length);
|
|
4071
3537
|
const holders = /* @__PURE__ */ new Map();
|
|
4072
3538
|
const control = (ws, event, data) => {
|
|
4073
|
-
if (ws.readyState === 1) ws.send(
|
|
4074
|
-
event,
|
|
4075
|
-
data
|
|
4076
|
-
}));
|
|
3539
|
+
if (ws.readyState === 1) ws.send(encodeFrame(event, data));
|
|
4077
3540
|
};
|
|
4078
3541
|
/** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */
|
|
4079
3542
|
const enter = async (connection, topic, live = true) => {
|
|
@@ -4101,8 +3564,7 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4101
3564
|
holders.delete(topic);
|
|
4102
3565
|
holder.unsubscribe();
|
|
4103
3566
|
};
|
|
4104
|
-
|
|
4105
|
-
const frameOf = (message) => message.seq === void 0 ? message.frame : `${message.frame.slice(0, -1)},"room":${JSON.stringify(roomOf(message.topic))},"seq":${JSON.stringify(sign(message.topic, message.seq))}}`;
|
|
3567
|
+
const frameOf = (message) => message.seq === void 0 ? message.frame : replayFrame(message.frame, roomOf(message.topic), sign(message.topic, message.seq));
|
|
4106
3568
|
const deliver = (message) => {
|
|
4107
3569
|
if (message.type === "emit") {
|
|
4108
3570
|
app.server?.publish(message.topic, frameOf(message));
|
|
@@ -4111,7 +3573,7 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4111
3573
|
for (const connection of holders.get(message.topic)?.connections ?? []) {
|
|
4112
3574
|
if (message.also && !connection.ws.isSubscribed(message.also)) continue;
|
|
4113
3575
|
exit(connection, message.topic);
|
|
4114
|
-
control(connection.ws,
|
|
3576
|
+
control(connection.ws, SOCKET_CONTROL.left, {
|
|
4115
3577
|
room: roomOf(message.topic),
|
|
4116
3578
|
...message.reason !== void 0 ? { reason: message.reason } : {}
|
|
4117
3579
|
});
|
|
@@ -4122,9 +3584,9 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4122
3584
|
const { room: name, since } = data && typeof data === "object" ? data : {};
|
|
4123
3585
|
if (!isSocketRoom(name) || since !== void 0 && !isSocketSeq(since)) throw new SocketDenied();
|
|
4124
3586
|
const topic = definition.topic(name);
|
|
4125
|
-
if (event ===
|
|
3587
|
+
if (event === SOCKET_CONTROL.leave) {
|
|
4126
3588
|
if (connection.requested.has(topic)) exit(connection, topic);
|
|
4127
|
-
control(connection.ws,
|
|
3589
|
+
control(connection.ws, SOCKET_CONTROL.leave, { room: name });
|
|
4128
3590
|
return;
|
|
4129
3591
|
}
|
|
4130
3592
|
const isOpen = () => !connection.closed && connection.ws.readyState === 1;
|
|
@@ -4145,20 +3607,23 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4145
3607
|
connection.ws.subscribe(topic);
|
|
4146
3608
|
if (since === void 0) seq = sign(topic, start);
|
|
4147
3609
|
for (const message of missed ?? []) if (message.type === "emit") connection.ws.send(frameOf(message));
|
|
4148
|
-
if (restart !== void 0) control(connection.ws,
|
|
3610
|
+
if (restart !== void 0) control(connection.ws, SOCKET_CONTROL.gap, {
|
|
4149
3611
|
room: name,
|
|
4150
3612
|
seq: sign(topic, restart)
|
|
4151
3613
|
});
|
|
4152
3614
|
}
|
|
4153
3615
|
}
|
|
4154
3616
|
}
|
|
4155
|
-
control(connection.ws,
|
|
3617
|
+
control(connection.ws, SOCKET_CONTROL.join, {
|
|
4156
3618
|
room: name,
|
|
4157
3619
|
ok: ok && connection.rooms.has(topic),
|
|
4158
3620
|
...seq !== void 0 ? { seq } : {}
|
|
4159
3621
|
});
|
|
4160
3622
|
};
|
|
4161
|
-
const raisable =
|
|
3623
|
+
const raisable = {
|
|
3624
|
+
...STANDARD_ERRORS,
|
|
3625
|
+
...definition.errors
|
|
3626
|
+
};
|
|
4162
3627
|
const fail = (ws, error) => {
|
|
4163
3628
|
if (!(error instanceof SocketDenied)) logger.error({
|
|
4164
3629
|
error,
|
|
@@ -4166,7 +3631,7 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4166
3631
|
socket: definition.schema.name
|
|
4167
3632
|
});
|
|
4168
3633
|
if (ws.readyState !== 1) return;
|
|
4169
|
-
ws.close(error instanceof SocketDenied ?
|
|
3634
|
+
ws.close(error instanceof SocketDenied ? SOCKET_CLOSE.policy : SOCKET_CLOSE.serverError, error instanceof SocketDenied ? "Message refused" : "Socket handler failed");
|
|
4170
3635
|
};
|
|
4171
3636
|
app.ws(path, {
|
|
4172
3637
|
async beforeHandle({ request }) {
|
|
@@ -4185,11 +3650,11 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4185
3650
|
return new Response("Socket connection refused", { status: error instanceof SocketDenied ? 403 : 500 });
|
|
4186
3651
|
}
|
|
4187
3652
|
},
|
|
4188
|
-
upgrade: ({ request }) => protocols(request).includes("brick.v1") ? { "Sec-WebSocket-Protocol":
|
|
3653
|
+
upgrade: ({ request }) => protocols(request).includes("brick.v1") ? { "Sec-WebSocket-Protocol": SOCKET_PROTOCOL } : void 0,
|
|
4189
3654
|
async open(ws) {
|
|
4190
3655
|
const session = sessions.get(ws.request);
|
|
4191
3656
|
if (!session) {
|
|
4192
|
-
ws.close(
|
|
3657
|
+
ws.close(SOCKET_CLOSE.serverError, "Missing socket session");
|
|
4193
3658
|
return;
|
|
4194
3659
|
}
|
|
4195
3660
|
const sender = {
|
|
@@ -4197,12 +3662,12 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4197
3662
|
return !state.closed && ws.readyState === 1;
|
|
4198
3663
|
},
|
|
4199
3664
|
close() {
|
|
4200
|
-
ws.close(
|
|
3665
|
+
ws.close(SOCKET_CLOSE.normal, "");
|
|
4201
3666
|
},
|
|
4202
3667
|
send(event, data) {
|
|
4203
3668
|
if (!sender.isOpen) throw new Error("Socket is closed");
|
|
4204
3669
|
if (ws.send(outputFrame(definition.output, event, data)) === 0) {
|
|
4205
|
-
ws.close(
|
|
3670
|
+
ws.close(SOCKET_CLOSE.tryAgainLater, "Socket buffer full");
|
|
4206
3671
|
throw new Error("Socket buffer full");
|
|
4207
3672
|
}
|
|
4208
3673
|
}
|
|
@@ -4230,45 +3695,39 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4230
3695
|
const state = connections.get(ws.request);
|
|
4231
3696
|
if (!state || state.closed || ws.readyState !== 1) return;
|
|
4232
3697
|
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
4233
|
-
ws.close(
|
|
3698
|
+
ws.close(SOCKET_CLOSE.unsupportedData, "Only JSON text is supported");
|
|
4234
3699
|
return;
|
|
4235
3700
|
}
|
|
4236
3701
|
if (typeof value === "string") {
|
|
4237
|
-
ws.close(
|
|
3702
|
+
ws.close(SOCKET_CLOSE.invalidPayload, "Expected JSON envelope");
|
|
4238
3703
|
return;
|
|
4239
3704
|
}
|
|
4240
3705
|
if (!isSocketEnvelope(value)) {
|
|
4241
|
-
ws.close(
|
|
3706
|
+
ws.close(SOCKET_CLOSE.policy, "Invalid socket envelope");
|
|
4242
3707
|
return;
|
|
4243
3708
|
}
|
|
4244
|
-
const size =
|
|
3709
|
+
const size = byteLength(JSON.stringify(value));
|
|
4245
3710
|
if (size > 65536) {
|
|
4246
|
-
ws.close(
|
|
3711
|
+
ws.close(SOCKET_CLOSE.tooLarge, "Message too large");
|
|
4247
3712
|
return;
|
|
4248
3713
|
}
|
|
4249
3714
|
if (state.pending >= 32 || state.bytes + size > 1048576) {
|
|
4250
|
-
ws.close(
|
|
3715
|
+
ws.close(SOCKET_CLOSE.tryAgainLater, "Socket queue full");
|
|
4251
3716
|
return;
|
|
4252
3717
|
}
|
|
4253
3718
|
state.pending++;
|
|
4254
3719
|
state.bytes += size;
|
|
4255
3720
|
state.tail = state.tail.then(async () => {
|
|
4256
3721
|
if (state.closed || ws.readyState !== 1) return;
|
|
4257
|
-
if (value.event ===
|
|
3722
|
+
if (value.event === SOCKET_CONTROL.join || value.event === SOCKET_CONTROL.leave) await room(state, value.event, value.data);
|
|
4258
3723
|
else await state.session.message(value.event, value.data, state.sender);
|
|
4259
3724
|
}).catch((error) => {
|
|
4260
|
-
if (error instanceof ActionExecutionError && !state.closed && value.event !==
|
|
4261
|
-
const frame =
|
|
4262
|
-
event:
|
|
4263
|
-
|
|
4264
|
-
event: value.event,
|
|
4265
|
-
code: error.code,
|
|
4266
|
-
message: error.message,
|
|
4267
|
-
status: error.status,
|
|
4268
|
-
...error.details !== void 0 ? { details: error.details } : {}
|
|
4269
|
-
}
|
|
3725
|
+
if (error instanceof ActionExecutionError && !state.closed && value.event !== SOCKET_CONTROL.join && value.event !== SOCKET_CONTROL.leave && Object.hasOwn(raisable, error.code)) try {
|
|
3726
|
+
const frame = encodeFrame(SOCKET_CONTROL.error, {
|
|
3727
|
+
event: value.event,
|
|
3728
|
+
...error.toJSON()
|
|
4270
3729
|
});
|
|
4271
|
-
if (
|
|
3730
|
+
if (byteLength(frame) > 65536) throw new Error("Socket error too large", { cause: error });
|
|
4272
3731
|
if (ws.readyState === 1) ws.send(frame);
|
|
4273
3732
|
return;
|
|
4274
3733
|
} catch (unsent) {
|
|
@@ -4301,42 +3760,6 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4301
3760
|
});
|
|
4302
3761
|
}
|
|
4303
3762
|
}
|
|
4304
|
-
// src/cors.ts
|
|
4305
|
-
const METHODS = "GET, POST, PUT, PATCH, DELETE";
|
|
4306
|
-
/**
|
|
4307
|
-
* A request hook that adds CORS headers for allowed origins and answers
|
|
4308
|
-
* preflights. An origin that doesn't match gets no `Access-Control-Allow-Origin`,
|
|
4309
|
-
* so the browser blocks it; origins are compared exactly and never reflected
|
|
4310
|
-
* unless the rule allows them.
|
|
4311
|
-
*/
|
|
4312
|
-
function corsHook(cors) {
|
|
4313
|
-
const { origin = true, credentials = false } = typeof cors === "object" && !Array.isArray(cors) ? cors : { origin: cors };
|
|
4314
|
-
const list = typeof origin === "string" ? [origin] : Array.isArray(origin) ? origin : void 0;
|
|
4315
|
-
if (list?.includes("*")) throw new Error("Brick: cors origin \"*\" is not supported. List the origins, or pass a predicate.");
|
|
4316
|
-
const allows = (from, request) => origin === true ? from === publicOrigin(request) : typeof origin === "function" ? origin(from, request) === true : list.includes(from);
|
|
4317
|
-
return ({ request, set }) => {
|
|
4318
|
-
const from = request.headers.get("origin");
|
|
4319
|
-
if (from === null) return;
|
|
4320
|
-
const headers = { vary: "Origin" };
|
|
4321
|
-
if (allows(from, request)) {
|
|
4322
|
-
headers["access-control-allow-origin"] = from;
|
|
4323
|
-
if (credentials) headers["access-control-allow-credentials"] = "true";
|
|
4324
|
-
}
|
|
4325
|
-
if (!(request.method === "OPTIONS" && request.headers.has("access-control-request-method"))) {
|
|
4326
|
-
Object.assign(set.headers, headers);
|
|
4327
|
-
return;
|
|
4328
|
-
}
|
|
4329
|
-
if (headers["access-control-allow-origin"]) {
|
|
4330
|
-
headers["access-control-allow-methods"] = METHODS;
|
|
4331
|
-
const requested = request.headers.get("access-control-request-headers");
|
|
4332
|
-
if (requested) headers["access-control-allow-headers"] = requested;
|
|
4333
|
-
}
|
|
4334
|
-
return new Response(null, {
|
|
4335
|
-
status: 204,
|
|
4336
|
-
headers
|
|
4337
|
-
});
|
|
4338
|
-
};
|
|
4339
|
-
}
|
|
4340
3763
|
// src/server.ts
|
|
4341
3764
|
/**
|
|
4342
3765
|
* Create the HTTP application: an Elysia app that serves every service's
|
|
@@ -4369,11 +3792,10 @@ function corsHook(cors) {
|
|
|
4369
3792
|
*/
|
|
4370
3793
|
function brick(options = {}) {
|
|
4371
3794
|
const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
|
|
4372
|
-
const title = options.title ??
|
|
4373
|
-
const version = options.version ??
|
|
4374
|
-
const compiled = options.compiler !== false;
|
|
3795
|
+
const title = options.title ?? OPENAPI_DEFAULTS.title;
|
|
3796
|
+
const version = options.version ?? OPENAPI_DEFAULTS.version;
|
|
4375
3797
|
const enableDocs = options.docs ?? true;
|
|
4376
|
-
const openApiPath = options.openApiPath ??
|
|
3798
|
+
const openApiPath = options.openApiPath ?? OPENAPI_DEFAULTS.path;
|
|
4377
3799
|
const docsPath = options.docsPath ?? "/docs";
|
|
4378
3800
|
const swaggerPath = options.swaggerPath ?? "/swagger";
|
|
4379
3801
|
const dashboard = normalizeDashboard(options.dashboard);
|
|
@@ -4384,31 +3806,25 @@ function brick(options = {}) {
|
|
|
4384
3806
|
const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
|
|
4385
3807
|
if (options.cors) app.onRequest(corsHook(options.cors));
|
|
4386
3808
|
for (const handler of plugins.middleware) app.onRequest(handler);
|
|
4387
|
-
|
|
3809
|
+
const registeredRoutes = /* @__PURE__ */ new Map();
|
|
3810
|
+
const builtIn = (path, handler) => {
|
|
3811
|
+
app.get(path, handler);
|
|
3812
|
+
registeredRoutes.set(routeKey("GET", path), false);
|
|
3813
|
+
};
|
|
3814
|
+
builtIn("/_health", () => ({
|
|
4388
3815
|
status: "ok",
|
|
4389
3816
|
uptime: process.uptime(),
|
|
4390
3817
|
timestamp: Date.now()
|
|
4391
3818
|
}));
|
|
4392
3819
|
const requestLogging = options.requestLogging ?? true;
|
|
4393
|
-
if (requestLogging !== false) {
|
|
4394
|
-
const pluginOpts = requestLogging === true ? {} : requestLogging;
|
|
4395
|
-
if (pluginOpts.enabled !== false) app.use(requestLoggingPlugin(pluginOpts));
|
|
4396
|
-
}
|
|
3820
|
+
if (requestLogging !== false) app.use(requestLoggingPlugin(requestLogging === true ? {} : requestLogging));
|
|
4397
3821
|
const reference = options.reference ?? false;
|
|
4398
3822
|
const referenceOptions = typeof reference === "object" ? reference : {};
|
|
4399
3823
|
const referencePath = reference === true ? "/reference" : referenceOptions.path;
|
|
4400
|
-
if (referencePath !== void 0)
|
|
4401
|
-
const settings = {
|
|
4402
|
-
path: referencePath,
|
|
4403
|
-
title: referenceOptions.title ?? title,
|
|
4404
|
-
specUrl: referenceOptions.specUrl ?? openApiPath
|
|
4405
|
-
};
|
|
4406
|
-
if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
|
|
4407
|
-
else registerReferenceRoute(app, settings);
|
|
4408
|
-
}
|
|
3824
|
+
if (referencePath !== void 0) builtIn(referencePath, htmlResponse(scalarDocsHTML(referenceOptions.specUrl ?? openApiPath, referenceOptions.title ?? title)));
|
|
4409
3825
|
const byName = /* @__PURE__ */ new Map();
|
|
4410
3826
|
for (const service of services) {
|
|
4411
|
-
if ((byName.get(service.name) ?? service) !== service) throw new
|
|
3827
|
+
if ((byName.get(service.name) ?? service) !== service) throw new DuplicateNameError(`Brick: duplicate service "${service.name}" in brick()`);
|
|
4412
3828
|
byName.set(service.name, service);
|
|
4413
3829
|
}
|
|
4414
3830
|
bindDeps(services, options.deps);
|
|
@@ -4419,7 +3835,7 @@ function brick(options = {}) {
|
|
|
4419
3835
|
const events = eventsOptions ? new EventsHub(eventsOptions, options.deps).attach(services) : void 0;
|
|
4420
3836
|
if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
|
|
4421
3837
|
if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
|
|
4422
|
-
for (const service of services)
|
|
3838
|
+
for (const service of services) service.build();
|
|
4423
3839
|
const endpointDefs = [];
|
|
4424
3840
|
let endpointRevision = 0;
|
|
4425
3841
|
const buildSpec = () => {
|
|
@@ -4441,31 +3857,11 @@ function brick(options = {}) {
|
|
|
4441
3857
|
};
|
|
4442
3858
|
};
|
|
4443
3859
|
if (enableDocs) {
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
|
|
4448
|
-
} else {
|
|
4449
|
-
app.get(docsPath, ({ set }) => {
|
|
4450
|
-
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
4451
|
-
return scalarDocsHTML(openApiPath, title);
|
|
4452
|
-
});
|
|
4453
|
-
app.get(swaggerPath, ({ set }) => {
|
|
4454
|
-
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
4455
|
-
return swaggerDocsHTML(openApiPath, title);
|
|
4456
|
-
});
|
|
4457
|
-
}
|
|
3860
|
+
builtIn(openApiPath, cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]));
|
|
3861
|
+
builtIn(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
|
|
3862
|
+
builtIn(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
|
|
4458
3863
|
}
|
|
4459
|
-
|
|
4460
|
-
const routeKey = (method, path) => `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
4461
|
-
registeredRoutes.set(routeKey("GET", "/_health"), false);
|
|
4462
|
-
registeredRoutes.set(routeKey("GET", "/_brick/services"), false);
|
|
4463
|
-
if (enableDocs) for (const path of [
|
|
4464
|
-
openApiPath,
|
|
4465
|
-
docsPath,
|
|
4466
|
-
swaggerPath
|
|
4467
|
-
]) registeredRoutes.set(routeKey("GET", path), false);
|
|
4468
|
-
if (referencePath !== void 0) registeredRoutes.set(routeKey("GET", referencePath), false);
|
|
3864
|
+
builtIn("/_brick/services", (context) => architecture(context));
|
|
4469
3865
|
const sockets = services.flatMap((service) => service.listSockets().map((definition) => ({
|
|
4470
3866
|
service: service.name,
|
|
4471
3867
|
path: socketPath(prefix, service.name, definition),
|
|
@@ -4474,31 +3870,17 @@ function brick(options = {}) {
|
|
|
4474
3870
|
const socketRoutes = /* @__PURE__ */ new Set();
|
|
4475
3871
|
for (const socket of sockets) {
|
|
4476
3872
|
const key = routeKey("GET", socket.path);
|
|
4477
|
-
if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new
|
|
3873
|
+
if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new DuplicateNameError(`Brick: duplicate socket route '${socket.path}'`);
|
|
4478
3874
|
socketRoutes.add(key);
|
|
4479
3875
|
}
|
|
4480
3876
|
const mountRoute = (method, path, handler, plugin = false) => {
|
|
4481
3877
|
const key = routeKey(method, path);
|
|
4482
|
-
if (socketRoutes.has(key)) throw new
|
|
3878
|
+
if (socketRoutes.has(key)) throw new DuplicateNameError(`Brick: route '${method} ${path}' conflicts with a socket`);
|
|
4483
3879
|
if (registeredRoutes.has(key)) {
|
|
4484
|
-
if (plugin || registeredRoutes.get(key)) throw new
|
|
3880
|
+
if (plugin || registeredRoutes.get(key)) throw new DuplicateNameError(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
4485
3881
|
return false;
|
|
4486
3882
|
}
|
|
4487
|
-
|
|
4488
|
-
case "GET":
|
|
4489
|
-
app.get(path, handler);
|
|
4490
|
-
break;
|
|
4491
|
-
case "POST":
|
|
4492
|
-
app.post(path, handler);
|
|
4493
|
-
break;
|
|
4494
|
-
case "PUT":
|
|
4495
|
-
app.put(path, handler);
|
|
4496
|
-
break;
|
|
4497
|
-
case "PATCH":
|
|
4498
|
-
app.patch(path, handler);
|
|
4499
|
-
break;
|
|
4500
|
-
case "DELETE": app.delete(path, handler);
|
|
4501
|
-
}
|
|
3883
|
+
app.route(method, path, handler);
|
|
4502
3884
|
registeredRoutes.set(key, plugin);
|
|
4503
3885
|
return true;
|
|
4504
3886
|
};
|
|
@@ -4515,6 +3897,7 @@ function brick(options = {}) {
|
|
|
4515
3897
|
mountEndpoint(def);
|
|
4516
3898
|
};
|
|
4517
3899
|
brickApp.listEndpoints = () => [...endpointDefs];
|
|
3900
|
+
brickApp.openApiDocument = buildSpec;
|
|
4518
3901
|
brickApp.referenceDocuments = async () => {
|
|
4519
3902
|
const documents = enableDocs ? [{
|
|
4520
3903
|
title,
|
|
@@ -4539,15 +3922,14 @@ function brick(options = {}) {
|
|
|
4539
3922
|
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");
|
|
4540
3923
|
const mountedRoutes = [];
|
|
4541
3924
|
for (const route of compilation.routes) {
|
|
4542
|
-
const action = services.find((candidate) => candidate.name === route.ir.service).listActions().find((candidate) => candidate.name === route.ir.action);
|
|
4543
3925
|
const invoke = (context) => {
|
|
4544
|
-
const result = telemetry ? withSpan(
|
|
4545
|
-
|
|
4546
|
-
|
|
3926
|
+
const result = telemetry ? withSpan(`${SPAN.actionPrefix}${route.ir.service}.${route.ir.action}`, {
|
|
3927
|
+
[ATTR.service]: route.ir.service,
|
|
3928
|
+
[ATTR.action]: route.ir.action
|
|
4547
3929
|
}, () => route.handler(context)) : route.handler(context);
|
|
4548
3930
|
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
4549
3931
|
};
|
|
4550
|
-
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke,
|
|
3932
|
+
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin))) mountedRoutes.push(route.ir);
|
|
4551
3933
|
}
|
|
4552
3934
|
mountSockets(app, sockets, options.sockets?.broker ?? localBroker(), options.sockets?.secret);
|
|
4553
3935
|
const definition = Object.freeze({
|
|
@@ -4572,7 +3954,10 @@ function brick(options = {}) {
|
|
|
4572
3954
|
const stop = app.stop.bind(app);
|
|
4573
3955
|
Object.defineProperty(brickApp, "start", { value: lifecycle.start });
|
|
4574
3956
|
brickApp.listen = ((...args) => {
|
|
4575
|
-
lifecycle.start().catch((error) =>
|
|
3957
|
+
lifecycle.start().catch((error) => {
|
|
3958
|
+
console.error("[Brick-TS] A plugin failed to start:", error);
|
|
3959
|
+
return stop(true);
|
|
3960
|
+
});
|
|
4576
3961
|
return listen(...args);
|
|
4577
3962
|
});
|
|
4578
3963
|
brickApp.stop = (async (closeActiveConnections) => {
|
|
@@ -4582,11 +3967,20 @@ function brick(options = {}) {
|
|
|
4582
3967
|
await lifecycle.stop();
|
|
4583
3968
|
}
|
|
4584
3969
|
});
|
|
4585
|
-
|
|
4586
|
-
|
|
3970
|
+
Object.defineProperty(brickApp, "serve", { value: async ({ port }) => {
|
|
3971
|
+
await lifecycle.start();
|
|
3972
|
+
listen(port);
|
|
3973
|
+
events?.start();
|
|
3974
|
+
return brickApp;
|
|
3975
|
+
} });
|
|
3976
|
+
Object.defineProperty(brickApp, "shutdown", { value: async (closeActiveConnections) => {
|
|
3977
|
+
await events?.stop();
|
|
3978
|
+
await brickApp.stop(closeActiveConnections);
|
|
3979
|
+
} });
|
|
3980
|
+
const architecture = cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
|
|
4587
3981
|
const registry = getGlobalRegistry();
|
|
4588
3982
|
return [registry, registry.revision];
|
|
4589
|
-
})
|
|
3983
|
+
});
|
|
4590
3984
|
return brickApp;
|
|
4591
3985
|
}
|
|
4592
3986
|
function normalizeDocumentation(documentation) {
|
|
@@ -4619,6 +4013,6 @@ function cachedJsonRoute(build, revision) {
|
|
|
4619
4013
|
return json;
|
|
4620
4014
|
};
|
|
4621
4015
|
}
|
|
4622
|
-
export {
|
|
4016
|
+
export { validateName as $, generateOpenApiSpec as A, createActionHandler as B, SecretRef as C, overrideSecret as D, listSecrets as E, bindCompiledApplication as F, useDeps as G, definitionSite as H, compileBrickApplication as I, getPluginEndpoints as J, defineResourcePlugin as K, loadCompiledBrickApp as L, setActionAccess as M, getGlobalRegistry as N, resetSecrets as O, resetGlobalRegistry as P, segmentClaimant as Q, isBrickApp as R, requestLoggingPlugin as S, envSource as T, INTERNALS as U, claimName as V, port as W, installPlugin as X, hasPlugin as Y, isInstallingPlugin as Z, isOutboxTable as _, WORKFLOW_BUNDLE as a, baseContext as at, registerReferenceRoute as b, checkEvent as c, t as ct, crudEventSource as d, withCallSpan as dt, portOf as et, eventRefs as f, PLUGIN_COMMIT as ft, runInTransaction as g, onTransactionCommit as h, stopAllEvents as i, deny as it, getActionAccess as j, resolveSecrets as k, checkPayload as l, validateWithSchema as lt, Dispatcher as m, defineServiceSocket as n, defineAction as nt, resolveWorkflowPaths as o, pickContextEnvelope as ot, isCrudEvent as p, PLUGIN_KIND as pt, defineServicePlugin as q, recordingServices as r, errorsOf as rt, defineListener as s, Type as st, brick as t, buildErrorHelpers as tt, crudEventName as u, traceRoute as ut, outboxTable as v, defineSecret as w, scalarDocsHTML as x, referencePlugin as y, requireBrickApp as z };
|
|
4623
4017
|
|
|
4624
4018
|
//# sourceMappingURL=server.js.map
|