@brickkit/core 0.15.0 → 0.16.0-beta.1

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.
@@ -1,17 +1,20 @@
1
- import { A as byteLength, B as splitSeq, C as SOCKET_BUFFER_BYTES, D as SOCKET_PROTOCOL, E as SOCKET_MAX_BYTES, F as isSocketRoom, G as DuplicateNameError, H as GLOBAL_SYMBOL, I as isSocketSeq, K as ValidationError, L as replayFrame, M as encodeFrame, N as isControlEvent, O as SOCKET_TOKEN_PROTOCOL, P as isSocketEnvelope, R as replayHeadroom, S as actionMeta, T as SOCKET_CONTROL, U as SPAN, V as ATTR, W as ActionExecutionError, _ as pathParamNames, b as toOpenApiPath, c as DEFAULT_PREFIX, d as getActionRoute, g as ownerPath, h as joinRoute, k as STANDARD_ERRORS, l as actionOwners, m as isReadLike, p as inputSource, s as serializeSocketSchema, u as checkSegments, v as pluginRoutePath, w as SOCKET_CLOSE, x as kebabCase, y as routeKey, z as signSeq } from "./client.js";
1
+ import { A as STANDARD_ERRORS, B as signSeq, C as actionMeta, D as SOCKET_MAX_BYTES, E as SOCKET_CONTROL, F as isSocketEnvelope, G as ActionExecutionError, H as ATTR, I as isSocketRoom, K as DuplicateNameError, L as isSocketSeq, M as compareSocketSeq, N as encodeFrame, O as SOCKET_PROTOCOL, P as isControlEvent, R as replayFrame, S as kebabCase, T as SOCKET_CLOSE, U as GLOBAL_SYMBOL, V as splitSeq, W as SPAN, _ as ownerPath, b as routeKey, c as DEFAULT_PREFIX, d as checkSegments, f as getActionRoute, g as joinRoute, h as isReadLike, j as byteLength, k as SOCKET_TOKEN_PROTOCOL, l as actionMethod, m as inputSource, q as ValidationError, s as serializeSocketSchema, u as actionOwners, v as pathParamNames, w as SOCKET_BUFFER_BYTES, x as toOpenApiPath, y as pluginRoutePath, z as replayHeadroom } from "./client.js";
2
2
  import { createRequire } from "node:module";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { format, formatWithOptions, inspect } from "node:util";
3
5
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
4
- import { Kind, Type, TypeRegistry } from "@sinclair/typebox";
6
+ import { Kind, Type as Type$1, TypeRegistry } from "@sinclair/typebox";
5
7
  import { TypeCompiler } from "@sinclair/typebox/compiler";
6
- import { formatWithOptions } from "node:util";
7
- import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
8
- import { join, resolve } from "node:path";
8
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
9
+ import { isIPv4, isIPv6 } from "node:net";
10
+ import { lstat, mkdir, readFile, realpath, rm } from "node:fs/promises";
11
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
9
12
  import { fileURLToPath, pathToFileURL } from "node:url";
13
+ import { Value } from "@sinclair/typebox/value";
14
+ import { bigserial, index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
15
+ import { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
10
16
  import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
11
- import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
12
- import { bigserial, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
13
17
  import { existsSync, readFileSync } from "node:fs";
14
- import { AsyncLocalStorage } from "node:async_hooks";
15
18
  import { Elysia } from "elysia";
16
19
  import { websocket } from "elysia/websocket";
17
20
  // src/plugin-types.ts
@@ -28,6 +31,419 @@ const PLUGIN_KIND = Symbol.for("brickkit.plugin.kind");
28
31
  * once its install succeeds; a failed install drops it.
29
32
  */
30
33
  const PLUGIN_COMMIT = Symbol.for("brickkit.plugin.commit");
34
+ // src/sensitive.ts
35
+ const SENSITIVE = Symbol.for("brickkit.sensitive");
36
+ /** The schema, unchanged in type and validation, marked sensitive. */
37
+ function Sensitive(schema) {
38
+ return {
39
+ ...schema,
40
+ [SENSITIVE]: true
41
+ };
42
+ }
43
+ const isSensitive = (schema) => schema?.[SENSITIVE] === true;
44
+ const analyses = /* @__PURE__ */ new WeakMap();
45
+ function analyze(schema) {
46
+ if (!schema || typeof schema !== "object") return {
47
+ paths: [],
48
+ publics: []
49
+ };
50
+ let analysis = analyses.get(schema);
51
+ if (!analysis) {
52
+ const walk = {
53
+ paths: [],
54
+ publics: [],
55
+ markedIds: /* @__PURE__ */ new Set(),
56
+ loops: /* @__PURE__ */ new Map()
57
+ };
58
+ collect(schema, [], false, [], walk);
59
+ analysis = {
60
+ paths: walk.paths,
61
+ publics: walk.publics,
62
+ hidden: walk.hidden
63
+ };
64
+ if (walk.paths.length || walk.hidden) analysis.ref = walk.external ?? [...walk.markedIds].map((id) => walk.loops.get(id)).find(Boolean);
65
+ analyses.set(schema, analysis);
66
+ }
67
+ return analysis;
68
+ }
69
+ function sensitivePaths(schema) {
70
+ return analyze(schema).paths;
71
+ }
72
+ const holdsMark = (node, seen = /* @__PURE__ */ new Set()) => {
73
+ if (!node || typeof node !== "object" || seen.has(node)) return false;
74
+ seen.add(node);
75
+ return isSensitive(node) || Object.values(node).some((child) => holdsMark(child, seen));
76
+ };
77
+ function collect(schema, segments, optional, ids, walk) {
78
+ if (!schema || typeof schema !== "object") return;
79
+ if (isSensitive(schema)) {
80
+ walk.paths.push({
81
+ segments,
82
+ optional
83
+ });
84
+ for (const id of ids) walk.markedIds.add(id);
85
+ return;
86
+ }
87
+ if (typeof schema.$ref === "string") {
88
+ if (!ids.includes(schema.$ref)) walk.external ??= pointer(segments);
89
+ else if (!walk.loops.has(schema.$ref)) walk.loops.set(schema.$ref, pointer(segments));
90
+ }
91
+ if (typeof schema.$id === "string") ids = [...ids, schema.$id];
92
+ const list = schema.type === "array" && !Array.isArray(schema.items);
93
+ for (const key of Object.keys(schema)) if (!WALKED.has(key) || key === "items" && !list && !Array.isArray(schema.items)) {
94
+ if (holdsMark(schema[key])) walk.hidden ??= pointer([...segments, key]);
95
+ }
96
+ const branchesSharingOnePath = [
97
+ ...schema.anyOf ?? [],
98
+ ...schema.allOf ?? [],
99
+ ...schema.oneOf ?? []
100
+ ];
101
+ for (const branch of branchesSharingOnePath) collect(branch, segments, optional, ids, walk);
102
+ const declared = Object.keys(schema.properties ?? {});
103
+ const required = new Set(schema.required ?? []);
104
+ const removable = !(schema.minProperties > declared.filter((key) => required.has(key) && !isSensitive(schema.properties[key])).length);
105
+ for (const key of declared) {
106
+ const child = schema.properties[key];
107
+ if (!isSensitive(child)) walk.publics.push({
108
+ segments: [...segments, key],
109
+ required: required.has(key)
110
+ });
111
+ collect(child, [...segments, key], removable && !required.has(key), ids, walk);
112
+ }
113
+ for (const child of Object.values(schema.patternProperties ?? {})) collect(child, [...segments, null], removable, ids, walk);
114
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") collect(schema.additionalProperties, [...segments, declared.length ? { except: declared } : null], removable, ids, walk);
115
+ const before = walk.paths.length;
116
+ const items = Array.isArray(schema.items) ? schema.items.map((child, index) => [child, String(index)]) : list ? [[schema.items, null]] : [];
117
+ for (const [child, segment] of items) {
118
+ if (!isSensitive(child)) walk.publics.push({
119
+ segments: [...segments, segment],
120
+ required: true
121
+ });
122
+ collect(child, [...segments, segment], false, ids, walk);
123
+ }
124
+ if (schema.uniqueItems) for (const path of walk.paths.slice(before)) path.optional = false;
125
+ }
126
+ const WALKED = /* @__PURE__ */ new Set([
127
+ "anyOf",
128
+ "allOf",
129
+ "oneOf",
130
+ "properties",
131
+ "patternProperties",
132
+ "additionalProperties",
133
+ "items"
134
+ ]);
135
+ const admits = (segment, key) => segment === null || (typeof segment === "string" ? segment === key : !segment.except.includes(key));
136
+ const overlap = (a, b) => typeof a === "string" ? admits(b, a) : typeof b === "string" ? admits(a, b) : true;
137
+ const marksKey = (schema, key) => sensitivePaths(schema).some(({ segments: [first] }) => first === void 0 || admits(first, key));
138
+ /** Whether any part of a schema is marked sensitive. */
139
+ function hasSensitive(schema) {
140
+ const { paths, hidden } = analyze(schema);
141
+ return paths.length > 0 || hidden !== void 0;
142
+ }
143
+ function writeOnly(schema) {
144
+ if (!hasSensitive(schema)) return schema;
145
+ const visit = (node) => {
146
+ if (Array.isArray(node)) return node.map(visit);
147
+ if (!node || typeof node !== "object") return node;
148
+ const copy = { ...node };
149
+ for (const key of Object.keys(copy)) copy[key] = visit(copy[key]);
150
+ if (isSensitive(node)) copy.writeOnly = true;
151
+ return copy;
152
+ };
153
+ return visit(schema);
154
+ }
155
+ const pointer = (segments) => segments.map((key) => `/${typeof key === "string" ? key : "*"}`).join("") || "/";
156
+ function sensitivePointer(schema) {
157
+ const { paths, hidden } = analyze(schema);
158
+ return paths[0] ? pointer(paths[0].segments) : hidden;
159
+ }
160
+ const escape = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
161
+ const keysAt = (value, segment) => segment === null ? Object.keys(value) : typeof segment === "object" ? Object.keys(value).filter((key) => !segment.except.includes(key)) : Object.hasOwn(value, segment) ? [segment] : [];
162
+ function* found(value, segments, index = 0, at = "") {
163
+ if (value === null || typeof value !== "object") return;
164
+ for (const key of keysAt(value, segments[index])) {
165
+ const field = `${at}/${escape(key)}`;
166
+ if (index === segments.length - 1) yield [
167
+ value,
168
+ key,
169
+ field
170
+ ];
171
+ else yield* found(value[key], segments, index + 1, field);
172
+ }
173
+ }
174
+ function omit(value, segments, hidden, index = 0, at = "") {
175
+ if (value === null || typeof value !== "object") return value;
176
+ let copy;
177
+ for (const key of keysAt(value, segments[index])) {
178
+ const field = `${at}/${escape(key)}`;
179
+ if (index === segments.length - 1) {
180
+ if (!hidden.has(field)) continue;
181
+ copy ??= Array.isArray(value) ? [...value] : { ...value };
182
+ delete copy[key];
183
+ } else {
184
+ const next = omit(value[key], segments, hidden, index + 1, field);
185
+ if (next === value[key]) continue;
186
+ copy ??= Array.isArray(value) ? [...value] : { ...value };
187
+ copy[key] = next;
188
+ }
189
+ }
190
+ return copy ?? value;
191
+ }
192
+ function sensitivity(config, service) {
193
+ const input = analyze(config.input);
194
+ const output = analyze(config.output);
195
+ const inputs = input.paths;
196
+ const outputs = output.paths;
197
+ if (!hasSensitive(config.input) && !hasSensitive(config.output)) return void 0;
198
+ const owner = service ? `Service '${service}' action '${config.name}'` : `Action '${config.name}'`;
199
+ for (const [kind, { ref, hidden }] of [["input", input], ["output", output]]) {
200
+ if (ref !== void 0) throw new Error(`${owner}: the ${kind} schema marks a field t.Sensitive and has a $ref at '${ref}' (t.Recursive, t.Module or t.Ref), which sensitive fields do not follow; move the secret out of the recursive or referenced schema`);
201
+ if (hidden !== void 0) throw new Error(`${owner}: the ${kind} schema marks a field t.Sensitive under '${hidden}', which sensitive fields do not follow; mark it in properties, items, records or union branches`);
202
+ }
203
+ const { reveal = false } = config;
204
+ if (reveal !== true) for (const path of outputs) {
205
+ const at = pointer(path.segments);
206
+ if (!path.optional) throw new Error(`${owner}: sensitive output field '${at}' is removed unless \`reveal\` allows it, so the schema must let it be absent: make it t.Optional in every union or intersect branch, not an array item, a record value or a property under minProperties, nor inside a uniqueItems array (or set \`reveal: true\`)`);
207
+ const exact = JSON.stringify(path.segments);
208
+ const hit = output.publics.find(({ segments, required }) => segments.length === path.segments.length && segments.every((segment, index) => overlap(segment, path.segments[index])) && (required || JSON.stringify(segments) !== exact));
209
+ if (hit) throw new Error(`${owner}: sensitive output field '${at}' is removed unless \`reveal\` allows it, and that path also matches the unmarked field '${pointer(hit.segments)}', which would be removed with it; give the secret a name of its own (or set \`reveal: true\`)`);
210
+ }
211
+ const values = (value, paths) => {
212
+ const all = [];
213
+ for (const { segments } of paths) if (!segments.length) all.push(value);
214
+ else for (const [parent, key] of found(value, segments)) all.push(parent[key]);
215
+ return all;
216
+ };
217
+ return {
218
+ input(input) {
219
+ for (const value of values(input, inputs)) redact(value);
220
+ },
221
+ async output(output, input, ctx) {
222
+ for (const value of values(output, outputs)) redact(value);
223
+ if (reveal === true) return output;
224
+ let result = output;
225
+ for (const { segments } of outputs) {
226
+ const hidden = /* @__PURE__ */ new Set();
227
+ for (const [, , field] of found(output, segments)) if (typeof reveal !== "function" || await reveal({
228
+ field,
229
+ input,
230
+ ctx
231
+ }) !== true) hidden.add(field);
232
+ if (hidden.size) result = omit(result, segments, hidden);
233
+ }
234
+ return result;
235
+ }
236
+ };
237
+ }
238
+ const MIN_REDACTED_LENGTH = 8;
239
+ const MIN_REDACTED_DIGITS = 4;
240
+ const MAX_REDACTED_VALUES = 1e4;
241
+ const MAX_WALKED_ENTRIES = 100;
242
+ const REDACTED = "[REDACTED]";
243
+ const WITHHELD = "[REDACTED: too many sensitive values in this call]";
244
+ const redactions = globalThis[Symbol.for("brickkit.redactions")] ??= new AsyncLocalStorage();
245
+ let warned$1 = false;
246
+ function add(set, value) {
247
+ if (set.values.has(value)) return;
248
+ if (set.count >= MAX_REDACTED_VALUES) {
249
+ if (!warned$1) console.warn(`[brick] A call's redaction set reached ${MAX_REDACTED_VALUES} values, so its log lines are now withheld. A timer or task started inside a call with t.Sensitive fields joins that call's set; bound an input's sensitive records and arrays with maxProperties or maxItems.`);
250
+ warned$1 = true;
251
+ set.full = true;
252
+ return;
253
+ }
254
+ set.count++;
255
+ set.values.add(value);
256
+ set.values.add(JSON.stringify(value).slice(1, -1));
257
+ set.sorted = void 0;
258
+ }
259
+ const longNumber = (value) => String(value).replace(/\D/g, "").length >= MIN_REDACTED_DIGITS;
260
+ /**
261
+ * Keep a secret out of what Brick logs and traces for the rest of the running
262
+ * call: the logger, the span recorder and error responses replace it with
263
+ * `[REDACTED]`. Call it as soon as `execute` loads a secret, before it can be
264
+ * logged. It takes each string and number in the value, as a `t.Sensitive`
265
+ * field's value is taken: booleans, and numbers under 4 digits, are left out.
266
+ * Outside a call with `t.Sensitive` fields it does nothing.
267
+ */
268
+ function redact(value) {
269
+ const set = redactions.getStore();
270
+ if (set) register(set, value, /* @__PURE__ */ new Set());
271
+ }
272
+ function register(set, value, seen) {
273
+ if (typeof value === "string") {
274
+ if (value) add(set, value);
275
+ } else if (typeof value === "number" || typeof value === "bigint") {
276
+ if (longNumber(value)) add(set, String(value));
277
+ } else if (value && typeof value === "object" && !seen.has(value)) {
278
+ seen.add(value);
279
+ for (const child of Object.values(value)) register(set, child, seen);
280
+ }
281
+ }
282
+ function redacting() {
283
+ const set = redactions.getStore();
284
+ return !!set && (set.full || set.values.size > 0);
285
+ }
286
+ function redactText(text) {
287
+ const set = redactions.getStore();
288
+ if (!set || typeof text !== "string") return text;
289
+ if (set.full) return WITHHELD;
290
+ set.sorted ??= [...set.values].filter((value) => value.length >= MIN_REDACTED_LENGTH).sort((a, b) => b.length - a.length);
291
+ let redacted = text;
292
+ for (const value of set.sorted) if (redacted.includes(value)) redacted = redacted.split(value).join(REDACTED);
293
+ return redacted;
294
+ }
295
+ function redactLeaf(set, value) {
296
+ if (typeof value === "string") return set.values.has(value) ? REDACTED : redactText(value);
297
+ if (typeof value === "number" || typeof value === "bigint") return longNumber(value) && set.values.has(String(value)) ? REDACTED : value;
298
+ return value;
299
+ }
300
+ const LEAF_DEPTH = 5;
301
+ function publicFieldsCopy(original, props) {
302
+ const copy = Object.create(Object.getPrototypeOf(original));
303
+ for (const [key, next] of props) Object.defineProperty(copy, key, {
304
+ value: next,
305
+ enumerable: true,
306
+ writable: true,
307
+ configurable: true
308
+ });
309
+ return copy;
310
+ }
311
+ function redactValues(value) {
312
+ const set = redactions.getStore();
313
+ if (!set || !set.full && !set.values.size) return value;
314
+ const walking = /* @__PURE__ */ new Set();
315
+ const done = /* @__PURE__ */ new Map();
316
+ const visit = (value, depth) => {
317
+ if (typeof value === "function") return Object.keys(value).length ? "[Function]" : value;
318
+ if (!value || typeof value !== "object") return redactLeaf(set, value);
319
+ if (value instanceof Date) return value;
320
+ if (walking.has(value)) return "[Circular]";
321
+ if (done.has(value)) return done.get(value);
322
+ if (depth > LEAF_DEPTH) return "[Object]";
323
+ walking.add(value);
324
+ let copy;
325
+ try {
326
+ copy = inside(value, depth);
327
+ } catch {
328
+ copy = "[Unreadable]";
329
+ }
330
+ walking.delete(value);
331
+ done.set(value, copy);
332
+ return copy;
333
+ };
334
+ const entries = (value, size, depth) => {
335
+ const items = [];
336
+ for (const item of value) {
337
+ if (items.length === MAX_WALKED_ENTRIES) break;
338
+ items.push(item);
339
+ }
340
+ const next = items.map((item) => visit(item, value instanceof Map ? depth : depth + 1));
341
+ const more = size - items.length;
342
+ return {
343
+ next,
344
+ more,
345
+ changed: more > 0 || next.some((item, i) => item !== items[i])
346
+ };
347
+ };
348
+ const inside = (value, depth) => {
349
+ if (Array.isArray(value)) {
350
+ const { next, more, changed } = entries(value, value.length, depth);
351
+ if (more) next.push(`... ${more} more items not shown`);
352
+ return changed || Object.keys(value).length !== value.length ? next : value;
353
+ }
354
+ if (value instanceof Map || value instanceof Set) {
355
+ const { next, more, changed } = entries(value, value.size, depth);
356
+ if (!changed) return value;
357
+ if (value instanceof Set) {
358
+ if (more) next.push(`... ${more} more items not shown`);
359
+ return new Set(next);
360
+ }
361
+ const map = new Map(next);
362
+ if (more) map.set("...", `${more} more entries not shown`);
363
+ return map;
364
+ }
365
+ if (value instanceof Error) {
366
+ let text = redactText(String(value.stack || `${value.name}: ${value.message}`));
367
+ if (Object.keys(value).length) text += ` ${inspect(visit({ ...value }, depth + 1), { depth: 2 })}`;
368
+ if (value.cause !== void 0) {
369
+ const cause = visit(value.cause, depth + 1);
370
+ text += `\n [cause]: ${typeof cause === "string" ? cause : inspect(cause, { depth: 2 })}`;
371
+ }
372
+ return text;
373
+ }
374
+ const tag = Object.prototype.toString.call(value);
375
+ if (tag !== "[object Object]") return `[${tag.slice(8, -1)}]`;
376
+ const descriptors = Object.getOwnPropertyDescriptors(value);
377
+ let changed = false;
378
+ const props = [];
379
+ for (const key of Reflect.ownKeys(descriptors)) {
380
+ const descriptor = descriptors[key];
381
+ if (!descriptor.enumerable) continue;
382
+ const name = typeof key === "string" ? redactLeaf(set, key) : key;
383
+ const next = "value" in descriptor ? visit(descriptor.value, depth + 1) : "[Getter]";
384
+ if (name !== key || next !== descriptor.value) changed = true;
385
+ props.push([name, next]);
386
+ }
387
+ return changed ? publicFieldsCopy(value, props) : value;
388
+ };
389
+ return visit(value, 0);
390
+ }
391
+ function redactDetails(details) {
392
+ const set = redactions.getStore();
393
+ if (!set || details === void 0 || !set.full && !set.values.size) return details;
394
+ if (set.full) return WITHHELD;
395
+ try {
396
+ const text = JSON.stringify(details);
397
+ if (text === void 0) return details;
398
+ const copy = JSON.parse(text, (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).map(([key, child]) => [redactLeaf(set, key), child])) : redactLeaf(set, value));
399
+ return JSON.stringify(copy) === text ? details : copy;
400
+ } catch {
401
+ return REDACTED;
402
+ }
403
+ }
404
+ const outsideRedaction = (fn) => redactions.exit(fn);
405
+ /** Set a property of an error, unless it is read-only (a `DOMException`, a frozen error). */
406
+ function assign(target, key, value) {
407
+ try {
408
+ target[key] = value;
409
+ } catch {}
410
+ }
411
+ const ESCAPED_ERROR_FIELDS = /* @__PURE__ */ new Set([
412
+ "message",
413
+ "stack",
414
+ "cause",
415
+ "details"
416
+ ]);
417
+ const MAX_CAUSE_DEPTH = 8;
418
+ /** `err`, redacted in place along its cause chain, for whoever logs it outside the call. */
419
+ function redactEscaped(err) {
420
+ if (!(err instanceof Error)) return redactValues(err);
421
+ let e = err;
422
+ for (let n = 0; n < MAX_CAUSE_DEPTH; n++) {
423
+ assign(e, "message", redactText(e.message));
424
+ if (e.stack) assign(e, "stack", redactText(e.stack));
425
+ if ("details" in e) assign(e, "details", redactDetails(e.details));
426
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(e))) if (descriptor.enumerable && "value" in descriptor && !ESCAPED_ERROR_FIELDS.has(key)) assign(e, key, redactValues(descriptor.value));
427
+ if (!(e.cause instanceof Error)) {
428
+ if (e.cause !== void 0) assign(e, "cause", redactValues(e.cause));
429
+ break;
430
+ }
431
+ e = e.cause;
432
+ }
433
+ return err;
434
+ }
435
+ async function withRedaction(fn) {
436
+ if (redactions.getStore()) return fn();
437
+ const set = {
438
+ values: /* @__PURE__ */ new Set(),
439
+ count: 0
440
+ };
441
+ try {
442
+ return await redactions.run(set, fn);
443
+ } catch (err) {
444
+ throw redactions.run(set, () => redactEscaped(err));
445
+ }
446
+ }
31
447
  // src/telemetry.ts
32
448
  const INSTRUMENTATION_SCOPE = "@brickkit/core";
33
449
  const MAX_TEXT_LENGTH = 500;
@@ -130,6 +546,13 @@ function recordFailure(error, failure) {
130
546
  });
131
547
  if (failure.status >= 500) recordThrown(span, error);
132
548
  }
549
+ function recordWebhook(name, eventId, outcome) {
550
+ trace.getActiveSpan()?.setAttributes({
551
+ [ATTR.webhook]: name,
552
+ ...eventId === void 0 ? {} : { [ATTR.webhookEventId]: eventId },
553
+ [ATTR.webhookOutcome]: outcome
554
+ });
555
+ }
133
556
  /**
134
557
  * Record SQL statements as client spans for the database behind a service.
135
558
  * Drizzle's logger has no timing, so the hook sits on the driver: each
@@ -247,10 +670,17 @@ function settle(fn, done) {
247
670
  return result;
248
671
  }
249
672
  function recordThrown(span, error) {
250
- span.recordException(error instanceof Error ? error : String(error));
673
+ if (!(error instanceof Error)) span.recordException(redactText(String(error)));
674
+ else if (!redacting()) span.recordException(error);
675
+ else span.recordException({
676
+ code: error.code,
677
+ name: error.name,
678
+ message: redactText(error.message),
679
+ stack: error.stack && redactText(error.stack)
680
+ });
251
681
  span.setStatus({
252
682
  code: SpanStatusCode.ERROR,
253
- message: truncate(messageOf(error))
683
+ message: truncate(redactText(messageOf(error)))
254
684
  });
255
685
  }
256
686
  function responseStatus(value) {
@@ -287,10 +717,15 @@ function normalizeActionError(err, { logger, requestId }) {
287
717
  * `details` or `errors` when there are any.
288
718
  */
289
719
  function toErrorResponse(err, context) {
290
- const envelope = buildErrorEnvelope(err, context);
720
+ const envelope = redactAnsweredEnvelope(buildErrorEnvelope(err, context));
291
721
  recordFailure(err, envelope);
292
722
  return envelope;
293
723
  }
724
+ function redactAnsweredEnvelope(envelope) {
725
+ envelope.message = redactText(envelope.message);
726
+ if (envelope.details !== void 0) envelope.details = redactDetails(envelope.details);
727
+ return envelope;
728
+ }
294
729
  function buildErrorEnvelope(err, context) {
295
730
  const failure = normalizeActionError(err, context);
296
731
  if (failure.status >= 500 && (err instanceof ActionExecutionError || err instanceof ValidationError)) context.logger.error("Server action error", { requestId: context.requestId }, err);
@@ -312,19 +747,28 @@ function buildErrorEnvelope(err, context) {
312
747
  * JSON values.
313
748
  */
314
749
  function Json(options) {
315
- return Type.Recursive((This) => Type.Union([
316
- Type.Null(),
317
- Type.Boolean(),
318
- Type.Number(),
319
- Type.String(),
320
- Type.Array(This),
321
- Type.Record(Type.String(), This)
750
+ return Type$1.Recursive((This) => Type$1.Union([
751
+ Type$1.Null(),
752
+ Type$1.Boolean(),
753
+ Type$1.Number(),
754
+ Type$1.String(),
755
+ Type$1.Array(This),
756
+ Type$1.Record(Type$1.String(), This)
322
757
  ]), options);
323
758
  }
324
- TypeRegistry.Set("File", (schema, value) => value instanceof Blob && !(value.size > (schema.maxSize ?? Infinity)));
325
- /** A file from a `multipart/form-data` body: a `File` (a `Blob`), at most `maxSize` bytes. */
759
+ function accepts(accept, type) {
760
+ if (!accept) return true;
761
+ const given = type.split(";")[0].trim().toLowerCase();
762
+ return accept.some((pattern) => {
763
+ const wanted = pattern.toLowerCase();
764
+ if (wanted === "*/*") return true;
765
+ return wanted.endsWith("/*") ? given.startsWith(wanted.slice(0, -1)) && given.length > wanted.length - 1 : given === wanted;
766
+ });
767
+ }
768
+ TypeRegistry.Set("File", (schema, value) => value instanceof Blob && !(value.size > (schema.maxSize ?? 1e400)) && accepts(schema.accept, value.type));
769
+ /** A file from a `multipart/form-data` body: a `File` (a `Blob`), at most `maxSize` bytes, of a type in `accept`. */
326
770
  function File(options = {}) {
327
- return Type.Unsafe({
771
+ return Type$1.Unsafe({
328
772
  [Kind]: "File",
329
773
  type: "string",
330
774
  format: "binary",
@@ -334,16 +778,17 @@ function File(options = {}) {
334
778
  /** Several files under one form field. */
335
779
  function Files(options = {}) {
336
780
  const { minItems, maxItems, ...file } = options;
337
- return Type.Array(File(file), {
781
+ return Type$1.Array(File(file), {
338
782
  minItems,
339
783
  maxItems
340
784
  });
341
785
  }
342
- /** TypeBox's `Type` plus Brick's `Json`, `File` and `Files`. */
343
- const Type$1 = Object.assign({}, Type, {
786
+ /** TypeBox's `Type` plus Brick's `Json`, `File`, `Files` and `Sensitive`. */
787
+ const Type = Object.assign({}, Type$1, {
344
788
  Json,
345
789
  File,
346
- Files
790
+ Files,
791
+ Sensitive
347
792
  });
348
793
  function fileFields(schema) {
349
794
  const fields = [];
@@ -383,7 +828,8 @@ function getCompiledCheck(schema) {
383
828
  * @param schema - A TypeBox schema, or `undefined` to accept anything.
384
829
  * @param value - The value to check.
385
830
  * @returns `{ success: true, data }`, or `{ success: false, errors }` with a
386
- * `path`, `message`, `type`, and the offending `value` for each problem.
831
+ * `path`, `message` and `type` for each problem. The offending value is
832
+ * left out so a rejected secret is never echoed or logged.
387
833
  */
388
834
  function validateWithSchema(schema, value) {
389
835
  if (!schema) return {
@@ -399,7 +845,6 @@ function validateWithSchema(schema, value) {
399
845
  for (const error of check.Errors(value)) errors.push({
400
846
  path: error.path,
401
847
  message: error.message,
402
- value: error.value,
403
848
  type: error.type
404
849
  });
405
850
  return {
@@ -432,17 +877,27 @@ const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)
432
877
  function stripAnsi(text) {
433
878
  return text.includes("\x1B") ? text.replace(ANSI, "") : text;
434
879
  }
880
+ const REDACTED_COPY_NOT_PRINTABLE = "[Unreadable]";
881
+ function formatRedacted(print, args) {
882
+ let printed;
883
+ try {
884
+ printed = print(...redactValues(args));
885
+ } catch {
886
+ printed = REDACTED_COPY_NOT_PRINTABLE;
887
+ }
888
+ return redactText(printed);
889
+ }
435
890
  /**
436
891
  * What `console.log` would print, without terminal colors, with objects cut off
437
892
  * at a sensible size.
438
893
  */
439
894
  function render(args) {
440
- const text = stripAnsi(formatWithOptions({
895
+ const text = formatRedacted((...values) => stripAnsi(formatWithOptions({
441
896
  depth: 3,
442
897
  breakLength: 120,
443
898
  maxArrayLength: 50,
444
899
  maxStringLength: 1e3
445
- }, ...args));
900
+ }, ...values)), args);
446
901
  return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;
447
902
  }
448
903
  function record(span, level, args) {
@@ -467,150 +922,1778 @@ function recordActive(level, args) {
467
922
  record(span, level, args);
468
923
  return true;
469
924
  }
470
- globalThis[Symbol.for(GLOBAL_SYMBOL.logsRecord)] = recordActive;
471
- /**
472
- * A logger for actions, tools, and endpoints. While a dashboard is on, a line
473
- * logged while a request is being traced becomes an event on the span that is
474
- * running, which the dashboard shows with that request (and in its Logs tab);
475
- * it is not printed. Everywhere else, and for lines logged outside a request,
476
- * it prints to the console, prefixed by `prefix`: one for all levels, or one
477
- * per level.
478
- *
479
- * Capturing costs one context lookup and a span event per line, and nothing
480
- * is serialized for the dashboard until the span ends, so it is cheaper than
481
- * a console write. Lines are cut at 4,000 characters and a span keeps 100.
482
- */
483
- function createLogger(prefix) {
484
- const level = (name, print) => (...args) => {
485
- if (globalThis[CAPTURE] === true && recordActive(name, args)) return;
486
- print(typeof prefix === "string" ? prefix : prefix[name], ...args);
487
- };
925
+ globalThis[Symbol.for(GLOBAL_SYMBOL.logsRecord)] = recordActive;
926
+ /**
927
+ * A logger for actions, tools, and endpoints. While a dashboard is on, a line
928
+ * logged while a request is being traced becomes an event on the span that is
929
+ * running, which the dashboard shows with that request (and in its Logs tab);
930
+ * it is not printed. Everywhere else, and for lines logged outside a request,
931
+ * it prints to the console, prefixed by `prefix`: one for all levels, or one
932
+ * per level.
933
+ *
934
+ * Capturing costs one context lookup and a span event per line, and nothing
935
+ * is serialized for the dashboard until the span ends, so it is cheaper than
936
+ * a console write. Lines are cut at 4,000 characters and a span keeps 100.
937
+ */
938
+ function createLogger(prefix) {
939
+ const level = (name, print) => (...args) => {
940
+ if (globalThis[CAPTURE] === true && recordActive(name, args)) return;
941
+ if (redacting()) args = [formatRedacted(format, args)];
942
+ print(typeof prefix === "string" ? prefix : prefix[name], ...args);
943
+ };
944
+ return {
945
+ info: level("info", (...args) => console.log(...args)),
946
+ warn: level("warn", (...args) => console.warn(...args)),
947
+ error: level("error", (...args) => console.error(...args)),
948
+ debug: level("debug", (...args) => console.debug(...args))
949
+ };
950
+ }
951
+ /** The prefixes of loggers a caller did not supply. */
952
+ const DEFAULT_LOG_PREFIXES = {
953
+ info: "[INFO]",
954
+ warn: "[WARN]",
955
+ error: "[ERROR]",
956
+ debug: "[DEBUG]"
957
+ };
958
+ // src/dashboard-identity.ts
959
+ /** The header the dashboard's `/app/*` proxy signs the identity into. */
960
+ const DASHBOARD_IDENTITY_HEADER = "x-brick-dashboard";
961
+ /** How `brick dev` hands the signing key to the app's process. */
962
+ const DASHBOARD_KEY_ENV = "BRICK_DASHBOARD_KEY";
963
+ const SIGNATURE_TTL_MS = 6e4;
964
+ const KEY = Symbol.for(GLOBAL_SYMBOL.dashboardKey);
965
+ const global = globalThis;
966
+ function hideKeyFromChildProcesses() {
967
+ const handedOver = process.env[DASHBOARD_KEY_ENV];
968
+ if (!handedOver) return;
969
+ global[KEY] = handedOver;
970
+ delete process.env[DASHBOARD_KEY_ENV];
971
+ }
972
+ hideKeyFromChildProcesses();
973
+ /**
974
+ * The key the dashboard signs identities with: random per process, or the one
975
+ * `brick dev` or the Vite plugin handed the app.
976
+ */
977
+ function dashboardKey() {
978
+ return global[KEY] ??= randomBytes(32).toString("base64url");
979
+ }
980
+ const arrivedAt = /* @__PURE__ */ new WeakMap();
981
+ /** Note when `request` arrived, before its body is read. */
982
+ function markDashboardArrival(request) {
983
+ arrivedAt.set(request, Date.now());
984
+ }
985
+ const mac$1 = (payload) => createHmac("sha256", dashboardKey()).update(payload).digest();
986
+ /** The header value for an identity: `<base64url(json)>.<hmac>`. */
987
+ function signDashboardIdentity(identity, now = Date.now()) {
988
+ const payload = Buffer.from(JSON.stringify({
989
+ user: identity.user,
990
+ exp: now + SIGNATURE_TTL_MS
991
+ })).toString("base64url");
992
+ return `${payload}.${mac$1(payload).toString("base64url")}`;
993
+ }
994
+ function dashboardIdentity(request) {
995
+ const header = request?.headers.get(DASHBOARD_IDENTITY_HEADER);
996
+ if (!header) return void 0;
997
+ const dot = header.indexOf(".");
998
+ if (dot < 0) return void 0;
999
+ const payload = header.slice(0, dot);
1000
+ const given = Buffer.from(header.slice(dot + 1), "base64url");
1001
+ const expected = mac$1(payload);
1002
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return void 0;
1003
+ try {
1004
+ const { user, exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1005
+ const now = (request && arrivedAt.get(request)) ?? Date.now();
1006
+ if (typeof exp !== "number" || exp < now) return void 0;
1007
+ return user === void 0 ? {} : { user };
1008
+ } catch {
1009
+ return;
1010
+ }
1011
+ }
1012
+ /**
1013
+ * The dashboard user a request came from, for an endpoint: the person
1014
+ * `dashboard.auth.authorize` let in, when the request arrived through the
1015
+ * dashboard's `/app/*` proxy. Undefined for any other request, and for one the
1016
+ * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.
1017
+ */
1018
+ function dashboardUser(request) {
1019
+ return dashboardIdentity(request)?.user;
1020
+ }
1021
+ // src/identity.ts
1022
+ const IDENTITY = Symbol.for("brickkit.identity");
1023
+ function attachIdentity(ctx, service, deps) {
1024
+ const hook = service.options.identity;
1025
+ if (typeof hook !== "function") return;
1026
+ let identity;
1027
+ ctx[IDENTITY] = () => identity ??= Promise.resolve().then(() => {
1028
+ const { [IDENTITY]: _own, ...withoutIdentity } = ctx;
1029
+ return hook({
1030
+ ...withoutIdentity,
1031
+ deps
1032
+ });
1033
+ }).then((value) => checked(service.name, value));
1034
+ }
1035
+ function checked(service, value) {
1036
+ if (value === null || value === void 0) return null;
1037
+ const { id, label, tenant } = value;
1038
+ if (typeof id !== "string" || !id || label !== void 0 && typeof label !== "string" || tenant !== void 0 && typeof tenant !== "string") throw new Error(`Service "${service}": identity must return { id: string, label?: string, tenant?: string } with a non-empty id, null or undefined`);
1039
+ return {
1040
+ id,
1041
+ ...label !== void 0 && { label },
1042
+ ...tenant !== void 0 && { tenant }
1043
+ };
1044
+ }
1045
+ function identityOf(ctx) {
1046
+ const resolve = ctx[IDENTITY];
1047
+ return typeof resolve === "function" ? resolve() : Promise.resolve(null);
1048
+ }
1049
+ function hasIdentity(service) {
1050
+ return typeof service.options.identity === "function";
1051
+ }
1052
+ // src/service-port.ts
1053
+ /** The port of a service: every `Service` is a `ServicePort`. */
1054
+ function portOf(service) {
1055
+ return service;
1056
+ }
1057
+ // src/deps.ts
1058
+ /** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */
1059
+ const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
1060
+ function sharedAcrossCoreCopies(key, create) {
1061
+ const store = globalThis;
1062
+ return store[Symbol.for(key)] ??= create();
1063
+ }
1064
+ const depsBuiltByBrick = sharedAcrossCoreCopies("brickkit.deps.built", () => /* @__PURE__ */ new WeakSet());
1065
+ function freezeAsBuiltDeps(deps) {
1066
+ depsBuiltByBrick.add(Object.freeze(deps));
1067
+ return deps;
1068
+ }
1069
+ function depsOverride(callCtx) {
1070
+ const deps = callCtx?.deps;
1071
+ return deps && typeof deps === "object" && !depsBuiltByBrick.has(deps) ? deps : void 0;
1072
+ }
1073
+ const running = new AsyncLocalStorage();
1074
+ /** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
1075
+ function runWithDeps(deps, fn) {
1076
+ return running.run(deps, fn);
1077
+ }
1078
+ function useDeps(service) {
1079
+ if (service) return portOf(service).deps;
1080
+ const deps = running.getStore();
1081
+ if (!deps) throw new Error("useDeps() was called outside a Brick app: call it from a listener, a schedule or a workflow step (actions read ctx.deps), or pass the service: useDeps(service).");
1082
+ return deps;
1083
+ }
1084
+ function makeAmbiguous(deps, name, firstService, otherService) {
1085
+ Object.defineProperty(deps, name, {
1086
+ enumerable: false,
1087
+ get() {
1088
+ throw new Error(`useDeps().${name} is ambiguous: services "${firstService}" and "${otherService}" both declare dep "${name}" with different values. Call useDeps(service) with the service you mean.`);
1089
+ }
1090
+ });
1091
+ }
1092
+ function appDeps(services) {
1093
+ const deps = {};
1094
+ const owner = /* @__PURE__ */ new Map();
1095
+ for (const service of services) for (const [name, value] of Object.entries(portOf(service).deps)) {
1096
+ const seen = Object.getOwnPropertyDescriptor(deps, name);
1097
+ const first = owner.get(name);
1098
+ if (!seen) {
1099
+ owner.set(name, service.name);
1100
+ deps[name] = value;
1101
+ } else if ("value" in seen && seen.value !== value) makeAmbiguous(deps, name, first, service.name);
1102
+ }
1103
+ return freezeAsBuiltDeps(deps);
1104
+ }
1105
+ // src/definition-site.ts
1106
+ const brickRoot = fileURLToPath(new URL("..", import.meta.url));
1107
+ /**
1108
+ * The first `file:line` outside Brick on the current stack: where a name is
1109
+ * being defined. Best-effort: `undefined` when there is no stack.
1110
+ */
1111
+ function definitionSite() {
1112
+ const limit = Error.stackTraceLimit;
1113
+ Error.stackTraceLimit = 50;
1114
+ const stack = (/* @__PURE__ */ new Error()).stack;
1115
+ Error.stackTraceLimit = limit;
1116
+ for (const line of stack?.split("\n").slice(1) ?? []) {
1117
+ const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
1118
+ if (!match) continue;
1119
+ const [, file, row] = match;
1120
+ if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
1121
+ return `${file}:${row}`;
1122
+ }
1123
+ }
1124
+ /**
1125
+ * Records where `name` is defined. The same file defining it again (a dev
1126
+ * reload) replaces the old definition.
1127
+ *
1128
+ * @throws When a different file already defined `name`.
1129
+ */
1130
+ function claimName(sites, label, name, site) {
1131
+ const file = (at) => at?.replace(/:\d+$/, "");
1132
+ if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new DuplicateNameError(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
1133
+ sites.set(name, site);
1134
+ }
1135
+ // src/secrets.ts
1136
+ /**
1137
+ * Type-safe secrets & environment variables.
1138
+ *
1139
+ * Declare each secret once at module scope instead of scattering untyped
1140
+ * `process.env.FOO` reads:
1141
+ *
1142
+ * const port = defineSecret("PORT").default("3333").transform(Number).require();
1143
+ * const baseUrl = defineSecret("BASE_URL").url().require();
1144
+ * const key = defineSecret("STRIPE_KEY").validate((v) =>
1145
+ * v.startsWith("sk_") || "must start with sk_"
1146
+ * ).require();
1147
+ *
1148
+ * Values resolve from the environment (Bun populates `process.env` from
1149
+ * `.env` locally; in prod the same env source applies — a future
1150
+ * `SecretSource` such as AWS can slot in without touching call sites).
1151
+ *
1152
+ * Resolution order per secret: test/session override → source (`process.env`
1153
+ * by default) → declared `default`. `resolveSecrets()` validates every
1154
+ * registered secret at boot and throws listing all missing required ones.
1155
+ */
1156
+ /** Default source: `process.env` (Bun loads `.env` into it automatically). */
1157
+ const envSource = { get: (name) => process.env[name] };
1158
+ const registry = /* @__PURE__ */ new Map();
1159
+ const overrides = /* @__PURE__ */ new Map();
1160
+ /** Where each secret was first declared. */
1161
+ const sites = /* @__PURE__ */ new Map();
1162
+ var SecretRef = class {
1163
+ name;
1164
+ options;
1165
+ transformFn;
1166
+ validators = [];
1167
+ constructor(name, options = {}) {
1168
+ this.name = name;
1169
+ this.options = options;
1170
+ }
1171
+ /** True when a default was declared (i.e. the secret is optional). */
1172
+ get hasDefault() {
1173
+ return this.options.default !== void 0;
1174
+ }
1175
+ /** Fallback used when the source has no value. Makes the secret optional. */
1176
+ default(value) {
1177
+ this.options.default = value;
1178
+ return this;
1179
+ }
1180
+ /**
1181
+ * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
1182
+ * Runs before validators; a throwing transform fails resolution.
1183
+ */
1184
+ transform(fn) {
1185
+ this.transformFn = fn;
1186
+ return this;
1187
+ }
1188
+ /** Run a custom check on the (transformed) value at every resolution. */
1189
+ validate(fn) {
1190
+ this.validators.push(fn);
1191
+ return this;
1192
+ }
1193
+ /** Shorthand validator: value must parse as a URL. String refs only. */
1194
+ url() {
1195
+ this.validators.push((v) => {
1196
+ try {
1197
+ new URL(v);
1198
+ } catch {
1199
+ return "must be a valid URL";
1200
+ }
1201
+ });
1202
+ return this;
1203
+ }
1204
+ resolveRaw(source) {
1205
+ return overrides.get(this.name) ?? source.get(this.name) ?? this.options.default;
1206
+ }
1207
+ coerce(raw) {
1208
+ let value;
1209
+ if (this.transformFn) try {
1210
+ value = this.transformFn(raw);
1211
+ } catch (err) {
1212
+ throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
1213
+ }
1214
+ else value = raw;
1215
+ for (const fn of this.validators) {
1216
+ let result;
1217
+ try {
1218
+ result = fn(value);
1219
+ } catch (err) {
1220
+ throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
1221
+ }
1222
+ if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
1223
+ if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
1224
+ }
1225
+ return value;
1226
+ }
1227
+ /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
1228
+ value(source = envSource) {
1229
+ const raw = this.resolveRaw(source);
1230
+ if (raw === void 0) return void 0;
1231
+ return this.coerce(raw);
1232
+ }
1233
+ /** Resolved value, or throws naming the missing/invalid secret. */
1234
+ require(source = envSource) {
1235
+ const raw = this.resolveRaw(source);
1236
+ if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
1237
+ return this.coerce(raw);
1238
+ }
1239
+ /** True when a value would resolve (override, source, or default). */
1240
+ isSet(source = envSource) {
1241
+ return this.resolveRaw(source) !== void 0;
1242
+ }
1243
+ };
1244
+ /**
1245
+ * Declare a secret. Calling it again for the name returns the same ref. From
1246
+ * the same line (a module evaluated again) it starts the declaration over, so
1247
+ * its builder calls replace the earlier ones instead of adding to them.
1248
+ */
1249
+ function defineSecret(name, options = {}) {
1250
+ const site = definitionSite();
1251
+ const existing = registry.get(name);
1252
+ if (existing) {
1253
+ if (site !== void 0 && sites.get(name) === site) {
1254
+ existing.options = options;
1255
+ existing["validators"] = [];
1256
+ existing["transformFn"] = void 0;
1257
+ }
1258
+ return existing;
1259
+ }
1260
+ sites.set(name, site);
1261
+ const ref = new SecretRef(name, options);
1262
+ registry.set(name, ref);
1263
+ return ref;
1264
+ }
1265
+ /**
1266
+ * Validate every registered secret at boot. Throws a single error listing
1267
+ * all missing required secrets. Returns the resolved values.
1268
+ */
1269
+ function resolveSecrets(opts = {}) {
1270
+ const source = opts.source ?? envSource;
1271
+ const missing = [];
1272
+ const resolved = {};
1273
+ for (const ref of registry.values()) {
1274
+ const v = ref.value(source);
1275
+ if (v === void 0) missing.push(ref.name);
1276
+ else resolved[ref.name] = v;
1277
+ }
1278
+ if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
1279
+ return resolved;
1280
+ }
1281
+ /** Metadata for introspection (values never exposed — future dashboard use). */
1282
+ function listSecrets(opts = {}) {
1283
+ const source = opts.source ?? envSource;
1284
+ return [...registry.values()].map((ref) => ({
1285
+ hasDefault: ref.hasDefault,
1286
+ isSet: ref.isSet(source),
1287
+ name: ref.name
1288
+ }));
1289
+ }
1290
+ /** Test/session override for one secret (`undefined` clears the override). */
1291
+ function overrideSecret(name, value) {
1292
+ if (value === void 0) overrides.delete(name);
1293
+ else overrides.set(name, value);
1294
+ }
1295
+ /** Clear registry and overrides. Test-only. */
1296
+ function resetSecrets() {
1297
+ registry.clear();
1298
+ overrides.clear();
1299
+ sites.clear();
1300
+ }
1301
+ // src/file-storage.ts
1302
+ const DEFAULT_EXPIRY_MS = 3e5;
1303
+ /** The longest a link may last: S3 refuses a presigned URL valid for longer. */
1304
+ const MAX_EXPIRY_MS = 6048e5;
1305
+ const S3_READ_IDLE_TIMEOUT_MS = 3e4;
1306
+ const LOCAL_FILES_ROUTE = "/_brick/files";
1307
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1308
+ const drivers = globalThis[Symbol.for("brickkit.storage.files")] ??= /* @__PURE__ */ new WeakMap();
1309
+ const sha256 = (value) => createHash("sha256").update(value).digest("hex");
1310
+ function tenantKey(tenant, local = false) {
1311
+ if (typeof tenant !== "string" || !tenant || tenant === "." || tenant === ".." || !tenant.isWellFormed()) throw new Error(`File storage: the tenant must be a non-empty, well-formed string other than "." and "..", got ${JSON.stringify(tenant)}`);
1312
+ return local ? sha256(tenant) : encodeURIComponent(tenant);
1313
+ }
1314
+ function attachment(download) {
1315
+ if (!download) return "attachment";
1316
+ return `attachment; filename="${download.replace(/[^\x20-\x7e]|["\\]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(download)}`;
1317
+ }
1318
+ function scoped(driver, tenant) {
1319
+ const folder = async () => `${driver.prefix}${tenantKey(await tenant(), !!driver.local)}/`;
1320
+ const keyOf = async (id) => {
1321
+ const at = await folder();
1322
+ return typeof id === "string" && UUID.test(id) ? at + id : void 0;
1323
+ };
1324
+ return Object.freeze({
1325
+ put: async (file, options) => {
1326
+ if (!(file instanceof Blob)) throw new TypeError("File storage: put needs a Blob or a File");
1327
+ const at = await folder();
1328
+ const id = crypto.randomUUID();
1329
+ const given = (options?.contentType || file.type).toLowerCase();
1330
+ const contentType = new Blob([], { type: given }).type || "application/octet-stream";
1331
+ await driver.write(at + id, file, contentType);
1332
+ return {
1333
+ id,
1334
+ size: file.size,
1335
+ contentType
1336
+ };
1337
+ },
1338
+ url: async (id, options = {}) => {
1339
+ const key = await keyOf(id);
1340
+ if (!key) throw new Error(`File storage: ${JSON.stringify(id)} is not a file id`);
1341
+ const expiresInMs = options.expiresInMs ?? DEFAULT_EXPIRY_MS;
1342
+ if (!Number.isSafeInteger(expiresInMs) || expiresInMs <= 0) throw new Error(`File storage: expiresInMs must be a positive integer, got ${expiresInMs}`);
1343
+ if (expiresInMs > MAX_EXPIRY_MS) throw new Error(`File storage: expiresInMs must be at most 7 days (${MAX_EXPIRY_MS}), got ${expiresInMs}`);
1344
+ return driver.sign(key, expiresInMs, attachment(options.download));
1345
+ },
1346
+ get: async (id) => {
1347
+ const key = await keyOf(id);
1348
+ return key ? driver.read(key) : void 0;
1349
+ },
1350
+ delete: async (id) => {
1351
+ const key = await keyOf(id);
1352
+ if (key) await driver.remove(key);
1353
+ }
1354
+ });
1355
+ }
1356
+ function fileStorage(driver) {
1357
+ const outside = () => Promise.reject(/* @__PURE__ */ new Error("File storage: there is no caller here to take the tenant from. In an action read ctx.deps.<name>; elsewhere name the tenant: files.in(tenantId)"));
1358
+ const handle = Object.freeze({
1359
+ kind: "file",
1360
+ in: (tenant) => {
1361
+ tenantKey(tenant);
1362
+ return scoped(driver, async () => tenant);
1363
+ },
1364
+ put: outside,
1365
+ url: outside,
1366
+ get: outside,
1367
+ delete: outside
1368
+ });
1369
+ drivers.set(handle, driver);
1370
+ return handle;
1371
+ }
1372
+ const fileNames = /* @__PURE__ */ new WeakMap();
1373
+ const views = /* @__PURE__ */ new WeakMap();
1374
+ function hasFilesView(ctx, deps) {
1375
+ const view = views.get(ctx.deps);
1376
+ return view?.deps === deps && view.ctx === ctx;
1377
+ }
1378
+ function scopeFiles(deps, ctx) {
1379
+ let names = fileNames.get(deps);
1380
+ if (!names) fileNames.set(deps, names = Object.keys(deps).filter((name) => drivers.has(deps[name])));
1381
+ if (!names.length) return deps;
1382
+ const tenant = async () => {
1383
+ const identity = await identityOf(ctx);
1384
+ if (!identity?.tenant) throw new Error("File storage: this call has no tenant. The service's identity hook must return { id, tenant } for callers that use files; outside a request use files.in(tenantId)");
1385
+ return identity.tenant;
1386
+ };
1387
+ const copy = { ...deps };
1388
+ for (const name of names) {
1389
+ const handle = deps[name];
1390
+ copy[name] = Object.freeze({
1391
+ kind: "file",
1392
+ ...scoped(drivers.get(handle), tenant)
1393
+ });
1394
+ }
1395
+ const view = freezeAsBuiltDeps(copy);
1396
+ views.set(view, {
1397
+ deps,
1398
+ ctx
1399
+ });
1400
+ return view;
1401
+ }
1402
+ function checkFileStorages(service, deps) {
1403
+ if (hasIdentity(service)) return;
1404
+ for (const values of deps) {
1405
+ const name = Object.keys(values).find((key) => drivers.has(values[key]));
1406
+ if (name) throw new Error(`Service "${service.name}" has file storage "${name}" in its deps or a plugin's but no identity hook. Files are kept per tenant: add identity: (ctx) => ({ id, tenant }) to the service.`);
1407
+ }
1408
+ }
1409
+ const warned = /* @__PURE__ */ new WeakSet();
1410
+ function localFileDirs(deps) {
1411
+ const dirs = /* @__PURE__ */ new Set();
1412
+ for (const values of deps) for (const value of Object.values(values)) {
1413
+ const driver = drivers.get(value);
1414
+ driver?.check?.();
1415
+ if (!driver?.local) continue;
1416
+ dirs.add(driver.local);
1417
+ if (process.env.NODE_ENV === "production" && !warned.has(driver)) {
1418
+ warned.add(driver);
1419
+ console.warn(`[Brick-TS] A file storage stores files in the local directory ${driver.local} while NODE_ENV is production. Set local only for development and tests.`);
1420
+ }
1421
+ }
1422
+ return dirs;
1423
+ }
1424
+ /**
1425
+ * File storage in S3 or an S3-compatible store (R2, MinIO), through Bun's
1426
+ * built-in client. Nothing connects or reads credentials until the first call.
1427
+ * With `local`, files are written under that directory instead.
1428
+ *
1429
+ * @param options - `bucket`, `prefix`, `local`, and the credentials and
1430
+ * `endpoint` Bun's client takes, each a string or a `SecretRef`; left out,
1431
+ * Bun's `S3_*` and `AWS_*` environment variables apply.
1432
+ */
1433
+ function s3(options = {}) {
1434
+ const prefix = options.prefix ?? "";
1435
+ if (prefix.startsWith("/") || prefix.split("/").some((part) => part === "." || part === "..")) throw new Error(`s3(): prefix must not start with "/" or hold "." or ".." segments, got ${JSON.stringify(prefix)}`);
1436
+ if (options.local !== void 0) return localDriver(resolve(options.local), prefix);
1437
+ let client;
1438
+ const bucket = () => options.bucket || process.env.S3_BUCKET || process.env.AWS_BUCKET;
1439
+ const check = () => {
1440
+ if (!bucket()) throw new Error("s3(): no bucket. Pass bucket, set S3_BUCKET or AWS_BUCKET, or set local for a directory.");
1441
+ };
1442
+ const open = () => {
1443
+ if (client) return client;
1444
+ check();
1445
+ const settings = { bucket: bucket() };
1446
+ for (const name of [
1447
+ "accessKeyId",
1448
+ "secretAccessKey",
1449
+ "sessionToken",
1450
+ "region",
1451
+ "endpoint"
1452
+ ]) {
1453
+ const value = options[name];
1454
+ if (value !== void 0) settings[name] = value instanceof SecretRef ? value.require() : value;
1455
+ }
1456
+ return client = new Bun.S3Client(settings);
1457
+ };
1458
+ const presign = (key, expiresInMs, contentDisposition) => open().presign(key, {
1459
+ method: "GET",
1460
+ expiresIn: Math.ceil(expiresInMs / 1e3),
1461
+ ...contentDisposition && { contentDisposition }
1462
+ });
1463
+ const rethrowWithoutUrl = async (operation, run) => {
1464
+ try {
1465
+ return await run();
1466
+ } catch (error) {
1467
+ const code = error.code;
1468
+ throw new Error(`File storage: S3 failed ${operation} a file${typeof code === "string" ? ` (${code})` : ""}`);
1469
+ }
1470
+ };
1471
+ return {
1472
+ kind: "file",
1473
+ prefix,
1474
+ check,
1475
+ write: async (key, file, contentType) => {
1476
+ const client = open();
1477
+ await rethrowWithoutUrl("writing", () => client.write(key, file, { type: contentType }));
1478
+ },
1479
+ read: async (key) => {
1480
+ const url = presign(key, 6e4);
1481
+ const stalled = new AbortController();
1482
+ let idle;
1483
+ const stillMoving = () => {
1484
+ clearTimeout(idle);
1485
+ idle = setTimeout(() => stalled.abort(), S3_READ_IDLE_TIMEOUT_MS);
1486
+ };
1487
+ stillMoving();
1488
+ try {
1489
+ const response = await rethrowWithoutUrl("reading", () => fetch(url, { signal: stalled.signal }));
1490
+ if (response.status === 404) return void 0;
1491
+ if (!response.ok) throw new Error(`File storage: S3 answered ${response.status} reading a file`);
1492
+ return await rethrowWithoutUrl("reading", async () => {
1493
+ const chunks = [];
1494
+ for await (const chunk of response.body ?? []) {
1495
+ stillMoving();
1496
+ chunks.push(chunk);
1497
+ }
1498
+ return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
1499
+ });
1500
+ } finally {
1501
+ clearTimeout(idle);
1502
+ }
1503
+ },
1504
+ remove: async (key) => {
1505
+ const client = open();
1506
+ await rethrowWithoutUrl("deleting", () => client.delete(key));
1507
+ },
1508
+ sign: async (key, expiresInMs, contentDisposition) => presign(key, expiresInMs, contentDisposition)
1509
+ };
1510
+ }
1511
+ const perProcessLinkKey = globalThis[Symbol.for("brickkit.storage.files.linkKey")] ??= randomBytes(32);
1512
+ const mac = (payload) => createHmac("sha256", perProcessLinkKey).update(payload).digest();
1513
+ function signFileLink(claims) {
1514
+ const payload = Buffer.from(JSON.stringify(claims)).toString("base64url");
1515
+ return `${payload}.${mac(payload).toString("base64url")}`;
1516
+ }
1517
+ function verifyFileLink(token) {
1518
+ const dot = token?.indexOf(".") ?? -1;
1519
+ if (!token || dot < 0) return void 0;
1520
+ const payload = token.slice(0, dot);
1521
+ const given = Buffer.from(token.slice(dot + 1), "base64url");
1522
+ const expected = mac(payload);
1523
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return void 0;
1524
+ try {
1525
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
1526
+ return typeof claims.expiresAt === "number" && claims.expiresAt > Date.now() ? claims : void 0;
1527
+ } catch {
1528
+ return;
1529
+ }
1530
+ }
1531
+ async function localPath(dir, key) {
1532
+ const folder = relative(dir, dirname(join(dir, key)));
1533
+ if (folder.split(sep).includes("..")) return void 0;
1534
+ try {
1535
+ const [root, real] = await Promise.all([realpath(dir), realpath(join(dir, folder))]);
1536
+ return real === join(root, folder) ? join(real, basename(key)) : void 0;
1537
+ } catch (error) {
1538
+ if (["ENOENT", "ENOTDIR"].includes(error.code)) return void 0;
1539
+ throw error;
1540
+ }
1541
+ }
1542
+ const isFile = (path) => lstat(path).then((stat) => stat.isFile(), (error) => {
1543
+ if (["ENOENT", "ENOTDIR"].includes(error.code)) return false;
1544
+ throw error;
1545
+ });
1546
+ async function readLocal(dir, key) {
1547
+ const path = await localPath(dir, key);
1548
+ if (!path || !await isFile(path) || !await isFile(`${path}.type`)) return void 0;
1549
+ const type = await readFile(`${path}.type`, "utf8");
1550
+ return new Blob([await readFile(path)], { type });
1551
+ }
1552
+ const outsideDir = () => /* @__PURE__ */ new Error("File storage: the file's folder is not inside the local directory; refusing to follow a symlink");
1553
+ function localDriver(dir, prefix) {
1554
+ return {
1555
+ kind: "file",
1556
+ prefix,
1557
+ local: dir,
1558
+ write: async (key, file, contentType) => {
1559
+ await mkdir(dirname(join(dir, key)), { recursive: true });
1560
+ const path = await localPath(dir, key);
1561
+ if (!path) throw outsideDir();
1562
+ await Bun.write(`${path}.type`, contentType);
1563
+ await Bun.write(path, file);
1564
+ },
1565
+ read: (key) => readLocal(dir, key),
1566
+ remove: async (key) => {
1567
+ const path = await localPath(dir, key);
1568
+ if (!path) return;
1569
+ await rm(path, { force: true });
1570
+ await rm(`${path}.type`, { force: true });
1571
+ },
1572
+ sign: async (key, expiresInMs, contentDisposition) => `${LOCAL_FILES_ROUTE}?token=${signFileLink({
1573
+ dirDigest: sha256(dir),
1574
+ key,
1575
+ expiresAt: Date.now() + expiresInMs,
1576
+ disposition: contentDisposition
1577
+ })}`
1578
+ };
1579
+ }
1580
+ function localFilesRoute(dirs) {
1581
+ const byDigest = new Map([...dirs].map((dir) => [sha256(dir), dir]));
1582
+ return async ({ request }) => {
1583
+ const claims = verifyFileLink(new URL(request.url).searchParams.get("token"));
1584
+ const dir = claims && byDigest.get(claims.dirDigest);
1585
+ if (!claims || !dir) return new Response("Invalid or expired link", { status: 403 });
1586
+ const file = await readLocal(dir, claims.key);
1587
+ if (!file) return new Response("Not found", { status: 404 });
1588
+ return new Response(file, { headers: {
1589
+ "content-type": file.type,
1590
+ "content-disposition": claims.disposition,
1591
+ "x-content-type-options": "nosniff",
1592
+ "cache-control": "private, no-store"
1593
+ } });
1594
+ };
1595
+ }
1596
+ // src/socket-redis.ts
1597
+ /** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */
1598
+ function reconnectDelay(failures) {
1599
+ const ceiling = Math.min(3e4, 500 * 2 ** failures);
1600
+ return ceiling / 2 + Math.random() * (ceiling / 2);
1601
+ }
1602
+ /** How long a call waits for Redis to connect before going on without it. */
1603
+ const REDIS_WAIT_MS = 1e3;
1604
+ /** One Redis connection that reconnects by itself and reports each fresh connection. */
1605
+ function connection(url, connected) {
1606
+ let redis;
1607
+ let timer;
1608
+ let closed = false;
1609
+ let failures = 0;
1610
+ let failure;
1611
+ const waiters = [];
1612
+ const lost = (client) => {
1613
+ if (redis !== client) return;
1614
+ redis = void 0;
1615
+ if (closed || timer) return;
1616
+ timer = setTimeout(() => {
1617
+ timer = void 0;
1618
+ start();
1619
+ }, reconnectDelay(failures++));
1620
+ timer.unref();
1621
+ };
1622
+ const start = () => {
1623
+ if (closed || redis || timer) return;
1624
+ const client = new Bun.RedisClient(url, {
1625
+ autoReconnect: false,
1626
+ enableOfflineQueue: false
1627
+ });
1628
+ redis = client;
1629
+ client.onclose = () => lost(client);
1630
+ client.connect().then(() => {
1631
+ if (redis !== client) return;
1632
+ failures = 0;
1633
+ failure = void 0;
1634
+ connected(client);
1635
+ for (const wake of waiters.splice(0)) wake();
1636
+ }, (error) => {
1637
+ failure = error;
1638
+ lost(client);
1639
+ });
1640
+ };
1641
+ return {
1642
+ get() {
1643
+ start();
1644
+ return redis?.connected ? redis : void 0;
1645
+ },
1646
+ failure: () => failure,
1647
+ /** Resolves after the next connection is made and announced, or after `ms`. */
1648
+ opened(ms) {
1649
+ if (redis?.connected) return Promise.resolve();
1650
+ start();
1651
+ return new Promise((resolve) => {
1652
+ const timeout = setTimeout(resolve, ms);
1653
+ waiters.push(() => {
1654
+ clearTimeout(timeout);
1655
+ resolve();
1656
+ });
1657
+ });
1658
+ },
1659
+ close() {
1660
+ closed = true;
1661
+ clearTimeout(timer);
1662
+ for (const wake of waiters.splice(0)) wake();
1663
+ const client = redis;
1664
+ redis = void 0;
1665
+ client?.close();
1666
+ }
1667
+ };
1668
+ }
1669
+ /**
1670
+ * Fans socket emits and kicks out across processes through Redis pub/sub, one
1671
+ * channel per room topic. An emit is a PUBLISH only: every process, the emitting
1672
+ * one included, delivers it once to its own connections. Uses Bun's built-in
1673
+ * Redis client and two connections, one to publish and one to subscribe.
1674
+ */
1675
+ function redisBroker(options = {}) {
1676
+ const limit = options.queue ?? 1e3;
1677
+ if (!Number.isInteger(limit) || limit < 0) throw new Error("redisBroker queue must be a nonnegative integer");
1678
+ const channel = (topic) => `brick:socket:${topic}`;
1679
+ const listeners = /* @__PURE__ */ new Map();
1680
+ const pending = /* @__PURE__ */ new Map();
1681
+ const stream = (topic) => `brick:socket:stream:${topic}`;
1682
+ const warned = /* @__PURE__ */ new Set();
1683
+ const warn = (what) => (error) => {
1684
+ if (warned.has(what)) return;
1685
+ warned.add(what);
1686
+ console.warn(`[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`, error);
1687
+ };
1688
+ const queue = [];
1689
+ const send = (work) => {
1690
+ const redis = publisher.get();
1691
+ if (redis) return work(redis);
1692
+ queue.push(work);
1693
+ if (queue.length > limit) queue.shift();
1694
+ };
1695
+ const receive = (payload, name) => {
1696
+ let message;
1697
+ try {
1698
+ message = JSON.parse(payload);
1699
+ } catch {
1700
+ return;
1701
+ }
1702
+ for (const deliver of listeners.get(name) ?? []) deliver(message);
1703
+ };
1704
+ const subscribe = (redis, name) => {
1705
+ const done = redis.subscribe(name, receive).catch(warn("SUBSCRIBE"));
1706
+ pending.set(name, done);
1707
+ done.then(() => {
1708
+ if (pending.get(name) === done) pending.delete(name);
1709
+ });
1710
+ };
1711
+ const publisher = connection(options.url, (redis) => {
1712
+ for (const work of queue.splice(0)) work(redis);
1713
+ });
1714
+ const subscriber = connection(options.url, (redis) => {
1715
+ for (const name of listeners.keys()) subscribe(redis, name);
1716
+ });
1717
+ return {
1718
+ publish(message, replay) {
1719
+ const name = channel(message.topic);
1720
+ if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(warn("PUBLISH")));
1721
+ const key = stream(message.topic);
1722
+ send((redis) => {
1723
+ redis.send("XADD", [
1724
+ key,
1725
+ "MAXLEN",
1726
+ "~",
1727
+ String(replay.keep),
1728
+ "*",
1729
+ "m",
1730
+ message.frame
1731
+ ]).then((seq) => {
1732
+ redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(warn("PEXPIRE"));
1733
+ return redis.publish(name, JSON.stringify({
1734
+ ...message,
1735
+ seq
1736
+ }));
1737
+ }).catch(warn("XADD/PUBLISH"));
1738
+ });
1739
+ },
1740
+ async head() {
1741
+ try {
1742
+ await publisher.opened(REDIS_WAIT_MS);
1743
+ const [seconds, micros] = await publisher.get().send("TIME", []);
1744
+ return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
1745
+ } catch {
1746
+ return `${Date.now() - 1}-0`;
1747
+ }
1748
+ },
1749
+ async history(topic, since, replay) {
1750
+ let raw;
1751
+ try {
1752
+ await publisher.opened(REDIS_WAIT_MS);
1753
+ raw = await publisher.get().send("XRANGE", [
1754
+ stream(topic),
1755
+ "-",
1756
+ "+"
1757
+ ]);
1758
+ } catch {
1759
+ return;
1760
+ }
1761
+ const ms = (seq) => Number(seq.split("-")[0]);
1762
+ const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);
1763
+ if (after.length === raw.length && (raw.length >= replay.keep || (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)) return void 0;
1764
+ return after.map(([seq, fields]) => ({
1765
+ type: "emit",
1766
+ topic,
1767
+ frame: fields[fields.indexOf("m") + 1],
1768
+ seq
1769
+ }));
1770
+ },
1771
+ subscribe(topic, deliver) {
1772
+ const name = channel(topic);
1773
+ let local = listeners.get(name);
1774
+ if (!local) {
1775
+ local = /* @__PURE__ */ new Set();
1776
+ listeners.set(name, local);
1777
+ const redis = subscriber.get();
1778
+ if (redis) subscribe(redis, name);
1779
+ }
1780
+ local.add(deliver);
1781
+ return () => {
1782
+ local.delete(deliver);
1783
+ if (local.size || listeners.get(name) !== local) return;
1784
+ listeners.delete(name);
1785
+ pending.delete(name);
1786
+ subscriber.get()?.unsubscribe(name).catch(warn("UNSUBSCRIBE"));
1787
+ };
1788
+ },
1789
+ async ready(topic) {
1790
+ const name = channel(topic);
1791
+ if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);
1792
+ await pending.get(name);
1793
+ },
1794
+ close() {
1795
+ publisher.close();
1796
+ subscriber.close();
1797
+ }
1798
+ };
1799
+ }
1800
+ // src/storage.ts
1801
+ /** A storage could not be reached, or did not answer in time. Thrown by every call while it is down. A write that rejects with it may still have been applied. */
1802
+ var StorageUnavailableError = class StorageUnavailableError extends Error {
1803
+ name = "StorageUnavailableError";
1804
+ static [Symbol.hasInstance](value) {
1805
+ if (this !== StorageUnavailableError) return Function.prototype[Symbol.hasInstance].call(this, value);
1806
+ return value instanceof Error && value.name === "StorageUnavailableError";
1807
+ }
1808
+ };
1809
+ const APP_PREFIX = "app:";
1810
+ const BRICK_PREFIX = "brick:storage:";
1811
+ /** The framework side of each storage handle; global so a second core copy finds it. */
1812
+ const frameworkSides = globalThis[Symbol.for("brickkit.storage")] ??= /* @__PURE__ */ new WeakMap();
1813
+ const users = globalThis[Symbol.for("brickkit.storage.users")] ??= /* @__PURE__ */ new WeakMap();
1814
+ function notACounter(key) {
1815
+ return /* @__PURE__ */ new Error(`Storage: "${key}" does not hold a counter`);
1816
+ }
1817
+ function counterOverflow(key) {
1818
+ return /* @__PURE__ */ new Error(`Storage: incrementing "${key}" would overflow`);
1819
+ }
1820
+ function ttl(ttlMs, required) {
1821
+ if (ttlMs === void 0 && !required) return;
1822
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) throw new Error(`Storage ttlMs must be a positive integer, got ${ttlMs}`);
1823
+ }
1824
+ function storageKey(feature, parts) {
1825
+ return `${feature}:${JSON.stringify(parts.map((part) => typeof part === "string" && part.length > 128 ? { sha256: createHash("sha256").update(part).digest("hex") } : part))}`;
1826
+ }
1827
+ function side(driver, prefix) {
1828
+ return Object.freeze({
1829
+ kind: "key-value",
1830
+ get: async (key) => driver.get(prefix + key),
1831
+ put: async (key, value, ttlMs) => {
1832
+ ttl(ttlMs, false);
1833
+ return driver.put(prefix + key, value, ttlMs);
1834
+ },
1835
+ putIfAbsent: async (key, value, ttlMs) => {
1836
+ ttl(ttlMs, true);
1837
+ return driver.putIfAbsent(prefix + key, value, ttlMs);
1838
+ },
1839
+ increment: async (key, ttlMs) => {
1840
+ ttl(ttlMs, true);
1841
+ return driver.increment(prefix + key, ttlMs);
1842
+ },
1843
+ delete: async (key) => driver.delete(prefix + key),
1844
+ close: async () => driver.close()
1845
+ });
1846
+ }
1847
+ /**
1848
+ * Declare a storage. The driver decides its kind: `redis()` and `memory()` make
1849
+ * key-value storage, `s3()` file storage kept per tenant. Pass it to a service
1850
+ * as a dep, and read it as `ctx.deps.<name>`. Nothing connects until the first call.
1851
+ *
1852
+ * @param options - `driver`: `redis({ url })`, or `memory()` for tests and local
1853
+ * development; `s3({ bucket, prefix, local })` for files.
1854
+ * @returns The handle. Key-value: `get`, `put`, `putIfAbsent`, `increment`,
1855
+ * `delete` and `close`. File: `put`, `url`, `get`, `delete` in the caller's
1856
+ * tenant, and `in(tenant)` outside a request.
1857
+ * @example
1858
+ * export const cache = defineStorage({ driver: redis({ url: process.env.REDIS_URL }) });
1859
+ * export const auth = defineService("auth", { deps: { cache } });
1860
+ * // in an action
1861
+ * await ctx.deps.cache.put(`otp:${input.email}`, code, 5 * 60_000);
1862
+ */
1863
+ function defineStorage(options) {
1864
+ const driver = options?.driver;
1865
+ if (driver?.kind === "file") return fileStorage(driver);
1866
+ if (driver?.kind !== "key-value") throw new Error("defineStorage needs a driver, such as redis(), memory() or s3()");
1867
+ const handle = side(driver, APP_PREFIX);
1868
+ frameworkSides.set(handle, Object.freeze({
1869
+ ...side(driver, BRICK_PREFIX),
1870
+ compareAndDelete: async (key, expected) => driver.compareAndDelete(BRICK_PREFIX + key, expected)
1871
+ }));
1872
+ return handle;
1873
+ }
1874
+ function serviceStorage(service, deps = portOf(service).deps) {
1875
+ const found = Object.entries(deps).filter(([, value], index, all) => frameworkSides.has(value) && all.findIndex(([, other]) => other === value) === index);
1876
+ if (found.length > 1) throw new Error(`Service "${service.name}" has two key-value storages in its deps, "${found[0][0]}" and "${found[1][0]}"; Brick needs one for its own keys. Keep one of them on this service.`);
1877
+ return found[0] && frameworkSides.get(found[0][1]);
1878
+ }
1879
+ function useStorages(deps) {
1880
+ const handles = new Set(deps.flatMap((values) => Object.values(values).filter((value) => frameworkSides.has(value))));
1881
+ for (const handle of handles) users.set(handle, (users.get(handle) ?? 0) + 1);
1882
+ let released = false;
1883
+ return async () => {
1884
+ if (released) return;
1885
+ released = true;
1886
+ const unused = [...handles].filter((handle) => {
1887
+ const left = users.get(handle) - 1;
1888
+ users.set(handle, left);
1889
+ return left === 0;
1890
+ });
1891
+ await Promise.all(unused.map((handle) => handle.close()));
1892
+ };
1893
+ }
1894
+ const NOT_A_COUNTER = "BRICK_NOT_A_COUNTER";
1895
+ const INCREMENT = `local n = redis.pcall('INCR', KEYS[1])
1896
+ if type(n) == 'table' and n.err then
1897
+ if string.find(n.err, '^WRONGTYPE') or string.find(n.err, 'not an integer') then return redis.error_reply('${NOT_A_COUNTER}') end
1898
+ return n
1899
+ end
1900
+ local t = redis.call('PTTL', KEYS[1])
1901
+ if t < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) t = tonumber(ARGV[1]) end
1902
+ return {n, t}`;
1903
+ const PUT_IF_ABSENT = `if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2]) then return {1, ARGV[1]} end
1904
+ return {0, redis.call('GET', KEYS[1])}`;
1905
+ const COMPARE_AND_DELETE = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
1906
+ return 0`;
1907
+ const TIMED_OUT = Symbol("timed out");
1908
+ const UNAVAILABLE_REPLY = /^(LOADING|READONLY|OOM|BUSY|MASTERDOWN|CLUSTERDOWN|NOREPLICAS|MISCONF|TRYAGAIN)\b/;
1909
+ /**
1910
+ * Key-value storage in Redis, through Bun's built-in client. Connects on first
1911
+ * use and reconnects by itself. While Redis is unreachable, calls reject with
1912
+ * `StorageUnavailableError`: the first after about a second, the rest at once.
1913
+ * A command Redis doesn't answer within a second rejects the same way, and the
1914
+ * connection is dropped so the next call opens a fresh one.
1915
+ *
1916
+ * @param options - `url`: defaults to `REDIS_URL`, then `redis://localhost:6379`.
1917
+ * `prefix`: put in front of every key, to share one Redis database between apps.
1918
+ */
1919
+ function redis(options = {}) {
1920
+ const prefix = options.prefix ?? "";
1921
+ let conn;
1922
+ let down = false;
1923
+ const send = async (command, args) => {
1924
+ const current = conn ??= connection(options.url, () => {
1925
+ down = false;
1926
+ });
1927
+ if (!down) await current.opened(REDIS_WAIT_MS);
1928
+ const closedMeanwhile = () => conn !== current;
1929
+ const client = current.get();
1930
+ if (!client) {
1931
+ if (!closedMeanwhile()) down = true;
1932
+ throw new StorageUnavailableError("Storage: Redis is unreachable", { cause: current.failure() });
1933
+ }
1934
+ let timer;
1935
+ try {
1936
+ return await Promise.race([client.send(command, args), new Promise((_, reject) => {
1937
+ timer = setTimeout(reject, REDIS_WAIT_MS, TIMED_OUT);
1938
+ })]);
1939
+ } catch (error) {
1940
+ if (error === TIMED_OUT) {
1941
+ if (!closedMeanwhile()) {
1942
+ conn = void 0;
1943
+ down = false;
1944
+ }
1945
+ current.close();
1946
+ throw new StorageUnavailableError(`Storage: Redis did not answer within ${REDIS_WAIT_MS} ms`);
1947
+ }
1948
+ if (client.connected) {
1949
+ if (UNAVAILABLE_REPLY.test(String(error?.message))) throw new StorageUnavailableError(`Storage: Redis cannot serve the command right now (${error.message})`, { cause: error });
1950
+ throw error;
1951
+ }
1952
+ throw new StorageUnavailableError("Storage: the Redis connection was lost", { cause: error });
1953
+ } finally {
1954
+ clearTimeout(timer);
1955
+ }
1956
+ };
1957
+ return {
1958
+ kind: "key-value",
1959
+ get: (key) => send("GET", [prefix + key]),
1960
+ put: async (key, value, ttlMs) => {
1961
+ const args = [prefix + key, value];
1962
+ await send("SET", ttlMs === void 0 ? args : [
1963
+ ...args,
1964
+ "PX",
1965
+ String(ttlMs)
1966
+ ]);
1967
+ },
1968
+ putIfAbsent: async (key, value, ttlMs) => {
1969
+ const [stored, now] = await send("EVAL", [
1970
+ PUT_IF_ABSENT,
1971
+ "1",
1972
+ prefix + key,
1973
+ value,
1974
+ String(ttlMs)
1975
+ ]);
1976
+ return {
1977
+ stored: stored === 1,
1978
+ value: now
1979
+ };
1980
+ },
1981
+ increment: async (key, ttlMs) => {
1982
+ const [count, expiresInMs] = await send("EVAL", [
1983
+ INCREMENT,
1984
+ "1",
1985
+ prefix + key,
1986
+ String(ttlMs)
1987
+ ]).catch((error) => {
1988
+ throw String(error?.message).includes(NOT_A_COUNTER) ? notACounter(key) : error;
1989
+ });
1990
+ return {
1991
+ count: Number(count),
1992
+ expiresInMs: Math.max(1, Number(expiresInMs))
1993
+ };
1994
+ },
1995
+ delete: async (key) => {
1996
+ await send("DEL", [prefix + key]);
1997
+ },
1998
+ compareAndDelete: async (key, expected) => await send("EVAL", [
1999
+ COMPARE_AND_DELETE,
2000
+ "1",
2001
+ prefix + key,
2002
+ expected
2003
+ ]) === 1,
2004
+ close: async () => {
2005
+ conn?.close();
2006
+ conn = void 0;
2007
+ down = false;
2008
+ }
2009
+ };
2010
+ }
2011
+ /**
2012
+ * Key-value storage in this process's memory, for tests and local development.
2013
+ * Lost on restart and not shared between processes.
2014
+ */
2015
+ function memory() {
2016
+ const entries = /* @__PURE__ */ new Map();
2017
+ const readEvictingExpired = (key) => {
2018
+ const entry = entries.get(key);
2019
+ if (entry?.expiresAt !== void 0 && entry.expiresAt <= Date.now()) {
2020
+ entries.delete(key);
2021
+ return;
2022
+ }
2023
+ return entry;
2024
+ };
2025
+ const expiry = (ttlMs) => ttlMs === void 0 ? void 0 : Date.now() + ttlMs;
2026
+ return {
2027
+ kind: "key-value",
2028
+ get: async (key) => readEvictingExpired(key)?.value ?? null,
2029
+ put: async (key, value, ttlMs) => {
2030
+ entries.set(key, {
2031
+ value,
2032
+ expiresAt: expiry(ttlMs)
2033
+ });
2034
+ },
2035
+ putIfAbsent: async (key, value, ttlMs) => {
2036
+ const entry = readEvictingExpired(key);
2037
+ if (entry) return {
2038
+ stored: false,
2039
+ value: entry.value
2040
+ };
2041
+ entries.set(key, {
2042
+ value,
2043
+ expiresAt: expiry(ttlMs)
2044
+ });
2045
+ return {
2046
+ stored: true,
2047
+ value
2048
+ };
2049
+ },
2050
+ increment: async (key, ttlMs) => {
2051
+ const entry = readEvictingExpired(key) ?? { value: "0" };
2052
+ const count = Number(entry.value) + 1;
2053
+ if (!/^(0|-?[1-9][0-9]*)$/.test(entry.value)) throw notACounter(key);
2054
+ if (!Number.isSafeInteger(count)) throw counterOverflow(key);
2055
+ const expiresAt = entry.expiresAt ?? Date.now() + ttlMs;
2056
+ entries.set(key, {
2057
+ value: String(count),
2058
+ expiresAt
2059
+ });
2060
+ return {
2061
+ count,
2062
+ expiresInMs: Math.max(1, expiresAt - Date.now())
2063
+ };
2064
+ },
2065
+ delete: async (key) => {
2066
+ entries.delete(key);
2067
+ },
2068
+ compareAndDelete: async (key, expected) => readEvictingExpired(key)?.value === expected && entries.delete(key),
2069
+ close: async () => {}
2070
+ };
2071
+ }
2072
+ // src/rate-limit.ts
2073
+ const SOURCE = Symbol.for("brickkit.addressSource");
2074
+ const CLIENT_REQUEST = Symbol.for("brickkit.clientRequest");
2075
+ function markAddressSource(request, source) {
2076
+ request[SOURCE] = source;
2077
+ }
2078
+ function withClientIp(request, clientIp) {
2079
+ const app = request[SOURCE];
2080
+ markAddressSource(request, {
2081
+ clientIp,
2082
+ server: app?.server ?? noServer
2083
+ });
2084
+ }
2085
+ const noServer = () => void 0;
2086
+ function clientRequestOf(ctx) {
2087
+ const request = ctx[CLIENT_REQUEST] ?? ctx.request;
2088
+ return request?.[SOURCE] ? request : void 0;
2089
+ }
2090
+ function carryClientRequest(envelope, from) {
2091
+ const request = clientRequestOf(from);
2092
+ if (request) envelope[CLIENT_REQUEST] = request;
2093
+ }
2094
+ /**
2095
+ * The client address of a call as rate limits count it, or `undefined` when it
2096
+ * has none: in-process without a request, or `app.handle` without `clientIp`.
2097
+ * An IPv4-mapped or NAT64 IPv6 address counts as its IPv4 address, any other
2098
+ * IPv6 address by its /64, and every spelling of one address the same. For a
2099
+ * custom `per` that combines it with another key.
2100
+ *
2101
+ * @throws When `clientIp` returns anything but a non-empty string or `undefined`.
2102
+ */
2103
+ function clientAddress(ctx) {
2104
+ const request = clientRequestOf(ctx);
2105
+ if (!request) return void 0;
2106
+ const source = request[SOURCE];
2107
+ const peer = source.server()?.requestIP(request)?.address ?? void 0;
2108
+ const ip = source.clientIp ? source.clientIp({
2109
+ request,
2110
+ peer
2111
+ }) : peer;
2112
+ if (ip !== void 0 && (typeof ip !== "string" || ip === "")) throw new Error(`clientIp must return a non-empty string, or undefined when there is no address; it returned ${ip === "" ? "an empty string" : ip instanceof Promise ? "a promise (it must not be async)" : String(ip)}`);
2113
+ return ip === void 0 ? void 0 : addressKey(ip);
2114
+ }
2115
+ function addressKey(address) {
2116
+ const ip = address.trim().toLowerCase().replace(/%.*$/, "");
2117
+ if (isIPv4(ip)) return ip;
2118
+ if (!isIPv6(ip)) return address;
2119
+ const [head = "", tail] = ip.split("::");
2120
+ const split = (part) => part ? part.split(":") : [];
2121
+ const left = split(head);
2122
+ const right = split(tail);
2123
+ const groups = (part) => part.flatMap((group) => {
2124
+ if (!group.includes(".")) return [parseInt(group, 16)];
2125
+ const [a, b, c, d] = group.split(".").map(Number);
2126
+ return [a << 8 | b, c << 8 | d];
2127
+ });
2128
+ const l = groups(left);
2129
+ const r = groups(right);
2130
+ const all = [
2131
+ ...l,
2132
+ ...Array(8 - l.length - r.length).fill(0),
2133
+ ...r
2134
+ ];
2135
+ const head6 = all.slice(0, 6).join(":");
2136
+ if (head6 === "0:0:0:0:0:65535" || head6 === "100:65435:0:0:0:0") return [
2137
+ all[6] >> 8,
2138
+ all[6] & 255,
2139
+ all[7] >> 8,
2140
+ all[7] & 255
2141
+ ].join(".");
2142
+ return `${all.slice(0, 4).map((g) => g.toString(16)).join(":")}::/64`;
2143
+ }
2144
+ function rateLimitsOf(config) {
2145
+ const { rateLimit } = config;
2146
+ if (rateLimit === void 0) return void 0;
2147
+ const limits = Array.isArray(rateLimit) ? rateLimit : [rateLimit];
2148
+ if (!limits.length) throw new Error(`Action '${config.name}': rateLimit is an empty list, which limits nothing. Give it at least one limit, or remove it.`);
2149
+ for (const { per, max, windowMs } of limits) if (!(per === "actor" || per === "ip" || typeof per === "function") || !Number.isSafeInteger(max) || max < 1 || !Number.isSafeInteger(windowMs) || windowMs < 1) throw new Error(`Action '${config.name}': each rateLimit needs per ("actor", "ip" or a function) and max and windowMs as positive integers`);
2150
+ return limits;
2151
+ }
2152
+ function checkRateLimits(service, action, deps) {
2153
+ const limits = rateLimitsOf(action.config);
2154
+ if (!limits) return;
2155
+ if (!storageOf(service, deps)) throw noStorage(service, action.name);
2156
+ if (limits.some((limit) => limit.per === "actor") && !hasIdentity(service)) throw new Error(`Service "${service.name}": action '${action.name}' limits per "actor", but the service declares no identity. Add identity: (ctx) => ctx.user && { id: ctx.user.id } to defineService("${service.name}", { ... }).`);
2157
+ }
2158
+ function storageOf(service, deps) {
2159
+ return serviceStorage(service, deps) ?? serviceStorage(service);
2160
+ }
2161
+ function noStorage(service, action) {
2162
+ return /* @__PURE__ */ new Error(`Service "${service.name}": action '${action}' declares rateLimit, but the service has no key-value storage to count in. Add one: defineService("${service.name}", { deps: { cache: defineStorage({ driver: redis() }) } }).`);
2163
+ }
2164
+ const QUIET_MS = 1e4;
2165
+ const PROBE_MS = 1e3;
2166
+ const SWEEP_MS = 1e3;
2167
+ const fallbacks = /* @__PURE__ */ new WeakMap();
2168
+ function countInMemory(fallback, key, windowMs, now) {
2169
+ if (now >= fallback.sweepAt) sweep(fallback, now);
2170
+ let entry = fallback.counters.get(key);
2171
+ if (!entry || entry.expiresAt <= now) fallback.counters.set(key, entry = {
2172
+ count: 0,
2173
+ expiresAt: now + windowMs
2174
+ });
2175
+ entry.count++;
2176
+ return {
2177
+ count: entry.count,
2178
+ expiresInMs: Math.max(1, entry.expiresAt - now)
2179
+ };
2180
+ }
2181
+ function sweep(fallback, now) {
2182
+ for (const [key, entry] of fallback.counters) if (entry.expiresAt <= now) fallback.counters.delete(key);
2183
+ fallback.sweepAt = now + SWEEP_MS;
2184
+ }
2185
+ const isTimeToProbe = (fallback, now) => now >= fallback.probeAt;
2186
+ const hasBeenHealthyLongEnough = (fallback, now) => fallback.healthySince !== void 0 && now - fallback.healthySince >= QUIET_MS;
2187
+ function enterFallback(fallback, now, cause) {
2188
+ Object.assign(fallback, {
2189
+ active: true,
2190
+ probeAt: now + PROBE_MS,
2191
+ healthySince: void 0
2192
+ });
2193
+ console.warn(`[Brick-TS] Rate limits: storage is unavailable (${cause.message}); counting in this process's memory until it is back.`);
2194
+ }
2195
+ function leaveFallback(fallback) {
2196
+ fallback.active = false;
2197
+ console.warn("[Brick-TS] Rate limits: storage is back; counting there again.");
2198
+ }
2199
+ function probe(storage, fallback, key, windowMs) {
2200
+ const answered = () => {
2201
+ const now = Date.now();
2202
+ fallback.healthySince ??= now;
2203
+ if (fallback.active && hasBeenHealthyLongEnough(fallback, now)) leaveFallback(fallback);
2204
+ };
2205
+ storage.increment(key, windowMs).then(answered, (error) => {
2206
+ if (error instanceof StorageUnavailableError) fallback.healthySince = void 0;
2207
+ else answered();
2208
+ });
2209
+ }
2210
+ async function increment(storage, key, windowMs) {
2211
+ let fallback = fallbacks.get(storage);
2212
+ if (fallback) {
2213
+ const now = Date.now();
2214
+ if (fallback.active) {
2215
+ if (isTimeToProbe(fallback, now)) {
2216
+ fallback.probeAt = now + PROBE_MS;
2217
+ probe(storage, fallback, key, windowMs);
2218
+ }
2219
+ return countInMemory(fallback, key, windowMs, now);
2220
+ }
2221
+ if (now >= fallback.sweepAt) {
2222
+ sweep(fallback, now);
2223
+ if (!fallback.counters.size) fallbacks.delete(storage);
2224
+ }
2225
+ }
2226
+ try {
2227
+ return await storage.increment(key, windowMs);
2228
+ } catch (error) {
2229
+ if (!(error instanceof StorageUnavailableError)) throw error;
2230
+ const now = Date.now();
2231
+ fallback = fallbacks.get(storage);
2232
+ if (!fallback) fallbacks.set(storage, fallback = {
2233
+ active: false,
2234
+ counters: /* @__PURE__ */ new Map(),
2235
+ probeAt: 0,
2236
+ sweepAt: now + SWEEP_MS
2237
+ });
2238
+ if (!fallback.active) enterFallback(fallback, now, error);
2239
+ return countInMemory(fallback, key, windowMs, now);
2240
+ }
2241
+ }
2242
+ async function keyOf(limit, input, ctx) {
2243
+ if (typeof limit.per === "function") {
2244
+ const key = limit.per({
2245
+ input,
2246
+ ctx
2247
+ });
2248
+ if (typeof key?.then === "function") {
2249
+ Promise.resolve(key).catch(() => {});
2250
+ throw new Error("rateLimit per must return a string, null or undefined; it returned a promise (it must not be async)");
2251
+ }
2252
+ return key == null ? void 0 : ["key", String(key)];
2253
+ }
2254
+ if (limit.per === "actor") {
2255
+ const identity = await identityOf(ctx);
2256
+ if (identity) return ["actor", identity.id];
2257
+ }
2258
+ const ip = clientAddress(ctx);
2259
+ return ip === void 0 ? void 0 : ["ip", ip];
2260
+ }
2261
+ async function enforceRateLimits(service, kind, action, limits, input, ctx) {
2262
+ if (!service) throw new Error(`Action '${action}' declares rateLimit, but it is not registered on a service`);
2263
+ const storage = storageOf(service, ctx.deps);
2264
+ if (!storage) throw noStorage(service, action);
2265
+ for (const [index, limit] of limits.entries()) {
2266
+ const key = await keyOf(limit, input, ctx);
2267
+ if (!key) continue;
2268
+ const { count, expiresInMs } = await increment(storage, storageKey("rate-limit", [
2269
+ service.name,
2270
+ kind,
2271
+ action,
2272
+ index,
2273
+ ...key
2274
+ ]), limit.windowMs);
2275
+ if (count > limit.max) {
2276
+ const retryAfterSeconds = Math.max(1, Math.ceil(expiresInMs / 1e3));
2277
+ throw new ActionExecutionError("RATE_LIMITED", `Too many calls to '${action}'; retry in ${retryAfterSeconds} s`, 429, { retryAfterSeconds });
2278
+ }
2279
+ }
2280
+ }
2281
+ // src/context.ts
2282
+ const DEFAULT_REQUEST = new Request("http://localhost");
2283
+ const EMPTY = Object.freeze({});
2284
+ const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
2285
+ /** Random, so ids never repeat across restarts or processes. */
2286
+ const newId = (kind) => `${kind}_${crypto.randomUUID()}`;
2287
+ /**
2288
+ * The trace and request ids of an HTTP request: the caller's `x-trace-id` and
2289
+ * `x-request-id` headers, else fresh ones. Both are echoed on the response.
2290
+ */
2291
+ function requestIds(headers, set) {
2292
+ const traceId = headers?.["x-trace-id"] || newId("tr");
2293
+ const requestId = headers?.["x-request-id"] || newId("req");
2294
+ if (set?.headers) {
2295
+ set.headers["x-trace-id"] = traceId;
2296
+ set.headers["x-request-id"] = requestId;
2297
+ }
2298
+ return {
2299
+ traceId,
2300
+ requestId
2301
+ };
2302
+ }
2303
+ /**
2304
+ * The framework fields of an action context: what the caller gave, the rest
2305
+ * defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.
2306
+ */
2307
+ function baseContext(fields) {
2308
+ return {
2309
+ request: fields.request ?? DEFAULT_REQUEST,
2310
+ db: fields.db,
2311
+ logger: fields.logger ?? defaultLogger,
2312
+ traceId: fields.traceId ?? newId("tr"),
2313
+ requestId: fields.requestId ?? newId("req"),
2314
+ services: fields.services ?? EMPTY,
2315
+ metadata: fields.metadata ?? EMPTY,
2316
+ deps: fields.deps ?? EMPTY,
2317
+ dashboard: fields.dashboard ?? dashboardIdentity(fields.request)
2318
+ };
2319
+ }
2320
+ function pickContextEnvelope(context) {
2321
+ if (!context) return {};
2322
+ const envelope = {};
2323
+ if (context.caller !== void 0) envelope.caller = context.caller;
2324
+ if (context.user !== void 0) envelope.user = context.user;
2325
+ if (context.traceId !== void 0) envelope.traceId = context.traceId;
2326
+ if (context.requestId !== void 0) envelope.requestId = context.requestId;
2327
+ if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
2328
+ if (context.dashboard !== void 0) envelope.dashboard = context.dashboard;
2329
+ carryClientRequest(envelope, context);
2330
+ return envelope;
2331
+ }
2332
+ const RESOLVED = Symbol("resolved");
2333
+ const OWN_DEPS = Symbol("ownDeps");
2334
+ function markResolved(ctx, service, ownDeps) {
2335
+ const marked = ctx;
2336
+ marked[RESOLVED] = service;
2337
+ marked[OWN_DEPS] = ownDeps;
2338
+ attachIdentity(marked, service, ownDeps);
2339
+ }
2340
+ function resolvedDeps(ctx, service) {
2341
+ const marked = ctx;
2342
+ return marked?.[RESOLVED] === service ? marked[OWN_DEPS] : void 0;
2343
+ }
2344
+ function serviceOf(ctx) {
2345
+ return ctx[RESOLVED];
2346
+ }
2347
+ // src/webhook.ts
2348
+ const DEFAULT_MAX_BODY_BYTES = 1048576;
2349
+ function webhookOf(action) {
2350
+ return action ? actionMeta(action).webhook : void 0;
2351
+ }
2352
+ /** Whether an action was declared with `service.webhook`. */
2353
+ function isWebhook(action) {
2354
+ return webhookOf(action) !== void 0;
2355
+ }
2356
+ function defineWebhookMeta(service, config) {
2357
+ const where = `Service "${service}": webhook '${config?.name}'`;
2358
+ if (typeof config?.verify !== "function") throw new Error(`${where} needs verify: a verifier such as hmacSignature({ secret, header }), standardWebhooks({ secret }) or twilioSignature({ authToken, url }), or your own (request) => boolean. A webhook cannot run without one.`);
2359
+ if (!config.input || typeof config.input !== "object") throw new Error(`${where} needs input: the schema of the payload, such as t.Object({ ... }).`);
2360
+ if (config.method !== void 0 && !["POST", "GET"].includes(config.method)) throw new Error(`${where}: method must be "POST" or "GET".`);
2361
+ if (config.method === "GET" && config.verify.signsBody) throw new Error(`${where}: method "GET" has no body, and this verifier signs the body, so it would accept one signature for every query. Use twilioSignature (it signs the URL) or a verifier of your own, or method "POST".`);
2362
+ for (const option of ["authorize", "output"]) if (config[option] !== void 0) throw new Error(`${where}: ${option} is not an option of a webhook, and would be ignored. verify is the check.`);
2363
+ const { maxBodyBytes = DEFAULT_MAX_BODY_BYTES, replay } = config;
2364
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) throw new Error(`${where}: maxBodyBytes must be a positive integer.`);
2365
+ const ttlMs = replay === false ? void 0 : replay?.ttlMs ?? 6048e5;
2366
+ if (ttlMs !== void 0 && (!Number.isSafeInteger(ttlMs) || ttlMs < 1)) throw new Error(`${where}: replay.ttlMs must be a positive integer.`);
2367
+ return {
2368
+ verify: config.verify,
2369
+ eventId: config.eventId,
2370
+ replay: ttlMs === void 0 ? false : { ttlMs },
2371
+ maxBodyBytes
2372
+ };
2373
+ }
2374
+ function checkWebhook(service, action, deps) {
2375
+ const webhook = webhookOf(action);
2376
+ if (!webhook) return;
2377
+ checkRateLimits(service, action, deps);
2378
+ if (webhook.replay === false) return;
2379
+ const where = `Service "${service.name}": webhook '${action.name}'`;
2380
+ if (!webhook.eventId && !webhook.verify.suppliesEventId) throw new Error(`${where} has no event id to tell deliveries apart by, so a delivery sent twice would run twice. Add eventId: ({ input }) => input.id, reading an id from a field of the signed payload (an id from a header the signature does not cover only removes accidental duplicates: anyone who captured a delivery can resend it with another id), use a verifier that supplies one (standardWebhooks), or set replay: false to run every delivery.`);
2381
+ if (!serviceStorage(service)) throw new Error(`${where} remembers the events it has handled, but the service has no key-value storage. Add one: defineService("${service.name}", { deps: { cache: defineStorage({ driver: redis() }) } }), or set replay: false.`);
2382
+ }
2383
+ // src/events/transaction.ts
2384
+ const sqliteQueues = /* @__PURE__ */ new WeakMap();
2385
+ const active = new AsyncLocalStorage();
2386
+ function joined(db) {
2387
+ const open = active.getStore();
2388
+ return open?.open && open.handles.has(db) ? open : void 0;
2389
+ }
2390
+ function isSqliteDatabase(db) {
2391
+ return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
2392
+ }
2393
+ function rollbackQuietly(db, statement = "ROLLBACK") {
2394
+ try {
2395
+ db.$client.run(statement);
2396
+ } catch {
2397
+ return;
2398
+ }
2399
+ }
2400
+ async function nested(db, open, fn) {
2401
+ const commits = open.commits.length;
2402
+ try {
2403
+ if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
2404
+ open.handles.add(tx);
2405
+ return fn(tx);
2406
+ });
2407
+ const name = `brick_${++open.savepoints}`;
2408
+ db.$client.run(`SAVEPOINT ${name}`);
2409
+ try {
2410
+ const result = await fn(db);
2411
+ db.$client.run(`RELEASE ${name}`);
2412
+ return result;
2413
+ } catch (error) {
2414
+ rollbackQuietly(db, `ROLLBACK TO ${name}`);
2415
+ rollbackQuietly(db, `RELEASE ${name}`);
2416
+ throw error;
2417
+ }
2418
+ } catch (error) {
2419
+ open.commits.length = commits;
2420
+ throw error;
2421
+ }
2422
+ }
2423
+ /**
2424
+ * Run `fn` in a database transaction: everything it writes through the `tx` it is
2425
+ * given is committed together when it returns, or undone if it throws.
2426
+ *
2427
+ * Postgres uses a real transaction on one connection. SQLite has one connection
2428
+ * and a synchronous driver, which Drizzle's own `transaction` cannot use with an
2429
+ * async callback (it would commit before the callback finished). So transactions
2430
+ * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
2431
+ * A write made elsewhere in the process during that time, outside this helper,
2432
+ * would join the transaction; use Postgres where that matters.
2433
+ *
2434
+ * A call made inside `fn` with the `tx` it was given (on SQLite, the database
2435
+ * itself) joins the open transaction as a savepoint instead of waiting for it: a
2436
+ * nested failure undoes only the nested work, and the outer transaction decides
2437
+ * the commit. Nested calls must run one at a time.
2438
+ *
2439
+ * @param db - A Drizzle database, from `service.getDb()`.
2440
+ * @param fn - Receives the transaction handle to run queries on.
2441
+ * @returns What `fn` returned.
2442
+ * @throws What `fn` threw, after rolling back.
2443
+ */
2444
+ async function runInTransaction(db, fn) {
2445
+ const outer = joined(db);
2446
+ if (outer) return nested(db, outer, fn);
2447
+ const open = {
2448
+ handles: /* @__PURE__ */ new Set(),
2449
+ commits: [],
2450
+ open: true,
2451
+ savepoints: 0
2452
+ };
2453
+ let result;
2454
+ try {
2455
+ result = await active.run(open, () => begin(db, open, fn));
2456
+ } finally {
2457
+ open.open = false;
2458
+ }
2459
+ for (const commit of open.commits) await commit();
2460
+ return result;
2461
+ }
2462
+ async function begin(db, open, fn) {
2463
+ if (!isSqliteDatabase(db)) return db.transaction((tx) => {
2464
+ open.handles.add(tx);
2465
+ return fn(tx);
2466
+ });
2467
+ open.handles.add(db);
2468
+ const previous = sqliteQueues.get(db) ?? Promise.resolve();
2469
+ let release;
2470
+ const turn = new Promise((resolve) => {
2471
+ release = resolve;
2472
+ });
2473
+ sqliteQueues.set(db, previous.then(() => turn));
2474
+ await previous;
2475
+ try {
2476
+ db.$client.run("BEGIN IMMEDIATE");
2477
+ try {
2478
+ const result = await fn(db);
2479
+ db.$client.run("COMMIT");
2480
+ return result;
2481
+ } catch (error) {
2482
+ rollbackQuietly(db);
2483
+ throw error;
2484
+ }
2485
+ } finally {
2486
+ release();
2487
+ }
2488
+ }
2489
+ /** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
2490
+ function inTransaction(db) {
2491
+ return joined(db) !== void 0;
2492
+ }
2493
+ /**
2494
+ * Run `fn` once the transaction that `db` belongs to has committed, or now when
2495
+ * `db` is not in one opened by `runInTransaction`. It never runs when that
2496
+ * transaction, or the savepoint it was queued in, rolls back. An error it throws
2497
+ * reaches the caller of the outermost `runInTransaction`, after the commit.
2498
+ *
2499
+ * @param db - The handle the work ran on: a `tx`, or a database.
2500
+ * @param fn - The side effect, such as clearing a cache.
2501
+ */
2502
+ async function onTransactionCommit(db, fn) {
2503
+ const open = joined(db);
2504
+ if (open) open.commits.push(fn);
2505
+ else await fn();
2506
+ }
2507
+ // src/audit.ts
2508
+ const AUDIT = Symbol.for("brick.audit");
2509
+ function sqliteAudit(name) {
2510
+ return sqliteTable(name, {
2511
+ seq: integer$1("seq").primaryKey({ autoIncrement: true }),
2512
+ id: text$1("id").notNull().unique(),
2513
+ at: integer$1("at", { mode: "timestamp_ms" }).notNull(),
2514
+ service: text$1("service").notNull(),
2515
+ action: text$1("action").notNull(),
2516
+ resource: text$1("resource"),
2517
+ recordId: text$1("record_id"),
2518
+ actorId: text$1("actor_id"),
2519
+ actorLabel: text$1("actor_label"),
2520
+ tenant: text$1("tenant"),
2521
+ traceId: text$1("trace_id"),
2522
+ requestId: text$1("request_id"),
2523
+ meta: text$1("meta", { mode: "json" })
2524
+ });
2525
+ }
2526
+ function postgresAudit(name) {
2527
+ return pgTable(name, {
2528
+ seq: bigserial("seq", { mode: "number" }).primaryKey(),
2529
+ id: text("id").notNull().unique(),
2530
+ at: timestamp("at", { withTimezone: true }).notNull(),
2531
+ service: text("service").notNull(),
2532
+ action: text("action").notNull(),
2533
+ resource: text("resource"),
2534
+ recordId: text("record_id"),
2535
+ actorId: text("actor_id"),
2536
+ actorLabel: text("actor_label"),
2537
+ tenant: text("tenant"),
2538
+ traceId: text("trace_id"),
2539
+ requestId: text("request_id"),
2540
+ meta: jsonb("meta")
2541
+ });
2542
+ }
2543
+ function auditTable(engine, options = {}) {
2544
+ const name = options.name ?? "brick_audit";
2545
+ const table = engine === "sqlite" ? sqliteAudit(name) : postgresAudit(name);
2546
+ Object.defineProperty(table, AUDIT, { value: { engine } });
2547
+ return table;
2548
+ }
2549
+ /** Whether a value is an audit table made by `auditTable`. */
2550
+ function isAuditTable(value) {
2551
+ return typeof value === "object" && value !== null && AUDIT in value;
2552
+ }
2553
+ function auditStage(service, action) {
2554
+ const table = service.getAuditTable();
2555
+ const config = action.config;
2556
+ if (!table || config.audit === false) return void 0;
2557
+ const { audit: mode, resourceAction } = actionMeta(action);
2558
+ if (mode === "none" || !mode && actionMethod(action) === "GET") return void 0;
488
2559
  return {
489
- info: level("info", (...args) => console.log(...args)),
490
- warn: level("warn", (...args) => console.warn(...args)),
491
- error: level("error", (...args) => console.error(...args)),
492
- debug: level("debug", (...args) => console.debug(...args))
2560
+ service,
2561
+ table,
2562
+ action: action.name,
2563
+ recordsInOwnTransaction: mode === "inline",
2564
+ resource: config.audit?.resource ?? resourceAction?.resource,
2565
+ record: config.audit?.record ?? (resourceAction?.record ? ({ input }) => input.id : void 0)
493
2566
  };
494
2567
  }
495
- /** The prefixes of loggers a caller did not supply. */
496
- const DEFAULT_LOG_PREFIXES = {
497
- info: "[INFO]",
498
- warn: "[WARN]",
499
- error: "[ERROR]",
500
- debug: "[DEBUG]"
501
- };
502
- // src/dashboard-identity.ts
503
- /** The header the dashboard's `/app/*` proxy signs the identity into. */
504
- const DASHBOARD_IDENTITY_HEADER = "x-brick-dashboard";
505
- /** How `brick dev` hands the signing key to the app's process. */
506
- const DASHBOARD_KEY_ENV = "BRICK_DASHBOARD_KEY";
507
- const SIGNATURE_TTL_MS = 6e4;
508
- const KEY = Symbol.for(GLOBAL_SYMBOL.dashboardKey);
509
- const global = globalThis;
510
- function hideKeyFromChildProcesses() {
511
- const handedOver = process.env[DASHBOARD_KEY_ENV];
512
- if (!handedOver) return;
513
- global[KEY] = handedOver;
514
- delete process.env[DASHBOARD_KEY_ENV];
2568
+ const calls = sharedAcrossCoreCopies("brickkit.audit.calls", () => new AsyncLocalStorage());
2569
+ function runUnaudited(run) {
2570
+ return calls.getStore() ? calls.exit(run) : run();
515
2571
  }
516
- hideKeyFromChildProcesses();
517
- /**
518
- * The key the dashboard signs identities with: random per process, or the one
519
- * `brick dev` or the Vite plugin handed the app.
520
- */
521
- function dashboardKey() {
522
- return global[KEY] ??= randomBytes(32).toString("base64url");
2572
+ function recordIdText(id) {
2573
+ if (id === void 0 || id === null) return null;
2574
+ if (typeof id === "string") return id;
2575
+ if (typeof id === "number" || typeof id === "bigint") return String(id);
2576
+ return JSON.stringify(id) ?? null;
523
2577
  }
524
- const arrivedAt = /* @__PURE__ */ new WeakMap();
525
- /** Note when `request` arrived, before its body is read. */
526
- function markDashboardArrival(request) {
527
- arrivedAt.set(request, Date.now());
2578
+ async function auditRow(ctx, target, entry) {
2579
+ const who = await identityOf(ctx);
2580
+ return {
2581
+ id: crypto.randomUUID(),
2582
+ at: /* @__PURE__ */ new Date(),
2583
+ service: target.service.name,
2584
+ action: entry.action,
2585
+ resource: entry.resource ?? null,
2586
+ recordId: recordIdText(entry.recordId),
2587
+ actorId: who?.id ?? null,
2588
+ actorLabel: who?.label ?? null,
2589
+ tenant: who?.tenant ?? null,
2590
+ traceId: ctx.traceId ?? null,
2591
+ requestId: ctx.requestId ?? null,
2592
+ meta: entry.meta ?? null
2593
+ };
528
2594
  }
529
- const mac = (payload) => createHmac("sha256", dashboardKey()).update(payload).digest();
530
- /** The header value for an identity: `<base64url(json)>.<hmac>`. */
531
- function signDashboardIdentity(identity, now = Date.now()) {
532
- const payload = Buffer.from(JSON.stringify({
533
- user: identity.user,
534
- exp: now + SIGNATURE_TTL_MS
535
- })).toString("base64url");
536
- return `${payload}.${mac(payload).toString("base64url")}`;
2595
+ function insertOutsideOtherRequestsTransactions(db, fn) {
2596
+ return isSqliteDatabase(db) && !inTransaction(db) ? runInTransaction(db, fn) : fn(db);
537
2597
  }
538
- function dashboardIdentity(request) {
539
- const header = request?.headers.get(DASHBOARD_IDENTITY_HEADER);
540
- if (!header) return void 0;
541
- const dot = header.indexOf(".");
542
- if (dot < 0) return void 0;
543
- const payload = header.slice(0, dot);
544
- const given = Buffer.from(header.slice(dot + 1), "base64url");
545
- const expected = mac(payload);
546
- if (given.length !== expected.length || !timingSafeEqual(given, expected)) return void 0;
547
- try {
548
- const { user, exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
549
- const now = (request && arrivedAt.get(request)) ?? Date.now();
550
- if (typeof exp !== "number" || exp < now) return void 0;
551
- return user === void 0 ? {} : { user };
552
- } catch {
553
- return;
554
- }
2598
+ async function writeAudit(handle, ctx, target, entry) {
2599
+ await handle.insert(target.table).values(await auditRow(ctx, target, entry));
555
2600
  }
556
- /**
557
- * The dashboard user a request came from, for an endpoint: the person
558
- * `dashboard.auth.authorize` let in, when the request arrived through the
559
- * dashboard's `/app/*` proxy. Undefined for any other request, and for one the
560
- * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.
561
- */
562
- function dashboardUser(request) {
563
- return dashboardIdentity(request)?.user;
2601
+ function resolveActorBeforeAction(ctx) {
2602
+ return identityOf(ctx);
564
2603
  }
565
- // src/context.ts
566
- const DEFAULT_REQUEST = new Request("http://localhost");
567
- const EMPTY = Object.freeze({});
568
- const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
569
- /** Random, so ids never repeat across restarts or processes. */
570
- const newId = (kind) => `${kind}_${crypto.randomUUID()}`;
571
- /**
572
- * The trace and request ids of an HTTP request: the caller's `x-trace-id` and
573
- * `x-request-id` headers, else fresh ones. Both are echoed on the response.
574
- */
575
- function requestIds(headers, set) {
576
- const traceId = headers?.["x-trace-id"] || newId("tr");
577
- const requestId = headers?.["x-request-id"] || newId("req");
578
- if (set?.headers) {
579
- set.headers["x-trace-id"] = traceId;
580
- set.headers["x-request-id"] = requestId;
2604
+ function buildRow(audit, ctx) {
2605
+ return auditRow(ctx, audit, {
2606
+ action: audit.action,
2607
+ resource: audit.resource
2608
+ });
2609
+ }
2610
+ function setRecordIdOf(row, audit, input, result) {
2611
+ row.recordId = recordIdText(audit.record?.({
2612
+ input,
2613
+ result
2614
+ }));
2615
+ }
2616
+ async function runAudited(audit, input, ctx, run) {
2617
+ await resolveActorBeforeAction(ctx);
2618
+ const call = {
2619
+ audit,
2620
+ written: false
2621
+ };
2622
+ const result = await calls.run(call, run);
2623
+ if (!audit.recordsInOwnTransaction && !call.written) {
2624
+ let row;
2625
+ try {
2626
+ row = await buildRow(audit, ctx);
2627
+ setRecordIdOf(row, audit, input, result);
2628
+ await insertOutsideOtherRequestsTransactions(ctx.db, (tx) => tx.insert(audit.table).values(row));
2629
+ } catch (error) {
2630
+ ctx.logger?.error?.(`audit: '${audit.action}' ran but its audit row was not written`, row, error);
2631
+ }
581
2632
  }
2633
+ return result;
2634
+ }
2635
+ function entryOf(audit, input, result) {
582
2636
  return {
583
- traceId,
584
- requestId
2637
+ action: audit.action,
2638
+ resource: audit.resource,
2639
+ recordId: audit.record?.({
2640
+ input,
2641
+ result
2642
+ })
585
2643
  };
586
2644
  }
2645
+ function inlineAudit() {
2646
+ const audit = calls.getStore()?.audit;
2647
+ return audit?.recordsInOwnTransaction ? audit : void 0;
2648
+ }
2649
+ function recordInline(audit, tx, ctx, entry) {
2650
+ return writeAudit(tx, ctx, audit, entry);
2651
+ }
2652
+ function commitsWithBrickTransaction(tx, ctx) {
2653
+ return tx === ctx.db || inTransaction(tx);
2654
+ }
587
2655
  /**
588
- * The framework fields of an action context: what the caller gave, the rest
589
- * defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.
2656
+ * Record a change of your own from an action: for what Brick cannot see, or to
2657
+ * add `meta`. By default the row is inserted at once. Pass the `tx` of a
2658
+ * transaction you have open to commit it with your writes instead; once `tx`
2659
+ * commits it is the record of this call, and Brick does not add the automatic row.
2660
+ *
2661
+ * Brick copies no input or output into the log: `meta` holds what you pass.
2662
+ *
2663
+ * @param ctx - The action context: it names the service and the actor.
2664
+ * @param entry - `action` defaults to the running action's name, and is needed
2665
+ * in an action that is not itself recorded (a `GET`, `audit: false`).
2666
+ * `resource` and `recordId` say which record; `meta` is JSON of your choosing.
2667
+ * @param options - `tx`: an open transaction on the service's database.
2668
+ * @throws When `ctx` is not from an action of a service whose database holds an
2669
+ * audit table (a listener, a schedule or a workflow step has no such context),
2670
+ * or when `action` is missing.
2671
+ * @example
2672
+ * await runInTransaction(ctx.db, async (tx) => {
2673
+ * await tx.update(orders).set({ status: "refunded" }).where(eq(orders.id, input.orderId));
2674
+ * await recordAudit(ctx, { resource: "order", recordId: input.orderId, meta: { reason: input.reason } }, { tx });
2675
+ * });
590
2676
  */
591
- function baseContext(fields) {
592
- return {
593
- request: fields.request ?? DEFAULT_REQUEST,
594
- db: fields.db,
595
- logger: fields.logger ?? defaultLogger,
596
- traceId: fields.traceId ?? newId("tr"),
597
- requestId: fields.requestId ?? newId("req"),
598
- services: fields.services ?? EMPTY,
599
- metadata: fields.metadata ?? EMPTY,
600
- deps: fields.deps ?? EMPTY,
601
- dashboard: fields.dashboard ?? dashboardIdentity(fields.request)
2677
+ async function recordAudit(ctx, entry, options = {}) {
2678
+ const service = serviceOf(ctx);
2679
+ const table = service && portOf(service).getAuditTable();
2680
+ if (!service || !table) throw new Error("recordAudit needs the ctx of an action of a service whose database holds an audit table");
2681
+ const call = calls.getStore();
2682
+ const action = entry.action ?? call?.audit.action;
2683
+ if (!action) throw new Error("recordAudit needs an action: it defaults to the running action only when that action is recorded");
2684
+ const target = {
2685
+ service: portOf(service),
2686
+ table
602
2687
  };
603
- }
604
- function pickContextEnvelope(context) {
605
- if (!context) return {};
606
- const envelope = {};
607
- if (context.caller !== void 0) envelope.caller = context.caller;
608
- if (context.user !== void 0) envelope.user = context.user;
609
- if (context.traceId !== void 0) envelope.traceId = context.traceId;
610
- if (context.requestId !== void 0) envelope.requestId = context.requestId;
611
- if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
612
- if (context.dashboard !== void 0) envelope.dashboard = context.dashboard;
613
- return envelope;
2688
+ const named = {
2689
+ ...entry,
2690
+ action
2691
+ };
2692
+ if (options.tx === void 0) await insertOutsideOtherRequestsTransactions(ctx.db, (tx) => writeAudit(tx, ctx, target, named));
2693
+ else {
2694
+ await writeAudit(options.tx, ctx, target, named);
2695
+ if (call && commitsWithBrickTransaction(options.tx, ctx)) await onTransactionCommit(options.tx, () => call.written = true);
2696
+ }
614
2697
  }
615
2698
  // src/compiler/runtime.ts
616
2699
  function isNonEmpty(value) {
@@ -652,6 +2735,19 @@ const BODY_TOO_LARGE = Symbol("brick.bodyTooLarge");
652
2735
  function bodyLimitParser(limit) {
653
2736
  return ({ request }) => Number(request.headers.get("content-length")) > limit ? BODY_TOO_LARGE : void 0;
654
2737
  }
2738
+ function rawBodyParser(limit) {
2739
+ return async ({ request }) => {
2740
+ if (Number(request.headers.get("content-length")) > limit) return BODY_TOO_LARGE;
2741
+ const chunks = [];
2742
+ let size = 0;
2743
+ if (request.body) for await (const chunk of request.body) {
2744
+ size += chunk.byteLength;
2745
+ if (size > limit) return BODY_TOO_LARGE;
2746
+ chunks.push(chunk);
2747
+ }
2748
+ return new Uint8Array(Buffer.concat(chunks));
2749
+ };
2750
+ }
655
2751
  /** The action's input from the path, query and body, coerced by its schema. */
656
2752
  function readInput(route, { params, body, query, request }) {
657
2753
  if (body === BODY_TOO_LARGE) throw new ActionExecutionError("PAYLOAD_TOO_LARGE", `Request body exceeds ${route.bodyLimit} bytes`, 413);
@@ -705,10 +2801,9 @@ function invalid(action, stage, errors) {
705
2801
  }
706
2802
  function validate(check, value, action, stage) {
707
2803
  if (check.Check(value)) return;
708
- throw invalid(action, stage, Array.from(check.Errors(value)).map((err) => ({
709
- path: err.path,
710
- message: err.message,
711
- value: err.value
2804
+ throw invalid(action, stage, Array.from(check.Errors(value), ({ path, message }) => ({
2805
+ path,
2806
+ message
712
2807
  })));
713
2808
  }
714
2809
  function validateInput(check, input, action, checkInput) {
@@ -732,26 +2827,35 @@ async function authorizeCall(authorize, ctx, input, action) {
732
2827
  user: ctx.user
733
2828
  })) deny(action, ctx.user);
734
2829
  }
735
- /** The stage order of every call, over HTTP and in-process: check input → authorize → execute → check output. */
2830
+ /** The stage order of every call, over HTTP and in-process: check input → rate limit → authorize → execute → check output. */
736
2831
  async function runStages(stages, input, ctx) {
737
2832
  if (stages.dashboardOnly && !ctx.dashboard) throw new ActionExecutionError("UNAUTHORIZED", `Action '${stages.name}' is only for the dashboard`, 401);
738
2833
  stages.checkInput(input);
2834
+ stages.sensitive?.input(input);
2835
+ if (stages.rateLimit) await stages.rateLimit(input, ctx);
739
2836
  await authorizeCall(stages.authorize, ctx, input, stages.name);
740
- return stages.checkOutput(await stages.execute({
2837
+ const output = stages.audit ? await runAudited(stages.audit, input, ctx, async () => stages.checkOutput(await stages.execute({
741
2838
  input,
742
2839
  ctx,
743
2840
  error: stages.errorBuilder
744
- }));
2841
+ }))) : stages.checkOutput(await runUnaudited(() => stages.execute({
2842
+ input,
2843
+ ctx,
2844
+ error: stages.errorBuilder
2845
+ })));
2846
+ return stages.sensitive ? stages.sensitive.output(output, input, ctx) : output;
745
2847
  }
746
2848
  function mapError(err, set, options) {
747
2849
  const response = toErrorResponse(err, options);
748
2850
  set.status = response.status;
2851
+ const retry = response.details?.retryAfterSeconds;
2852
+ if (response.status === 429 && Number.isFinite(retry)) set.headers["retry-after"] = String(BigInt(Math.max(1, Math.ceil(retry))));
749
2853
  return response;
750
2854
  }
751
2855
  const isThenable = (value) => value != null && typeof value.then === "function";
752
2856
  /** The context of one HTTP request, with the trace and request id headers set. */
753
2857
  function requestContext(plan, { headers, request, set }) {
754
- return baseContext({
2858
+ const ctx = baseContext({
755
2859
  ...requestIds(headers, set),
756
2860
  request: request instanceof Request ? request : void 0,
757
2861
  db: plan.cachedDb ?? plan.service.getDb(),
@@ -759,39 +2863,234 @@ function requestContext(plan, { headers, request, set }) {
759
2863
  metadata: { headers },
760
2864
  deps: plan.contextHook ? plan.service.deps : plan.deps ?? plan.service.deps
761
2865
  });
2866
+ if (!plan.contextHook) resolveServiceDeps(ctx, plan);
2867
+ return ctx;
2868
+ }
2869
+ const HANDLED = "handled";
2870
+ const IN_FLIGHT_CLAIM_MS = 3e5;
2871
+ const eventIdFrom = (value) => Number.isSafeInteger(value) ? String(value) : typeof value === "string" && value ? value : void 0;
2872
+ const refuse = (code, message, status) => new ActionExecutionError(code, message, status);
2873
+ function fieldsOf(params) {
2874
+ const grouped = /* @__PURE__ */ new Map();
2875
+ for (const [name, value] of params) grouped.set(name, [...grouped.get(name) ?? [], value]);
2876
+ return Object.fromEntries([...grouped].map(([name, values]) => [name, values.length > 1 ? values : values[0]]));
2877
+ }
2878
+ function webhookInput(route, request, rawBody) {
2879
+ const text = new TextDecoder().decode(rawBody);
2880
+ const form = route.method === "GET" ? new URL(request.url).searchParams : /^application\/x-www-form-urlencoded/i.test(request.headers.get("content-type") ?? "") ? new URLSearchParams(text) : void 0;
2881
+ if (form) return readInput(route, { query: fieldsOf(form) });
2882
+ if (!text) return void 0;
2883
+ try {
2884
+ return JSON.parse(text);
2885
+ } catch {
2886
+ throw invalid(route.action, "input", [{
2887
+ path: "",
2888
+ message: "Body is not valid JSON"
2889
+ }]);
2890
+ }
2891
+ }
2892
+ function bindWebhook(plan) {
2893
+ const { execute } = plan;
2894
+ const name = plan.route.action;
2895
+ const webhook = webhookOf(plan.action);
2896
+ const limits = rateLimitsOf(plan.action.config);
2897
+ const audit = auditStage(plan.service, plan.action);
2898
+ const storage = webhook.replay ? serviceStorage(plan.service) : void 0;
2899
+ if (webhook.replay && !storage) throw new Error(`Webhook '${name}' remembers the events it has handled, but its service has no key-value storage`);
2900
+ const brickWebhook = async (context) => {
2901
+ const delivery = {
2902
+ plan,
2903
+ webhook,
2904
+ storage,
2905
+ limits,
2906
+ request: context.request,
2907
+ ctx: requestContext(plan, context),
2908
+ outcome: "failed"
2909
+ };
2910
+ try {
2911
+ rejectOversizedBody(delivery, context.body);
2912
+ const rawBody = rawBodyOf(context.body);
2913
+ await verifyDelivery(delivery, rawBody);
2914
+ const input = parseAndCheckInput(delivery, rawBody);
2915
+ plan.sensitive?.input(input);
2916
+ await resolveEventId(delivery, input);
2917
+ if (await claimEvent(delivery) === ALREADY_HANDLED) return { duplicate: true };
2918
+ let result;
2919
+ try {
2920
+ await resolveContext(delivery);
2921
+ await enforceWebhookRateLimits(delivery, input);
2922
+ const run = () => execute({
2923
+ input,
2924
+ ctx: delivery.ctx,
2925
+ error: plan.errorBuilder,
2926
+ eventId: delivery.eventId
2927
+ });
2928
+ result = audit ? await runAudited(audit, input, delivery.ctx, async () => run()) : await runUnaudited(run);
2929
+ if (plan.sensitive && !(result instanceof Response)) result = await plan.sensitive.output(result, input, delivery.ctx);
2930
+ } catch (error) {
2931
+ await releaseClaim(delivery);
2932
+ throw error;
2933
+ }
2934
+ await settleClaim(delivery, result);
2935
+ return result === void 0 ? { ok: true } : result;
2936
+ } catch (err) {
2937
+ return mapError(err, context.set, delivery.ctx);
2938
+ } finally {
2939
+ recordWebhook(name, delivery.eventId, delivery.outcome);
2940
+ }
2941
+ };
2942
+ return plan.sensitive ? (context) => withRedaction(() => brickWebhook(context)) : brickWebhook;
2943
+ }
2944
+ const ALREADY_HANDLED = Symbol("alreadyHandled");
2945
+ function rejectOversizedBody(delivery, body) {
2946
+ if (body !== BODY_TOO_LARGE) return;
2947
+ delivery.outcome = "too_large";
2948
+ throw refuse("PAYLOAD_TOO_LARGE", `Request body exceeds ${delivery.webhook.maxBodyBytes} bytes`, 413);
2949
+ }
2950
+ const rawBodyOf = (body) => body instanceof Uint8Array ? body : /* @__PURE__ */ new Uint8Array();
2951
+ function logVerifierThrowWithoutItsMessage({ plan, ctx }, error) {
2952
+ plan.logger.warn("A webhook verifier threw, so its delivery was refused", {
2953
+ service: plan.service.name,
2954
+ webhook: plan.route.action,
2955
+ error: error instanceof Error ? error.constructor.name : typeof error,
2956
+ requestId: ctx.requestId
2957
+ });
2958
+ }
2959
+ async function verifyDelivery(delivery, rawBody) {
2960
+ const { webhook, request } = delivery;
2961
+ let verdict;
2962
+ try {
2963
+ verdict = await webhook.verify({
2964
+ rawBody,
2965
+ headers: request.headers,
2966
+ url: request.url,
2967
+ method: request.method
2968
+ });
2969
+ } catch (error) {
2970
+ logVerifierThrowWithoutItsMessage(delivery, error);
2971
+ verdict = false;
2972
+ }
2973
+ const given = eventIdFrom(verdict?.eventId);
2974
+ if (verdict !== true && !given) {
2975
+ delivery.outcome = "refused";
2976
+ throw refuse("UNAUTHORIZED", "Webhook verification failed", 401);
2977
+ }
2978
+ delivery.eventId = verdict === true ? void 0 : given;
2979
+ }
2980
+ function parseAndCheckInput(delivery, rawBody) {
2981
+ const { plan, request } = delivery;
2982
+ const { route, inputChecker, checkInput } = plan;
2983
+ delivery.outcome = "invalid";
2984
+ let input = webhookInput(route, request, rawBody);
2985
+ if (inputChecker) validateInput(inputChecker, input, route.action, checkInput);
2986
+ input = Value.Clean(plan.action.config.input, input);
2987
+ delivery.outcome = "failed";
2988
+ return input;
2989
+ }
2990
+ async function resolveEventId(delivery, input) {
2991
+ const { webhook, request } = delivery;
2992
+ delivery.eventId ??= eventIdFrom(await webhook.eventId?.({
2993
+ input,
2994
+ headers: request.headers,
2995
+ url: request.url,
2996
+ method: request.method
2997
+ }));
2998
+ }
2999
+ async function claimEvent(delivery) {
3000
+ const { plan, storage, eventId } = delivery;
3001
+ if (!storage) return;
3002
+ if (!eventId) {
3003
+ delivery.outcome = "no_event_id";
3004
+ throw refuse("BAD_REQUEST", "The delivery has no event id", 400);
3005
+ }
3006
+ const claim = delivery.claim = {
3007
+ key: storageKey("webhook", [
3008
+ plan.service.name,
3009
+ plan.route.action,
3010
+ eventId
3011
+ ]),
3012
+ mine: `pending:${crypto.randomUUID()}`
3013
+ };
3014
+ try {
3015
+ const claimed = await storage.putIfAbsent(claim.key, claim.mine, IN_FLIGHT_CLAIM_MS);
3016
+ if (claimed.stored) return;
3017
+ if (claimed.value === HANDLED) {
3018
+ delivery.outcome = "duplicate";
3019
+ return ALREADY_HANDLED;
3020
+ }
3021
+ delivery.outcome = "in_flight";
3022
+ throw refuse("CONFLICT", "Another delivery of this event is being handled; retry later", 409);
3023
+ } catch (error) {
3024
+ if (!(error instanceof StorageUnavailableError)) throw error;
3025
+ releaseClaim(delivery);
3026
+ delivery.outcome = "unavailable";
3027
+ throw new ActionExecutionError("SERVICE_UNAVAILABLE", "Webhook storage is unavailable; retry later", 503, void 0, { cause: error });
3028
+ }
3029
+ }
3030
+ async function resolveContext({ plan, ctx }) {
3031
+ if (!plan.contextHook) return;
3032
+ const extra = await plan.contextHook(ctx);
3033
+ if (extra) Object.assign(ctx, extra);
3034
+ resolveServiceDeps(ctx, plan);
3035
+ }
3036
+ async function enforceWebhookRateLimits({ plan, limits, ctx }, input) {
3037
+ if (limits) await enforceRateLimits(plan.service, "action", plan.route.action, limits, input, ctx);
3038
+ }
3039
+ async function releaseClaim({ storage, claim }) {
3040
+ await storage?.compareAndDelete(claim.key, claim.mine).catch(() => {});
3041
+ }
3042
+ async function settleClaim(delivery, result) {
3043
+ const { plan, webhook, storage, claim, ctx } = delivery;
3044
+ const failed = result instanceof Response && result.status >= 400;
3045
+ if (storage && failed) await releaseClaim(delivery);
3046
+ else if (storage && webhook.replay) await storage.put(claim.key, HANDLED, webhook.replay.ttlMs).catch((error) => plan.logger.warn("Webhook handled, but its id was not recorded; a retry may run it again", { requestId: ctx.requestId }, error));
3047
+ delivery.outcome = failed ? "failed" : "processed";
3048
+ }
3049
+ function resolveServiceDeps(ctx, plan) {
3050
+ markResolved(ctx, plan.service, plan.service.deps);
3051
+ ctx.deps = scopeFiles(plan.deps ?? plan.service.deps, ctx);
762
3052
  }
763
3053
  /** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */
764
3054
  function bindRoute(plan) {
3055
+ if (plan.route.kind === "webhook") return bindWebhook(plan);
765
3056
  const { route, execute, contextHook, authorize, inputChecker, outputChecker, checkInput, errorBuilder } = plan;
766
3057
  const name = route.action;
3058
+ const limits = rateLimitsOf(plan.action.config);
3059
+ const audit = auditStage(plan.service, plan.action);
767
3060
  const stages = {
768
3061
  name,
769
3062
  dashboardOnly: plan.action.config.dashboard === true,
770
3063
  checkInput: (input) => {
771
3064
  if (inputChecker) validateInput(inputChecker, input, name, checkInput);
772
3065
  },
3066
+ rateLimit: limits && ((input, ctx) => enforceRateLimits(plan.service, plan.action.kind === "tool" ? "tool" : "action", name, limits, input, ctx)),
773
3067
  authorize,
3068
+ audit,
774
3069
  execute,
775
3070
  errorBuilder,
776
3071
  checkOutput: (result) => {
777
3072
  if (outputChecker) validate(outputChecker, result, name, "output");
778
3073
  return result;
779
- }
3074
+ },
3075
+ sensitive: plan.sensitive
780
3076
  };
781
- if (contextHook || authorize || stages.dashboardOnly) return async function brickAction(context) {
782
- const ctx = requestContext(plan, context);
783
- try {
784
- const input = readInput(route, context);
785
- if (contextHook) {
786
- const extra = await contextHook(ctx);
787
- if (extra) Object.assign(ctx, extra);
788
- if (plan.deps) ctx.deps = plan.deps;
3077
+ if (contextHook || authorize || stages.dashboardOnly || limits || audit || stages.sensitive) {
3078
+ const brickAction = async (context) => {
3079
+ const ctx = requestContext(plan, context);
3080
+ try {
3081
+ const input = readInput(route, context);
3082
+ if (contextHook) {
3083
+ const extra = await contextHook(ctx);
3084
+ if (extra) Object.assign(ctx, extra);
3085
+ resolveServiceDeps(ctx, plan);
3086
+ }
3087
+ return await runStages(stages, input, ctx);
3088
+ } catch (err) {
3089
+ return mapError(err, context.set, ctx);
789
3090
  }
790
- return await runStages(stages, input, ctx);
791
- } catch (err) {
792
- return mapError(err, context.set, ctx);
793
- }
794
- };
3091
+ };
3092
+ return stages.sensitive ? (context) => withRedaction(() => brickAction(context)) : brickAction;
3093
+ }
795
3094
  return function brickAction(context) {
796
3095
  const ctx = requestContext(plan, context);
797
3096
  try {
@@ -816,7 +3115,7 @@ const compilerRuntime = Object.freeze({ bindRoute });
816
3115
  * The `error` helpers an action receives: one function per error code that
817
3116
  * throws an `ActionExecutionError` with that code and status. The standard HTTP
818
3117
  * codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
819
- * `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
3118
+ * `RATE_LIMITED`, `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
820
3119
  * them or replace one.
821
3120
  *
822
3121
  * @param errorsDef - The action's `errors`: for each code, its `message` and
@@ -863,6 +3162,7 @@ function defineAction(config) {
863
3162
  ctx
864
3163
  });
865
3164
  };
3165
+ const limits = rateLimitsOf(config);
866
3166
  const stages = {
867
3167
  name: config.name,
868
3168
  dashboardOnly: config.dashboard === true,
@@ -871,6 +3171,7 @@ function defineAction(config) {
871
3171
  const checked = actionFn.validateInput(input);
872
3172
  if (!checked.success) throw invalid(config.name, "input", checked.errors);
873
3173
  },
3174
+ rateLimit: limits && ((input, ctx) => enforceRateLimits(actionMeta(actionFn).service, actionFn.kind === "tool" ? "tool" : "action", config.name, limits, input, ctx)),
874
3175
  authorize: config.authorize,
875
3176
  execute: config.execute,
876
3177
  errorBuilder: errorHelpers,
@@ -879,22 +3180,43 @@ function defineAction(config) {
879
3180
  const checked = actionFn.validateOutput(result);
880
3181
  if (!checked.success) throw invalid(config.name, "output", checked.errors);
881
3182
  return result;
882
- }
3183
+ },
3184
+ sensitive: sensitivity(config)
883
3185
  };
884
- actionFn.execute = async (params) => {
3186
+ const auditStageOf = memoizedPerAuditTable(actionFn);
3187
+ const run = async (params) => {
885
3188
  const meta = actionMeta(actionFn);
886
3189
  const ctx = meta.service ? await meta.service.resolveContext(params?.ctx, meta.deps?.values) : {
887
3190
  ...baseContext(params?.ctx ?? {}),
888
3191
  ...params?.ctx
889
3192
  };
890
3193
  try {
891
- return await runStages(stages, params?.input, ctx);
3194
+ const audit = auditStageOf(meta.service);
3195
+ return await runStages(audit ? {
3196
+ ...stages,
3197
+ audit
3198
+ } : stages, params?.input, ctx);
892
3199
  } catch (err) {
893
3200
  throw normalizeActionError(err, ctx);
894
3201
  }
895
3202
  };
3203
+ actionFn.execute = stages.sensitive ? (params) => withRedaction(() => run(params)) : run;
896
3204
  return actionFn;
897
3205
  }
3206
+ function memoizedPerAuditTable(action) {
3207
+ let memo;
3208
+ return (service) => {
3209
+ const table = service?.getAuditTable();
3210
+ if (memo && table === memo.table && service === memo.service) return memo.stage;
3211
+ const stage = service && auditStage(service, action);
3212
+ memo = {
3213
+ service,
3214
+ table,
3215
+ stage
3216
+ };
3217
+ return stage;
3218
+ };
3219
+ }
898
3220
  // src/http.ts
899
3221
  /** The HTTP methods an action, endpoint or plugin route can use. */
900
3222
  const HTTP_METHODS = [
@@ -904,11 +3226,6 @@ const HTTP_METHODS = [
904
3226
  "PATCH",
905
3227
  "DELETE"
906
3228
  ];
907
- // src/service-port.ts
908
- /** The port of a service: every `Service` is a `ServicePort`. */
909
- function portOf(service) {
910
- return service;
911
- }
912
3229
  // src/plugin.ts
913
3230
  /**
914
3231
  * Define a plugin that installs onto a service with `service.use(plugin)`. Its
@@ -1115,6 +3432,10 @@ function installPlugin(service, resource, descriptor) {
1115
3432
  const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
1116
3433
  if (service.getAction(name)) throw new DuplicateNameError(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
1117
3434
  const { scope: _scope, runtimeOutput, checkInput, ...actionConfig } = config;
3435
+ sensitivity({
3436
+ ...actionConfig,
3437
+ name
3438
+ }, service.name);
1118
3439
  const action = defineAction({
1119
3440
  ...actionConfig,
1120
3441
  name
@@ -1189,75 +3510,25 @@ function installPlugin(service, resource, descriptor) {
1189
3510
  restoreState();
1190
3511
  throw error;
1191
3512
  } finally {
1192
- active = false;
1193
- }
1194
- }
1195
- /** Whether a plugin named `name` is installed on `host` (the service or a resource). */
1196
- function hasPlugin(service, host, name) {
1197
- return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
1198
- }
1199
- /** Every descriptor installed on the service or its resources, in install order per host. */
1200
- function installedPlugins(service) {
1201
- return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
1202
- }
1203
- // src/deps.ts
1204
- /**
1205
- * Declare a dependency a service needs, without creating it. The app provides
1206
- * the value with `brick({ deps })`, and the service's code reads it as
1207
- * `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
1208
- *
1209
- * @returns A slot typed as `T`. It holds nothing at runtime.
1210
- * @example
1211
- * import { defineService, port } from "@brickkit/core";
1212
- *
1213
- * export const orders = defineService("orders", {
1214
- * database,
1215
- * deps: { carrier: port<Carrier>() },
1216
- * });
1217
- *
1218
- * // app.ts
1219
- * export default brick({ services: [orders], deps: { carrier: createCarrier() } });
1220
- */
1221
- function port() {
1222
- return Object.freeze({});
1223
- }
1224
- /** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */
1225
- const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
1226
- const running = new AsyncLocalStorage();
1227
- /** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
1228
- function runWithDeps(deps, fn) {
1229
- return running.run(deps, fn);
1230
- }
1231
- function useDeps() {
1232
- const deps = running.getStore();
1233
- 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).");
1234
- return deps;
1235
- }
1236
- /**
1237
- * Check `brick({ deps })` against what the services declare, and give each
1238
- * service the values of its own ports.
1239
- *
1240
- * @throws When a service declares a dep the app does not provide, or the app
1241
- * provides one that no service declares.
1242
- */
1243
- function bindDeps(services, provided = {}) {
1244
- const declared = /* @__PURE__ */ new Set();
1245
- for (const service of services) {
1246
- const own = {};
1247
- for (const name of Object.keys(service.options.deps ?? {})) {
1248
- 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`);
1249
- declared.add(name);
1250
- own[name] = provided[name];
1251
- }
1252
- portOf(service).setDeps(Object.freeze(own));
3513
+ active = false;
1253
3514
  }
1254
- 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"})`);
3515
+ }
3516
+ /** Whether a plugin named `name` is installed on `host` (the service or a resource). */
3517
+ function hasPlugin(service, host, name) {
3518
+ return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
3519
+ }
3520
+ /** Every descriptor installed on the service or its resources, in install order per host. */
3521
+ function installedPlugins(service) {
3522
+ return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
1255
3523
  }
1256
3524
  // src/plugin-app.ts
1257
3525
  const INTERNALS = Symbol.for("brickkit.plugin.internals");
1258
3526
  function isPluginInstance(value) {
1259
3527
  return typeof value === "object" && value !== null && INTERNALS in value;
1260
3528
  }
3529
+ function pluginDepsOf(value) {
3530
+ return internalsOf(value)?.deps ?? {};
3531
+ }
1261
3532
  function internalsOf(value) {
1262
3533
  return isPluginInstance(value) ? value[INTERNALS] ?? void 0 : void 0;
1263
3534
  }
@@ -1335,7 +3606,8 @@ function setupAppPlugins(installedOnServices, appPlugins) {
1335
3606
  lifecycles,
1336
3607
  middleware,
1337
3608
  listeners,
1338
- plugins: listed
3609
+ plugins: listed,
3610
+ deps: ordered.map((plugin) => internalsOf(plugin).deps)
1339
3611
  };
1340
3612
  }
1341
3613
  /**
@@ -1377,36 +3649,6 @@ function pluginLifecycle(lifecycles) {
1377
3649
  }
1378
3650
  };
1379
3651
  }
1380
- // src/definition-site.ts
1381
- const brickRoot = fileURLToPath(new URL("..", import.meta.url));
1382
- /**
1383
- * The first `file:line` outside Brick on the current stack: where a name is
1384
- * being defined. Best-effort: `undefined` when there is no stack.
1385
- */
1386
- function definitionSite() {
1387
- const limit = Error.stackTraceLimit;
1388
- Error.stackTraceLimit = 50;
1389
- const stack = (/* @__PURE__ */ new Error()).stack;
1390
- Error.stackTraceLimit = limit;
1391
- for (const line of stack?.split("\n").slice(1) ?? []) {
1392
- const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
1393
- if (!match) continue;
1394
- const [, file, row] = match;
1395
- if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
1396
- return `${file}:${row}`;
1397
- }
1398
- }
1399
- /**
1400
- * Records where `name` is defined. The same file defining it again (a dev
1401
- * reload) replaces the old definition.
1402
- *
1403
- * @throws When a different file already defined `name`.
1404
- */
1405
- function claimName(sites, label, name, site) {
1406
- const file = (at) => at?.replace(/:\d+$/, "");
1407
- if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new DuplicateNameError(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
1408
- sites.set(name, site);
1409
- }
1410
3652
  // src/compiler/ir.ts
1411
3653
  const FORM_FIELDS_AND_FRAMING_BYTES = 1048576;
1412
3654
  function coercionOf(schema) {
@@ -1447,6 +3689,7 @@ function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
1447
3689
  const key = routeKey(method, path);
1448
3690
  const previous = registered.get(key);
1449
3691
  if (previous) {
3692
+ if (route.kind === "webhook" || previous.webhook) throw new DuplicateNameError(`Brick compiler: '${service.name}.${action.name}' and '${previous.name}' both claim '${method} ${path}', and a webhook cannot share its route`);
1450
3693
  if (route.plugin || previous.plugin) throw new DuplicateNameError(`Brick compiler: duplicate plugin route '${method} ${path}'`);
1451
3694
  diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (earlier service, then lower action name, wins)`);
1452
3695
  return;
@@ -1454,7 +3697,8 @@ function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
1454
3697
  if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
1455
3698
  registered.set(key, {
1456
3699
  name: `${service.name}.${action.name}`,
1457
- plugin: Boolean(route.plugin)
3700
+ plugin: Boolean(route.plugin),
3701
+ webhook: route.kind === "webhook"
1458
3702
  });
1459
3703
  routes.push(route);
1460
3704
  bindings.push({
@@ -1502,6 +3746,7 @@ function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
1502
3746
  const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1503
3747
  /** What the compiler records about one action route. */
1504
3748
  function describeRoute(service, action, method, path) {
3749
+ for (const name of pathParamNames(path)) if (marksKey(action.config.input, name)) throw new Error(`Service '${service.name}' action '${action.name}': sensitive input field '/${name}' is a path parameter of '${method} ${path}', and request logs and traces record the path; take it in the request body instead`);
1505
3750
  const coercions = [];
1506
3751
  for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) {
1507
3752
  const type = coercionOf(prop);
@@ -1518,13 +3763,14 @@ function describeRoute(service, action, method, path) {
1518
3763
  }
1519
3764
  const plugin = actionMeta(action).route?.plugin;
1520
3765
  const files = fileFields(action.config.input);
1521
- const bodyLimit = files.length && files.every((field) => field.maxBytes !== void 0) ? files.reduce((sum, field) => sum + (field.maxBytes ?? 0), 0) + FORM_FIELDS_AND_FRAMING_BYTES : void 0;
3766
+ const webhook = webhookOf(action);
3767
+ const bodyLimit = webhook ? webhook.maxBodyBytes : files.length && files.every((field) => field.maxBytes !== void 0) ? files.reduce((sum, field) => sum + (field.maxBytes ?? 0), 0) + FORM_FIELDS_AND_FRAMING_BYTES : void 0;
1522
3768
  return {
1523
3769
  method,
1524
3770
  path,
1525
3771
  service: service.name,
1526
3772
  action: action.name,
1527
- kind: "action",
3773
+ kind: webhook ? "webhook" : "action",
1528
3774
  ...plugin ? { plugin } : {},
1529
3775
  input: Boolean(action.config.input),
1530
3776
  output: Boolean(action.config.output),
@@ -1556,6 +3802,7 @@ function planRoute(route, service, action) {
1556
3802
  logger: createLogger(`[${service.name}:${action.name}]`),
1557
3803
  cachedDb: service.getDb(),
1558
3804
  checkInput: meta.checkInput,
3805
+ sensitive: sensitivity(action.config, service.name),
1559
3806
  deps: meta.deps?.values
1560
3807
  };
1561
3808
  }
@@ -1611,6 +3858,8 @@ function eventRefs(service, catalog) {
1611
3858
  for (const [key, schema] of Object.entries(catalog ?? {})) {
1612
3859
  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`);
1613
3860
  if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
3861
+ const at = sensitivePointer(schema);
3862
+ if (at) throw new Error(`Event "${service}.${key}" payload marks '${at}' t.Sensitive, which event payloads do not support yet; carry an id and load the secret in the listener`);
1614
3863
  refs[key] = Object.freeze({
1615
3864
  name: `${service}.${key}`,
1616
3865
  service,
@@ -2092,6 +4341,15 @@ function getActionAccess(action) {
2092
4341
  policy
2093
4342
  };
2094
4343
  }
4344
+ /**
4345
+ * Say how the audit log records an action a plugin owns: `"inline"` when the
4346
+ * plugin writes in its own transaction and records the write there with a
4347
+ * host hook, `"none"` when it never writes. Without this, an action that is not
4348
+ * a `GET` is recorded after it runs, as a plain action is.
4349
+ */
4350
+ function setActionAudit(action, mode) {
4351
+ actionMeta(action).audit = mode;
4352
+ }
2095
4353
  // src/openapi.ts
2096
4354
  /** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */
2097
4355
  const OPENAPI_DEFAULTS = Object.freeze({
@@ -2184,6 +4442,7 @@ function generateOpenApiSpec(options = {}) {
2184
4442
  const { plugin, resource } = actionOwners(action);
2185
4443
  const group = resource ? `${service.name} · ${resource}` : service.name;
2186
4444
  if (resource) tags.set(group, `Routes of resource '${resource}' in service '${service.name}'`);
4445
+ const webhook = webhookOf(action);
2187
4446
  const hasAuth = getActionAccess(action).hasAuthorize;
2188
4447
  if (hasAuth) hasAnyAuthorizedAction = true;
2189
4448
  const responses = {};
@@ -2219,7 +4478,32 @@ function generateOpenApiSpec(options = {}) {
2219
4478
  addError("UNAUTHORIZED", 401, "Authentication required");
2220
4479
  addError("FORBIDDEN", 403, "Access denied");
2221
4480
  }
4481
+ if (webhook) {
4482
+ addError("UNAUTHORIZED", 401, "Webhook verification failed");
4483
+ addError("PAYLOAD_TOO_LARGE", 413, `Body over ${webhook.maxBodyBytes} bytes`);
4484
+ if (webhook.replay) {
4485
+ addError("CONFLICT", 409, "Another delivery of this event is being handled; retry later");
4486
+ addError("SERVICE_UNAVAILABLE", 503, "Webhook storage is unavailable; retry later");
4487
+ }
4488
+ }
2222
4489
  if (action.config.dashboard === true) addError("UNAUTHORIZED", 401, "Only for the dashboard");
4490
+ if (rateLimitsOf(action.config)) {
4491
+ addError("RATE_LIMITED", 429, "Too many calls; retry after Retry-After seconds", {
4492
+ type: "object",
4493
+ properties: { retryAfterSeconds: {
4494
+ type: "integer",
4495
+ minimum: 1
4496
+ } },
4497
+ required: ["retryAfterSeconds"]
4498
+ });
4499
+ responses["429"].headers = { "Retry-After": {
4500
+ description: "Seconds until the window resets",
4501
+ schema: {
4502
+ type: "integer",
4503
+ minimum: 1
4504
+ }
4505
+ } };
4506
+ }
2223
4507
  if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
2224
4508
  const def = errorDef;
2225
4509
  addError(code, def.status || 400, def.message || code, def.details);
@@ -2231,11 +4515,12 @@ function generateOpenApiSpec(options = {}) {
2231
4515
  summary: `${service.name}.${action.name}`,
2232
4516
  description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
2233
4517
  tags: [.../* @__PURE__ */ new Set([group, ...action.config.tags ?? []])],
4518
+ ...webhook ? { "x-brick-webhook": true } : {},
2234
4519
  ...plugin ? { "x-brick-plugin": plugin } : {},
2235
4520
  ...resource ? { "x-brick-resource": resource } : {},
2236
4521
  responses
2237
4522
  };
2238
- const inputSchema = action.config.input;
4523
+ const inputSchema = writeOnly(action.config.input);
2239
4524
  const properties = inputSchema?.properties ?? {};
2240
4525
  const parameters = [...new Set(pathParams)].map((key) => ({
2241
4526
  name: key,
@@ -2259,239 +4544,75 @@ function generateOpenApiSpec(options = {}) {
2259
4544
  required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
2260
4545
  } : inputSchema;
2261
4546
  operation.requestBody = {
2262
- required: true,
2263
- content: { [fileFields(inputSchema).length ? "multipart/form-data" : "application/json"]: { schema: bodySchema } }
2264
- };
2265
- }
2266
- if (parameters.length) operation.parameters = parameters;
2267
- if (hasAuth) operation.security = [{ bearerAuth: [] }];
2268
- paths[actionPath][method] = operation;
2269
- }
2270
- }
2271
- const spec = {
2272
- openapi: "3.1.0",
2273
- info: {
2274
- title,
2275
- version,
2276
- description
2277
- },
2278
- paths,
2279
- tags: Array.from(tags, ([name, description]) => ({
2280
- name,
2281
- description
2282
- }))
2283
- };
2284
- spec.components = { schemas: { ErrorEnvelope: {
2285
- type: "object",
2286
- required: [
2287
- "name",
2288
- "code",
2289
- "message",
2290
- "status",
2291
- "requestId"
2292
- ],
2293
- properties: {
2294
- name: { type: "string" },
2295
- code: { type: "string" },
2296
- message: { type: "string" },
2297
- status: { type: "integer" },
2298
- requestId: { type: "string" },
2299
- details: {},
2300
- errors: {
2301
- type: "array",
2302
- items: {
2303
- type: "object",
2304
- required: ["path", "message"],
2305
- properties: {
2306
- path: { type: "string" },
2307
- message: { type: "string" },
2308
- value: {}
2309
- }
2310
- }
2311
- }
2312
- }
2313
- } } };
2314
- if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
2315
- type: "http",
2316
- scheme: "bearer",
2317
- bearerFormat: "JWT",
2318
- description: "Enter your Bearer authentication token"
2319
- } } });
2320
- const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
2321
- service: service.name,
2322
- payload: ref.schema,
2323
- ...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
2324
- }])));
2325
- if (Object.keys(events).length) spec["x-brick-events"] = events;
2326
- const document = JSON.parse(JSON.stringify(spec));
2327
- hoistAnchoredSchemas(document);
2328
- return document;
2329
- }
2330
- // src/secrets.ts
2331
- /**
2332
- * Type-safe secrets & environment variables.
2333
- *
2334
- * Declare each secret once at module scope instead of scattering untyped
2335
- * `process.env.FOO` reads:
2336
- *
2337
- * const port = defineSecret("PORT").default("3333").transform(Number).require();
2338
- * const baseUrl = defineSecret("BASE_URL").url().require();
2339
- * const key = defineSecret("STRIPE_KEY").validate((v) =>
2340
- * v.startsWith("sk_") || "must start with sk_"
2341
- * ).require();
2342
- *
2343
- * Values resolve from the environment (Bun populates `process.env` from
2344
- * `.env` locally; in prod the same env source applies — a future
2345
- * `SecretSource` such as AWS can slot in without touching call sites).
2346
- *
2347
- * Resolution order per secret: test/session override → source (`process.env`
2348
- * by default) → declared `default`. `resolveSecrets()` validates every
2349
- * registered secret at boot and throws listing all missing required ones.
2350
- */
2351
- /** Default source: `process.env` (Bun loads `.env` into it automatically). */
2352
- const envSource = { get: (name) => process.env[name] };
2353
- const registry = /* @__PURE__ */ new Map();
2354
- const overrides = /* @__PURE__ */ new Map();
2355
- /** Where each secret was first declared. */
2356
- const sites = /* @__PURE__ */ new Map();
2357
- var SecretRef = class {
2358
- name;
2359
- options;
2360
- transformFn;
2361
- validators = [];
2362
- constructor(name, options = {}) {
2363
- this.name = name;
2364
- this.options = options;
2365
- }
2366
- /** True when a default was declared (i.e. the secret is optional). */
2367
- get hasDefault() {
2368
- return this.options.default !== void 0;
2369
- }
2370
- /** Fallback used when the source has no value. Makes the secret optional. */
2371
- default(value) {
2372
- this.options.default = value;
2373
- return this;
2374
- }
2375
- /**
2376
- * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
2377
- * Runs before validators; a throwing transform fails resolution.
2378
- */
2379
- transform(fn) {
2380
- this.transformFn = fn;
2381
- return this;
2382
- }
2383
- /** Run a custom check on the (transformed) value at every resolution. */
2384
- validate(fn) {
2385
- this.validators.push(fn);
2386
- return this;
2387
- }
2388
- /** Shorthand validator: value must parse as a URL. String refs only. */
2389
- url() {
2390
- this.validators.push((v) => {
2391
- try {
2392
- new URL(v);
2393
- } catch {
2394
- return "must be a valid URL";
2395
- }
2396
- });
2397
- return this;
2398
- }
2399
- resolveRaw(source) {
2400
- return overrides.get(this.name) ?? source.get(this.name) ?? this.options.default;
2401
- }
2402
- coerce(raw) {
2403
- let value;
2404
- if (this.transformFn) try {
2405
- value = this.transformFn(raw);
2406
- } catch (err) {
2407
- throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
2408
- }
2409
- else value = raw;
2410
- for (const fn of this.validators) {
2411
- let result;
2412
- try {
2413
- result = fn(value);
2414
- } catch (err) {
2415
- throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
2416
- }
2417
- if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
2418
- if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
2419
- }
2420
- return value;
2421
- }
2422
- /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
2423
- value(source = envSource) {
2424
- const raw = this.resolveRaw(source);
2425
- if (raw === void 0) return void 0;
2426
- return this.coerce(raw);
2427
- }
2428
- /** Resolved value, or throws naming the missing/invalid secret. */
2429
- require(source = envSource) {
2430
- const raw = this.resolveRaw(source);
2431
- if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
2432
- return this.coerce(raw);
2433
- }
2434
- /** True when a value would resolve (override, source, or default). */
2435
- isSet(source = envSource) {
2436
- return this.resolveRaw(source) !== void 0;
2437
- }
2438
- };
2439
- /**
2440
- * Declare a secret. Calling it again for the name returns the same ref. From
2441
- * the same line (a module evaluated again) it starts the declaration over, so
2442
- * its builder calls replace the earlier ones instead of adding to them.
2443
- */
2444
- function defineSecret(name, options = {}) {
2445
- const site = definitionSite();
2446
- const existing = registry.get(name);
2447
- if (existing) {
2448
- if (site !== void 0 && sites.get(name) === site) {
2449
- existing.options = options;
2450
- existing["validators"] = [];
2451
- existing["transformFn"] = void 0;
2452
- }
2453
- return existing;
2454
- }
2455
- sites.set(name, site);
2456
- const ref = new SecretRef(name, options);
2457
- registry.set(name, ref);
2458
- return ref;
2459
- }
2460
- /**
2461
- * Validate every registered secret at boot. Throws a single error listing
2462
- * all missing required secrets. Returns the resolved values.
2463
- */
2464
- function resolveSecrets(opts = {}) {
2465
- const source = opts.source ?? envSource;
2466
- const missing = [];
2467
- const resolved = {};
2468
- for (const ref of registry.values()) {
2469
- const v = ref.value(source);
2470
- if (v === void 0) missing.push(ref.name);
2471
- else resolved[ref.name] = v;
4547
+ required: true,
4548
+ content: {
4549
+ [fileFields(inputSchema).length ? "multipart/form-data" : "application/json"]: { schema: bodySchema },
4550
+ ...webhook ? { "application/x-www-form-urlencoded": { schema: bodySchema } } : {}
4551
+ }
4552
+ };
4553
+ }
4554
+ if (parameters.length) operation.parameters = parameters;
4555
+ if (hasAuth) operation.security = [{ bearerAuth: [] }];
4556
+ paths[actionPath][method] = operation;
4557
+ }
2472
4558
  }
2473
- if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
2474
- return resolved;
2475
- }
2476
- /** Metadata for introspection (values never exposed — future dashboard use). */
2477
- function listSecrets(opts = {}) {
2478
- const source = opts.source ?? envSource;
2479
- return [...registry.values()].map((ref) => ({
2480
- hasDefault: ref.hasDefault,
2481
- isSet: ref.isSet(source),
2482
- name: ref.name
2483
- }));
2484
- }
2485
- /** Test/session override for one secret (`undefined` clears the override). */
2486
- function overrideSecret(name, value) {
2487
- if (value === void 0) overrides.delete(name);
2488
- else overrides.set(name, value);
2489
- }
2490
- /** Clear registry and overrides. Test-only. */
2491
- function resetSecrets() {
2492
- registry.clear();
2493
- overrides.clear();
2494
- sites.clear();
4559
+ const spec = {
4560
+ openapi: "3.1.0",
4561
+ info: {
4562
+ title,
4563
+ version,
4564
+ description
4565
+ },
4566
+ paths,
4567
+ tags: Array.from(tags, ([name, description]) => ({
4568
+ name,
4569
+ description
4570
+ }))
4571
+ };
4572
+ spec.components = { schemas: { ErrorEnvelope: {
4573
+ type: "object",
4574
+ required: [
4575
+ "name",
4576
+ "code",
4577
+ "message",
4578
+ "status",
4579
+ "requestId"
4580
+ ],
4581
+ properties: {
4582
+ name: { type: "string" },
4583
+ code: { type: "string" },
4584
+ message: { type: "string" },
4585
+ status: { type: "integer" },
4586
+ requestId: { type: "string" },
4587
+ details: {},
4588
+ errors: {
4589
+ type: "array",
4590
+ items: {
4591
+ type: "object",
4592
+ required: ["path", "message"],
4593
+ properties: {
4594
+ path: { type: "string" },
4595
+ message: { type: "string" }
4596
+ }
4597
+ }
4598
+ }
4599
+ }
4600
+ } } };
4601
+ if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
4602
+ type: "http",
4603
+ scheme: "bearer",
4604
+ bearerFormat: "JWT",
4605
+ description: "Enter your Bearer authentication token"
4606
+ } } });
4607
+ const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
4608
+ service: service.name,
4609
+ payload: ref.schema,
4610
+ ...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
4611
+ }])));
4612
+ if (Object.keys(events).length) spec["x-brick-events"] = events;
4613
+ const document = JSON.parse(JSON.stringify(spec));
4614
+ hoistAnchoredSchemas(document);
4615
+ return document;
2495
4616
  }
2496
4617
  // src/request-logger.ts
2497
4618
  function formatLog(method, path, status, elapsedMs) {
@@ -2756,44 +4877,44 @@ const OUTBOX_STATUSES = [
2756
4877
  "dead"
2757
4878
  ];
2758
4879
  function sqliteOutbox(name) {
2759
- const timestampMs = (column) => integer(column, { mode: "timestamp_ms" });
4880
+ const timestampMs = (column) => integer$1(column, { mode: "timestamp_ms" });
2760
4881
  return sqliteTable(name, {
2761
- seq: integer("seq").primaryKey({ autoIncrement: true }),
2762
- id: text("id").notNull().unique(),
2763
- eventId: text("event_id").notNull(),
2764
- listener: text("listener").notNull(),
2765
- name: text("name").notNull(),
2766
- payload: text("payload", { mode: "json" }).notNull(),
2767
- traceId: text("trace_id"),
2768
- source: text("source"),
4882
+ seq: integer$1("seq").primaryKey({ autoIncrement: true }),
4883
+ id: text$1("id").notNull().unique(),
4884
+ eventId: text$1("event_id").notNull(),
4885
+ listener: text$1("listener").notNull(),
4886
+ name: text$1("name").notNull(),
4887
+ payload: text$1("payload", { mode: "json" }).notNull(),
4888
+ traceId: text$1("trace_id"),
4889
+ source: text$1("source"),
2769
4890
  occurredAt: timestampMs("occurred_at").notNull(),
2770
- status: text("status").$type().notNull(),
2771
- attempts: integer("attempts").notNull().default(0),
2772
- lastError: text("last_error"),
4891
+ status: text$1("status").$type().notNull(),
4892
+ attempts: integer$1("attempts").notNull().default(0),
4893
+ lastError: text$1("last_error"),
2773
4894
  availableAt: timestampMs("available_at").notNull(),
2774
4895
  claimedAt: timestampMs("claimed_at"),
2775
4896
  deliveredAt: timestampMs("delivered_at")
2776
- }, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
4897
+ }, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
2777
4898
  }
2778
4899
  function postgresOutbox(name) {
2779
4900
  const at = (column) => timestamp(column, { withTimezone: true });
2780
4901
  return pgTable(name, {
2781
4902
  seq: bigserial("seq", { mode: "number" }).primaryKey(),
2782
- id: text$1("id").notNull().unique(),
2783
- eventId: text$1("event_id").notNull(),
2784
- listener: text$1("listener").notNull(),
2785
- name: text$1("name").notNull(),
4903
+ id: text("id").notNull().unique(),
4904
+ eventId: text("event_id").notNull(),
4905
+ listener: text("listener").notNull(),
4906
+ name: text("name").notNull(),
2786
4907
  payload: jsonb("payload").notNull(),
2787
- traceId: text$1("trace_id"),
2788
- source: text$1("source"),
4908
+ traceId: text("trace_id"),
4909
+ source: text("source"),
2789
4910
  occurredAt: at("occurred_at").notNull(),
2790
- status: text$1("status").$type().notNull(),
2791
- attempts: integer$1("attempts").notNull().default(0),
2792
- lastError: text$1("last_error"),
4911
+ status: text("status").$type().notNull(),
4912
+ attempts: integer("attempts").notNull().default(0),
4913
+ lastError: text("last_error"),
2793
4914
  availableAt: at("available_at").notNull(),
2794
4915
  claimedAt: at("claimed_at"),
2795
4916
  deliveredAt: at("delivered_at")
2796
- }, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
4917
+ }, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
2797
4918
  }
2798
4919
  function outboxTable(engine, options = {}) {
2799
4920
  const name = options.name ?? "brick_outbox";
@@ -2843,130 +4964,6 @@ function deliveryOf(row) {
2843
4964
  function outboxEngine(table) {
2844
4965
  return table[OUTBOX].engine;
2845
4966
  }
2846
- // src/events/transaction.ts
2847
- const sqliteQueues = /* @__PURE__ */ new WeakMap();
2848
- const active = new AsyncLocalStorage();
2849
- function joined(db) {
2850
- const open = active.getStore();
2851
- return open?.open && open.handles.has(db) ? open : void 0;
2852
- }
2853
- function isSqliteDatabase(db) {
2854
- return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
2855
- }
2856
- function rollbackQuietly(db, statement = "ROLLBACK") {
2857
- try {
2858
- db.$client.run(statement);
2859
- } catch {
2860
- return;
2861
- }
2862
- }
2863
- async function nested(db, open, fn) {
2864
- const commits = open.commits.length;
2865
- try {
2866
- if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
2867
- open.handles.add(tx);
2868
- return fn(tx);
2869
- });
2870
- const name = `brick_${++open.savepoints}`;
2871
- db.$client.run(`SAVEPOINT ${name}`);
2872
- try {
2873
- const result = await fn(db);
2874
- db.$client.run(`RELEASE ${name}`);
2875
- return result;
2876
- } catch (error) {
2877
- rollbackQuietly(db, `ROLLBACK TO ${name}`);
2878
- rollbackQuietly(db, `RELEASE ${name}`);
2879
- throw error;
2880
- }
2881
- } catch (error) {
2882
- open.commits.length = commits;
2883
- throw error;
2884
- }
2885
- }
2886
- /**
2887
- * Run `fn` in a database transaction: everything it writes through the `tx` it is
2888
- * given is committed together when it returns, or undone if it throws.
2889
- *
2890
- * Postgres uses a real transaction on one connection. SQLite has one connection
2891
- * and a synchronous driver, which Drizzle's own `transaction` cannot use with an
2892
- * async callback (it would commit before the callback finished). So transactions
2893
- * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
2894
- * A write made elsewhere in the process during that time, outside this helper,
2895
- * would join the transaction; use Postgres where that matters.
2896
- *
2897
- * A call made inside `fn` with the `tx` it was given (on SQLite, the database
2898
- * itself) joins the open transaction as a savepoint instead of waiting for it: a
2899
- * nested failure undoes only the nested work, and the outer transaction decides
2900
- * the commit. Nested calls must run one at a time.
2901
- *
2902
- * @param db - A Drizzle database, from `service.getDb()`.
2903
- * @param fn - Receives the transaction handle to run queries on.
2904
- * @returns What `fn` returned.
2905
- * @throws What `fn` threw, after rolling back.
2906
- */
2907
- async function runInTransaction(db, fn) {
2908
- const outer = joined(db);
2909
- if (outer) return nested(db, outer, fn);
2910
- const open = {
2911
- handles: /* @__PURE__ */ new Set(),
2912
- commits: [],
2913
- open: true,
2914
- savepoints: 0
2915
- };
2916
- let result;
2917
- try {
2918
- result = await active.run(open, () => begin(db, open, fn));
2919
- } finally {
2920
- open.open = false;
2921
- }
2922
- for (const commit of open.commits) await commit();
2923
- return result;
2924
- }
2925
- async function begin(db, open, fn) {
2926
- if (!isSqliteDatabase(db)) return db.transaction((tx) => {
2927
- open.handles.add(tx);
2928
- return fn(tx);
2929
- });
2930
- open.handles.add(db);
2931
- const previous = sqliteQueues.get(db) ?? Promise.resolve();
2932
- let release;
2933
- const turn = new Promise((resolve) => {
2934
- release = resolve;
2935
- });
2936
- sqliteQueues.set(db, previous.then(() => turn));
2937
- await previous;
2938
- try {
2939
- db.$client.run("BEGIN IMMEDIATE");
2940
- try {
2941
- const result = await fn(db);
2942
- db.$client.run("COMMIT");
2943
- return result;
2944
- } catch (error) {
2945
- rollbackQuietly(db);
2946
- throw error;
2947
- }
2948
- } finally {
2949
- release();
2950
- }
2951
- }
2952
- /** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
2953
- function inTransaction(db) {
2954
- return joined(db) !== void 0;
2955
- }
2956
- /**
2957
- * Run `fn` once the transaction that `db` belongs to has committed, or now when
2958
- * `db` is not in one opened by `runInTransaction`. It never runs when that
2959
- * transaction, or the savepoint it was queued in, rolls back. An error it throws
2960
- * reaches the caller of the outermost `runInTransaction`, after the commit.
2961
- *
2962
- * @param db - The handle the work ran on: a `tx`, or a database.
2963
- * @param fn - The side effect, such as clearing a cache.
2964
- */
2965
- async function onTransactionCommit(db, fn) {
2966
- const open = joined(db);
2967
- if (open) open.commits.push(fn);
2968
- else await fn();
2969
- }
2970
4967
  // src/events/dispatcher.ts
2971
4968
  function resolveDispatchOptions(options) {
2972
4969
  return {
@@ -3848,8 +5845,8 @@ var EventsHub = class {
3848
5845
  stopping;
3849
5846
  /**
3850
5847
  * @param options - The `events` option.
3851
- * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
3852
- * listeners and workflow steps.
5848
+ * @param deps - The deps of the app's services, which `useDeps()` returns in
5849
+ * its listeners, schedules and workflow steps.
3853
5850
  */
3854
5851
  constructor(options, deps = {}) {
3855
5852
  this.deps = deps;
@@ -4049,10 +6046,10 @@ var EventsHub = class {
4049
6046
  return found;
4050
6047
  }
4051
6048
  bind(table, check) {
4052
- const startAndNotify = () => {
6049
+ const startAndNotify = () => outsideRedaction(() => {
4053
6050
  this.start();
4054
6051
  this.dispatchers.get(table)?.notify();
4055
- };
6052
+ });
4056
6053
  const insert = async (tx, context, name, payload) => {
4057
6054
  check(name, payload);
4058
6055
  const listeners = this.matching(name);
@@ -4112,6 +6109,7 @@ function corsHook(cors) {
4112
6109
  if (allows(from, request)) {
4113
6110
  headers["access-control-allow-origin"] = from;
4114
6111
  if (credentials) headers["access-control-allow-credentials"] = "true";
6112
+ headers["access-control-expose-headers"] = "Retry-After";
4115
6113
  }
4116
6114
  if (!(request.method === "OPTIONS" && request.headers.has("access-control-request-method"))) {
4117
6115
  Object.assign(set.headers, headers);
@@ -4219,6 +6217,8 @@ function defineServiceSocket(service, config, resolve) {
4219
6217
  for (const [path, schema] of [...Object.entries(input).map(([k, v]) => [`input.${k}`, v]), ...Object.entries(output).map(([k, v]) => [`output.${k}`, v])]) {
4220
6218
  serializeSocketSchema(schema, path);
4221
6219
  getCompiledCheck(schema);
6220
+ const at = sensitivePointer(schema);
6221
+ if (at) throw new Error(`Service '${service}' socket '${config.name}': ${path} marks '${at}' t.Sensitive, which sockets do not support yet; keep the secret out of socket messages`);
4222
6222
  }
4223
6223
  const typed = (socket) => socket;
4224
6224
  const error = buildErrorHelpers(config.errors);
@@ -4621,11 +6621,11 @@ function mountSockets(app, sockets, broker, secret) {
4621
6621
  * @param options - `prefix` for action routes (default `/api`), `services`,
4622
6622
  * `title`, `version`, and `description` for the OpenAPI document, `docs` and the
4623
6623
  * paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
4624
- * `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.
6624
+ * `telemetry`, `documentation`, and `dashboard`. See `CreateServerOptions`.
4625
6625
  * @returns The app, with `definition` (its services, prefix, and routes),
4626
6626
  * `endpoint()` to add raw routes, and `listEndpoints()` to list them.
4627
6627
  * @throws When a required secret is missing, `documentation` or `dashboard`
4628
- * is invalid, or `deps` misses a dep a service declares or has one none declares.
6628
+ * is invalid, or `deps` is passed (it moved to `defineService({ deps })`).
4629
6629
  * @example
4630
6630
  * import { brick } from "@brickkit/core";
4631
6631
  * import { pagesService } from "./services/pages";
@@ -4637,6 +6637,7 @@ function mountSockets(app, sockets, broker, secret) {
4637
6637
  * });
4638
6638
  */
4639
6639
  function brick(options = {}) {
6640
+ if ("deps" in options) throw new Error("Brick: brick({ deps }) was removed in 0.16. Move each value into the service that uses it: defineService(name, { deps: { ... } }).");
4640
6641
  const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
4641
6642
  const title = options.title ?? OPENAPI_DEFAULTS.title;
4642
6643
  const version = options.version ?? OPENAPI_DEFAULTS.version;
@@ -4650,10 +6651,18 @@ function brick(options = {}) {
4650
6651
  if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
4651
6652
  const services = options.services ?? getGlobalRegistry().list();
4652
6653
  const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
4653
- app.onRequest(({ request }) => markDashboardArrival(request));
6654
+ const addressSource = {
6655
+ clientIp: options.clientIp,
6656
+ server: () => app.server
6657
+ };
6658
+ app.onRequest(({ request }) => {
6659
+ markDashboardArrival(request);
6660
+ markAddressSource(request, addressSource);
6661
+ });
4654
6662
  if (options.cors) app.onRequest(corsHook(options.cors));
4655
6663
  for (const handler of plugins.middleware) app.onRequest(handler);
4656
6664
  const registeredRoutes = /* @__PURE__ */ new Map();
6665
+ const webhookRoutes = /* @__PURE__ */ new Map();
4657
6666
  const builtIn = (path, handler) => {
4658
6667
  app.get(path, handler);
4659
6668
  registeredRoutes.set(routeKey("GET", path), false);
@@ -4674,15 +6683,17 @@ function brick(options = {}) {
4674
6683
  if ((byName.get(service.name) ?? service) !== service) throw new DuplicateNameError(`Brick: duplicate service "${service.name}" in brick()`);
4675
6684
  byName.set(service.name, service);
4676
6685
  }
4677
- bindDeps(services, options.deps);
4678
6686
  const eventsOptions = plugins.listeners.length ? {
4679
6687
  ...options.events,
4680
6688
  listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
4681
6689
  } : options.events;
4682
- const events = eventsOptions ? new EventsHub(eventsOptions, options.deps).attach(services) : void 0;
6690
+ const events = eventsOptions ? new EventsHub(eventsOptions, appDeps(services)).attach(services) : void 0;
4683
6691
  if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
4684
6692
  if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
4685
6693
  for (const service of services) service.build();
6694
+ for (const service of services) checkFileStorages(service, [portOf(service).deps, ...installedPlugins(service).map(pluginDepsOf)]);
6695
+ const localDirs = localFileDirs([...services.map((service) => portOf(service).deps), ...plugins.deps]);
6696
+ if (localDirs.size) builtIn(LOCAL_FILES_ROUTE, localFilesRoute(localDirs));
4686
6697
  const endpointDefs = [];
4687
6698
  let endpointRevision = 0;
4688
6699
  const buildSpec = () => {
@@ -4720,16 +6731,19 @@ function brick(options = {}) {
4720
6731
  if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new DuplicateNameError(`Brick: duplicate socket route '${socket.path}'`);
4721
6732
  socketRoutes.add(key);
4722
6733
  }
4723
- const mountRoute = (method, path, handler, plugin = false, hook) => {
6734
+ const mountRoute = (method, path, handler, plugin = false, hook, webhook) => {
4724
6735
  const key = routeKey(method, path);
4725
6736
  if (socketRoutes.has(key)) throw new DuplicateNameError(`Brick: route '${method} ${path}' conflicts with a socket`);
4726
6737
  if (registeredRoutes.has(key)) {
6738
+ const other = webhook ?? webhookRoutes.get(key);
6739
+ if (other) throw new DuplicateNameError(`Brick: route '${method} ${path}' is claimed by webhook '${other}' and by another route; a webhook cannot share its route`);
4727
6740
  if (plugin || registeredRoutes.get(key)) throw new DuplicateNameError(`Brick: duplicate plugin route '${method} ${path}'`);
4728
6741
  return false;
4729
6742
  }
4730
6743
  if (hook) app.route(method, path, hook, handler);
4731
6744
  else app.route(method, path, handler);
4732
6745
  registeredRoutes.set(key, plugin);
6746
+ if (webhook) webhookRoutes.set(key, webhook);
4733
6747
  return true;
4734
6748
  };
4735
6749
  const mountEndpoint = (def, plugin = false) => {
@@ -4770,14 +6784,15 @@ function brick(options = {}) {
4770
6784
  if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
4771
6785
  const mountedRoutes = [];
4772
6786
  for (const route of compilation.routes) {
6787
+ const { handler } = route;
4773
6788
  const invoke = (context) => {
4774
6789
  const result = telemetry ? withSpan(`${SPAN.actionPrefix}${route.ir.service}.${route.ir.action}`, {
4775
6790
  [ATTR.service]: route.ir.service,
4776
6791
  [ATTR.action]: route.ir.action
4777
- }, () => route.handler(context)) : route.handler(context);
6792
+ }, () => handler(context)) : handler(context);
4778
6793
  return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
4779
6794
  };
4780
- if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin), route.ir.bodyLimit ? { parse: bodyLimitParser(route.ir.bodyLimit) } : void 0)) mountedRoutes.push(route.ir);
6795
+ if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin), route.ir.kind === "webhook" ? { parse: rawBodyParser(route.ir.bodyLimit) } : route.ir.bodyLimit ? { parse: bodyLimitParser(route.ir.bodyLimit) } : void 0, route.ir.kind === "webhook" ? `${route.ir.service}.${route.ir.action}` : void 0)) mountedRoutes.push(route.ir);
4781
6796
  }
4782
6797
  mountSockets(app, sockets, options.sockets?.broker ?? localBroker(), options.sockets?.secret);
4783
6798
  const definition = Object.freeze({
@@ -4798,13 +6813,14 @@ function brick(options = {}) {
4798
6813
  Object.defineProperty(brickApp, "definition", { value: definition });
4799
6814
  Object.defineProperty(brickApp, "events", { value: events });
4800
6815
  const lifecycle = pluginLifecycle(plugins.lifecycles);
6816
+ const releaseStorages = useStorages([...services.map((service) => portOf(service).deps), ...plugins.deps]);
4801
6817
  const listen = app.listen.bind(app);
4802
6818
  const stop = app.stop.bind(app);
4803
6819
  Object.defineProperty(brickApp, "start", { value: lifecycle.start });
4804
6820
  brickApp.listen = ((...args) => {
4805
6821
  lifecycle.start().catch((error) => {
4806
6822
  console.error("[Brick-TS] A plugin failed to start:", error);
4807
- return stop(true);
6823
+ return Promise.resolve(stop(true)).finally(releaseStorages).catch((stopError) => console.error("[Brick-TS] Stopping after a failed plugin start failed:", stopError));
4808
6824
  });
4809
6825
  return listen(...args);
4810
6826
  });
@@ -4812,7 +6828,11 @@ function brick(options = {}) {
4812
6828
  try {
4813
6829
  await stop(closeActiveConnections);
4814
6830
  } finally {
4815
- await lifecycle.stop();
6831
+ try {
6832
+ await lifecycle.stop();
6833
+ } finally {
6834
+ await releaseStorages();
6835
+ }
4816
6836
  }
4817
6837
  });
4818
6838
  Object.defineProperty(brickApp, "serve", { value: async ({ port }) => {
@@ -4861,6 +6881,6 @@ function cachedJsonRoute(build, revision) {
4861
6881
  return json;
4862
6882
  };
4863
6883
  }
4864
- export { segmentClaimant as $, WORKFLOW_BUNDLE as A, requireBrickApp as B, getActionAccess as C, bindCompiledApplication as D, resetGlobalRegistry as E, crudEventName as F, port as G, claimName as H, crudEventSource as I, defineServicePlugin as J, useDeps as K, eventRefs as L, defineListener as M, checkEvent as N, compileBrickApplication as O, checkPayload as P, isInstallingPlugin as Q, isCrudEvent as R, generateOpenApiSpec as S, getGlobalRegistry as T, definitionSite as U, createActionHandler as V, INTERNALS as W, hasPlugin as X, getPluginEndpoints as Y, installPlugin as Z, envSource as _, withCallSpan as _t, defineSchedule as a, deny as at, resetSecrets as b, runInTransaction as c, DASHBOARD_IDENTITY_HEADER as ct, referencePlugin as d, dashboardUser as dt, validateName as et, registerReferenceRoute as f, signDashboardIdentity as ft, defineSecret as g, traceRoute as gt, SecretRef as h, validateWithSchema as ht, stopAllEvents as i, errorsOf as it, resolveWorkflowPaths as j, loadCompiledBrickApp as k, isOutboxTable as l, DASHBOARD_KEY_ENV as lt, requestLoggingPlugin as m, fileFields as mt, defineServiceSocket as n, buildErrorHelpers as nt, Dispatcher as o, baseContext as ot, scalarDocsHTML as p, Type$1 as pt, defineResourcePlugin as q, recordingServices as r, defineAction as rt, onTransactionCommit as s, pickContextEnvelope as st, brick as t, portOf as tt, outboxTable as u, dashboardKey as ut, listSecrets as v, PLUGIN_COMMIT as vt, setActionAccess as w, resolveSecrets as x, overrideSecret as y, PLUGIN_KIND as yt, isBrickApp as z };
6884
+ export { recordInline as $, isCrudEvent as A, definitionSite as At, isInstallingPlugin as B, signDashboardIdentity as Bt, resolveWorkflowPaths as C, defineSecret as Ct, crudEventName as D, resetSecrets as Dt, checkPayload as E, overrideSecret as Et, defineResourcePlugin as F, hasIdentity as Ft, errorsOf as G, withCallSpan as Gt, validateName as H, fileFields as Ht, defineServicePlugin as I, DASHBOARD_IDENTITY_HEADER as It, auditTable as J, isSensitive as Jt, deny as K, Sensitive as Kt, getPluginEndpoints as L, DASHBOARD_KEY_ENV as Lt, requireBrickApp as M, freezeAsBuiltDeps as Mt, createActionHandler as N, useDeps as Nt, crudEventSource as O, resolveSecrets as Ot, INTERNALS as P, portOf as Pt, recordAudit as Q, PLUGIN_KIND as Qt, hasPlugin as R, dashboardKey as Rt, WORKFLOW_BUNDLE as S, SecretRef as St, checkEvent as T, listSecrets as Tt, buildErrorHelpers as U, validateWithSchema as Ut, segmentClaimant as V, Type as Vt, defineAction as W, traceRoute as Wt, inlineAudit as X, sensitivity as Xt, entryOf as Y, redact as Yt, isAuditTable as Z, PLUGIN_COMMIT as Zt, getGlobalRegistry as _, redis as _t, defineSchedule as a, webhookOf as at, compileBrickApplication as b, s3 as bt, outboxTable as c, pickContextEnvelope as ct, scalarDocsHTML as d, clientAddress as dt, onTransactionCommit as et, requestLoggingPlugin as f, rateLimitsOf as ft, setActionAudit as g, memory as gt, setActionAccess as h, defineStorage as ht, stopAllEvents as i, isWebhook as it, isBrickApp as j, depsOverride as jt, eventRefs as k, claimName as kt, referencePlugin as l, resolvedDeps as lt, getActionAccess as m, StorageUnavailableError as mt, defineServiceSocket as n, checkWebhook as nt, Dispatcher as o, baseContext as ot, generateOpenApiSpec as p, withClientIp as pt, auditStage as q, hasSensitive as qt, recordingServices as r, defineWebhookMeta as rt, isOutboxTable as s, markResolved as st, brick as t, runInTransaction as tt, registerReferenceRoute as u, checkRateLimits as ut, resetGlobalRegistry as v, redisBroker as vt, defineListener as w, envSource as wt, loadCompiledBrickApp as x, scopeFiles as xt, bindCompiledApplication as y, hasFilesView as yt, installPlugin as z, dashboardUser as zt };
4865
6885
 
4866
6886
  //# sourceMappingURL=server.js.map