@brickkit/core 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunks/client.d.ts +1655 -643
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js +462 -2
- package/dist/chunks/client.js.map +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/index.d.ts +266 -176
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2074 -224
- package/dist/index.js.map +1 -1
- package/dist/tanstack-query.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,22 +1,85 @@
|
|
|
1
|
-
import { a as isBrickTransportError, i as isBrickServerError, n as BrickTransportError,
|
|
1
|
+
import { a as isBrickTransportError, c as SOCKET_MAX_BYTES, d as isSocketRoom, f as isSocketSeq, g as kebabCase, h as ValidationError, i as isBrickServerError, l as compareSocketSeq, m as ActionExecutionError, n as BrickTransportError, p as serializeSocketSchema, r as createBrickClient, s as SOCKET_BUFFER_BYTES, t as BrickServerError, u as isSocketEnvelope } from "./chunks/client.js";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
3
4
|
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
4
5
|
import { Type, Type as t } from "@sinclair/typebox";
|
|
5
6
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
6
7
|
import { formatWithOptions } from "node:util";
|
|
7
|
-
import {
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
9
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
10
|
+
import { Value } from "@sinclair/typebox/value";
|
|
8
11
|
import { Table, and, and as and$1, asc, asc as asc$1, desc, eq, eq as eq$1, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, inArray as inArray$1, is, isNotNull, isNull, like, lt, lt as lt$1, lte, lte as lte$1, ne, not, notInArray, or, or as or$1, relations, sql, sql as sql$1 } from "drizzle-orm";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
12
|
+
import { blob, foreignKey, index, index as index$1, integer, integer as integer$1, primaryKey, real, real as real$1, sqliteTable, sqliteTable as sqliteTable$1, text, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
13
|
+
import { bigserial, boolean, doublePrecision, index as index$2, integer as integer$2, jsonb, pgTable, text as text$2, timestamp } from "drizzle-orm/pg-core";
|
|
11
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
+
import { Elysia } from "elysia";
|
|
16
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
17
|
+
import { websocket } from "elysia/websocket";
|
|
15
18
|
import postgres from "postgres";
|
|
16
19
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
17
20
|
//#region \0rolldown/runtime.js
|
|
18
21
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
19
22
|
//#endregion
|
|
23
|
+
//#region src/routes.ts
|
|
24
|
+
/**
|
|
25
|
+
* The route every name of an owner mounts under: `${prefix}`,
|
|
26
|
+
* `${prefix}/${service}`, or `${prefix}/${service}/${resource}`, in kebab-case.
|
|
27
|
+
*/
|
|
28
|
+
function ownerPath(prefix, service, resource) {
|
|
29
|
+
let path = prefix.replace(/\/$/, "");
|
|
30
|
+
if (service !== void 0) path += `/${kebabCase(service)}`;
|
|
31
|
+
if (resource !== void 0) path += `/${kebabCase(resource)}`;
|
|
32
|
+
return path;
|
|
33
|
+
}
|
|
34
|
+
/** Joins a path relative to its owner. `/` is the owner's own route. */
|
|
35
|
+
function joinRoute(base, path) {
|
|
36
|
+
return `${base}${path === "/" ? "" : path}` || "/";
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Where an action is served over HTTP: its method and its path under the owner
|
|
40
|
+
* tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource
|
|
41
|
+
* action's `${prefix}/${service}/${resource}[/:id]/${action}`).
|
|
42
|
+
*
|
|
43
|
+
* @param action - An action registered on a service.
|
|
44
|
+
* @param prefix - The application's route prefix (default `/api`).
|
|
45
|
+
* @returns `false` when a plugin switched the route off, otherwise the route.
|
|
46
|
+
*/
|
|
47
|
+
function getActionRoute(action, prefix = "/api") {
|
|
48
|
+
const plugin = getPluginActionRoute(action, prefix);
|
|
49
|
+
if (plugin === false) return false;
|
|
50
|
+
if (plugin) return {
|
|
51
|
+
method: plugin.method,
|
|
52
|
+
path: plugin.path,
|
|
53
|
+
legacyPath: plugin.legacyPath
|
|
54
|
+
};
|
|
55
|
+
const service = action.serviceName ?? "";
|
|
56
|
+
const method = action.config.method ?? "POST";
|
|
57
|
+
const { resourceAction } = action;
|
|
58
|
+
if (resourceAction) {
|
|
59
|
+
const base = ownerPath(prefix, service, resourceAction.resource);
|
|
60
|
+
return {
|
|
61
|
+
method,
|
|
62
|
+
path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}${resourceAction.record ? "/:id" : ""}/${kebabCase(resourceAction.name)}`
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const base = ownerPath(prefix, service);
|
|
66
|
+
return {
|
|
67
|
+
method,
|
|
68
|
+
path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}/${kebabCase(action.name)}`,
|
|
69
|
+
legacyPath: legacyPath(prefix, service, action.name, action.config.path)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The v0.10 route of a service action or socket: the names as declared, or an
|
|
74
|
+
* explicit path that still reads as absolute (it starts with the prefix). A
|
|
75
|
+
* path already rewritten as relative has no v0.10 form.
|
|
76
|
+
*/
|
|
77
|
+
function legacyPath(prefix, service, name, path) {
|
|
78
|
+
const root = prefix.replace(/\/$/, "");
|
|
79
|
+
if (path === void 0) return `${root}/${service}/${name}`;
|
|
80
|
+
return path.startsWith(`${root}/`) ? path : void 0;
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
20
83
|
//#region src/compiler/ir.ts
|
|
21
84
|
function freezeIR(value) {
|
|
22
85
|
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
@@ -101,11 +164,13 @@ function analyzeDeclaredApplication(services, prefix = "/api") {
|
|
|
101
164
|
action
|
|
102
165
|
});
|
|
103
166
|
};
|
|
104
|
-
for (const service of services)
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
167
|
+
for (const service of services) {
|
|
168
|
+
checkSegments(service);
|
|
169
|
+
for (const action of service.listActions()) {
|
|
170
|
+
const route = getActionRoute(action, prefix);
|
|
171
|
+
if (route === false) continue;
|
|
172
|
+
add(service, action, route.method, route.path, "action");
|
|
173
|
+
}
|
|
109
174
|
}
|
|
110
175
|
const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
|
|
111
176
|
service: service.name,
|
|
@@ -125,8 +190,49 @@ function analyzeDeclaredApplication(services, prefix = "/api") {
|
|
|
125
190
|
bindings
|
|
126
191
|
};
|
|
127
192
|
}
|
|
193
|
+
/** A service action, resource, and socket own the URL segment after the service. */
|
|
194
|
+
function checkSegments(service) {
|
|
195
|
+
const owners = /* @__PURE__ */ new Map();
|
|
196
|
+
const claim = (segment, owner) => {
|
|
197
|
+
const previous = owners.get(segment);
|
|
198
|
+
if (previous) throw new Error(`Brick: duplicate name "${segment}" in service "${service.name}": ${previous} and ${owner} share the URL segment`);
|
|
199
|
+
owners.set(segment, owner);
|
|
200
|
+
};
|
|
201
|
+
for (const resource of service.listResources()) claim(kebabCase(resource.name), `resource "${resource.name}"`);
|
|
202
|
+
for (const socket of service.listSockets()) if (socket.schema.path === void 0) claim(kebabCase(socket.schema.name), `socket "${socket.schema.name}"`);
|
|
203
|
+
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}"`);
|
|
204
|
+
}
|
|
128
205
|
//#endregion
|
|
129
206
|
//#region src/registry.ts
|
|
207
|
+
const brickRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
208
|
+
/**
|
|
209
|
+
* The first `file:line` outside Brick on the current stack: where a name is
|
|
210
|
+
* being defined. Best-effort: `undefined` when there is no stack.
|
|
211
|
+
*/
|
|
212
|
+
function definitionSite() {
|
|
213
|
+
const limit = Error.stackTraceLimit;
|
|
214
|
+
Error.stackTraceLimit = 50;
|
|
215
|
+
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
216
|
+
Error.stackTraceLimit = limit;
|
|
217
|
+
for (const line of stack?.split("\n").slice(1) ?? []) {
|
|
218
|
+
const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
|
|
219
|
+
if (!match) continue;
|
|
220
|
+
const [, file, row] = match;
|
|
221
|
+
if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
|
|
222
|
+
return `${file}:${row}`;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Records where `name` is defined. The same file defining it again (a dev
|
|
227
|
+
* reload) replaces the old definition.
|
|
228
|
+
*
|
|
229
|
+
* @throws When a different file already defined `name`.
|
|
230
|
+
*/
|
|
231
|
+
function claimName(sites, label, name, site) {
|
|
232
|
+
const file = (at) => at?.replace(/:\d+$/, "");
|
|
233
|
+
if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new Error(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
|
|
234
|
+
sites.set(name, site);
|
|
235
|
+
}
|
|
130
236
|
var ServiceRegistry = class {
|
|
131
237
|
_revision = 0;
|
|
132
238
|
/** Definition revision for invalidating serialized architecture snapshots. */
|
|
@@ -137,14 +243,16 @@ var ServiceRegistry = class {
|
|
|
137
243
|
this._revision++;
|
|
138
244
|
}
|
|
139
245
|
services = /* @__PURE__ */ new Map();
|
|
246
|
+
sites = /* @__PURE__ */ new Map();
|
|
140
247
|
routes = /* @__PURE__ */ new Map();
|
|
141
248
|
/** Remember the actual registered routes for subsequent registry exports. */
|
|
142
249
|
setApplicationRoutes(application) {
|
|
143
250
|
for (const service of application.services) this.routes.set(service, application.routes.filter((route) => route.service === service.name));
|
|
144
251
|
this.touch();
|
|
145
252
|
}
|
|
146
|
-
|
|
147
|
-
|
|
253
|
+
/** @throws When a different file already registered a service with this name. */
|
|
254
|
+
register(service, site = definitionSite()) {
|
|
255
|
+
claimName(this.sites, `service "${service.name}"`, service.name, site);
|
|
148
256
|
const previous = this.services.get(service.name);
|
|
149
257
|
if (previous) this.routes.delete(previous);
|
|
150
258
|
this.services.set(service.name, service);
|
|
@@ -161,6 +269,7 @@ var ServiceRegistry = class {
|
|
|
161
269
|
}
|
|
162
270
|
clear() {
|
|
163
271
|
this.services.clear();
|
|
272
|
+
this.sites.clear();
|
|
164
273
|
this.routes.clear();
|
|
165
274
|
this.touch();
|
|
166
275
|
}
|
|
@@ -168,12 +277,14 @@ var ServiceRegistry = class {
|
|
|
168
277
|
return {
|
|
169
278
|
version: "1.0.0",
|
|
170
279
|
...application?.events ? { events: application.events } : {},
|
|
280
|
+
...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
|
|
171
281
|
services: (application?.services ?? this.list()).map((service) => {
|
|
172
282
|
const routes = application ? application.routes.filter((route) => route.service === service.name) : this.routes.get(service) ?? analyzeDeclaredApplication([service]).ir.routes;
|
|
173
283
|
const byAction = new Map(routes.map((route) => [route.action, route]));
|
|
174
284
|
const schema = service.introspect();
|
|
175
285
|
return {
|
|
176
286
|
...schema,
|
|
287
|
+
...application?.sockets ? { sockets: application.sockets.filter((socket) => socket.service === service.name) } : {},
|
|
177
288
|
actions: schema.actions.map((action) => {
|
|
178
289
|
const route = byAction.get(action.name);
|
|
179
290
|
return route ? {
|
|
@@ -190,7 +301,7 @@ var ServiceRegistry = class {
|
|
|
190
301
|
let globalRegistry = new ServiceRegistry();
|
|
191
302
|
/**
|
|
192
303
|
* The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
|
|
193
|
-
* generator, `
|
|
304
|
+
* generator, `useService`, and the dashboard find services by name.
|
|
194
305
|
*
|
|
195
306
|
* @returns The current global registry.
|
|
196
307
|
*/
|
|
@@ -260,12 +371,14 @@ function traceRoute(route, handler) {
|
|
|
260
371
|
* Wrap one HTTP request in a server span. The span continues the caller's
|
|
261
372
|
* trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the
|
|
262
373
|
* request id Brick returns is the span's trace id, so clients can find the
|
|
263
|
-
* request in the dashboard.
|
|
374
|
+
* request in the dashboard. `extra` adds attributes, such as
|
|
375
|
+
* `brick.legacy_route` on a v0.10 path.
|
|
264
376
|
*/
|
|
265
|
-
function traceHttpRequest(request, method, route, fn) {
|
|
377
|
+
function traceHttpRequest(request, method, route, fn, extra) {
|
|
266
378
|
const attributes = {
|
|
267
379
|
"http.request.method": method,
|
|
268
|
-
"http.route": route
|
|
380
|
+
"http.route": route,
|
|
381
|
+
...extra
|
|
269
382
|
};
|
|
270
383
|
if (request.request) attributes["url.path"] = new URL(request.request.url).pathname;
|
|
271
384
|
const headers = request.headers ?? {};
|
|
@@ -703,6 +816,26 @@ function buildErrorHelpers(errorsDef) {
|
|
|
703
816
|
};
|
|
704
817
|
return helpers;
|
|
705
818
|
}
|
|
819
|
+
/**
|
|
820
|
+
* Define a reusable error. Spread it into the `errors` of any action, listener or
|
|
821
|
+
* command; give it a `details` schema and `error.CODE(message, details)` checks
|
|
822
|
+
* the details against it in types. The details are not validated at runtime.
|
|
823
|
+
*
|
|
824
|
+
* @example
|
|
825
|
+
* const SlugExists = defineError("SLUG_EXISTS", {
|
|
826
|
+
* status: 409,
|
|
827
|
+
* message: "Slug is already taken",
|
|
828
|
+
* details: t.Object({ slug: t.String() }),
|
|
829
|
+
* });
|
|
830
|
+
* // errors: { ...SlugExists } then error.SLUG_EXISTS(undefined, { slug })
|
|
831
|
+
*/
|
|
832
|
+
function defineError(code, definition) {
|
|
833
|
+
return { [code]: definition };
|
|
834
|
+
}
|
|
835
|
+
/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */
|
|
836
|
+
function errorsOf(action) {
|
|
837
|
+
return action.config.errors ?? {};
|
|
838
|
+
}
|
|
706
839
|
function defineAction(config) {
|
|
707
840
|
const errorHelpers = buildErrorHelpers(config.errors);
|
|
708
841
|
const actionFn = (async (params) => {
|
|
@@ -764,6 +897,8 @@ function defineAction(config) {
|
|
|
764
897
|
//#endregion
|
|
765
898
|
//#region src/plugin.ts
|
|
766
899
|
const pluginKind = Symbol.for("brickkit.plugin.kind");
|
|
900
|
+
/** `definePlugin` instances install on either host; see `define-plugin.ts`. */
|
|
901
|
+
const pluginFinish = Symbol.for("brickkit.plugin.finish");
|
|
767
902
|
/**
|
|
768
903
|
* Define a plugin that installs onto a service with `service.use(plugin)`. Its
|
|
769
904
|
* `setup` receives the service and a `routes` registrar for adding actions and
|
|
@@ -805,7 +940,7 @@ function defineServicePlugin(definition) {
|
|
|
805
940
|
/**
|
|
806
941
|
* Define a plugin that installs onto a resource (a table and its entity) with
|
|
807
942
|
* `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
|
|
808
|
-
* `routes` registrar, whose routes
|
|
943
|
+
* `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and
|
|
809
944
|
* returns the typed API that `resource.use` hands back. `crud` is built this way.
|
|
810
945
|
*
|
|
811
946
|
* @param definition - A unique `name`, optional `routes` controls, and `setup`,
|
|
@@ -872,8 +1007,12 @@ function isInstallingPlugin(service) {
|
|
|
872
1007
|
return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
|
|
873
1008
|
}
|
|
874
1009
|
function pathOf(binding, prefix) {
|
|
1010
|
+
return joinRoute(binding.scope === "app" ? ownerPath(prefix) : ownerPath(prefix, binding.service.name, binding.scope === "resource" ? binding.resource.name : void 0), binding.path);
|
|
1011
|
+
}
|
|
1012
|
+
/** v0.10 mounted resource scope at `${prefix}/${resource}`, with names as declared. */
|
|
1013
|
+
function legacyPathOf(binding, prefix) {
|
|
875
1014
|
const scope = binding.scope === "app" ? "" : `/${binding.scope === "resource" ? binding.resource.name : binding.service.name}`;
|
|
876
|
-
return `${prefix.replace(/\/$/, "")}${scope}
|
|
1015
|
+
return joinRoute(`${prefix.replace(/\/$/, "")}${scope}`, binding.path);
|
|
877
1016
|
}
|
|
878
1017
|
/**
|
|
879
1018
|
* Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
|
|
@@ -883,7 +1022,7 @@ function pathOf(binding, prefix) {
|
|
|
883
1022
|
* @param prefix - The application's route prefix (default `/api`).
|
|
884
1023
|
* @returns `undefined` when no plugin bound the action (it uses its own route),
|
|
885
1024
|
* `false` when the plugin's route was switched off, otherwise the route's
|
|
886
|
-
* `path
|
|
1025
|
+
* `path`, the v0.10 `legacyPath`, `method`, the `clientPath` the typed client uses, and the owning
|
|
887
1026
|
* `plugin` and `resource`.
|
|
888
1027
|
*/
|
|
889
1028
|
function getPluginActionRoute(action, prefix = "/api") {
|
|
@@ -892,6 +1031,7 @@ function getPluginActionRoute(action, prefix = "/api") {
|
|
|
892
1031
|
if (!binding.enabled) return false;
|
|
893
1032
|
return {
|
|
894
1033
|
path: pathOf(binding, prefix),
|
|
1034
|
+
legacyPath: legacyPathOf(binding, prefix),
|
|
895
1035
|
method: binding.method,
|
|
896
1036
|
clientPath: binding.clientPath,
|
|
897
1037
|
plugin: binding.plugin,
|
|
@@ -910,8 +1050,10 @@ function getPluginActionRoute(action, prefix = "/api") {
|
|
|
910
1050
|
function getPluginEndpoints(service, prefix = "/api") {
|
|
911
1051
|
return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
|
|
912
1052
|
path: pathOf(binding, prefix),
|
|
1053
|
+
legacyPath: legacyPathOf(binding, prefix),
|
|
913
1054
|
method: binding.method,
|
|
914
1055
|
service,
|
|
1056
|
+
plugin: binding.plugin,
|
|
915
1057
|
summary: binding.summary,
|
|
916
1058
|
description: binding.description,
|
|
917
1059
|
tags: binding.tags,
|
|
@@ -924,7 +1066,7 @@ function getPluginEndpoints(service, prefix = "/api") {
|
|
|
924
1066
|
/** Descriptor identity is scoped to the service or resource installation host. */
|
|
925
1067
|
function installPlugin(service, resource, descriptor) {
|
|
926
1068
|
if (service.isBuilt) throw new Error("Plugins must be installed before service build");
|
|
927
|
-
if (descriptor[pluginKind] !== (resource ? "resource" : "service")) throw new Error("Plugin does not support this installation host");
|
|
1069
|
+
if (descriptor[pluginKind] !== (resource ? "resource" : "service") && descriptor[pluginKind] !== "plugin") throw new Error("Plugin does not support this installation host");
|
|
928
1070
|
const state = stateOf(service);
|
|
929
1071
|
const host = resource ?? service;
|
|
930
1072
|
const existing = state.hosts.get(host)?.get(descriptor.name);
|
|
@@ -1033,7 +1175,11 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1033
1175
|
const binding = state.actions.get(value);
|
|
1034
1176
|
if (binding && ownedActions.has(value)) {
|
|
1035
1177
|
if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
|
|
1036
|
-
binding.clientPath =
|
|
1178
|
+
binding.clientPath = resource ? [
|
|
1179
|
+
service.name,
|
|
1180
|
+
resource.name,
|
|
1181
|
+
...path
|
|
1182
|
+
] : [service.name, ...path];
|
|
1037
1183
|
}
|
|
1038
1184
|
} else if (value && typeof value === "object" && !ancestors.has(value)) {
|
|
1039
1185
|
const next = new Set(ancestors).add(value);
|
|
@@ -1055,9 +1201,11 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1055
1201
|
status: "installed",
|
|
1056
1202
|
api
|
|
1057
1203
|
});
|
|
1204
|
+
finish(descriptor, true);
|
|
1058
1205
|
getGlobalRegistry().touch();
|
|
1059
1206
|
return resource ?? api;
|
|
1060
1207
|
} catch (error) {
|
|
1208
|
+
finish(descriptor, false);
|
|
1061
1209
|
for (const action of state.actions.keys()) if (!snapshots.bindings.has(action)) {
|
|
1062
1210
|
actionBindings.delete(action);
|
|
1063
1211
|
delete action[actionBindingKey];
|
|
@@ -1080,11 +1228,571 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1080
1228
|
active = false;
|
|
1081
1229
|
}
|
|
1082
1230
|
}
|
|
1231
|
+
function finish(descriptor, installed) {
|
|
1232
|
+
descriptor[pluginFinish]?.(installed);
|
|
1233
|
+
}
|
|
1234
|
+
/** Whether a plugin named `name` is installed on `host` (the service or a resource). */
|
|
1235
|
+
function hasPlugin(service, host, name) {
|
|
1236
|
+
return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
|
|
1237
|
+
}
|
|
1238
|
+
/** Every descriptor installed on the service or its resources, in install order per host. */
|
|
1239
|
+
function installedPlugins(service) {
|
|
1240
|
+
return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
|
|
1241
|
+
}
|
|
1083
1242
|
function restoreMap(target, snapshot) {
|
|
1084
1243
|
target.clear();
|
|
1085
1244
|
for (const [key, value] of snapshot) target.set(key, value);
|
|
1086
1245
|
}
|
|
1087
1246
|
//#endregion
|
|
1247
|
+
//#region src/deps.ts
|
|
1248
|
+
/**
|
|
1249
|
+
* Declare a dependency a service needs, without creating it. The app provides
|
|
1250
|
+
* the value with `brick({ deps })`, and the service's code reads it as
|
|
1251
|
+
* `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
|
|
1252
|
+
*
|
|
1253
|
+
* @returns A slot typed as `T`. It holds nothing at runtime.
|
|
1254
|
+
* @example
|
|
1255
|
+
* import { defineService, port } from "@brickkit/core";
|
|
1256
|
+
*
|
|
1257
|
+
* export const orders = defineService("orders", {
|
|
1258
|
+
* database,
|
|
1259
|
+
* deps: { carrier: port<Carrier>() },
|
|
1260
|
+
* });
|
|
1261
|
+
*
|
|
1262
|
+
* // app.ts
|
|
1263
|
+
* export default brick({ services: [orders], deps: { carrier: createCarrier() } });
|
|
1264
|
+
*/
|
|
1265
|
+
function port() {
|
|
1266
|
+
return Object.freeze({});
|
|
1267
|
+
}
|
|
1268
|
+
/** Where a socket a plugin declared keeps the plugin's deps; global so a second core copy finds it. */
|
|
1269
|
+
const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
|
|
1270
|
+
const running = new AsyncLocalStorage();
|
|
1271
|
+
/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
|
|
1272
|
+
function runWithDeps(deps, fn) {
|
|
1273
|
+
return running.run(deps, fn);
|
|
1274
|
+
}
|
|
1275
|
+
function useDeps() {
|
|
1276
|
+
const deps = running.getStore();
|
|
1277
|
+
if (!deps) throw new Error("useDeps() was called outside a Brick app: call it from a listener or a workflow step (actions read ctx.deps).");
|
|
1278
|
+
return deps;
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Check `brick({ deps })` against what the services declare, and give each
|
|
1282
|
+
* service the values of its own ports.
|
|
1283
|
+
*
|
|
1284
|
+
* @throws When a service declares a dep the app does not provide, or the app
|
|
1285
|
+
* provides one that no service declares.
|
|
1286
|
+
*/
|
|
1287
|
+
function bindDeps(services, provided = {}) {
|
|
1288
|
+
const declared = /* @__PURE__ */ new Set();
|
|
1289
|
+
for (const service of services) {
|
|
1290
|
+
const own = {};
|
|
1291
|
+
for (const name of Object.keys(service.options.deps ?? {})) {
|
|
1292
|
+
if (!Object.hasOwn(provided, name) || provided[name] === void 0) throw new Error(`Brick: service "${service.name}" declares dep "${name}", but brick({ deps }) does not provide it`);
|
|
1293
|
+
declared.add(name);
|
|
1294
|
+
own[name] = provided[name];
|
|
1295
|
+
}
|
|
1296
|
+
service.setDeps?.(Object.freeze(own));
|
|
1297
|
+
}
|
|
1298
|
+
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"})`);
|
|
1299
|
+
}
|
|
1300
|
+
//#endregion
|
|
1301
|
+
//#region src/define-plugin.ts
|
|
1302
|
+
let runningVersion;
|
|
1303
|
+
/** The version of this @brickkit/core, read from its package.json; `""` when unknown. */
|
|
1304
|
+
function brickVersion() {
|
|
1305
|
+
if (runningVersion !== void 0) return runningVersion;
|
|
1306
|
+
for (const relative of ["../package.json", "../../package.json"]) try {
|
|
1307
|
+
const json = JSON.parse(readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8"));
|
|
1308
|
+
if (json.name === "@brickkit/core") return runningVersion = json.version;
|
|
1309
|
+
} catch {}
|
|
1310
|
+
return runningVersion = "";
|
|
1311
|
+
}
|
|
1312
|
+
function parseVersion(version) {
|
|
1313
|
+
const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[-+]/)[0].split(".").map(Number);
|
|
1314
|
+
return [
|
|
1315
|
+
major,
|
|
1316
|
+
minor,
|
|
1317
|
+
patch
|
|
1318
|
+
];
|
|
1319
|
+
}
|
|
1320
|
+
function compare(a, b) {
|
|
1321
|
+
return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,
|
|
1325
|
+
* `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.
|
|
1326
|
+
*/
|
|
1327
|
+
function satisfiesRange(version, range) {
|
|
1328
|
+
const current = parseVersion(version);
|
|
1329
|
+
return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
|
|
1330
|
+
const match = /^(\^|~|>=|<=|>|<|=)?v?([\dx*]+(?:\.[\dx*]+){0,2})?/i.exec(comparator);
|
|
1331
|
+
const operator = match?.[1] ?? "";
|
|
1332
|
+
const parts = (match?.[2] ?? "*").split(".");
|
|
1333
|
+
const wild = parts.findIndex((part) => /^[x*]$/i.test(part));
|
|
1334
|
+
const given = wild === -1 ? parts.length : wild;
|
|
1335
|
+
const low = parseVersion(parts.slice(0, given).join(".") || "0");
|
|
1336
|
+
if (given === 0) return true;
|
|
1337
|
+
const cmp = compare(current, low);
|
|
1338
|
+
if (operator === ">=") return cmp >= 0;
|
|
1339
|
+
if (operator === ">") return cmp > 0;
|
|
1340
|
+
if (operator === "<") return cmp < 0;
|
|
1341
|
+
if (operator === "<=") return cmp <= 0;
|
|
1342
|
+
let high;
|
|
1343
|
+
if (operator === "^") high = low[0] > 0 || given === 1 ? [
|
|
1344
|
+
low[0] + 1,
|
|
1345
|
+
0,
|
|
1346
|
+
0
|
|
1347
|
+
] : low[1] > 0 || given === 2 ? [
|
|
1348
|
+
0,
|
|
1349
|
+
low[1] + 1,
|
|
1350
|
+
0
|
|
1351
|
+
] : [
|
|
1352
|
+
0,
|
|
1353
|
+
0,
|
|
1354
|
+
low[2] + 1
|
|
1355
|
+
];
|
|
1356
|
+
else if (operator === "~" || given < 3) high = given === 1 ? [
|
|
1357
|
+
low[0] + 1,
|
|
1358
|
+
0,
|
|
1359
|
+
0
|
|
1360
|
+
] : [
|
|
1361
|
+
low[0],
|
|
1362
|
+
low[1] + 1,
|
|
1363
|
+
0
|
|
1364
|
+
];
|
|
1365
|
+
else return cmp === 0;
|
|
1366
|
+
return cmp >= 0 && compare(current, high) < 0;
|
|
1367
|
+
}));
|
|
1368
|
+
}
|
|
1369
|
+
const OWNER = Symbol.for("brickkit.plugin.owner");
|
|
1370
|
+
/** The plugin that owns a table, for tables a `definePlugin` contributed. */
|
|
1371
|
+
function pluginOwner(table) {
|
|
1372
|
+
return table && typeof table === "object" ? table[OWNER] : void 0;
|
|
1373
|
+
}
|
|
1374
|
+
const sqliteBuilders = {
|
|
1375
|
+
/** A table. Its name gets the plugin's prefix (`page_comments`). */
|
|
1376
|
+
table: (name, columns) => sqliteTable$1(name, columns),
|
|
1377
|
+
text: (name) => text$1(name),
|
|
1378
|
+
integer: (name) => integer$1(name, { mode: "number" }),
|
|
1379
|
+
real: (name) => real$1(name),
|
|
1380
|
+
boolean: (name) => integer$1(name, { mode: "boolean" }),
|
|
1381
|
+
/** A `Date`, stored as epoch milliseconds or `timestamptz`. */
|
|
1382
|
+
timestamp: (name) => integer$1(name, { mode: "timestamp_ms" }),
|
|
1383
|
+
json: (name) => text$1(name, { mode: "json" })
|
|
1384
|
+
};
|
|
1385
|
+
function builders(engine, tableName) {
|
|
1386
|
+
if (engine === "postgres") return {
|
|
1387
|
+
engine,
|
|
1388
|
+
table: (name, columns) => pgTable(tableName(name), columns),
|
|
1389
|
+
text: (name) => text$2(name),
|
|
1390
|
+
integer: (name) => integer$2(name),
|
|
1391
|
+
real: (name) => doublePrecision(name),
|
|
1392
|
+
boolean: (name) => boolean(name),
|
|
1393
|
+
timestamp: (name) => timestamp(name, {
|
|
1394
|
+
mode: "date",
|
|
1395
|
+
withTimezone: true
|
|
1396
|
+
}),
|
|
1397
|
+
json: (name) => jsonb(name)
|
|
1398
|
+
};
|
|
1399
|
+
return {
|
|
1400
|
+
...sqliteBuilders,
|
|
1401
|
+
engine,
|
|
1402
|
+
table: (name, columns) => sqliteTable$1(tableName(name), columns)
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
/** Where `hooks.*` stores a plugin's hooks; `@brickkit/crud` runs them. */
|
|
1406
|
+
const HOST_HOOKS = Symbol.for("brickkit.plugin.hooks");
|
|
1407
|
+
const HOOK_NAMES = [
|
|
1408
|
+
"beforeCreate",
|
|
1409
|
+
"afterCreate",
|
|
1410
|
+
"beforeUpdate",
|
|
1411
|
+
"afterUpdate",
|
|
1412
|
+
"beforeDelete",
|
|
1413
|
+
"afterDelete",
|
|
1414
|
+
"afterCommit"
|
|
1415
|
+
];
|
|
1416
|
+
const INTERNALS = Symbol.for("brickkit.plugin.internals");
|
|
1417
|
+
let installCount = 0;
|
|
1418
|
+
const toWords = (name) => (name.split("/").pop() ?? name).replace(/^brick-/, "").replace(/-plugin$/, "").split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
1419
|
+
const snake = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
1420
|
+
/**
|
|
1421
|
+
* Define a plugin: a manifest Brick checks, plus the capabilities the plugin
|
|
1422
|
+
* brings. Install its instances with `resource.use()`, `service.use()` or
|
|
1423
|
+
* `brick({ plugins })`; scope comes from where it is installed.
|
|
1424
|
+
*
|
|
1425
|
+
* @param manifest - `name`, `brick` (semver range), `requires`, `options`
|
|
1426
|
+
* (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
|
|
1427
|
+
* parts, and a `dashboard` extension.
|
|
1428
|
+
* @returns A factory: `comments({ maxLength: 500 })` validates the options and
|
|
1429
|
+
* the Brick version and returns an instance to install.
|
|
1430
|
+
* @throws From the factory, when the running Brick is outside `brick` or an
|
|
1431
|
+
* option is invalid; when installed, when a required plugin is missing or the
|
|
1432
|
+
* host does not suit the plugin.
|
|
1433
|
+
* @example
|
|
1434
|
+
* export const audit = definePlugin({
|
|
1435
|
+
* name: "@acme/brick-audit",
|
|
1436
|
+
* brick: "^0.11.0",
|
|
1437
|
+
* requires: ["@brickkit/crud"],
|
|
1438
|
+
* options: t.Object({ table: t.String({ default: "audit" }) }),
|
|
1439
|
+
* tables: ({ table, text, timestamp }) => ({
|
|
1440
|
+
* log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
|
|
1441
|
+
* }),
|
|
1442
|
+
* resource: ({ tables, hooks }) => {
|
|
1443
|
+
* hooks.afterCreate(({ row, tx }) =>
|
|
1444
|
+
* tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
|
|
1445
|
+
* return {};
|
|
1446
|
+
* },
|
|
1447
|
+
* });
|
|
1448
|
+
*
|
|
1449
|
+
* page.use(audit());
|
|
1450
|
+
*/
|
|
1451
|
+
function definePlugin(manifest) {
|
|
1452
|
+
const { name } = manifest;
|
|
1453
|
+
if (!name || name.trim() !== name) throw new Error("Plugin names must be nonempty and have no surrounding whitespace");
|
|
1454
|
+
if (!manifest.resource && !manifest.service && !manifest.app) throw new Error(`Plugin "${name}" needs a resource, service or app part to install`);
|
|
1455
|
+
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`);
|
|
1456
|
+
const site = definitionSite()?.replace(/:\d+$/, "");
|
|
1457
|
+
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);
|
|
1458
|
+
const info = Object.freeze({
|
|
1459
|
+
name,
|
|
1460
|
+
description: manifest.description,
|
|
1461
|
+
brick: manifest.brick,
|
|
1462
|
+
requires: Object.freeze([...manifest.requires ?? []]),
|
|
1463
|
+
options: manifest.options,
|
|
1464
|
+
secrets: Object.freeze(Object.values(manifest.secrets ?? {}).map((secret) => secret.name)),
|
|
1465
|
+
deps: Object.freeze(Object.keys(manifest.deps ?? {})),
|
|
1466
|
+
capabilities: Object.freeze([
|
|
1467
|
+
"tables",
|
|
1468
|
+
"events",
|
|
1469
|
+
"resource",
|
|
1470
|
+
"service",
|
|
1471
|
+
"app",
|
|
1472
|
+
"dashboard"
|
|
1473
|
+
].filter((key) => manifest[key] !== void 0))
|
|
1474
|
+
});
|
|
1475
|
+
const words = toWords(name);
|
|
1476
|
+
const eventSpace = words.map((word, index) => index ? word[0].toUpperCase() + word.slice(1) : word).join("");
|
|
1477
|
+
const tableSpace = snake(words.join("_"));
|
|
1478
|
+
if (!eventSpace) throw new Error(`Plugin "${name}" needs letters or digits in its name`);
|
|
1479
|
+
const factory = (input = {}, install = {}) => {
|
|
1480
|
+
const version = brickVersion();
|
|
1481
|
+
if (manifest.brick && version && !satisfiesRange(version, manifest.brick)) throw new Error(`${name} supports Brick ${manifest.brick}; this app runs ${version}`);
|
|
1482
|
+
const options = checkOptions(name, manifest.options, input);
|
|
1483
|
+
const deps = checkDeps(name, eventSpace, manifest.deps, install.deps);
|
|
1484
|
+
const secrets = manifest.secrets ?? {};
|
|
1485
|
+
const internals = {
|
|
1486
|
+
manifest,
|
|
1487
|
+
options,
|
|
1488
|
+
deps,
|
|
1489
|
+
install,
|
|
1490
|
+
dashboard,
|
|
1491
|
+
installs: []
|
|
1492
|
+
};
|
|
1493
|
+
const pending = [];
|
|
1494
|
+
const setup = (context) => {
|
|
1495
|
+
const { service, resource } = context;
|
|
1496
|
+
const host = resource ?? service;
|
|
1497
|
+
const where = resource ? `resource "${resource.name}"` : `service "${service.name}"`;
|
|
1498
|
+
const part = resource ? manifest.resource : manifest.service;
|
|
1499
|
+
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 })"}`);
|
|
1500
|
+
for (const required of manifest.requires ?? []) if (!hasPlugin(service, host, required)) throw new Error(`${name} requires ${required}, installed on ${where} before it`);
|
|
1501
|
+
let tables = {};
|
|
1502
|
+
if (manifest.tables) {
|
|
1503
|
+
const database = service.getDatabaseHandle?.();
|
|
1504
|
+
if (!database) throw new Error(`${name} owns tables, so service "${service.name}" needs a database`);
|
|
1505
|
+
const prefix = install.prefix ?? `${snake(resource?.name ?? service.name)}_`;
|
|
1506
|
+
tables = manifest.tables(builders(database.engine, (table) => install.prefix !== void 0 || table === tableSpace ? `${prefix}${table}` : `${prefix}${tableSpace}_${table}`));
|
|
1507
|
+
const taken = new Set([...service.tables.values(), ...Object.values(database.tables)].map((table) => getTableName$1(table)));
|
|
1508
|
+
for (const table of Object.values(tables)) {
|
|
1509
|
+
const tableName = getTableName$1(table);
|
|
1510
|
+
if (taken.has(tableName)) throw new Error(`${name} table "${tableName}" clashes with a table service "${service.name}" already has; install it with another prefix`);
|
|
1511
|
+
taken.add(tableName);
|
|
1512
|
+
Object.defineProperty(table, OWNER, { value: name });
|
|
1513
|
+
service.registerTable(table);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
const catalog = service.events;
|
|
1517
|
+
const events = {};
|
|
1518
|
+
for (const [key, schema] of Object.entries(manifest.events ?? {})) {
|
|
1519
|
+
const existing = catalog[`${eventSpace}.${key}`];
|
|
1520
|
+
if (existing && existing.plugin !== name) throw new Error(`${name} event "${eventSpace}.${key}" is already in the catalog of service "${service.name}"`);
|
|
1521
|
+
events[key] = existing ?? Object.freeze({
|
|
1522
|
+
name: `${service.name}.${eventSpace}.${key}`,
|
|
1523
|
+
service: service.name,
|
|
1524
|
+
schema,
|
|
1525
|
+
plugin: name
|
|
1526
|
+
});
|
|
1527
|
+
}
|
|
1528
|
+
const added = {};
|
|
1529
|
+
const hooks = Object.fromEntries(HOOK_NAMES.map((hook) => [hook, (fn) => {
|
|
1530
|
+
if (typeof fn !== "function") throw new Error(`${name}: hooks.${hook} needs a function`);
|
|
1531
|
+
(added[hook] ??= []).push((args) => fn({
|
|
1532
|
+
...args,
|
|
1533
|
+
ctx: {
|
|
1534
|
+
...args.ctx,
|
|
1535
|
+
deps
|
|
1536
|
+
}
|
|
1537
|
+
}));
|
|
1538
|
+
}]));
|
|
1539
|
+
const routes = {
|
|
1540
|
+
action: (config) => context.routes.action(config),
|
|
1541
|
+
endpoint: (config) => context.routes.endpoint({
|
|
1542
|
+
...config,
|
|
1543
|
+
handler: (args) => config.handler({
|
|
1544
|
+
...args,
|
|
1545
|
+
ctx: {
|
|
1546
|
+
...args.ctx,
|
|
1547
|
+
deps
|
|
1548
|
+
}
|
|
1549
|
+
})
|
|
1550
|
+
})
|
|
1551
|
+
};
|
|
1552
|
+
const before = /* @__PURE__ */ new Set([
|
|
1553
|
+
...service.actions.values(),
|
|
1554
|
+
...service.tools.values(),
|
|
1555
|
+
...service.listSockets()
|
|
1556
|
+
]);
|
|
1557
|
+
const started = bindings;
|
|
1558
|
+
const api = part({
|
|
1559
|
+
options,
|
|
1560
|
+
secrets,
|
|
1561
|
+
tables,
|
|
1562
|
+
events,
|
|
1563
|
+
deps,
|
|
1564
|
+
service,
|
|
1565
|
+
resource,
|
|
1566
|
+
routes,
|
|
1567
|
+
hooks
|
|
1568
|
+
});
|
|
1569
|
+
if (api && typeof api.then === "function") throw new Error("Plugin setup must be synchronous");
|
|
1570
|
+
for (const action of [...service.actions.values(), ...service.tools.values()]) if (!before.has(action)) bindPluginDeps(name, action, deps, started);
|
|
1571
|
+
for (const socket of service.listSockets()) if (!before.has(socket)) socket[PLUGIN_DEPS] ??= deps;
|
|
1572
|
+
pending.push(() => {
|
|
1573
|
+
const database = service.getDatabaseHandle?.();
|
|
1574
|
+
for (const table of Object.values(tables)) database?.addTable?.(getTableName$1(table), table);
|
|
1575
|
+
if (Object.keys(events).length) service.events = Object.freeze({
|
|
1576
|
+
...catalog,
|
|
1577
|
+
...Object.fromEntries(Object.entries(events).map(([key, ref]) => [`${eventSpace}.${key}`, ref]))
|
|
1578
|
+
});
|
|
1579
|
+
const store = host[HOST_HOOKS] ??= {};
|
|
1580
|
+
for (const [hook, fns] of Object.entries(added)) (store[hook] ??= []).push(...fns);
|
|
1581
|
+
internals.installs.push({
|
|
1582
|
+
scope: resource ? "resource" : "service",
|
|
1583
|
+
service: service.name,
|
|
1584
|
+
resource: resource?.name
|
|
1585
|
+
});
|
|
1586
|
+
internals.order ??= ++installCount;
|
|
1587
|
+
});
|
|
1588
|
+
return resource ? api ?? {} : api;
|
|
1589
|
+
};
|
|
1590
|
+
return Object.freeze({
|
|
1591
|
+
[Symbol.for("brickkit.plugin.kind")]: "plugin",
|
|
1592
|
+
name,
|
|
1593
|
+
info,
|
|
1594
|
+
setup,
|
|
1595
|
+
[INTERNALS]: internals,
|
|
1596
|
+
[pluginFinish]: (installed) => {
|
|
1597
|
+
const commit = pending.pop();
|
|
1598
|
+
if (installed) commit?.();
|
|
1599
|
+
}
|
|
1600
|
+
});
|
|
1601
|
+
};
|
|
1602
|
+
return Object.assign(factory, { info });
|
|
1603
|
+
}
|
|
1604
|
+
/** Counts bindings, so a setup can tell a nested install's from an earlier one's. */
|
|
1605
|
+
let bindings = 0;
|
|
1606
|
+
/**
|
|
1607
|
+
* Give an action's `execute` and `authorize` the plugin's deps as `ctx.deps`.
|
|
1608
|
+
* The config is changed in place: every way an action runs (HTTP, compiled
|
|
1609
|
+
* routes, `action.run`, RPC) reads `config.execute` from it. A nested
|
|
1610
|
+
* definePlugin binds its own actions first, so they keep its deps.
|
|
1611
|
+
*
|
|
1612
|
+
* @throws When the action is already bound to another install's deps: one
|
|
1613
|
+
* action object shared by two installs could only run with one of them.
|
|
1614
|
+
*/
|
|
1615
|
+
function bindPluginDeps(plugin, action, deps, started) {
|
|
1616
|
+
const config = action.config;
|
|
1617
|
+
if (!config) return;
|
|
1618
|
+
const bound = config[PLUGIN_DEPS];
|
|
1619
|
+
if (bound) {
|
|
1620
|
+
if (bound.deps === deps || bound.at > started) return;
|
|
1621
|
+
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`);
|
|
1622
|
+
}
|
|
1623
|
+
config[PLUGIN_DEPS] = {
|
|
1624
|
+
deps,
|
|
1625
|
+
at: ++bindings
|
|
1626
|
+
};
|
|
1627
|
+
const { execute, authorize } = config;
|
|
1628
|
+
if (typeof execute === "function") config.execute = (args) => execute({
|
|
1629
|
+
...args,
|
|
1630
|
+
ctx: {
|
|
1631
|
+
...args.ctx,
|
|
1632
|
+
deps
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
if (typeof authorize === "function") config.authorize = (args) => authorize({
|
|
1636
|
+
...args,
|
|
1637
|
+
ctx: {
|
|
1638
|
+
...args.ctx,
|
|
1639
|
+
deps
|
|
1640
|
+
}
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
/** Check the deps passed at install against the ports the plugin declares. */
|
|
1644
|
+
function checkDeps(plugin, factory, ports, given = {}) {
|
|
1645
|
+
if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${plugin}: deps must be an object`);
|
|
1646
|
+
const declared = Object.keys(ports ?? {});
|
|
1647
|
+
const provided = given;
|
|
1648
|
+
const extra = Object.keys(provided).filter((key) => !declared.includes(key));
|
|
1649
|
+
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"}`);
|
|
1650
|
+
const missing = declared.filter((key) => provided[key] === void 0);
|
|
1651
|
+
if (missing.length) throw new Error(`${plugin} needs ${missing.map((key) => `deps.${key}`).join(", ")}; pass it when installing: ${factory}(options, { deps: { ${missing.join(", ")} } })`);
|
|
1652
|
+
return Object.freeze(Object.fromEntries(declared.map((key) => [key, provided[key]])));
|
|
1653
|
+
}
|
|
1654
|
+
function checkOptions(plugin, schema, input) {
|
|
1655
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error(`${plugin}: options must be an object`);
|
|
1656
|
+
if (!schema) {
|
|
1657
|
+
if (Object.keys(input).length) throw new Error(`${plugin} takes no options`);
|
|
1658
|
+
return {};
|
|
1659
|
+
}
|
|
1660
|
+
const value = Value.Default(schema, structuredClone(input));
|
|
1661
|
+
const result = validateWithSchema(schema, value);
|
|
1662
|
+
if (!result.success) {
|
|
1663
|
+
const [first] = result.errors;
|
|
1664
|
+
const option = first.path.replace(/^\//, "").replaceAll("/", ".");
|
|
1665
|
+
throw new Error(`${plugin}: option ${option ? `"${option}"` : ""} ${first.message}`.replace(/\s+/g, " "));
|
|
1666
|
+
}
|
|
1667
|
+
return value;
|
|
1668
|
+
}
|
|
1669
|
+
function isPluginInstance(value) {
|
|
1670
|
+
return typeof value === "object" && value !== null && INTERNALS in value;
|
|
1671
|
+
}
|
|
1672
|
+
function internalsOf(value) {
|
|
1673
|
+
return isPluginInstance(value) ? value[INTERNALS] ?? void 0 : void 0;
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* What `brick()` does with plugins: install those given in `plugins` on the
|
|
1677
|
+
* app, run every plugin's `app` part in install order, and return the
|
|
1678
|
+
* lifecycle, middleware and listeners they contributed.
|
|
1679
|
+
*/
|
|
1680
|
+
function setupAppPlugins(installedOnServices, appPlugins) {
|
|
1681
|
+
const instances = /* @__PURE__ */ new Set();
|
|
1682
|
+
for (const descriptor of installedOnServices) if (isPluginInstance(descriptor)) instances.add(descriptor);
|
|
1683
|
+
const ordered = [...instances].sort((a, b) => (internalsOf(a).order ?? 0) - (internalsOf(b).order ?? 0));
|
|
1684
|
+
const onApp = /* @__PURE__ */ new Set();
|
|
1685
|
+
for (const plugin of appPlugins) {
|
|
1686
|
+
const internals = internalsOf(plugin);
|
|
1687
|
+
if (!internals) throw new Error("brick({ plugins }) takes instances from definePlugin(), such as audit()");
|
|
1688
|
+
const { manifest } = internals;
|
|
1689
|
+
if (!manifest.app || manifest.tables || manifest.events) throw new Error(`${manifest.name} cannot be installed on the app; ${manifest.resource ? "use resource.use()" : "use service.use()"}`);
|
|
1690
|
+
for (const required of manifest.requires ?? []) if (!onApp.has(required)) throw new Error(`${manifest.name} requires ${required}, installed in brick({ plugins }) before it`);
|
|
1691
|
+
if (onApp.has(manifest.name)) throw new Error(`Plugin ${manifest.name} is installed on the app twice`);
|
|
1692
|
+
const installed = ordered.find((other) => internalsOf(other).manifest.name === manifest.name);
|
|
1693
|
+
if (installed) throw new Error(`Plugin ${manifest.name} is already installed with ${internalsOf(installed).installs.map((install) => install.scope === "resource" ? `${install.service}.${install.resource}.use()` : `${install.service}.use()`).join(", ")}, which runs its app part too; remove it from brick({ plugins })`);
|
|
1694
|
+
onApp.add(manifest.name);
|
|
1695
|
+
if (!internals.installs.some((item) => item.scope === "app")) internals.installs.push({ scope: "app" });
|
|
1696
|
+
ordered.push(plugin);
|
|
1697
|
+
}
|
|
1698
|
+
const lifecycles = [];
|
|
1699
|
+
const middleware = [];
|
|
1700
|
+
const listeners = [];
|
|
1701
|
+
const listed = [];
|
|
1702
|
+
for (const plugin of ordered) {
|
|
1703
|
+
const { manifest, options, deps, installs, dashboard } = internalsOf(plugin);
|
|
1704
|
+
for (const install of installs) listed.push(Object.freeze({
|
|
1705
|
+
name: manifest.name,
|
|
1706
|
+
...manifest.brick ? { brick: manifest.brick } : {},
|
|
1707
|
+
...install,
|
|
1708
|
+
...dashboard ? { dashboard } : {}
|
|
1709
|
+
}));
|
|
1710
|
+
if (!manifest.app) continue;
|
|
1711
|
+
const lifecycle = {
|
|
1712
|
+
options,
|
|
1713
|
+
secrets: manifest.secrets ?? {},
|
|
1714
|
+
deps
|
|
1715
|
+
};
|
|
1716
|
+
const own = {
|
|
1717
|
+
start: [],
|
|
1718
|
+
stop: []
|
|
1719
|
+
};
|
|
1720
|
+
manifest.app({
|
|
1721
|
+
...lifecycle,
|
|
1722
|
+
on(event, handler) {
|
|
1723
|
+
if (event !== "start" && event !== "stop") throw new Error(`${manifest.name}: on() takes "start" or "stop"`);
|
|
1724
|
+
own[event].push(handler);
|
|
1725
|
+
},
|
|
1726
|
+
middleware(handler) {
|
|
1727
|
+
middleware.push(handler);
|
|
1728
|
+
},
|
|
1729
|
+
listeners(...items) {
|
|
1730
|
+
listeners.push(...items.map((listener) => {
|
|
1731
|
+
if (listener.workflow) throw new Error(`${manifest.name}: plugins can't add workflow listeners yet, because workflow steps would see the app's deps instead of the plugin's; use a run listener ('${listener.name}')`);
|
|
1732
|
+
const run = listener.run;
|
|
1733
|
+
return run ? {
|
|
1734
|
+
...listener,
|
|
1735
|
+
run: (delivery) => runWithDeps(deps, () => run(delivery))
|
|
1736
|
+
} : listener;
|
|
1737
|
+
}));
|
|
1738
|
+
}
|
|
1739
|
+
});
|
|
1740
|
+
lifecycles.push({
|
|
1741
|
+
start: async () => {
|
|
1742
|
+
for (const handler of own.start) await handler(lifecycle);
|
|
1743
|
+
},
|
|
1744
|
+
stop: async () => {
|
|
1745
|
+
for (const handler of own.stop) await handler(lifecycle);
|
|
1746
|
+
}
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
return {
|
|
1750
|
+
lifecycles,
|
|
1751
|
+
middleware,
|
|
1752
|
+
listeners,
|
|
1753
|
+
plugins: listed
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
/**
|
|
1757
|
+
* Start in install order. Stop what started, in reverse order; a start that
|
|
1758
|
+
* fails stops those before it and rethrows.
|
|
1759
|
+
*/
|
|
1760
|
+
function pluginLifecycle(lifecycles) {
|
|
1761
|
+
let started;
|
|
1762
|
+
const running = [];
|
|
1763
|
+
const stopAll = async () => {
|
|
1764
|
+
const errors = [];
|
|
1765
|
+
for (const item of running.splice(0).reverse()) try {
|
|
1766
|
+
await item.stop();
|
|
1767
|
+
} catch (error) {
|
|
1768
|
+
errors.push(error);
|
|
1769
|
+
}
|
|
1770
|
+
if (errors.length === 1) throw errors[0];
|
|
1771
|
+
if (errors.length) throw new AggregateError(errors, "Plugins failed to stop");
|
|
1772
|
+
};
|
|
1773
|
+
return {
|
|
1774
|
+
start() {
|
|
1775
|
+
return started ??= (async () => {
|
|
1776
|
+
for (const item of lifecycles) {
|
|
1777
|
+
try {
|
|
1778
|
+
await item.start();
|
|
1779
|
+
} catch (error) {
|
|
1780
|
+
await stopAll().catch(() => void 0);
|
|
1781
|
+
started = void 0;
|
|
1782
|
+
throw error;
|
|
1783
|
+
}
|
|
1784
|
+
running.push(item);
|
|
1785
|
+
}
|
|
1786
|
+
})();
|
|
1787
|
+
},
|
|
1788
|
+
async stop() {
|
|
1789
|
+
await started?.catch(() => void 0);
|
|
1790
|
+
started = void 0;
|
|
1791
|
+
await stopAll();
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
//#endregion
|
|
1088
1796
|
//#region src/compiler/runtime.ts
|
|
1089
1797
|
const EMPTY_SERVICES$2 = Object.freeze({});
|
|
1090
1798
|
const DEFAULT_REQUEST$2 = new Request("http://localhost");
|
|
@@ -1283,18 +1991,26 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
1283
1991
|
}
|
|
1284
1992
|
}
|
|
1285
1993
|
}
|
|
1286
|
-
|
|
1994
|
+
let coercedParams = params;
|
|
1995
|
+
if (params && plan.coercions) for (const c of plan.coercions) {
|
|
1996
|
+
if (!c.isNumber || typeof params[c.key] !== "string") continue;
|
|
1997
|
+
const num = Number(params[c.key]);
|
|
1998
|
+
if (isNaN(num)) continue;
|
|
1999
|
+
if (coercedParams === params) coercedParams = { ...params };
|
|
2000
|
+
coercedParams[c.key] = num;
|
|
2001
|
+
}
|
|
2002
|
+
const hasP = isNonEmpty(coercedParams);
|
|
1287
2003
|
const hasB = isNonEmpty(body);
|
|
1288
2004
|
const hasQ = isNonEmpty(coercedQuery);
|
|
1289
2005
|
if (plan.isGetLike) {
|
|
1290
2006
|
if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
1291
|
-
else if (hasP && !hasQ && !hasB) input =
|
|
2007
|
+
else if (hasP && !hasQ && !hasB) input = coercedParams;
|
|
1292
2008
|
else if (hasB && !hasP && !hasQ) input = body;
|
|
1293
|
-
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery,
|
|
2009
|
+
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, coercedParams, body);
|
|
1294
2010
|
} else if (hasB && !hasP && !hasQ) input = body;
|
|
1295
|
-
else if (hasP && !hasB && !hasQ) input =
|
|
2011
|
+
else if (hasP && !hasB && !hasQ) input = coercedParams;
|
|
1296
2012
|
else if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
1297
|
-
else if (hasP || hasB || hasQ) input = Object.assign({},
|
|
2013
|
+
else if (hasP || hasB || hasQ) input = Object.assign({}, coercedParams, body, coercedQuery);
|
|
1298
2014
|
}
|
|
1299
2015
|
const ctx = {
|
|
1300
2016
|
request: request instanceof Request ? request : DEFAULT_REQUEST$1,
|
|
@@ -1303,6 +2019,7 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
1303
2019
|
db: plan.cachedDb ?? plan.service.getDb(),
|
|
1304
2020
|
logger: plan.logger,
|
|
1305
2021
|
services: EMPTY_SERVICES$1,
|
|
2022
|
+
deps: plan.service.deps ?? EMPTY_SERVICES$1,
|
|
1306
2023
|
metadata: { headers },
|
|
1307
2024
|
_resolved: true
|
|
1308
2025
|
};
|
|
@@ -1405,7 +2122,15 @@ function createHandlerFactory(route) {
|
|
|
1405
2122
|
coercedQuery = { ...query };
|
|
1406
2123
|
for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
|
|
1407
2124
|
}
|
|
1408
|
-
let
|
|
2125
|
+
let coercedParams = params;
|
|
2126
|
+
if (params && route.coercions.length) for (const { key, type } of route.coercions) {
|
|
2127
|
+
if (type !== "number" || typeof params[key] !== "string") continue;
|
|
2128
|
+
const value = Number(params[key]);
|
|
2129
|
+
if (Number.isNaN(value)) continue;
|
|
2130
|
+
if (coercedParams === params) coercedParams = { ...params };
|
|
2131
|
+
coercedParams[key] = value;
|
|
2132
|
+
}
|
|
2133
|
+
let input = readLike ? runtime.mergeInput(coercedQuery, coercedParams, body) : runtime.mergeInput(coercedParams, body, coercedQuery);
|
|
1409
2134
|
if (objectInput) input ??= {};
|
|
1410
2135
|
return input;
|
|
1411
2136
|
} : () => void 0;
|
|
@@ -1434,6 +2159,7 @@ function createHandlerFactory(route) {
|
|
|
1434
2159
|
db: cachedDb ?? service.getDb(),
|
|
1435
2160
|
logger,
|
|
1436
2161
|
services: runtime.emptyServices,
|
|
2162
|
+
deps: service.deps ?? runtime.emptyServices,
|
|
1437
2163
|
metadata: { headers },
|
|
1438
2164
|
_resolved: true
|
|
1439
2165
|
};
|
|
@@ -1674,7 +2400,8 @@ function hoistAnchoredSchemas(spec) {
|
|
|
1674
2400
|
* Build the OpenAPI 3.1 document for the services: one path per action route,
|
|
1675
2401
|
* with request and response schemas from the actions' TypeBox schemas, their
|
|
1676
2402
|
* declared errors, tags by service, and a bearer security scheme where any
|
|
1677
|
-
* action needs authorization.
|
|
2403
|
+
* action needs authorization. Declared events are listed under `x-brick-events`,
|
|
2404
|
+
* by wire name, with their service and payload schema.
|
|
1678
2405
|
*
|
|
1679
2406
|
* `brick()` calls this for `/openapi.json`; call it yourself to write the
|
|
1680
2407
|
* document to a file or feed another tool.
|
|
@@ -1691,19 +2418,22 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1691
2418
|
const prefix = options.prefix ?? "/api";
|
|
1692
2419
|
const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
|
|
1693
2420
|
const paths = {};
|
|
1694
|
-
const
|
|
2421
|
+
const tags = /* @__PURE__ */ new Map();
|
|
1695
2422
|
let hasAnyAuthorizedAction = false;
|
|
1696
2423
|
for (const service of services) {
|
|
1697
|
-
|
|
2424
|
+
tags.set(service.name, `Actions exposed by '${service.name}' service`);
|
|
1698
2425
|
for (const action of service.listActions()) {
|
|
1699
|
-
const
|
|
1700
|
-
if (
|
|
1701
|
-
const routePath =
|
|
1702
|
-
const method =
|
|
2426
|
+
const route = getActionRoute(action, prefix);
|
|
2427
|
+
if (route === false) continue;
|
|
2428
|
+
const routePath = route.path;
|
|
2429
|
+
const method = route.method.toLowerCase();
|
|
1703
2430
|
const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
|
|
1704
2431
|
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
1705
2432
|
if (!paths[actionPath]) paths[actionPath] = {};
|
|
1706
2433
|
if (paths[actionPath][method]) continue;
|
|
2434
|
+
const resource = action.resource;
|
|
2435
|
+
const group = resource ? `${service.name} · ${resource}` : service.name;
|
|
2436
|
+
if (resource) tags.set(group, `Routes of resource '${resource}' in service '${service.name}'`);
|
|
1707
2437
|
const hasAuth = getActionAccess(action).hasAuthorize;
|
|
1708
2438
|
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
1709
2439
|
const responses = {};
|
|
@@ -1713,7 +2443,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1713
2443
|
};
|
|
1714
2444
|
else responses["200"] = { description: "Successful response" };
|
|
1715
2445
|
const errorAlternatives = /* @__PURE__ */ new Set();
|
|
1716
|
-
const addError = (code, status, message) => {
|
|
2446
|
+
const addError = (code, status, message, details) => {
|
|
1717
2447
|
const key = `${status}:${code}`;
|
|
1718
2448
|
if (errorAlternatives.has(key)) return;
|
|
1719
2449
|
errorAlternatives.add(key);
|
|
@@ -1721,7 +2451,8 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1721
2451
|
type: "object",
|
|
1722
2452
|
properties: {
|
|
1723
2453
|
code: { const: code },
|
|
1724
|
-
status: { const: status }
|
|
2454
|
+
status: { const: status },
|
|
2455
|
+
...details ? { details } : {}
|
|
1725
2456
|
}
|
|
1726
2457
|
}] };
|
|
1727
2458
|
const existing = responses[String(status)];
|
|
@@ -1740,7 +2471,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1740
2471
|
}
|
|
1741
2472
|
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1742
2473
|
const def = errorDef;
|
|
1743
|
-
addError(code, def.status || 400, def.message || code);
|
|
2474
|
+
addError(code, def.status || 400, def.message || code, def.details);
|
|
1744
2475
|
}
|
|
1745
2476
|
addError("INTERNAL_SERVER_ERROR", 500, "Internal server error");
|
|
1746
2477
|
if (action.config.output) addError("VALIDATION_FAILED", 500, "Output validation error");
|
|
@@ -1748,7 +2479,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1748
2479
|
operationId: `${service.name}_${action.name}_${method}`,
|
|
1749
2480
|
summary: `${service.name}.${action.name}`,
|
|
1750
2481
|
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1751
|
-
tags:
|
|
2482
|
+
tags: [.../* @__PURE__ */ new Set([group, ...action.config.tags ?? []])],
|
|
1752
2483
|
...action.plugin ? { "x-brick-plugin": action.plugin } : {},
|
|
1753
2484
|
...action.resource ? { "x-brick-resource": action.resource } : {},
|
|
1754
2485
|
responses
|
|
@@ -1791,9 +2522,9 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1791
2522
|
description
|
|
1792
2523
|
},
|
|
1793
2524
|
paths,
|
|
1794
|
-
tags: Array.from(
|
|
2525
|
+
tags: Array.from(tags, ([name, description]) => ({
|
|
1795
2526
|
name,
|
|
1796
|
-
description
|
|
2527
|
+
description
|
|
1797
2528
|
}))
|
|
1798
2529
|
};
|
|
1799
2530
|
spec.components = { schemas: { ErrorEnvelope: {
|
|
@@ -1832,6 +2563,12 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1832
2563
|
bearerFormat: "JWT",
|
|
1833
2564
|
description: "Enter your Bearer authentication token"
|
|
1834
2565
|
} } });
|
|
2566
|
+
const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
|
|
2567
|
+
service: service.name,
|
|
2568
|
+
payload: ref.schema,
|
|
2569
|
+
...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
|
|
2570
|
+
}])));
|
|
2571
|
+
if (Object.keys(events).length) spec["x-brick-events"] = events;
|
|
1835
2572
|
const document = JSON.parse(JSON.stringify(spec));
|
|
1836
2573
|
hoistAnchoredSchemas(document);
|
|
1837
2574
|
return document;
|
|
@@ -1932,7 +2669,7 @@ var SecretRef = class {
|
|
|
1932
2669
|
* Declare a secret. Idempotent: re-declaring the same name returns the
|
|
1933
2670
|
* original ref (first declaration wins) so module re-evaluation is safe.
|
|
1934
2671
|
*/
|
|
1935
|
-
function
|
|
2672
|
+
function defineSecret(name, options = {}) {
|
|
1936
2673
|
const existing = registry.get(name);
|
|
1937
2674
|
if (existing) return existing;
|
|
1938
2675
|
const ref = new SecretRef(name, options);
|
|
@@ -2215,6 +2952,7 @@ function endpointPaths(defs) {
|
|
|
2215
2952
|
...def.summary ? { summary: def.summary } : {},
|
|
2216
2953
|
...def.description ? { description: def.description } : {},
|
|
2217
2954
|
...def.tags ? { tags: def.tags } : {},
|
|
2955
|
+
...def.plugin ? { "x-brick-plugin": def.plugin } : {},
|
|
2218
2956
|
...params.length > 0 ? { parameters: params } : {},
|
|
2219
2957
|
responses: { 200: { description: "Successful response" } }
|
|
2220
2958
|
};
|
|
@@ -2225,44 +2963,44 @@ function endpointPaths(defs) {
|
|
|
2225
2963
|
//#region src/events/outbox.ts
|
|
2226
2964
|
const OUTBOX = Symbol.for("brick.outbox");
|
|
2227
2965
|
function sqliteOutbox(name) {
|
|
2228
|
-
const timestampMs = (column) => integer$
|
|
2966
|
+
const timestampMs = (column) => integer$1(column, { mode: "timestamp_ms" });
|
|
2229
2967
|
return sqliteTable$1(name, {
|
|
2230
|
-
seq: integer$
|
|
2231
|
-
id: text$
|
|
2232
|
-
eventId: text$
|
|
2233
|
-
listener: text$
|
|
2234
|
-
name: text$
|
|
2235
|
-
payload: text$
|
|
2236
|
-
traceId: text$
|
|
2237
|
-
source: text$
|
|
2968
|
+
seq: integer$1("seq").primaryKey({ autoIncrement: true }),
|
|
2969
|
+
id: text$1("id").notNull().unique(),
|
|
2970
|
+
eventId: text$1("event_id").notNull(),
|
|
2971
|
+
listener: text$1("listener").notNull(),
|
|
2972
|
+
name: text$1("name").notNull(),
|
|
2973
|
+
payload: text$1("payload", { mode: "json" }).notNull(),
|
|
2974
|
+
traceId: text$1("trace_id"),
|
|
2975
|
+
source: text$1("source"),
|
|
2238
2976
|
occurredAt: timestampMs("occurred_at").notNull(),
|
|
2239
|
-
status: text$
|
|
2240
|
-
attempts: integer$
|
|
2241
|
-
lastError: text$
|
|
2977
|
+
status: text$1("status").$type().notNull(),
|
|
2978
|
+
attempts: integer$1("attempts").notNull().default(0),
|
|
2979
|
+
lastError: text$1("last_error"),
|
|
2242
2980
|
availableAt: timestampMs("available_at").notNull(),
|
|
2243
2981
|
claimedAt: timestampMs("claimed_at"),
|
|
2244
2982
|
deliveredAt: timestampMs("delivered_at")
|
|
2245
|
-
}, (table) => [index$
|
|
2983
|
+
}, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
|
|
2246
2984
|
}
|
|
2247
2985
|
function postgresOutbox(name) {
|
|
2248
2986
|
const at = (column) => timestamp(column, { withTimezone: true });
|
|
2249
2987
|
return pgTable(name, {
|
|
2250
2988
|
seq: bigserial("seq", { mode: "number" }).primaryKey(),
|
|
2251
|
-
id: text$
|
|
2252
|
-
eventId: text$
|
|
2253
|
-
listener: text$
|
|
2254
|
-
name: text$
|
|
2989
|
+
id: text$2("id").notNull().unique(),
|
|
2990
|
+
eventId: text$2("event_id").notNull(),
|
|
2991
|
+
listener: text$2("listener").notNull(),
|
|
2992
|
+
name: text$2("name").notNull(),
|
|
2255
2993
|
payload: jsonb("payload").notNull(),
|
|
2256
|
-
traceId: text$
|
|
2257
|
-
source: text$
|
|
2994
|
+
traceId: text$2("trace_id"),
|
|
2995
|
+
source: text$2("source"),
|
|
2258
2996
|
occurredAt: at("occurred_at").notNull(),
|
|
2259
|
-
status: text$
|
|
2260
|
-
attempts: integer$
|
|
2261
|
-
lastError: text$
|
|
2997
|
+
status: text$2("status").$type().notNull(),
|
|
2998
|
+
attempts: integer$2("attempts").notNull().default(0),
|
|
2999
|
+
lastError: text$2("last_error"),
|
|
2262
3000
|
availableAt: at("available_at").notNull(),
|
|
2263
3001
|
claimedAt: at("claimed_at"),
|
|
2264
3002
|
deliveredAt: at("delivered_at")
|
|
2265
|
-
}, (table) => [index$
|
|
3003
|
+
}, (table) => [index$2(`${name}_due`).on(table.status, table.availableAt), index$2(`${name}_event`).on(table.eventId)]);
|
|
2266
3004
|
}
|
|
2267
3005
|
function outboxTable(engine, options = {}) {
|
|
2268
3006
|
const name = options.name ?? "brick_outbox";
|
|
@@ -2389,6 +3127,10 @@ async function begin(db, open, fn) {
|
|
|
2389
3127
|
release();
|
|
2390
3128
|
}
|
|
2391
3129
|
}
|
|
3130
|
+
/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
|
|
3131
|
+
function inTransaction(db) {
|
|
3132
|
+
return joined(db) !== void 0;
|
|
3133
|
+
}
|
|
2392
3134
|
/**
|
|
2393
3135
|
* Run `fn` once the transaction that `db` belongs to has committed, or now when
|
|
2394
3136
|
* `db` is not in one opened by `runInTransaction`. It never runs when that
|
|
@@ -2417,6 +3159,23 @@ function resolveDispatchOptions(options = {}) {
|
|
|
2417
3159
|
};
|
|
2418
3160
|
}
|
|
2419
3161
|
const PURGE_INTERVAL_MS = 6e4;
|
|
3162
|
+
/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry". */
|
|
3163
|
+
function decideRetry(listener, error) {
|
|
3164
|
+
if (!listener.retry) return "retry";
|
|
3165
|
+
try {
|
|
3166
|
+
return listener.retry(error instanceof ActionExecutionError && listener.errors?.[error.code] ? {
|
|
3167
|
+
code: error.code,
|
|
3168
|
+
message: error.message,
|
|
3169
|
+
details: error.details
|
|
3170
|
+
} : {
|
|
3171
|
+
code: "UNKNOWN",
|
|
3172
|
+
message: error instanceof Error ? error.message : String(error),
|
|
3173
|
+
cause: error
|
|
3174
|
+
});
|
|
3175
|
+
} catch {
|
|
3176
|
+
return "retry";
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
2420
3179
|
function backoffMs(attempt, maxBackoffMs) {
|
|
2421
3180
|
return Math.min(1e3 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);
|
|
2422
3181
|
}
|
|
@@ -2594,7 +3353,7 @@ var Dispatcher = class {
|
|
|
2594
3353
|
try {
|
|
2595
3354
|
await listener.run(delivery);
|
|
2596
3355
|
} catch (error) {
|
|
2597
|
-
await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts);
|
|
3356
|
+
await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(listener, error));
|
|
2598
3357
|
return;
|
|
2599
3358
|
}
|
|
2600
3359
|
await this.markDelivered(row);
|
|
@@ -2612,9 +3371,9 @@ var Dispatcher = class {
|
|
|
2612
3371
|
this.onError(error);
|
|
2613
3372
|
}
|
|
2614
3373
|
}
|
|
2615
|
-
async fail(row, error, maxAttempts) {
|
|
3374
|
+
async fail(row, error, maxAttempts, decision = "retry") {
|
|
2616
3375
|
const message = error instanceof Error ? error.message : String(error);
|
|
2617
|
-
if (row.attempts >= maxAttempts) {
|
|
3376
|
+
if (decision === "dead" || row.attempts >= maxAttempts) {
|
|
2618
3377
|
await this.park(row, message);
|
|
2619
3378
|
return;
|
|
2620
3379
|
}
|
|
@@ -2700,14 +3459,16 @@ function resolveWorkflowPaths(options = {}) {
|
|
|
2700
3459
|
var WorkflowRuntime = class {
|
|
2701
3460
|
world;
|
|
2702
3461
|
listeners;
|
|
3462
|
+
deps;
|
|
2703
3463
|
root;
|
|
2704
3464
|
dir;
|
|
2705
3465
|
ready;
|
|
2706
3466
|
connected;
|
|
2707
3467
|
closed = false;
|
|
2708
|
-
constructor(world, options, listeners) {
|
|
3468
|
+
constructor(world, options, listeners, deps = {}) {
|
|
2709
3469
|
this.world = world;
|
|
2710
3470
|
this.listeners = listeners;
|
|
3471
|
+
this.deps = deps;
|
|
2711
3472
|
({root: this.root, dir: this.dir} = resolveWorkflowPaths(options));
|
|
2712
3473
|
}
|
|
2713
3474
|
/** Begin loading the runtime now rather than at the first delivery. */
|
|
@@ -2786,7 +3547,8 @@ var WorkflowRuntime = class {
|
|
|
2786
3547
|
this.checkListeners(manifest);
|
|
2787
3548
|
const bundle = await this.loadBundle(flow);
|
|
2788
3549
|
if (typeof bundle.POST !== "function") throw new Error(`${flow} does not export a POST handler`);
|
|
2789
|
-
|
|
3550
|
+
const post = bundle.POST;
|
|
3551
|
+
this.world.registerHandler?.(WORKFLOW_QUEUE_PREFIX, (request) => runWithDeps(this.deps, () => post(request)));
|
|
2790
3552
|
await this.world.start?.();
|
|
2791
3553
|
return sdk;
|
|
2792
3554
|
}
|
|
@@ -2868,6 +3630,7 @@ async function stopAllEvents() {
|
|
|
2868
3630
|
* `app.events`.
|
|
2869
3631
|
*/
|
|
2870
3632
|
var EventsHub = class {
|
|
3633
|
+
deps;
|
|
2871
3634
|
byName = /* @__PURE__ */ new Map();
|
|
2872
3635
|
dispatchers = /* @__PURE__ */ new Map();
|
|
2873
3636
|
deliverables = /* @__PURE__ */ new Map();
|
|
@@ -2876,7 +3639,13 @@ var EventsHub = class {
|
|
|
2876
3639
|
recorderNames = [];
|
|
2877
3640
|
started = false;
|
|
2878
3641
|
stopping;
|
|
2879
|
-
|
|
3642
|
+
/**
|
|
3643
|
+
* @param options - The `events` option.
|
|
3644
|
+
* @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
|
|
3645
|
+
* listeners and workflow steps.
|
|
3646
|
+
*/
|
|
3647
|
+
constructor(options, deps = {}) {
|
|
3648
|
+
this.deps = deps;
|
|
2880
3649
|
for (const listener of options.listeners ?? []) {
|
|
2881
3650
|
if (typeof listener.name !== "string" || !listener.name) throw new Error("An event listener needs a name");
|
|
2882
3651
|
if (listener.name.includes(":")) throw new Error(`Event listener name '${listener.name}' must not contain ':'`);
|
|
@@ -2888,7 +3657,7 @@ var EventsHub = class {
|
|
|
2888
3657
|
const workflowListeners = [...this.byName.values()].filter((listener) => listener.workflow);
|
|
2889
3658
|
if (workflowListeners.length) {
|
|
2890
3659
|
if (!options.world) throw new Error(`Event listener '${workflowListeners[0].name}' runs a workflow, so events needs a world: brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.`);
|
|
2891
|
-
this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners);
|
|
3660
|
+
this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners, deps);
|
|
2892
3661
|
}
|
|
2893
3662
|
this.dispatchOptions = options.dispatch === false ? false : options.dispatch === true || options.dispatch === void 0 ? {} : options.dispatch;
|
|
2894
3663
|
}
|
|
@@ -2907,8 +3676,8 @@ var EventsHub = class {
|
|
|
2907
3676
|
if (!table) continue;
|
|
2908
3677
|
attached++;
|
|
2909
3678
|
this.recorderNames.push(service.name);
|
|
2910
|
-
const bound = this.bind(table);
|
|
2911
|
-
service.
|
|
3679
|
+
const bound = this.bind(table, (name, payload) => service.checkEvent?.(name, payload));
|
|
3680
|
+
service.setRecorder?.(bound);
|
|
2912
3681
|
const db = service.getDb();
|
|
2913
3682
|
if (db && typeof db === "object") recorders.set(db, bound);
|
|
2914
3683
|
}
|
|
@@ -3028,22 +3797,30 @@ var EventsHub = class {
|
|
|
3028
3797
|
let found = this.deliverables.get(name);
|
|
3029
3798
|
if (!found) {
|
|
3030
3799
|
const runtime = this.runtime;
|
|
3031
|
-
found =
|
|
3032
|
-
...listener.
|
|
3033
|
-
|
|
3034
|
-
|
|
3800
|
+
found = {
|
|
3801
|
+
...listener.errors ? { errors: listener.errors } : {},
|
|
3802
|
+
...listener.retry ? { retry: listener.retry } : {},
|
|
3803
|
+
...listener.workflow ? {
|
|
3804
|
+
...listener.maxAttempts !== void 0 ? { maxAttempts: listener.maxAttempts } : {},
|
|
3805
|
+
run: async (delivery) => {
|
|
3806
|
+
await runtime.startRun(listener, delivery);
|
|
3807
|
+
}
|
|
3808
|
+
} : {
|
|
3809
|
+
...listener.maxAttempts !== void 0 ? { maxAttempts: listener.maxAttempts } : {},
|
|
3810
|
+
run: (delivery) => runWithDeps(this.deps, () => listener.run(delivery))
|
|
3035
3811
|
}
|
|
3036
|
-
}
|
|
3812
|
+
};
|
|
3037
3813
|
this.deliverables.set(name, found);
|
|
3038
3814
|
}
|
|
3039
3815
|
return found;
|
|
3040
3816
|
}
|
|
3041
|
-
bind(table) {
|
|
3817
|
+
bind(table, check) {
|
|
3042
3818
|
const startAndNotify = () => {
|
|
3043
3819
|
this.start();
|
|
3044
3820
|
this.dispatchers.get(table)?.notify();
|
|
3045
3821
|
};
|
|
3046
3822
|
const insert = async (tx, context, name, payload) => {
|
|
3823
|
+
check(name, payload);
|
|
3047
3824
|
const listeners = this.matching(name);
|
|
3048
3825
|
if (!listeners.length) return false;
|
|
3049
3826
|
const eventId = newEventId();
|
|
@@ -3083,6 +3860,489 @@ var EventsHub = class {
|
|
|
3083
3860
|
}
|
|
3084
3861
|
};
|
|
3085
3862
|
//#endregion
|
|
3863
|
+
//#region src/socket.ts
|
|
3864
|
+
var SocketDenied = class extends Error {};
|
|
3865
|
+
const bytes = (value) => new TextEncoder().encode(value).byteLength;
|
|
3866
|
+
/** Validates and serializes one output message, rechecking what survives JSON. */
|
|
3867
|
+
function outputFrame(output, event, data) {
|
|
3868
|
+
const schema = Object.hasOwn(output, event) ? output[event] : void 0;
|
|
3869
|
+
if (!schema || !getCompiledCheck(schema).Check(data)) throw new Error("Invalid socket output");
|
|
3870
|
+
const frame = JSON.stringify({
|
|
3871
|
+
event,
|
|
3872
|
+
data
|
|
3873
|
+
});
|
|
3874
|
+
if (bytes(frame) > 65536) throw new Error("Socket output too large");
|
|
3875
|
+
if (!getCompiledCheck(schema).Check(JSON.parse(frame).data)) throw new Error("Socket output is not JSON-compatible");
|
|
3876
|
+
return frame;
|
|
3877
|
+
}
|
|
3878
|
+
/** Delivers within this process. The default broker of every app. */
|
|
3879
|
+
function localBroker() {
|
|
3880
|
+
const topics = /* @__PURE__ */ new Map();
|
|
3881
|
+
const epoch = Date.now();
|
|
3882
|
+
let counter = 0;
|
|
3883
|
+
/** Rooms dropped from `kept` once idle, at counter values up to this. */
|
|
3884
|
+
let swept = 0;
|
|
3885
|
+
const kept = /* @__PURE__ */ new Map();
|
|
3886
|
+
const prune = (names) => {
|
|
3887
|
+
for (const topic of names) {
|
|
3888
|
+
const room = kept.get(topic);
|
|
3889
|
+
if (!room) continue;
|
|
3890
|
+
const oldest = Date.now() - room.maxAgeMs;
|
|
3891
|
+
while (room.entries[0] && room.entries[0].at < oldest) room.trimmed = room.entries.shift().n;
|
|
3892
|
+
if (!room.entries.length) {
|
|
3893
|
+
kept.delete(topic);
|
|
3894
|
+
swept = counter;
|
|
3895
|
+
}
|
|
3896
|
+
}
|
|
3897
|
+
};
|
|
3898
|
+
return {
|
|
3899
|
+
publish(message, replay) {
|
|
3900
|
+
if (message.type === "emit" && replay) {
|
|
3901
|
+
const n = ++counter;
|
|
3902
|
+
message = {
|
|
3903
|
+
...message,
|
|
3904
|
+
seq: `${epoch}-${n}`
|
|
3905
|
+
};
|
|
3906
|
+
const room = kept.get(message.topic) ?? {
|
|
3907
|
+
entries: [],
|
|
3908
|
+
trimmed: 0,
|
|
3909
|
+
maxAgeMs: replay.maxAgeMs
|
|
3910
|
+
};
|
|
3911
|
+
kept.set(message.topic, room);
|
|
3912
|
+
room.entries.push({
|
|
3913
|
+
n,
|
|
3914
|
+
at: Date.now(),
|
|
3915
|
+
message
|
|
3916
|
+
});
|
|
3917
|
+
if (room.entries.length > replay.keep) room.trimmed = room.entries.shift().n;
|
|
3918
|
+
if (n % 1e3 === 0) prune([...kept.keys()]);
|
|
3919
|
+
}
|
|
3920
|
+
for (const deliver of topics.get(message.topic) ?? []) deliver(message);
|
|
3921
|
+
},
|
|
3922
|
+
head: () => `${epoch}-${counter}`,
|
|
3923
|
+
history(topic, since) {
|
|
3924
|
+
const [from, n] = since.split("-").map(Number);
|
|
3925
|
+
if (from !== epoch || n > counter) return void 0;
|
|
3926
|
+
prune([topic]);
|
|
3927
|
+
const room = kept.get(topic);
|
|
3928
|
+
if (!room) return n >= swept ? [] : void 0;
|
|
3929
|
+
if (n < room.trimmed) return void 0;
|
|
3930
|
+
return room.entries.filter((entry) => entry.n > n).map((entry) => entry.message);
|
|
3931
|
+
},
|
|
3932
|
+
subscribe(topic, deliver) {
|
|
3933
|
+
const listeners = topics.get(topic) ?? /* @__PURE__ */ new Set();
|
|
3934
|
+
listeners.add(deliver);
|
|
3935
|
+
topics.set(topic, listeners);
|
|
3936
|
+
return () => {
|
|
3937
|
+
listeners.delete(deliver);
|
|
3938
|
+
if (!listeners.size) topics.delete(topic);
|
|
3939
|
+
};
|
|
3940
|
+
}
|
|
3941
|
+
};
|
|
3942
|
+
}
|
|
3943
|
+
function defineServiceSocket(service, config, resolve) {
|
|
3944
|
+
if (!config.name || config.name.split(".").some((part) => !/^[a-zA-Z_][\w-]*$/.test(part))) throw new Error("Invalid socket name");
|
|
3945
|
+
if (config.path !== void 0 && (!config.path.startsWith("/") || /[?#*]/.test(config.path) || config.path.split("/").some((segment) => segment.startsWith(":")))) throw new Error("Socket path must be a static route (relative to its service) without a query or fragment");
|
|
3946
|
+
const input = Object.freeze({ ...config.input });
|
|
3947
|
+
const output = Object.freeze({ ...config.output });
|
|
3948
|
+
const handlers = { ...config.handlers };
|
|
3949
|
+
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");
|
|
3950
|
+
if ([...Object.keys(input), ...Object.keys(output)].some((key) => key.startsWith("$"))) throw new Error("Socket event names starting with $ are reserved");
|
|
3951
|
+
const maxRooms = config.maxRooms ?? 100;
|
|
3952
|
+
if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
|
|
3953
|
+
const replay = config.replay && { ...config.replay };
|
|
3954
|
+
if (replay && !(Number.isInteger(replay.keep) && replay.keep > 0 && replay.maxAgeMs > 0 && Number.isFinite(replay.maxAgeMs))) throw new Error("Socket replay needs a positive integer keep and a positive finite maxAgeMs");
|
|
3955
|
+
for (const schema of [...Object.values(input), ...Object.values(output)]) {
|
|
3956
|
+
serializeSocketSchema(schema);
|
|
3957
|
+
getCompiledCheck(schema);
|
|
3958
|
+
}
|
|
3959
|
+
const typed = (socket) => socket;
|
|
3960
|
+
const context = async (request) => {
|
|
3961
|
+
const ctx = await resolve(request);
|
|
3962
|
+
if (config.authorize && !await config.authorize({ ctx })) throw new SocketDenied();
|
|
3963
|
+
return ctx;
|
|
3964
|
+
};
|
|
3965
|
+
const topicPrefix = `${service}.${config.name}:`;
|
|
3966
|
+
const topic = (room) => {
|
|
3967
|
+
if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);
|
|
3968
|
+
return topicPrefix + room;
|
|
3969
|
+
};
|
|
3970
|
+
const brokers = /* @__PURE__ */ new Set();
|
|
3971
|
+
const publish = (messages, after) => {
|
|
3972
|
+
const send = () => {
|
|
3973
|
+
for (const broker of brokers) for (const message of messages) broker.publish(message, replay);
|
|
3974
|
+
};
|
|
3975
|
+
if (after === void 0) return send();
|
|
3976
|
+
if (!inTransaction(after)) throw new Error("Socket emit { after: tx } needs a tx from runInTransaction(db, (tx) => ...); a plain db.transaction() is not tracked, so the emit could be sent for a write that rolls back");
|
|
3977
|
+
onTransactionCommit(after, send);
|
|
3978
|
+
};
|
|
3979
|
+
return {
|
|
3980
|
+
schema: {
|
|
3981
|
+
name: config.name,
|
|
3982
|
+
path: config.path,
|
|
3983
|
+
description: config.description,
|
|
3984
|
+
input: Object.keys(input),
|
|
3985
|
+
output: Object.keys(output),
|
|
3986
|
+
hasAuthorize: !!config.authorize
|
|
3987
|
+
},
|
|
3988
|
+
input,
|
|
3989
|
+
output,
|
|
3990
|
+
allowedOrigins: config.allowedOrigins ? [...config.allowedOrigins] : void 0,
|
|
3991
|
+
allowMissingOrigin: config.allowMissingOrigin,
|
|
3992
|
+
maxRooms,
|
|
3993
|
+
replay,
|
|
3994
|
+
brokers,
|
|
3995
|
+
topicPrefix,
|
|
3996
|
+
topic,
|
|
3997
|
+
handle: {
|
|
3998
|
+
name: config.name,
|
|
3999
|
+
emit(rooms, ...[event, payload, options]) {
|
|
4000
|
+
const topics = [...new Set(typeof rooms === "string" ? [rooms] : rooms)].map(topic);
|
|
4001
|
+
const frame = outputFrame(output, event, payload);
|
|
4002
|
+
if (replay && bytes(frame) > 65236) throw new Error("Socket output too large");
|
|
4003
|
+
publish(topics.map((topic) => ({
|
|
4004
|
+
type: "emit",
|
|
4005
|
+
topic,
|
|
4006
|
+
frame
|
|
4007
|
+
})), options?.after);
|
|
4008
|
+
},
|
|
4009
|
+
kick(room, options = {}) {
|
|
4010
|
+
publish([{
|
|
4011
|
+
type: "kick",
|
|
4012
|
+
topic: topic(room),
|
|
4013
|
+
...options.also !== void 0 ? { also: topic(options.also) } : {},
|
|
4014
|
+
...options.reason !== void 0 ? { reason: String(options.reason) } : {}
|
|
4015
|
+
}], void 0);
|
|
4016
|
+
}
|
|
4017
|
+
},
|
|
4018
|
+
async connect(request) {
|
|
4019
|
+
const initial = await context(request);
|
|
4020
|
+
const rooms = [...new Set(config.rooms ? await config.rooms({ ctx: initial }) : [])];
|
|
4021
|
+
rooms.forEach(topic);
|
|
4022
|
+
if (rooms.length > maxRooms) throw new Error("Too many socket rooms");
|
|
4023
|
+
return {
|
|
4024
|
+
rooms,
|
|
4025
|
+
async open(socket) {
|
|
4026
|
+
await config.open?.({
|
|
4027
|
+
ctx: initial,
|
|
4028
|
+
socket: typed(socket)
|
|
4029
|
+
});
|
|
4030
|
+
},
|
|
4031
|
+
async message(event, data, socket) {
|
|
4032
|
+
const schema = Object.hasOwn(input, event) ? input[event] : void 0;
|
|
4033
|
+
if (!schema || !getCompiledCheck(schema).Check(data)) throw new SocketDenied();
|
|
4034
|
+
const ctx = await context(request);
|
|
4035
|
+
if (!socket.isOpen) return;
|
|
4036
|
+
const handler = handlers[event];
|
|
4037
|
+
await handler({
|
|
4038
|
+
input: data,
|
|
4039
|
+
ctx,
|
|
4040
|
+
socket: typed(socket)
|
|
4041
|
+
});
|
|
4042
|
+
},
|
|
4043
|
+
async join(room) {
|
|
4044
|
+
const ctx = await context(request);
|
|
4045
|
+
return !!config.join && await config.join({
|
|
4046
|
+
ctx,
|
|
4047
|
+
room
|
|
4048
|
+
});
|
|
4049
|
+
},
|
|
4050
|
+
async close(socket, code, reason) {
|
|
4051
|
+
await config.close?.({
|
|
4052
|
+
ctx: initial,
|
|
4053
|
+
socket: typed(socket),
|
|
4054
|
+
code,
|
|
4055
|
+
reason
|
|
4056
|
+
});
|
|
4057
|
+
}
|
|
4058
|
+
};
|
|
4059
|
+
}
|
|
4060
|
+
};
|
|
4061
|
+
}
|
|
4062
|
+
/** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */
|
|
4063
|
+
function socketPath(prefix, service, socket) {
|
|
4064
|
+
return joinRoute(ownerPath(prefix, service), socket.schema.path ?? `/${kebabCase(socket.schema.name)}`);
|
|
4065
|
+
}
|
|
4066
|
+
/** The v0.10 route, served too by `brick({ legacyRoutes: true })`. */
|
|
4067
|
+
function legacySocketPath(prefix, service, socket) {
|
|
4068
|
+
return legacyPath(prefix, service, socket.schema.name, socket.schema.path);
|
|
4069
|
+
}
|
|
4070
|
+
/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */
|
|
4071
|
+
function publicOrigin(request) {
|
|
4072
|
+
const forwarded = (name) => request.headers.get(name)?.split(",")[0]?.trim() || void 0;
|
|
4073
|
+
const url = new URL(request.url);
|
|
4074
|
+
const proto = forwarded("x-forwarded-proto");
|
|
4075
|
+
return `${proto ? `${proto}:` : url.protocol}//${forwarded("x-forwarded-host") ?? url.host}`;
|
|
4076
|
+
}
|
|
4077
|
+
const TOKEN_PROTOCOL = "brick.token.";
|
|
4078
|
+
const protocols = (request) => (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((protocol) => protocol.trim()).filter(Boolean);
|
|
4079
|
+
/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */
|
|
4080
|
+
function tokenRequest(request) {
|
|
4081
|
+
const offered = protocols(request);
|
|
4082
|
+
const token = offered.find((protocol) => protocol.startsWith(TOKEN_PROTOCOL))?.slice(12);
|
|
4083
|
+
if (!token) return {
|
|
4084
|
+
token: false,
|
|
4085
|
+
request
|
|
4086
|
+
};
|
|
4087
|
+
const headers = new Headers(request.headers);
|
|
4088
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
4089
|
+
const rest = offered.filter((protocol) => !protocol.startsWith(TOKEN_PROTOCOL));
|
|
4090
|
+
if (rest.length) headers.set("sec-websocket-protocol", rest.join(", "));
|
|
4091
|
+
else headers.delete("sec-websocket-protocol");
|
|
4092
|
+
return {
|
|
4093
|
+
token: true,
|
|
4094
|
+
request: new Request(request.url, {
|
|
4095
|
+
method: request.method,
|
|
4096
|
+
headers
|
|
4097
|
+
})
|
|
4098
|
+
};
|
|
4099
|
+
}
|
|
4100
|
+
/** Mounts native adapters. Each connection owns its queue and service session. */
|
|
4101
|
+
function mountSockets(app, sockets, broker, secret) {
|
|
4102
|
+
if (secret === "") throw new Error("Brick: sockets.secret can't be empty");
|
|
4103
|
+
const key = secret ?? randomBytes(32);
|
|
4104
|
+
const signature = (topic, seq) => createHmac("sha256", key).update(`${topic}\n${seq}`).digest("base64url").slice(0, 22);
|
|
4105
|
+
const sign = (topic, seq) => `${seq}.${signature(topic, seq)}`;
|
|
4106
|
+
const verify = (topic, signed) => {
|
|
4107
|
+
const [seq, sig] = signed.split(".");
|
|
4108
|
+
return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq))) ? seq : void 0;
|
|
4109
|
+
};
|
|
4110
|
+
if (sockets.some(({ definition }) => definition.replay) && !(broker.head && broker.history)) throw new Error("Brick: the socket broker does not support replay");
|
|
4111
|
+
for (const { definition } of sockets) definition.brokers.add(broker);
|
|
4112
|
+
app.cleanup(async () => {
|
|
4113
|
+
for (const { definition } of sockets) definition.brokers.delete(broker);
|
|
4114
|
+
await broker.close?.();
|
|
4115
|
+
});
|
|
4116
|
+
if (!sockets.length) return;
|
|
4117
|
+
app.use(websocket({
|
|
4118
|
+
maxPayloadLength: SOCKET_MAX_BYTES,
|
|
4119
|
+
backpressureLimit: SOCKET_BUFFER_BYTES,
|
|
4120
|
+
closeOnBackpressureLimit: true
|
|
4121
|
+
}));
|
|
4122
|
+
const paths = /* @__PURE__ */ new Map();
|
|
4123
|
+
for (const { path, definition } of sockets) paths.set(definition, [...paths.get(definition) ?? [], path]);
|
|
4124
|
+
for (const { service, definition } of sockets) {
|
|
4125
|
+
const routes = paths.get(definition);
|
|
4126
|
+
if (!routes) continue;
|
|
4127
|
+
paths.delete(definition);
|
|
4128
|
+
const logger = createLogger(`[Brick socket ${service}.${definition.schema.name}]`);
|
|
4129
|
+
const sessions = /* @__PURE__ */ new WeakMap();
|
|
4130
|
+
const connections = /* @__PURE__ */ new WeakMap();
|
|
4131
|
+
const roomOf = (topic) => topic.slice(definition.topicPrefix.length);
|
|
4132
|
+
const holders = /* @__PURE__ */ new Map();
|
|
4133
|
+
const control = (ws, event, data) => {
|
|
4134
|
+
if (ws.readyState === 1) ws.send(JSON.stringify({
|
|
4135
|
+
event,
|
|
4136
|
+
data
|
|
4137
|
+
}));
|
|
4138
|
+
};
|
|
4139
|
+
/** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */
|
|
4140
|
+
const enter = async (connection, topic, live = true) => {
|
|
4141
|
+
if (connection.rooms.has(topic)) return;
|
|
4142
|
+
connection.rooms.add(topic);
|
|
4143
|
+
if (live) connection.ws.subscribe(topic);
|
|
4144
|
+
let holder = holders.get(topic);
|
|
4145
|
+
if (!holder) {
|
|
4146
|
+
holder = {
|
|
4147
|
+
connections: /* @__PURE__ */ new Set(),
|
|
4148
|
+
unsubscribe: () => {}
|
|
4149
|
+
};
|
|
4150
|
+
holders.set(topic, holder);
|
|
4151
|
+
holder.unsubscribe = broker.subscribe(topic, deliver);
|
|
4152
|
+
}
|
|
4153
|
+
holder.connections.add(connection);
|
|
4154
|
+
await broker.ready?.(topic).catch(() => {});
|
|
4155
|
+
};
|
|
4156
|
+
const exit = (connection, topic) => {
|
|
4157
|
+
if (!connection.rooms.delete(topic)) return;
|
|
4158
|
+
connection.requested.delete(topic);
|
|
4159
|
+
if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);
|
|
4160
|
+
const holder = holders.get(topic);
|
|
4161
|
+
if (!holder?.connections.delete(connection) || holder.connections.size) return;
|
|
4162
|
+
holders.delete(topic);
|
|
4163
|
+
holder.unsubscribe();
|
|
4164
|
+
};
|
|
4165
|
+
/** A replayable emit carries its room and sequence. */
|
|
4166
|
+
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))}}`;
|
|
4167
|
+
const deliver = (message) => {
|
|
4168
|
+
if (message.type === "emit") {
|
|
4169
|
+
app.server?.publish(message.topic, frameOf(message));
|
|
4170
|
+
return;
|
|
4171
|
+
}
|
|
4172
|
+
for (const connection of holders.get(message.topic)?.connections ?? []) {
|
|
4173
|
+
if (message.also && !connection.ws.isSubscribed(message.also)) continue;
|
|
4174
|
+
exit(connection, message.topic);
|
|
4175
|
+
control(connection.ws, "$left", {
|
|
4176
|
+
room: roomOf(message.topic),
|
|
4177
|
+
...message.reason !== void 0 ? { reason: message.reason } : {}
|
|
4178
|
+
});
|
|
4179
|
+
}
|
|
4180
|
+
};
|
|
4181
|
+
/** `$join` and `$leave`, acknowledged with the same event. */
|
|
4182
|
+
const room = async (connection, event, data) => {
|
|
4183
|
+
const { room: name, since } = data && typeof data === "object" ? data : {};
|
|
4184
|
+
if (!isSocketRoom(name) || since !== void 0 && !isSocketSeq(since)) throw new SocketDenied();
|
|
4185
|
+
const topic = definition.topic(name);
|
|
4186
|
+
if (event === "$leave") {
|
|
4187
|
+
if (connection.requested.has(topic)) exit(connection, topic);
|
|
4188
|
+
control(connection.ws, "$leave", { room: name });
|
|
4189
|
+
return;
|
|
4190
|
+
}
|
|
4191
|
+
const isOpen = () => !connection.closed && connection.ws.readyState === 1;
|
|
4192
|
+
const ok = connection.rooms.has(topic) || connection.rooms.size < definition.maxRooms && await connection.session.join(name);
|
|
4193
|
+
if (!isOpen()) return;
|
|
4194
|
+
const replay = definition.replay;
|
|
4195
|
+
let seq;
|
|
4196
|
+
if (ok && !connection.rooms.has(topic)) {
|
|
4197
|
+
const entered = enter(connection, topic, !replay);
|
|
4198
|
+
connection.requested.add(topic);
|
|
4199
|
+
await entered;
|
|
4200
|
+
if (replay && connection.rooms.has(topic)) {
|
|
4201
|
+
const start = since === void 0 ? await broker.head(topic) : verify(topic, since);
|
|
4202
|
+
const missed = start === void 0 ? void 0 : await broker.history(topic, start, replay);
|
|
4203
|
+
const restart = missed ? void 0 : await broker.head(topic);
|
|
4204
|
+
if (!isOpen()) return;
|
|
4205
|
+
if (connection.rooms.has(topic)) {
|
|
4206
|
+
connection.ws.subscribe(topic);
|
|
4207
|
+
if (since === void 0) seq = sign(topic, start);
|
|
4208
|
+
for (const message of missed ?? []) if (message.type === "emit") connection.ws.send(frameOf(message));
|
|
4209
|
+
if (restart !== void 0) control(connection.ws, "$gap", {
|
|
4210
|
+
room: name,
|
|
4211
|
+
seq: sign(topic, restart)
|
|
4212
|
+
});
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
4215
|
+
}
|
|
4216
|
+
control(connection.ws, "$join", {
|
|
4217
|
+
room: name,
|
|
4218
|
+
ok: ok && connection.rooms.has(topic),
|
|
4219
|
+
...seq !== void 0 ? { seq } : {}
|
|
4220
|
+
});
|
|
4221
|
+
};
|
|
4222
|
+
const fail = (ws, error) => {
|
|
4223
|
+
if (!(error instanceof SocketDenied)) logger.error({
|
|
4224
|
+
error,
|
|
4225
|
+
service,
|
|
4226
|
+
socket: definition.schema.name
|
|
4227
|
+
});
|
|
4228
|
+
if (ws.readyState !== 1) return;
|
|
4229
|
+
ws.close(error instanceof SocketDenied ? 1008 : 1011, error instanceof SocketDenied ? "Message refused" : "Socket handler failed");
|
|
4230
|
+
};
|
|
4231
|
+
for (const path of routes) app.ws(path, {
|
|
4232
|
+
async beforeHandle({ request }) {
|
|
4233
|
+
if (sessions.has(request)) return;
|
|
4234
|
+
const { token, request: resolved } = tokenRequest(request);
|
|
4235
|
+
const origin = request.headers.get("origin");
|
|
4236
|
+
if (origin ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(origin) : !(definition.allowMissingOrigin ?? token)) return new Response("Socket origin refused", { status: 403 });
|
|
4237
|
+
try {
|
|
4238
|
+
sessions.set(request, await definition.connect(resolved));
|
|
4239
|
+
} catch (error) {
|
|
4240
|
+
if (!(error instanceof SocketDenied)) logger.error({
|
|
4241
|
+
error,
|
|
4242
|
+
service,
|
|
4243
|
+
socket: definition.schema.name
|
|
4244
|
+
});
|
|
4245
|
+
return new Response("Socket connection refused", { status: error instanceof SocketDenied ? 403 : 500 });
|
|
4246
|
+
}
|
|
4247
|
+
},
|
|
4248
|
+
upgrade: ({ request }) => protocols(request).includes("brick.v1") ? { "Sec-WebSocket-Protocol": "brick.v1" } : void 0,
|
|
4249
|
+
async open(ws) {
|
|
4250
|
+
const session = sessions.get(ws.request);
|
|
4251
|
+
if (!session) {
|
|
4252
|
+
ws.close(1011, "Missing socket session");
|
|
4253
|
+
return;
|
|
4254
|
+
}
|
|
4255
|
+
const sender = {
|
|
4256
|
+
get isOpen() {
|
|
4257
|
+
return !state.closed && ws.readyState === 1;
|
|
4258
|
+
},
|
|
4259
|
+
close() {
|
|
4260
|
+
ws.close(1e3, "");
|
|
4261
|
+
},
|
|
4262
|
+
send(event, data) {
|
|
4263
|
+
if (!sender.isOpen) throw new Error("Socket is closed");
|
|
4264
|
+
if (ws.send(outputFrame(definition.output, event, data)) === 0) {
|
|
4265
|
+
ws.close(1013, "Socket buffer full");
|
|
4266
|
+
throw new Error("Socket buffer full");
|
|
4267
|
+
}
|
|
4268
|
+
}
|
|
4269
|
+
};
|
|
4270
|
+
const state = {
|
|
4271
|
+
ws,
|
|
4272
|
+
session,
|
|
4273
|
+
sender,
|
|
4274
|
+
tail: Promise.resolve(),
|
|
4275
|
+
pending: 0,
|
|
4276
|
+
bytes: 0,
|
|
4277
|
+
closed: false,
|
|
4278
|
+
rooms: /* @__PURE__ */ new Set(),
|
|
4279
|
+
requested: /* @__PURE__ */ new Set()
|
|
4280
|
+
};
|
|
4281
|
+
connections.set(ws.request, state);
|
|
4282
|
+
try {
|
|
4283
|
+
await Promise.all(session.rooms.map((room) => enter(state, definition.topic(room))));
|
|
4284
|
+
await session.open(sender);
|
|
4285
|
+
} catch (error) {
|
|
4286
|
+
fail(ws, error);
|
|
4287
|
+
}
|
|
4288
|
+
},
|
|
4289
|
+
message(ws, value) {
|
|
4290
|
+
const state = connections.get(ws.request);
|
|
4291
|
+
if (!state || state.closed || ws.readyState !== 1) return;
|
|
4292
|
+
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
4293
|
+
ws.close(1003, "Only JSON text is supported");
|
|
4294
|
+
return;
|
|
4295
|
+
}
|
|
4296
|
+
if (typeof value === "string") {
|
|
4297
|
+
ws.close(1007, "Expected JSON envelope");
|
|
4298
|
+
return;
|
|
4299
|
+
}
|
|
4300
|
+
if (!isSocketEnvelope(value)) {
|
|
4301
|
+
ws.close(1008, "Invalid socket envelope");
|
|
4302
|
+
return;
|
|
4303
|
+
}
|
|
4304
|
+
const size = bytes(JSON.stringify(value));
|
|
4305
|
+
if (size > 65536) {
|
|
4306
|
+
ws.close(1009, "Message too large");
|
|
4307
|
+
return;
|
|
4308
|
+
}
|
|
4309
|
+
if (state.pending >= 32 || state.bytes + size > 1048576) {
|
|
4310
|
+
ws.close(1013, "Socket queue full");
|
|
4311
|
+
return;
|
|
4312
|
+
}
|
|
4313
|
+
state.pending++;
|
|
4314
|
+
state.bytes += size;
|
|
4315
|
+
state.tail = state.tail.then(async () => {
|
|
4316
|
+
if (state.closed || ws.readyState !== 1) return;
|
|
4317
|
+
if (value.event === "$join" || value.event === "$leave") await room(state, value.event, value.data);
|
|
4318
|
+
else await state.session.message(value.event, value.data, state.sender);
|
|
4319
|
+
}).catch((error) => fail(ws, error)).finally(() => {
|
|
4320
|
+
state.pending--;
|
|
4321
|
+
state.bytes -= size;
|
|
4322
|
+
});
|
|
4323
|
+
},
|
|
4324
|
+
async close(ws, code = 1006, reason = "") {
|
|
4325
|
+
const state = connections.get(ws.request);
|
|
4326
|
+
sessions.delete(ws.request);
|
|
4327
|
+
if (!state || state.closed) return;
|
|
4328
|
+
state.closed = true;
|
|
4329
|
+
for (const topic of state.rooms) exit(state, topic);
|
|
4330
|
+
try {
|
|
4331
|
+
await state.session.close(state.sender, code, reason);
|
|
4332
|
+
} catch (error) {
|
|
4333
|
+
logger.error({
|
|
4334
|
+
error,
|
|
4335
|
+
service,
|
|
4336
|
+
socket: definition.schema.name,
|
|
4337
|
+
phase: "cleanup"
|
|
4338
|
+
});
|
|
4339
|
+
}
|
|
4340
|
+
connections.delete(ws.request);
|
|
4341
|
+
}
|
|
4342
|
+
});
|
|
4343
|
+
}
|
|
4344
|
+
}
|
|
4345
|
+
//#endregion
|
|
3086
4346
|
//#region src/server.ts
|
|
3087
4347
|
/**
|
|
3088
4348
|
* Create the HTTP application: an Elysia app that serves every service's
|
|
@@ -3098,11 +4358,11 @@ var EventsHub = class {
|
|
|
3098
4358
|
* @param options - `prefix` for action routes (default `/api`), `services`,
|
|
3099
4359
|
* `title`, `version`, and `description` for the OpenAPI document, `docs` and the
|
|
3100
4360
|
* paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
|
|
3101
|
-
* `telemetry`, `documentation`, and `
|
|
4361
|
+
* `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.
|
|
3102
4362
|
* @returns The app, with `definition` (its services, prefix, and routes),
|
|
3103
4363
|
* `endpoint()` to add raw routes, and `listEndpoints()` to list them.
|
|
3104
|
-
* @throws When a required secret is missing,
|
|
3105
|
-
* is invalid.
|
|
4364
|
+
* @throws When a required secret is missing, `documentation` or `dashboard`
|
|
4365
|
+
* is invalid, or `deps` misses a dep a service declares or has one none declares.
|
|
3106
4366
|
* @example
|
|
3107
4367
|
* import { brick } from "@brickkit/core";
|
|
3108
4368
|
* import { pagesService } from "./services/pages";
|
|
@@ -3126,6 +4386,9 @@ function brick(options = {}) {
|
|
|
3126
4386
|
const telemetry = options.telemetry === true || dashboard !== void 0;
|
|
3127
4387
|
const app = new Elysia();
|
|
3128
4388
|
if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
|
|
4389
|
+
const services = options.services ?? getGlobalRegistry().list();
|
|
4390
|
+
const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
|
|
4391
|
+
for (const handler of plugins.middleware) app.request(handler);
|
|
3129
4392
|
app.get("/_health", () => ({
|
|
3130
4393
|
status: "ok",
|
|
3131
4394
|
uptime: process.uptime(),
|
|
@@ -3148,8 +4411,17 @@ function brick(options = {}) {
|
|
|
3148
4411
|
if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
|
|
3149
4412
|
else registerReferenceRoute(app, settings);
|
|
3150
4413
|
}
|
|
3151
|
-
const
|
|
3152
|
-
const
|
|
4414
|
+
const byName = /* @__PURE__ */ new Map();
|
|
4415
|
+
for (const service of services) {
|
|
4416
|
+
if ((byName.get(service.name) ?? service) !== service) throw new Error(`Brick: duplicate service "${service.name}" in brick()`);
|
|
4417
|
+
byName.set(service.name, service);
|
|
4418
|
+
}
|
|
4419
|
+
bindDeps(services, options.deps);
|
|
4420
|
+
const eventsOptions = plugins.listeners.length ? {
|
|
4421
|
+
...options.events,
|
|
4422
|
+
listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
|
|
4423
|
+
} : options.events;
|
|
4424
|
+
const events = eventsOptions ? new EventsHub(eventsOptions, options.deps).attach(services) : void 0;
|
|
3153
4425
|
if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
|
|
3154
4426
|
if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
|
|
3155
4427
|
for (const service of services) if (typeof service.build === "function") service.build();
|
|
@@ -3199,8 +4471,41 @@ function brick(options = {}) {
|
|
|
3199
4471
|
swaggerPath
|
|
3200
4472
|
]) registeredRoutes.set(routeKey("GET", path), false);
|
|
3201
4473
|
if (referencePath !== void 0) registeredRoutes.set(routeKey("GET", referencePath), false);
|
|
4474
|
+
const sockets = services.flatMap((service) => service.listSockets().map((definition) => ({
|
|
4475
|
+
service: service.name,
|
|
4476
|
+
path: socketPath(prefix, service.name, definition),
|
|
4477
|
+
definition
|
|
4478
|
+
})));
|
|
4479
|
+
const socketRoutes = /* @__PURE__ */ new Set();
|
|
4480
|
+
for (const socket of sockets) {
|
|
4481
|
+
const key = routeKey("GET", socket.path);
|
|
4482
|
+
if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new Error(`Brick: duplicate socket route '${socket.path}'`);
|
|
4483
|
+
socketRoutes.add(key);
|
|
4484
|
+
}
|
|
4485
|
+
const legacySockets = options.legacyRoutes ? services.flatMap((service) => service.listSockets().flatMap((definition) => {
|
|
4486
|
+
const path = legacySocketPath(prefix, service.name, definition);
|
|
4487
|
+
if (path === void 0) return [];
|
|
4488
|
+
const key = routeKey("GET", path);
|
|
4489
|
+
if (registeredRoutes.has(key) || socketRoutes.has(key)) return [];
|
|
4490
|
+
socketRoutes.add(key);
|
|
4491
|
+
return [{
|
|
4492
|
+
service: service.name,
|
|
4493
|
+
path,
|
|
4494
|
+
definition
|
|
4495
|
+
}];
|
|
4496
|
+
})) : [];
|
|
4497
|
+
const legacyRoutes = [];
|
|
4498
|
+
const addLegacy = (method, path, successor, handler) => {
|
|
4499
|
+
if (options.legacyRoutes && path !== void 0 && path !== successor) legacyRoutes.push({
|
|
4500
|
+
method,
|
|
4501
|
+
path,
|
|
4502
|
+
successor,
|
|
4503
|
+
handler
|
|
4504
|
+
});
|
|
4505
|
+
};
|
|
3202
4506
|
const mountRoute = (method, path, handler, plugin = false) => {
|
|
3203
4507
|
const key = routeKey(method, path);
|
|
4508
|
+
if (socketRoutes.has(key)) throw new Error(`Brick: route '${method} ${path}' conflicts with a socket`);
|
|
3204
4509
|
if (registeredRoutes.has(key)) {
|
|
3205
4510
|
if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
3206
4511
|
return false;
|
|
@@ -3223,13 +4528,14 @@ function brick(options = {}) {
|
|
|
3223
4528
|
registeredRoutes.set(key, plugin);
|
|
3224
4529
|
return true;
|
|
3225
4530
|
};
|
|
3226
|
-
const mountEndpoint = (def, plugin = false) => {
|
|
4531
|
+
const mountEndpoint = (def, plugin = false, legacyPath) => {
|
|
3227
4532
|
const handler = createEndpointHandler(def, services);
|
|
4533
|
+
addLegacy(def.method, legacyPath, def.path, handler);
|
|
3228
4534
|
mountRoute(def.method, def.path, telemetry ? (context) => traceHttpRequest(context, def.method, def.path, () => handler(context)) : handler, plugin);
|
|
3229
4535
|
endpointDefs.push(def);
|
|
3230
4536
|
endpointRevision++;
|
|
3231
4537
|
};
|
|
3232
|
-
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
4538
|
+
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true, def.legacyPath);
|
|
3233
4539
|
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
3234
4540
|
const brickApp = app;
|
|
3235
4541
|
brickApp.endpoint = (def) => {
|
|
@@ -3268,19 +4574,55 @@ function brick(options = {}) {
|
|
|
3268
4574
|
}, () => route.handler(context)) : route.handler(context);
|
|
3269
4575
|
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
3270
4576
|
};
|
|
3271
|
-
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, getPluginActionRoute(action, prefix) !== void 0))
|
|
4577
|
+
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, getPluginActionRoute(action, prefix) !== void 0)) {
|
|
4578
|
+
mountedRoutes.push(route.ir);
|
|
4579
|
+
const current = getActionRoute(action, prefix);
|
|
4580
|
+
if (current) addLegacy(route.ir.method, current.legacyPath, route.ir.path, invoke);
|
|
4581
|
+
}
|
|
3272
4582
|
}
|
|
4583
|
+
for (const legacy of legacyRoutes) {
|
|
4584
|
+
const key = routeKey(legacy.method, legacy.path);
|
|
4585
|
+
if (registeredRoutes.has(key) || socketRoutes.has(key)) continue;
|
|
4586
|
+
const handle = (context) => {
|
|
4587
|
+
context.set.headers["deprecation"] = "true";
|
|
4588
|
+
context.set.headers["link"] = `<${legacy.successor.replace(/:([^/]+)/g, (match, name) => context.params?.[name] === void 0 ? match : encodeURIComponent(context.params[name]))}>; rel="successor-version"`;
|
|
4589
|
+
return legacy.handler(context);
|
|
4590
|
+
};
|
|
4591
|
+
mountRoute(legacy.method, legacy.path, telemetry ? (context) => traceHttpRequest(context, legacy.method, legacy.path, () => handle(context), { "brick.legacy_route": true }) : handle);
|
|
4592
|
+
}
|
|
4593
|
+
mountSockets(app, [...sockets, ...legacySockets], options.sockets?.broker ?? localBroker(), options.sockets?.secret);
|
|
3273
4594
|
const definition = Object.freeze({
|
|
3274
4595
|
services: Object.freeze([...services]),
|
|
3275
4596
|
prefix,
|
|
3276
4597
|
routes: Object.freeze(mountedRoutes),
|
|
4598
|
+
sockets: Object.freeze(sockets.map(({ service, path, definition }) => ({
|
|
4599
|
+
...definition.schema,
|
|
4600
|
+
service,
|
|
4601
|
+
path
|
|
4602
|
+
}))),
|
|
3277
4603
|
telemetry,
|
|
3278
4604
|
documentation: normalizeDocumentation(options.documentation),
|
|
3279
4605
|
dashboard,
|
|
3280
|
-
...events ? { events: events.describe() } : {}
|
|
4606
|
+
...events ? { events: events.describe() } : {},
|
|
4607
|
+
plugins: Object.freeze(plugins.plugins)
|
|
3281
4608
|
});
|
|
3282
4609
|
Object.defineProperty(brickApp, "definition", { value: definition });
|
|
3283
4610
|
Object.defineProperty(brickApp, "events", { value: events });
|
|
4611
|
+
const lifecycle = pluginLifecycle(plugins.lifecycles);
|
|
4612
|
+
const listen = app.listen.bind(app);
|
|
4613
|
+
const stop = app.stop.bind(app);
|
|
4614
|
+
Object.defineProperty(brickApp, "start", { value: lifecycle.start });
|
|
4615
|
+
brickApp.listen = ((...args) => {
|
|
4616
|
+
lifecycle.start().catch((error) => console.error("[Brick-TS] A plugin failed to start:", error));
|
|
4617
|
+
return listen(...args);
|
|
4618
|
+
});
|
|
4619
|
+
brickApp.stop = (async (closeActiveConnections) => {
|
|
4620
|
+
try {
|
|
4621
|
+
await stop(closeActiveConnections);
|
|
4622
|
+
} finally {
|
|
4623
|
+
await lifecycle.stop();
|
|
4624
|
+
}
|
|
4625
|
+
});
|
|
3284
4626
|
getGlobalRegistry().setApplicationRoutes(definition);
|
|
3285
4627
|
app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
|
|
3286
4628
|
const registry = getGlobalRegistry();
|
|
@@ -3338,7 +4680,17 @@ function emitHandlerFactory(route) {
|
|
|
3338
4680
|
}
|
|
3339
4681
|
input.push("}");
|
|
3340
4682
|
}
|
|
3341
|
-
input.push(
|
|
4683
|
+
input.push("let coercedParams = params;");
|
|
4684
|
+
const numeric = route.coercions.filter(({ type }) => type === "number");
|
|
4685
|
+
if (numeric.length) {
|
|
4686
|
+
input.push("if (params) {", "coercedParams = { ...params };");
|
|
4687
|
+
for (const [index, coercion] of numeric.entries()) {
|
|
4688
|
+
const key = JSON.stringify(coercion.key);
|
|
4689
|
+
input.push(`const p${index} = params[${key}]; if (typeof p${index} === "string") { const pn${index} = Number(p${index}); if (!Number.isNaN(pn${index})) coercedParams[${key}] = pn${index}; }`);
|
|
4690
|
+
}
|
|
4691
|
+
input.push("}");
|
|
4692
|
+
}
|
|
4693
|
+
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source === "params" ? "coercedParams" : source).join(", ")});`);
|
|
3342
4694
|
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
3343
4695
|
}
|
|
3344
4696
|
const asyncStages = route.context || route.authorize;
|
|
@@ -3363,7 +4715,7 @@ const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
|
|
|
3363
4715
|
if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
|
|
3364
4716
|
${input.join("\n")}
|
|
3365
4717
|
const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
|
|
3366
|
-
db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
|
|
4718
|
+
db: cachedDb ?? service.getDb(), logger, services: emptyServices, deps: service.deps ?? emptyServices, metadata: { headers }, _resolved: true };
|
|
3367
4719
|
try {
|
|
3368
4720
|
${context}
|
|
3369
4721
|
${validation}
|
|
@@ -3482,6 +4834,7 @@ function defineDatabase(options = {}) {
|
|
|
3482
4834
|
const declared = options.tables ?? {};
|
|
3483
4835
|
const tables = Array.isArray(declared) ? Object.fromEntries(declared.map((table) => [getTableName$1(table), table])) : { ...declared };
|
|
3484
4836
|
const schema = options.schema ?? tables;
|
|
4837
|
+
let frozen = Object.freeze({ ...tables });
|
|
3485
4838
|
let db;
|
|
3486
4839
|
let closeClient;
|
|
3487
4840
|
let closed = false;
|
|
@@ -3490,8 +4843,16 @@ function defineDatabase(options = {}) {
|
|
|
3490
4843
|
kind: "brick-database",
|
|
3491
4844
|
name: options.name,
|
|
3492
4845
|
engine,
|
|
3493
|
-
tables
|
|
4846
|
+
get tables() {
|
|
4847
|
+
return frozen;
|
|
4848
|
+
},
|
|
3494
4849
|
schema,
|
|
4850
|
+
addTable(key, table) {
|
|
4851
|
+
const name = getTableName$1(table);
|
|
4852
|
+
if (Object.hasOwn(tables, key) || Object.values(tables).some((item) => getTableName$1(item) === name)) throw new Error(`Database already has a table "${key}" or one named "${name}"`);
|
|
4853
|
+
tables[key] = table;
|
|
4854
|
+
frozen = Object.freeze({ ...tables });
|
|
4855
|
+
},
|
|
3495
4856
|
close() {
|
|
3496
4857
|
if (closed) return closing;
|
|
3497
4858
|
closed = true;
|
|
@@ -3750,6 +5111,217 @@ function syncSchema(tablesOrService, dbInstance) {
|
|
|
3750
5111
|
}
|
|
3751
5112
|
//#endregion
|
|
3752
5113
|
//#region src/resource.ts
|
|
5114
|
+
/** Resource actions can't take a CRUD route segment. */
|
|
5115
|
+
const CRUD_SEGMENTS = /* @__PURE__ */ new Set([
|
|
5116
|
+
"query",
|
|
5117
|
+
"count",
|
|
5118
|
+
"exists",
|
|
5119
|
+
"find-one",
|
|
5120
|
+
"bulk-create",
|
|
5121
|
+
"bulk-update",
|
|
5122
|
+
"bulk-delete"
|
|
5123
|
+
]);
|
|
5124
|
+
/**
|
|
5125
|
+
* Load the row a record action (or command) works on, through its `access`.
|
|
5126
|
+
*
|
|
5127
|
+
* @returns The row, or `undefined` when it is missing or hidden.
|
|
5128
|
+
* @throws When `access` is missing.
|
|
5129
|
+
*/
|
|
5130
|
+
async function loadRecord(resource, args) {
|
|
5131
|
+
if (!args.access) throw new Error(`Resource '${resource.name}' has no access rule for loading records: set \`access\` on the record action`);
|
|
5132
|
+
const db = args.db ?? args.ctx?.db;
|
|
5133
|
+
const id = idValue(resource.id, args.id);
|
|
5134
|
+
if (id === void 0) return void 0;
|
|
5135
|
+
if (!db) throw new Error("Record actions require a configured database");
|
|
5136
|
+
const scope = args.access === "public" ? void 0 : await args.access.scope({ ctx: args.ctx });
|
|
5137
|
+
const [row] = await db.select().from(resource.table).where(and$1(scope, eq$1(resource.id, id))).limit(1);
|
|
5138
|
+
return row;
|
|
5139
|
+
}
|
|
5140
|
+
/** Startup check: a record action needs its own `access`. */
|
|
5141
|
+
function checkRecordAccess(resource, info) {
|
|
5142
|
+
const name = `${resource.name}.${info.name}`;
|
|
5143
|
+
if (info.access === void 0) throw new Error(`Record action '${name}' needs \`access\` ("public" or { scope })`);
|
|
5144
|
+
}
|
|
5145
|
+
/** The id from the path as its column stores it: a Date or BigInt for those columns, undefined when it can't be one. */
|
|
5146
|
+
function idValue(column, id) {
|
|
5147
|
+
if (typeof id !== "string") return id;
|
|
5148
|
+
if (column.dataType === "date") {
|
|
5149
|
+
const date = new Date(id);
|
|
5150
|
+
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
5151
|
+
}
|
|
5152
|
+
if (column.dataType === "bigint") return /^-?\d+$/.test(id) ? BigInt(id) : void 0;
|
|
5153
|
+
return id;
|
|
5154
|
+
}
|
|
5155
|
+
function idSchema(column) {
|
|
5156
|
+
return column.dataType === "number" ? Type.Number() : Type.String();
|
|
5157
|
+
}
|
|
5158
|
+
function defineResourceAction(service, resource, config, command) {
|
|
5159
|
+
const { record = false, access, execute, ...rest } = config;
|
|
5160
|
+
if (!config.name || /[./]/.test(config.name)) throw new Error(`Invalid resource action name '${config.name}'`);
|
|
5161
|
+
const name = `${resource.name}.${config.name}`;
|
|
5162
|
+
const segment = kebabCase(config.name);
|
|
5163
|
+
if (CRUD_SEGMENTS.has(segment)) throw new Error(`Brick: duplicate name "${name}" in service "${service.name}": "${segment}" is a CRUD route`);
|
|
5164
|
+
if (service.getAction(name)?.plugin) throw new Error(`Brick: duplicate name "${name}" in service "${service.name}"`);
|
|
5165
|
+
if (!record && access !== void 0) throw new Error(`Only record actions take \`access\` ('${name}')`);
|
|
5166
|
+
if (record && config.path !== void 0 && !/\/:id(\/|$)/.test(config.path)) throw new Error(`Record action '${name}' needs ':id' in its path`);
|
|
5167
|
+
let input = config.input;
|
|
5168
|
+
if (record) {
|
|
5169
|
+
const own = input;
|
|
5170
|
+
if (own && own.type !== "object") throw new Error(`Record action '${name}' input must be an object`);
|
|
5171
|
+
input = Type.Object({
|
|
5172
|
+
...own?.properties,
|
|
5173
|
+
id: idSchema(resource.id)
|
|
5174
|
+
}, own?.additionalProperties === void 0 ? {} : { additionalProperties: own.additionalProperties });
|
|
5175
|
+
}
|
|
5176
|
+
const action = defineAction({
|
|
5177
|
+
...rest,
|
|
5178
|
+
name,
|
|
5179
|
+
input,
|
|
5180
|
+
execute: async ({ input, ctx, error }) => {
|
|
5181
|
+
if (command) return command({
|
|
5182
|
+
input,
|
|
5183
|
+
ctx,
|
|
5184
|
+
error
|
|
5185
|
+
});
|
|
5186
|
+
const row = record ? await loadRecord(resource, {
|
|
5187
|
+
id: input.id,
|
|
5188
|
+
ctx,
|
|
5189
|
+
access
|
|
5190
|
+
}) : void 0;
|
|
5191
|
+
if (record && row === void 0) error.NOT_FOUND(`${resource.name} '${String(input.id)}' not found`);
|
|
5192
|
+
return execute({
|
|
5193
|
+
input,
|
|
5194
|
+
ctx,
|
|
5195
|
+
error,
|
|
5196
|
+
row
|
|
5197
|
+
});
|
|
5198
|
+
}
|
|
5199
|
+
});
|
|
5200
|
+
const info = {
|
|
5201
|
+
resource: resource.name,
|
|
5202
|
+
name: config.name,
|
|
5203
|
+
record,
|
|
5204
|
+
...access === void 0 ? {} : { access }
|
|
5205
|
+
};
|
|
5206
|
+
Object.assign(action, {
|
|
5207
|
+
resource: resource.name,
|
|
5208
|
+
resourceAction: info
|
|
5209
|
+
});
|
|
5210
|
+
service.action(action);
|
|
5211
|
+
return action;
|
|
5212
|
+
}
|
|
5213
|
+
function primaryColumn(table) {
|
|
5214
|
+
const primary = Object.entries(getTableColumns$1(table)).filter(([, column]) => column.primary);
|
|
5215
|
+
return primary.length === 1 ? primary[0] : void 0;
|
|
5216
|
+
}
|
|
5217
|
+
function fieldOf(table, column) {
|
|
5218
|
+
return Object.entries(getTableColumns$1(table)).find(([, own]) => own === column)?.[0];
|
|
5219
|
+
}
|
|
5220
|
+
function childInfo(resource, name, where) {
|
|
5221
|
+
const child = resource.config.children?.[name];
|
|
5222
|
+
if (!child || !Object.hasOwn(resource.config.children ?? {}, name)) throw new Error(`${where}: resource '${resource.name}' has no child table '${name}'`);
|
|
5223
|
+
const parentField = fieldOf(child.table, child.parent);
|
|
5224
|
+
const id = child.id ?? primaryColumn(child.table)?.[1];
|
|
5225
|
+
const idField = id && fieldOf(child.table, id);
|
|
5226
|
+
if (!parentField || !id || !idField) throw new Error(`Resource '${resource.name}' child '${name}' needs a parent column and an id column of its table`);
|
|
5227
|
+
return {
|
|
5228
|
+
table: child.table,
|
|
5229
|
+
parent: child.parent,
|
|
5230
|
+
parentField,
|
|
5231
|
+
id,
|
|
5232
|
+
idField
|
|
5233
|
+
};
|
|
5234
|
+
}
|
|
5235
|
+
/** The `error` helpers of `decide`: they return the rejection, not throw it. */
|
|
5236
|
+
function commandErrors(errors) {
|
|
5237
|
+
const throwing = buildErrorHelpers(errors);
|
|
5238
|
+
return Object.fromEntries(Object.entries(throwing).map(([code, helper]) => [code, (message, details) => {
|
|
5239
|
+
try {
|
|
5240
|
+
helper(message, details);
|
|
5241
|
+
} catch (rejection) {
|
|
5242
|
+
return rejection;
|
|
5243
|
+
}
|
|
5244
|
+
}]));
|
|
5245
|
+
}
|
|
5246
|
+
function defineCommand(service, resource, name, config) {
|
|
5247
|
+
const where = `Command '${resource.name}.${name}'`;
|
|
5248
|
+
if (typeof config.decide !== "function") throw new Error(`${where} needs a decide function`);
|
|
5249
|
+
const loaded = (config.load?.children ?? []).map((child) => ({
|
|
5250
|
+
name: child,
|
|
5251
|
+
...childInfo(resource, child, where)
|
|
5252
|
+
}));
|
|
5253
|
+
const error = commandErrors(config.errors);
|
|
5254
|
+
const decide = (row, input) => config.decide(row, input, { error });
|
|
5255
|
+
const events = service.events;
|
|
5256
|
+
const run = async ({ input, ctx }) => {
|
|
5257
|
+
const db = ctx.db;
|
|
5258
|
+
if (!db) throw new Error(`${where} requires a configured database`);
|
|
5259
|
+
const recorder = service.recorder;
|
|
5260
|
+
const body = async (tx, record) => {
|
|
5261
|
+
const row = await loadRecord(resource, {
|
|
5262
|
+
id: input.id,
|
|
5263
|
+
ctx,
|
|
5264
|
+
db: tx,
|
|
5265
|
+
access: config.access
|
|
5266
|
+
});
|
|
5267
|
+
if (row === void 0) throw new ActionExecutionError("NOT_FOUND", `${resource.name} '${String(input.id)}' not found`, 404);
|
|
5268
|
+
const id = row[resource.idField];
|
|
5269
|
+
for (const child of loaded) row[child.name] = await tx.select().from(child.table).where(eq$1(child.parent, id));
|
|
5270
|
+
const decision = decide(row, input);
|
|
5271
|
+
if (decision instanceof ActionExecutionError) throw decision;
|
|
5272
|
+
const { set, children, emit } = decision ?? {};
|
|
5273
|
+
const emits = Object.entries(emit ?? {}).filter(([, payload]) => payload !== void 0).map(([key, payload]) => {
|
|
5274
|
+
const ref = Object.hasOwn(events, key) ? events[key] : void 0;
|
|
5275
|
+
if (!ref) throw new Error(`${where} emits '${key}', which is not in the event catalog of service '${service.name}'`);
|
|
5276
|
+
service.checkEvent?.(ref.name, payload);
|
|
5277
|
+
return [ref.name, payload];
|
|
5278
|
+
});
|
|
5279
|
+
if (emits.length && !record) throw new Error(`${where} emits events, but service '${service.name}' records none: give its database an outbox table and the app \`events\``);
|
|
5280
|
+
if (set && Object.keys(set).length) await tx.update(resource.table).set(set).where(eq$1(resource.id, id));
|
|
5281
|
+
for (const [childName, changes] of Object.entries(children ?? {})) {
|
|
5282
|
+
if (!changes) continue;
|
|
5283
|
+
const child = childInfo(resource, childName, where);
|
|
5284
|
+
const own = eq$1(child.parent, id);
|
|
5285
|
+
if (changes.insert?.length) await tx.insert(child.table).values(changes.insert.map((item) => ({
|
|
5286
|
+
...item,
|
|
5287
|
+
[child.parentField]: id
|
|
5288
|
+
})));
|
|
5289
|
+
for (const item of changes.update ?? []) {
|
|
5290
|
+
const { [child.idField]: childId, ...values } = item;
|
|
5291
|
+
if (childId === void 0) throw new Error(`${where}: an update of child '${childName}' needs its '${child.idField}'`);
|
|
5292
|
+
if (Object.keys(values).length) await tx.update(child.table).set(values).where(and$1(eq$1(child.id, childId), own));
|
|
5293
|
+
}
|
|
5294
|
+
if (changes.delete?.length) await tx.delete(child.table).where(and$1(inArray$1(child.id, changes.delete), own));
|
|
5295
|
+
}
|
|
5296
|
+
for (const [eventName, payload] of emits) await record(eventName, payload);
|
|
5297
|
+
if (!config.output) return { id };
|
|
5298
|
+
const [updated] = await tx.select().from(resource.table).where(eq$1(resource.id, id)).limit(1);
|
|
5299
|
+
for (const child of loaded) updated[child.name] = await tx.select().from(child.table).where(eq$1(child.parent, id));
|
|
5300
|
+
return Value.Clean(config.output, updated);
|
|
5301
|
+
};
|
|
5302
|
+
return recorder ? recorder.transaction(db, {
|
|
5303
|
+
traceId: ctx.traceId,
|
|
5304
|
+
source: `${service.name}.${resource.name}`
|
|
5305
|
+
}, body) : runInTransaction(db, (tx) => body(tx));
|
|
5306
|
+
};
|
|
5307
|
+
const action = defineResourceAction(service, resource, {
|
|
5308
|
+
name,
|
|
5309
|
+
record: true,
|
|
5310
|
+
description: config.description,
|
|
5311
|
+
tags: config.tags,
|
|
5312
|
+
input: config.input,
|
|
5313
|
+
output: config.output ?? Type.Object({ id: idSchema(resource.id) }),
|
|
5314
|
+
errors: config.errors,
|
|
5315
|
+
...config.access === void 0 ? {} : { access: config.access },
|
|
5316
|
+
...config.authorize ? { authorize: config.authorize } : {},
|
|
5317
|
+
execute: () => void 0
|
|
5318
|
+
}, run);
|
|
5319
|
+
Object.assign(action, {
|
|
5320
|
+
decide,
|
|
5321
|
+
command: true
|
|
5322
|
+
});
|
|
5323
|
+
return action;
|
|
5324
|
+
}
|
|
3753
5325
|
/** Declares a plugin host without registering actions or changing the schema. */
|
|
3754
5326
|
function defineResource(service, config) {
|
|
3755
5327
|
const columns = getTableColumns$1(config.table);
|
|
@@ -3775,11 +5347,58 @@ function defineResource(service, config) {
|
|
|
3775
5347
|
}),
|
|
3776
5348
|
use(plugin) {
|
|
3777
5349
|
return installPlugin(service, resource, plugin);
|
|
5350
|
+
},
|
|
5351
|
+
action(actionConfig) {
|
|
5352
|
+
return defineResourceAction(service, resource, actionConfig);
|
|
5353
|
+
},
|
|
5354
|
+
command(name, commandConfig) {
|
|
5355
|
+
return defineCommand(service, resource, name, commandConfig);
|
|
3778
5356
|
}
|
|
3779
5357
|
};
|
|
3780
5358
|
return resource;
|
|
3781
5359
|
}
|
|
3782
5360
|
//#endregion
|
|
5361
|
+
//#region src/events/catalog.ts
|
|
5362
|
+
function isEventRef(value) {
|
|
5363
|
+
return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.service === "string" && typeof value.schema === "object";
|
|
5364
|
+
}
|
|
5365
|
+
/** Build `service.events` from its catalog. */
|
|
5366
|
+
function eventRefs(service, catalog) {
|
|
5367
|
+
const refs = Object.create(null);
|
|
5368
|
+
for (const [key, schema] of Object.entries(catalog ?? {})) {
|
|
5369
|
+
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`);
|
|
5370
|
+
if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
|
|
5371
|
+
refs[key] = Object.freeze({
|
|
5372
|
+
name: `${service}.${key}`,
|
|
5373
|
+
service,
|
|
5374
|
+
schema
|
|
5375
|
+
});
|
|
5376
|
+
}
|
|
5377
|
+
return Object.freeze(refs);
|
|
5378
|
+
}
|
|
5379
|
+
const CRUD_EVENT = /^(create|update|delete)$/;
|
|
5380
|
+
/**
|
|
5381
|
+
* Check an event against the catalog of the service recording it. Without a
|
|
5382
|
+
* catalog any name goes. With one, the name must be `<service>.<event>` from it
|
|
5383
|
+
* (the payload is checked against its schema) or a CRUD event of one of the
|
|
5384
|
+
* service's resources (`<resource>.create|update|delete`).
|
|
5385
|
+
*
|
|
5386
|
+
* @throws When the name is not declared or the payload does not match.
|
|
5387
|
+
*/
|
|
5388
|
+
function checkEvent(service, name, payload) {
|
|
5389
|
+
const prefix = `${service.name}.`;
|
|
5390
|
+
const ref = name.startsWith(prefix) ? service.events[name.slice(prefix.length)] : void 0;
|
|
5391
|
+
if (ref) {
|
|
5392
|
+
const result = validateWithSchema(ref.schema, payload);
|
|
5393
|
+
if (!result.success) throw new Error(`Event "${name}" payload does not match its schema: ${result.errors.map((error) => `${error.path || "/"} ${error.message}`).join("; ")}`);
|
|
5394
|
+
return;
|
|
5395
|
+
}
|
|
5396
|
+
if (!service.hasCatalog) return;
|
|
5397
|
+
const dot = name.indexOf(".");
|
|
5398
|
+
if (dot > 0 && CRUD_EVENT.test(name.slice(dot + 1)) && service.listResources().some((r) => r.name === name.slice(0, dot))) return;
|
|
5399
|
+
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"})`);
|
|
5400
|
+
}
|
|
5401
|
+
//#endregion
|
|
3783
5402
|
//#region src/context.ts
|
|
3784
5403
|
function pickContextEnvelope(context) {
|
|
3785
5404
|
if (!context) return {};
|
|
@@ -3797,21 +5416,31 @@ const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
|
|
|
3797
5416
|
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
3798
5417
|
const EMPTY_SERVICES = Object.freeze({});
|
|
3799
5418
|
const EMPTY_METADATA = Object.freeze({});
|
|
5419
|
+
const EMPTY_DEPS = Object.freeze({});
|
|
3800
5420
|
let _ctxSeq = 0;
|
|
3801
5421
|
const RESOLVED_SYMBOL = Symbol("resolved");
|
|
5422
|
+
/** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */
|
|
5423
|
+
const OWN_DEPS = Symbol("ownDeps");
|
|
3802
5424
|
var ServiceImpl = class {
|
|
3803
5425
|
name;
|
|
3804
5426
|
options;
|
|
3805
5427
|
actions = /* @__PURE__ */ new Map();
|
|
3806
5428
|
tools = /* @__PURE__ */ new Map();
|
|
3807
5429
|
tables = /* @__PURE__ */ new Map();
|
|
5430
|
+
sockets = /* @__PURE__ */ new Map();
|
|
3808
5431
|
resources = /* @__PURE__ */ new Map();
|
|
3809
5432
|
preparations = /* @__PURE__ */ new Map();
|
|
5433
|
+
/** Where each `kind:name` was defined, to reject duplicates from another file. */
|
|
5434
|
+
sites = /* @__PURE__ */ new Map();
|
|
3810
5435
|
database;
|
|
3811
5436
|
_isBuilt = false;
|
|
5437
|
+
/** The declared events: `service.events.<name>`. */
|
|
5438
|
+
events;
|
|
3812
5439
|
constructor(name, options = {}) {
|
|
3813
5440
|
this.name = name;
|
|
3814
5441
|
this.options = options;
|
|
5442
|
+
this.events = eventRefs(name, options.events);
|
|
5443
|
+
for (const key of Object.keys(this.events)) this.claim("event", key);
|
|
3815
5444
|
if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
|
|
3816
5445
|
this.database = options.database;
|
|
3817
5446
|
}
|
|
@@ -3830,9 +5459,17 @@ var ServiceImpl = class {
|
|
|
3830
5459
|
build() {
|
|
3831
5460
|
if (isInstallingPlugin(this)) throw new Error("Cannot build a service during plugin setup");
|
|
3832
5461
|
if (this._isBuilt) return this;
|
|
5462
|
+
for (const action of this.actions.values()) {
|
|
5463
|
+
const info = action.resourceAction;
|
|
5464
|
+
const resource = info?.record && this.resources.get(info.resource);
|
|
5465
|
+
if (resource) checkRecordAccess(resource, info);
|
|
5466
|
+
}
|
|
3833
5467
|
this._isBuilt = true;
|
|
3834
5468
|
return this;
|
|
3835
5469
|
}
|
|
5470
|
+
claim(kind, name) {
|
|
5471
|
+
claimName(this.sites, `${kind} "${name}" in service "${this.name}"`, `${kind}:${name}`, definitionSite());
|
|
5472
|
+
}
|
|
3836
5473
|
contributePreparation(contribution) {
|
|
3837
5474
|
if (this._isBuilt) throw new Error("Preparations must be registered before service build");
|
|
3838
5475
|
if (this.preparations.has(contribution.name)) throw new Error(`Duplicate preparation '${contribution.name}'`);
|
|
@@ -3857,7 +5494,7 @@ var ServiceImpl = class {
|
|
|
3857
5494
|
}
|
|
3858
5495
|
resource = (config) => {
|
|
3859
5496
|
if (this._isBuilt) throw new Error("Resources must be registered before service build");
|
|
3860
|
-
|
|
5497
|
+
this.claim("resource", config.name);
|
|
3861
5498
|
const resourceInstance = defineResource(this, config);
|
|
3862
5499
|
this.resources.set(resourceInstance.name, resourceInstance);
|
|
3863
5500
|
getGlobalRegistry().touch();
|
|
@@ -3875,6 +5512,7 @@ var ServiceImpl = class {
|
|
|
3875
5512
|
if (isActionFunction) actionInstance = actionOrConfig;
|
|
3876
5513
|
else actionInstance = defineAction(actionOrConfig);
|
|
3877
5514
|
if (isInstallingPlugin(this) && this.actions.has(actionInstance.name) && this.actions.get(actionInstance.name) !== actionInstance) throw new Error(`Duplicate plugin action: ${actionInstance.name}`);
|
|
5515
|
+
if (this.actions.get(actionInstance.name) !== actionInstance) this.claim("action", actionInstance.name);
|
|
3878
5516
|
if (isTool(actionInstance)) actionInstance.config.http = true;
|
|
3879
5517
|
actionInstance.serviceName = this.name;
|
|
3880
5518
|
actionInstance.service = this;
|
|
@@ -3886,7 +5524,7 @@ var ServiceImpl = class {
|
|
|
3886
5524
|
tool(toolOrConfig) {
|
|
3887
5525
|
const existing = isTool(toolOrConfig);
|
|
3888
5526
|
const tool = existing ? toolOrConfig : defineTool(toolOrConfig);
|
|
3889
|
-
|
|
5527
|
+
this.claim("tool", tool.name);
|
|
3890
5528
|
tool.serviceName = this.name;
|
|
3891
5529
|
tool.service = this;
|
|
3892
5530
|
this.tools.set(tool.name, tool);
|
|
@@ -3897,6 +5535,24 @@ var ServiceImpl = class {
|
|
|
3897
5535
|
getTool(name) {
|
|
3898
5536
|
return this.tools.get(name);
|
|
3899
5537
|
}
|
|
5538
|
+
socket(config) {
|
|
5539
|
+
if (this._isBuilt) throw new Error("Sockets must be declared before service build");
|
|
5540
|
+
this.claim("socket", config.name);
|
|
5541
|
+
const socket = defineServiceSocket(this.name, config, async (request) => {
|
|
5542
|
+
const ctx = await resolveServiceContext(this, { request });
|
|
5543
|
+
const deps = socket[PLUGIN_DEPS];
|
|
5544
|
+
return deps ? {
|
|
5545
|
+
...ctx,
|
|
5546
|
+
deps
|
|
5547
|
+
} : ctx;
|
|
5548
|
+
});
|
|
5549
|
+
this.sockets.set(config.name, socket);
|
|
5550
|
+
getGlobalRegistry().touch();
|
|
5551
|
+
return socket.handle;
|
|
5552
|
+
}
|
|
5553
|
+
listSockets() {
|
|
5554
|
+
return [...this.sockets.values()];
|
|
5555
|
+
}
|
|
3900
5556
|
listTools() {
|
|
3901
5557
|
return Array.from(this.tools.values());
|
|
3902
5558
|
}
|
|
@@ -3909,13 +5565,30 @@ var ServiceImpl = class {
|
|
|
3909
5565
|
getDb() {
|
|
3910
5566
|
return this.database?.getDb();
|
|
3911
5567
|
}
|
|
5568
|
+
/** The handle from `defineDatabase`, without connecting. */
|
|
5569
|
+
getDatabaseHandle() {
|
|
5570
|
+
return this.database;
|
|
5571
|
+
}
|
|
3912
5572
|
/** What a write needs to record events. Set by `brick({ events })`. */
|
|
3913
|
-
|
|
5573
|
+
recorder;
|
|
3914
5574
|
getOutbox() {
|
|
3915
5575
|
return Object.values(this.database?.tables ?? {}).find(isOutboxTable);
|
|
3916
5576
|
}
|
|
3917
|
-
|
|
3918
|
-
this.
|
|
5577
|
+
setRecorder(recorder) {
|
|
5578
|
+
this.recorder = recorder;
|
|
5579
|
+
}
|
|
5580
|
+
/** Whether the service declares an event catalog. */
|
|
5581
|
+
get hasCatalog() {
|
|
5582
|
+
return this.options.events !== void 0;
|
|
5583
|
+
}
|
|
5584
|
+
/** @throws When the event is not in the catalog or its payload does not match. */
|
|
5585
|
+
checkEvent(name, payload) {
|
|
5586
|
+
checkEvent(this, name, payload);
|
|
5587
|
+
}
|
|
5588
|
+
/** The values of this service's `deps`. Set by `brick({ deps })`. */
|
|
5589
|
+
deps;
|
|
5590
|
+
setDeps(deps) {
|
|
5591
|
+
this.deps = deps;
|
|
3919
5592
|
}
|
|
3920
5593
|
setDb(database) {
|
|
3921
5594
|
if (!isDatabaseHandle(database)) throw new Error("Use defineDatabase() to set a service database");
|
|
@@ -3934,14 +5607,16 @@ var ServiceImpl = class {
|
|
|
3934
5607
|
const databaseConfig = this.database ? {
|
|
3935
5608
|
name: this.database.name,
|
|
3936
5609
|
engine: this.database.engine,
|
|
3937
|
-
tables: Object.keys(this.database.tables)
|
|
5610
|
+
tables: Object.keys(this.database.tables),
|
|
5611
|
+
...pluginTables(this.database.tables)
|
|
3938
5612
|
} : void 0;
|
|
3939
|
-
const { database: _database, ...config } = this.options;
|
|
5613
|
+
const { database: _database, events: _events, ...config } = this.options;
|
|
3940
5614
|
const options = JSON.parse(JSON.stringify(config));
|
|
3941
5615
|
return {
|
|
3942
5616
|
name: this.name,
|
|
3943
5617
|
options,
|
|
3944
5618
|
hasDatabase: Boolean(this.database),
|
|
5619
|
+
sockets: this.listSockets().map((socket) => socket.schema),
|
|
3945
5620
|
databaseConfig,
|
|
3946
5621
|
actions: this.listActions().map((act) => {
|
|
3947
5622
|
const access = getActionAccess(act);
|
|
@@ -3962,43 +5637,75 @@ var ServiceImpl = class {
|
|
|
3962
5637
|
};
|
|
3963
5638
|
}),
|
|
3964
5639
|
tools: this.listTools().map((tool) => ({ name: tool.name })),
|
|
5640
|
+
...this.hasCatalog || Object.keys(this.events).length ? { events: Object.values(this.events).map((ref) => ({
|
|
5641
|
+
name: ref.name,
|
|
5642
|
+
schema: JSON.parse(JSON.stringify(ref.schema)),
|
|
5643
|
+
...ref.plugin ? { plugin: ref.plugin } : {}
|
|
5644
|
+
})) } : {},
|
|
3965
5645
|
resources: this.listResources().map((res) => ({ name: res.name }))
|
|
3966
5646
|
};
|
|
3967
5647
|
}
|
|
3968
5648
|
};
|
|
5649
|
+
/** `plugins`: which plugin owns each table it contributed, by table key. */
|
|
5650
|
+
function pluginTables(tables) {
|
|
5651
|
+
const owners = Object.entries(tables).flatMap(([key, table]) => {
|
|
5652
|
+
const plugin = pluginOwner(table);
|
|
5653
|
+
return plugin ? [[key, plugin]] : [];
|
|
5654
|
+
});
|
|
5655
|
+
return owners.length ? { plugins: Object.fromEntries(owners) } : {};
|
|
5656
|
+
}
|
|
3969
5657
|
async function resolveServiceContext(service, callCtx) {
|
|
3970
|
-
if (callCtx?.[RESOLVED_SYMBOL] === service)
|
|
5658
|
+
if (callCtx?.[RESOLVED_SYMBOL] === service) {
|
|
5659
|
+
const own = callCtx[OWN_DEPS];
|
|
5660
|
+
return callCtx.deps === own ? callCtx : {
|
|
5661
|
+
...callCtx,
|
|
5662
|
+
deps: own
|
|
5663
|
+
};
|
|
5664
|
+
}
|
|
3971
5665
|
const seq = ++_ctxSeq;
|
|
5666
|
+
const req = callCtx?.request ?? DEFAULT_REQUEST;
|
|
5667
|
+
const db = service.getDb();
|
|
5668
|
+
const logger = callCtx?.logger ?? defaultLogger;
|
|
5669
|
+
const traceId = callCtx?.traceId ?? `tr_${seq.toString(36)}`;
|
|
5670
|
+
const requestId = callCtx?.requestId ?? `req_${seq.toString(36)}`;
|
|
5671
|
+
const services = callCtx?.services ?? EMPTY_SERVICES;
|
|
5672
|
+
const metadata = callCtx?.metadata ?? EMPTY_METADATA;
|
|
5673
|
+
const deps = service.deps ?? (callCtx?.[RESOLVED_SYMBOL] ? void 0 : callCtx?.deps) ?? EMPTY_DEPS;
|
|
3972
5674
|
const fullBaseCtx = {
|
|
3973
|
-
request:
|
|
3974
|
-
db
|
|
3975
|
-
logger
|
|
3976
|
-
traceId
|
|
3977
|
-
requestId
|
|
3978
|
-
services
|
|
3979
|
-
metadata
|
|
5675
|
+
request: req,
|
|
5676
|
+
db,
|
|
5677
|
+
logger,
|
|
5678
|
+
traceId,
|
|
5679
|
+
requestId,
|
|
5680
|
+
services,
|
|
5681
|
+
metadata,
|
|
3980
5682
|
...pickContextEnvelope(callCtx)
|
|
3981
5683
|
};
|
|
3982
5684
|
const resolvedExtra = service.options.context ? await service.options.context(fullBaseCtx) : {};
|
|
3983
5685
|
return {
|
|
3984
5686
|
...fullBaseCtx,
|
|
3985
5687
|
...resolvedExtra,
|
|
3986
|
-
|
|
5688
|
+
deps,
|
|
5689
|
+
[RESOLVED_SYMBOL]: service,
|
|
5690
|
+
[OWN_DEPS]: deps
|
|
3987
5691
|
};
|
|
3988
5692
|
}
|
|
3989
5693
|
/**
|
|
3990
5694
|
* Declare a service: a named group of actions, tools, and resources with its own
|
|
3991
5695
|
* database and request context. It is registered globally, so `brick()`, the
|
|
3992
|
-
* OpenAPI generator, and `
|
|
5696
|
+
* OpenAPI generator, and `useService` find it by name.
|
|
3993
5697
|
*
|
|
3994
5698
|
* Add actions with `service.action(...)`, tools with `service.tool(...)`,
|
|
3995
5699
|
* resources with `service.resource(...)`, and plugins with `service.use(...)`.
|
|
3996
5700
|
*
|
|
3997
5701
|
* @param name - Unique name. It is the service's segment of every action route
|
|
3998
|
-
* (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining
|
|
3999
|
-
*
|
|
4000
|
-
* @param options - `database` (a handle from `defineDatabase`), `
|
|
4001
|
-
*
|
|
5702
|
+
* (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it
|
|
5703
|
+
* again from the same file (a dev reload) replaces it; from another file throws.
|
|
5704
|
+
* @param options - `database` (a handle from `defineDatabase`), `deps` (typed
|
|
5705
|
+
* slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),
|
|
5706
|
+
* `context` (adds fields such as the signed-in user to every action's `ctx`),
|
|
5707
|
+
* `events` (the event catalog: a payload schema per event name, recorded as
|
|
5708
|
+
* `<service>.<name>` and offered as `service.events.<name>`), and `auth`,
|
|
4002
5709
|
* `rateLimit`, `cache`, `resilience`, `telemetry`, and `lifecycle`.
|
|
4003
5710
|
* @returns The service.
|
|
4004
5711
|
* @example
|
|
@@ -4026,53 +5733,252 @@ function defineService(name, options) {
|
|
|
4026
5733
|
return service;
|
|
4027
5734
|
}
|
|
4028
5735
|
//#endregion
|
|
5736
|
+
//#region src/socket-redis.ts
|
|
5737
|
+
/** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */
|
|
5738
|
+
function reconnectDelay(failures) {
|
|
5739
|
+
const ceiling = Math.min(3e4, 500 * 2 ** failures);
|
|
5740
|
+
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
5741
|
+
}
|
|
5742
|
+
/** One Redis connection that reconnects by itself and reports each fresh connection. */
|
|
5743
|
+
function connection(url, connected) {
|
|
5744
|
+
let redis;
|
|
5745
|
+
let timer;
|
|
5746
|
+
let closed = false;
|
|
5747
|
+
let failures = 0;
|
|
5748
|
+
const waiters = [];
|
|
5749
|
+
const lost = (client) => {
|
|
5750
|
+
if (redis !== client) return;
|
|
5751
|
+
redis = void 0;
|
|
5752
|
+
if (closed || timer) return;
|
|
5753
|
+
timer = setTimeout(() => {
|
|
5754
|
+
timer = void 0;
|
|
5755
|
+
start();
|
|
5756
|
+
}, reconnectDelay(failures++));
|
|
5757
|
+
};
|
|
5758
|
+
const start = () => {
|
|
5759
|
+
if (closed || redis || timer) return;
|
|
5760
|
+
const client = new Bun.RedisClient(url, {
|
|
5761
|
+
autoReconnect: false,
|
|
5762
|
+
enableOfflineQueue: false
|
|
5763
|
+
});
|
|
5764
|
+
redis = client;
|
|
5765
|
+
client.onclose = () => lost(client);
|
|
5766
|
+
client.connect().then(() => {
|
|
5767
|
+
if (redis !== client) return;
|
|
5768
|
+
failures = 0;
|
|
5769
|
+
connected(client);
|
|
5770
|
+
for (const wake of waiters.splice(0)) wake();
|
|
5771
|
+
}, () => lost(client));
|
|
5772
|
+
};
|
|
5773
|
+
return {
|
|
5774
|
+
/** The connected client, starting a connection when there is none. */
|
|
5775
|
+
get() {
|
|
5776
|
+
start();
|
|
5777
|
+
return redis?.connected ? redis : void 0;
|
|
5778
|
+
},
|
|
5779
|
+
/** Resolves after the next connection is made and announced, or after `ms`. */
|
|
5780
|
+
opened(ms) {
|
|
5781
|
+
if (redis?.connected) return Promise.resolve();
|
|
5782
|
+
start();
|
|
5783
|
+
return new Promise((resolve) => {
|
|
5784
|
+
waiters.push(resolve);
|
|
5785
|
+
setTimeout(resolve, ms);
|
|
5786
|
+
});
|
|
5787
|
+
},
|
|
5788
|
+
close() {
|
|
5789
|
+
closed = true;
|
|
5790
|
+
clearTimeout(timer);
|
|
5791
|
+
for (const wake of waiters.splice(0)) wake();
|
|
5792
|
+
const client = redis;
|
|
5793
|
+
redis = void 0;
|
|
5794
|
+
client?.close();
|
|
5795
|
+
}
|
|
5796
|
+
};
|
|
5797
|
+
}
|
|
5798
|
+
/**
|
|
5799
|
+
* Fans socket emits and kicks out across processes through Redis pub/sub, one
|
|
5800
|
+
* channel per room topic. An emit is a PUBLISH only: every process, the emitting
|
|
5801
|
+
* one included, delivers it once to its own connections. Uses Bun's built-in
|
|
5802
|
+
* Redis client and two connections, one to publish and one to subscribe.
|
|
5803
|
+
*/
|
|
5804
|
+
function redisBroker(options = {}) {
|
|
5805
|
+
const limit = options.queue ?? 1e3;
|
|
5806
|
+
if (!Number.isInteger(limit) || limit < 0) throw new Error("redisBroker queue must be a nonnegative integer");
|
|
5807
|
+
const channel = (topic) => `brick:socket:${topic}`;
|
|
5808
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
5809
|
+
const pending = /* @__PURE__ */ new Map();
|
|
5810
|
+
const stream = (topic) => `brick:socket:stream:${topic}`;
|
|
5811
|
+
const queue = [];
|
|
5812
|
+
const send = (work) => {
|
|
5813
|
+
const redis = publisher.get();
|
|
5814
|
+
if (redis) return work(redis);
|
|
5815
|
+
queue.push(work);
|
|
5816
|
+
if (queue.length > limit) queue.shift();
|
|
5817
|
+
};
|
|
5818
|
+
const receive = (payload, name) => {
|
|
5819
|
+
let message;
|
|
5820
|
+
try {
|
|
5821
|
+
message = JSON.parse(payload);
|
|
5822
|
+
} catch {
|
|
5823
|
+
return;
|
|
5824
|
+
}
|
|
5825
|
+
for (const deliver of listeners.get(name) ?? []) deliver(message);
|
|
5826
|
+
};
|
|
5827
|
+
const subscribe = (redis, name) => {
|
|
5828
|
+
const done = redis.subscribe(name, receive).catch(() => {});
|
|
5829
|
+
pending.set(name, done);
|
|
5830
|
+
done.then(() => {
|
|
5831
|
+
if (pending.get(name) === done) pending.delete(name);
|
|
5832
|
+
});
|
|
5833
|
+
};
|
|
5834
|
+
const publisher = connection(options.url, (redis) => {
|
|
5835
|
+
for (const work of queue.splice(0)) work(redis);
|
|
5836
|
+
});
|
|
5837
|
+
const subscriber = connection(options.url, (redis) => {
|
|
5838
|
+
for (const name of listeners.keys()) subscribe(redis, name);
|
|
5839
|
+
});
|
|
5840
|
+
return {
|
|
5841
|
+
publish(message, replay) {
|
|
5842
|
+
const name = channel(message.topic);
|
|
5843
|
+
if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(() => {}));
|
|
5844
|
+
const key = stream(message.topic);
|
|
5845
|
+
send((redis) => {
|
|
5846
|
+
redis.send("XADD", [
|
|
5847
|
+
key,
|
|
5848
|
+
"MAXLEN",
|
|
5849
|
+
"~",
|
|
5850
|
+
String(replay.keep),
|
|
5851
|
+
"*",
|
|
5852
|
+
"m",
|
|
5853
|
+
message.frame
|
|
5854
|
+
]).then((seq) => {
|
|
5855
|
+
redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(() => {});
|
|
5856
|
+
return redis.publish(name, JSON.stringify({
|
|
5857
|
+
...message,
|
|
5858
|
+
seq
|
|
5859
|
+
}));
|
|
5860
|
+
}).catch(() => {});
|
|
5861
|
+
});
|
|
5862
|
+
},
|
|
5863
|
+
async head() {
|
|
5864
|
+
try {
|
|
5865
|
+
await publisher.opened(1e3);
|
|
5866
|
+
const [seconds, micros] = await publisher.get().send("TIME", []);
|
|
5867
|
+
return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
|
|
5868
|
+
} catch {
|
|
5869
|
+
return `${Date.now() - 1}-0`;
|
|
5870
|
+
}
|
|
5871
|
+
},
|
|
5872
|
+
async history(topic, since, replay) {
|
|
5873
|
+
let raw;
|
|
5874
|
+
try {
|
|
5875
|
+
await publisher.opened(1e3);
|
|
5876
|
+
raw = await publisher.get().send("XRANGE", [
|
|
5877
|
+
stream(topic),
|
|
5878
|
+
"-",
|
|
5879
|
+
"+"
|
|
5880
|
+
]);
|
|
5881
|
+
} catch {
|
|
5882
|
+
return;
|
|
5883
|
+
}
|
|
5884
|
+
const ms = (seq) => Number(seq.split("-")[0]);
|
|
5885
|
+
const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);
|
|
5886
|
+
if (after.length === raw.length && (raw.length >= replay.keep || (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)) return void 0;
|
|
5887
|
+
return after.map(([seq, fields]) => ({
|
|
5888
|
+
type: "emit",
|
|
5889
|
+
topic,
|
|
5890
|
+
frame: fields[fields.indexOf("m") + 1],
|
|
5891
|
+
seq
|
|
5892
|
+
}));
|
|
5893
|
+
},
|
|
5894
|
+
subscribe(topic, deliver) {
|
|
5895
|
+
const name = channel(topic);
|
|
5896
|
+
let local = listeners.get(name);
|
|
5897
|
+
if (!local) {
|
|
5898
|
+
local = /* @__PURE__ */ new Set();
|
|
5899
|
+
listeners.set(name, local);
|
|
5900
|
+
const redis = subscriber.get();
|
|
5901
|
+
if (redis) subscribe(redis, name);
|
|
5902
|
+
}
|
|
5903
|
+
local.add(deliver);
|
|
5904
|
+
return () => {
|
|
5905
|
+
local.delete(deliver);
|
|
5906
|
+
if (local.size || listeners.get(name) !== local) return;
|
|
5907
|
+
listeners.delete(name);
|
|
5908
|
+
pending.delete(name);
|
|
5909
|
+
subscriber.get()?.unsubscribe(name).catch(() => {});
|
|
5910
|
+
};
|
|
5911
|
+
},
|
|
5912
|
+
async ready(topic) {
|
|
5913
|
+
const name = channel(topic);
|
|
5914
|
+
if (!pending.has(name)) await subscriber.opened(1e3);
|
|
5915
|
+
await pending.get(name);
|
|
5916
|
+
},
|
|
5917
|
+
close() {
|
|
5918
|
+
publisher.close();
|
|
5919
|
+
subscriber.close();
|
|
5920
|
+
}
|
|
5921
|
+
};
|
|
5922
|
+
}
|
|
5923
|
+
//#endregion
|
|
4029
5924
|
//#region src/rpc.ts
|
|
4030
5925
|
/**
|
|
4031
|
-
*
|
|
4032
|
-
*
|
|
4033
|
-
*
|
|
5926
|
+
* Call another service's actions in-process, typed from that service. Each
|
|
5927
|
+
* action is a method, and each resource's actions sit under the resource's
|
|
5928
|
+
* name: `billing.charge(input)`, `billing.invoice.list()`.
|
|
5929
|
+
*
|
|
5930
|
+
* The types come from the app's generated contract (`_brick/contract.ts`, which
|
|
5931
|
+
* `brick dev` and `brick gen client` keep current), so renaming an action or
|
|
5932
|
+
* changing its input is a compile error at every caller. Until the contract
|
|
5933
|
+
* describes the service, the client is untyped.
|
|
4034
5934
|
*
|
|
4035
|
-
*
|
|
4036
|
-
* target's database and
|
|
4037
|
-
* span in the trace.
|
|
4038
|
-
* a call throws. Use the typed client to call a service over HTTP.
|
|
5935
|
+
* A call runs through the target's own validation and authorization, with the
|
|
5936
|
+
* target's database, context and deps (never the caller's), and shows as an
|
|
5937
|
+
* `rpc` span in the trace.
|
|
4039
5938
|
*
|
|
4040
|
-
* @param
|
|
5939
|
+
* @param service - The service to call, as `defineService` returned it.
|
|
4041
5940
|
* @param options - `from` (the calling service's name, which becomes `ctx.caller`
|
|
4042
|
-
* in the target and cannot be spoofed)
|
|
4043
|
-
*
|
|
4044
|
-
* @returns
|
|
4045
|
-
* @throws On a call, when the service or
|
|
5941
|
+
* in the target and cannot be spoofed) and `context` (defaults for every call).
|
|
5942
|
+
* Each call also takes an optional call context after its input.
|
|
5943
|
+
* @returns The client.
|
|
5944
|
+
* @throws On a call, when the service is not registered or has no such action.
|
|
4046
5945
|
* @example
|
|
4047
|
-
* import {
|
|
5946
|
+
* import { useService } from "@brickkit/core";
|
|
5947
|
+
* import { billingService } from "../billing/billing.service";
|
|
4048
5948
|
*
|
|
4049
|
-
* const
|
|
4050
|
-
*
|
|
4051
|
-
*
|
|
4052
|
-
* );
|
|
4053
|
-
* const page = await pages.get({ id: "p_1" });
|
|
5949
|
+
* const billing = useService(billingService, { from: "orders" });
|
|
5950
|
+
* await billing.charge({ orderId, amountCents });
|
|
5951
|
+
* await billing.invoice.list({ limit: 10 });
|
|
4054
5952
|
*/
|
|
4055
|
-
function
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
|
|
4069
|
-
|
|
4070
|
-
|
|
4071
|
-
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
|
|
4075
|
-
} });
|
|
5953
|
+
function useService(service, options = {}) {
|
|
5954
|
+
return serviceRef(service.name, options, []);
|
|
5955
|
+
}
|
|
5956
|
+
function serviceRef(serviceName, options, path) {
|
|
5957
|
+
return new Proxy(function() {}, {
|
|
5958
|
+
get(_, key) {
|
|
5959
|
+
if (typeof key !== "string" || key === "then") return void 0;
|
|
5960
|
+
return serviceRef(serviceName, options, [...path, key]);
|
|
5961
|
+
},
|
|
5962
|
+
apply(_, __, [payload, callCtx]) {
|
|
5963
|
+
const name = path.join(".");
|
|
5964
|
+
const clientPath = [serviceName, ...path].join(".");
|
|
5965
|
+
return callAction(serviceName, name, (service) => service.getAction(name) ?? service.listActions().find((action) => (getPluginActionRoute(action) || void 0)?.clientPath?.join(".") === clientPath), payload, callCtx, options);
|
|
5966
|
+
}
|
|
5967
|
+
});
|
|
5968
|
+
}
|
|
5969
|
+
async function callAction(serviceName, actionName, find, payload, callCtx, options) {
|
|
5970
|
+
const service = getGlobalRegistry().get(serviceName);
|
|
5971
|
+
if (!service) throw new Error(`[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`);
|
|
5972
|
+
const action = find(service);
|
|
5973
|
+
if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
|
|
5974
|
+
const envelopeCtx = createRpcEnvelope(options.from, options.context, callCtx);
|
|
5975
|
+
return withCallSpan(`rpc ${serviceName}.${actionName}`, {
|
|
5976
|
+
"brick.service": serviceName,
|
|
5977
|
+
"brick.action": actionName
|
|
5978
|
+
}, () => action.execute({
|
|
5979
|
+
input: payload,
|
|
5980
|
+
ctx: envelopeCtx
|
|
5981
|
+
}));
|
|
4076
5982
|
}
|
|
4077
5983
|
/** Build the trusted envelope for a proxy call.
|
|
4078
5984
|
*
|
|
@@ -4092,94 +5998,38 @@ function createRpcEnvelope(from, defaultContext, callContext) {
|
|
|
4092
5998
|
}
|
|
4093
5999
|
//#endregion
|
|
4094
6000
|
//#region src/events/listener.ts
|
|
4095
|
-
/**
|
|
4096
|
-
* Define a listener: code that runs for each event it listens for, after the write
|
|
4097
|
-
* that caused the event has been committed. Pass it to `brick({ events: {
|
|
4098
|
-
* listeners } })`.
|
|
4099
|
-
*
|
|
4100
|
-
* It either runs a handler (`run`) in the process that delivers events, or starts
|
|
4101
|
-
* a durable workflow (`workflow`) on the app's `events.world`. Delivery is at
|
|
4102
|
-
* least once. A handler that throws is retried later with a growing delay, then
|
|
4103
|
-
* parked as dead, so it can run again for the same event: use
|
|
4104
|
-
* `delivery.deliveryId` to make its work idempotent. A workflow needs no such
|
|
4105
|
-
* care: a delivery starts one run however often it is tried, and the workflow
|
|
4106
|
-
* retries its own steps.
|
|
4107
|
-
*
|
|
4108
|
-
* @param config - `name` (unique; it is part of each delivery's id), `on` (an
|
|
4109
|
-
* event name or a list of them; a trailing `*` matches a prefix, as in
|
|
4110
|
-
* `user.*`), `run` or `workflow`, and optionally `maxAttempts`.
|
|
4111
|
-
* @returns The listener.
|
|
4112
|
-
* @throws When the name is empty or contains `:`, `on` is empty, or the listener
|
|
4113
|
-
* has both or neither of `run` and `workflow`.
|
|
4114
|
-
* @example
|
|
4115
|
-
* import { brick, defineListener } from "@brickkit/core";
|
|
4116
|
-
*
|
|
4117
|
-
* const welcome = defineListener({
|
|
4118
|
-
* name: "welcome-email",
|
|
4119
|
-
* on: "user.create",
|
|
4120
|
-
* run: async ({ payload, deliveryId }) => {
|
|
4121
|
-
* await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });
|
|
4122
|
-
* },
|
|
4123
|
-
* });
|
|
4124
|
-
*
|
|
4125
|
-
* export default brick({ services, events: { listeners: [welcome] } });
|
|
4126
|
-
* @example
|
|
4127
|
-
* // src/workflows/onboard.ts
|
|
4128
|
-
* export async function onboard(event: WorkflowEvent<CrudEventPayload>) {
|
|
4129
|
-
* "use workflow";
|
|
4130
|
-
* await sendWelcome(event.payload.row.email);
|
|
4131
|
-
* }
|
|
4132
|
-
*
|
|
4133
|
-
* defineListener({ name: "onboard", on: "user.create", workflow: onboard });
|
|
4134
|
-
*/
|
|
4135
6001
|
function defineListener(config) {
|
|
4136
6002
|
if (typeof config.name !== "string" || !config.name) throw new Error("An event listener needs a name");
|
|
4137
6003
|
if (config.name.includes(":")) throw new Error(`Event listener name '${config.name}' must not contain ':'`);
|
|
4138
|
-
const on =
|
|
4139
|
-
if (!on.length || on.some((pattern) => !pattern)) throw new Error(`Event listener '${config.name}' listens for nothing`);
|
|
6004
|
+
const on = (Array.isArray(config.on) ? config.on : [config.on]).map((item) => isEventRef(item) ? item.name : item);
|
|
6005
|
+
if (!on.length || on.some((pattern) => !pattern || typeof pattern !== "string")) throw new Error(`Event listener '${config.name}' listens for nothing`);
|
|
4140
6006
|
if (config.maxAttempts !== void 0 && (!Number.isInteger(config.maxAttempts) || config.maxAttempts < 1)) throw new Error(`Event listener '${config.name}': maxAttempts must be a positive integer`);
|
|
4141
6007
|
const { name, run, workflow } = config;
|
|
4142
6008
|
if (run !== void 0 && workflow !== void 0) throw new Error(`Event listener '${name}' has both run and workflow; give it one`);
|
|
4143
6009
|
if (run === void 0 && workflow === void 0) throw new Error(`Event listener '${name}' needs a run handler or a workflow`);
|
|
4144
6010
|
if (run !== void 0 && typeof run !== "function") throw new Error(`Event listener '${name}': run must be a function`);
|
|
4145
6011
|
if (workflow !== void 0 && typeof workflow !== "function") throw new Error(`Event listener '${name}': workflow must be a function marked "use workflow"`);
|
|
6012
|
+
const helpers = buildErrorHelpers(config.errors);
|
|
4146
6013
|
return Object.freeze({
|
|
4147
6014
|
name: config.name,
|
|
4148
6015
|
on: Object.freeze(on),
|
|
4149
|
-
...config.run !== void 0 ? { run: config.run } : {},
|
|
6016
|
+
...config.run !== void 0 ? { run: ((delivery) => config.run(delivery, { error: helpers })) } : {},
|
|
6017
|
+
...config.errors ? { errors: config.errors } : {},
|
|
6018
|
+
...config.retry ? { retry: config.retry } : {},
|
|
4150
6019
|
...config.workflow !== void 0 ? { workflow: config.workflow } : {},
|
|
4151
6020
|
...config.maxAttempts !== void 0 ? { maxAttempts: config.maxAttempts } : {}
|
|
4152
6021
|
});
|
|
4153
6022
|
}
|
|
4154
6023
|
//#endregion
|
|
4155
6024
|
//#region src/events/emit.ts
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4161
|
-
|
|
4162
|
-
|
|
4163
|
-
|
|
4164
|
-
*
|
|
4165
|
-
* @param ctx - The action context: its `db` finds the service's outbox, and its
|
|
4166
|
-
* `traceId` follows the event to its listeners.
|
|
4167
|
-
* @param name - The event name, such as `order.refunded`.
|
|
4168
|
-
* @param payload - JSON data for the listeners.
|
|
4169
|
-
* @param options - `tx`: an open transaction on the service's database. `source`:
|
|
4170
|
-
* what emitted it, shown to listeners.
|
|
4171
|
-
* @throws When the context's database has no outbox table, or the app has no
|
|
4172
|
-
* `events`.
|
|
4173
|
-
* @example
|
|
4174
|
-
* refund: service.action({
|
|
4175
|
-
* name: "refund",
|
|
4176
|
-
* execute: async ({ ctx, input }) => {
|
|
4177
|
-
* await ctx.db.update(orders).set({ status: "refunded" }).where(eq(orders.id, input.id));
|
|
4178
|
-
* await emitEvent(ctx, "order.refunded", { id: input.id });
|
|
4179
|
-
* },
|
|
4180
|
-
* });
|
|
4181
|
-
*/
|
|
4182
|
-
async function emitEvent(ctx, name, payload, options = {}) {
|
|
6025
|
+
async function emitEvent(ctx, event, payload, options = {}) {
|
|
6026
|
+
const name = typeof event === "string" ? event : event.name;
|
|
6027
|
+
if (typeof event !== "string") checkEvent({
|
|
6028
|
+
name: event.service,
|
|
6029
|
+
events: { [name.slice(event.service.length + 1)]: event },
|
|
6030
|
+
hasCatalog: true,
|
|
6031
|
+
listResources: () => []
|
|
6032
|
+
}, name, payload);
|
|
4183
6033
|
const events = ctx.db && typeof ctx.db === "object" ? recorders.get(ctx.db) : void 0;
|
|
4184
6034
|
if (!events) throw new Error(`Cannot emit '${name}': ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database, not a transaction)`);
|
|
4185
6035
|
const context = {
|
|
@@ -4313,6 +6163,6 @@ function createMcpHandler(options) {
|
|
|
4313
6163
|
};
|
|
4314
6164
|
}
|
|
4315
6165
|
//#endregion
|
|
4316
|
-
export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, Dispatcher, EventsHub, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase,
|
|
6166
|
+
export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, Dispatcher, EventsHub, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, brickVersion, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, defineAction, defineDatabase, defineError, defineListener, definePlugin, defineResource, defineResourcePlugin, defineSecret, defineService, defineServicePlugin, defineTool, desc, emitEvent, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, errorsOf, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getActionRoute, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hoistAnchoredSchemas, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isEventRef, isNotNull, isNull, isOutboxTable, isPluginInstance, isTool, kebabCase, like, listSecrets, loadCompiledBrickApp, loadRecord, lt, lte, ne, not, notInArray, onTransactionCommit, or, outboxTable, overrideSecret, overrideSecrets, port, primaryKey, real, redisBroker, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, resolveWorkflowPaths, runInTransaction, satisfiesRange, scalarDocsHTML, serializeSocketSchema, setActionAccess, sql, sqliteTable, stopAllEvents, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, traceRoute, uniqueIndex, useDeps, useService, validateWithSchema };
|
|
4317
6167
|
|
|
4318
6168
|
//# sourceMappingURL=index.js.map
|