@brickkit/core 0.13.3 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
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";
2
2
  import { createRequire } from "node:module";
3
3
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
4
- import { Type, Type as t } from "@sinclair/typebox";
4
+ import { Kind, Type, TypeRegistry } from "@sinclair/typebox";
5
5
  import { TypeCompiler } from "@sinclair/typebox/compiler";
6
6
  import { formatWithOptions } from "node:util";
7
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
7
8
  import { join, resolve } from "node:path";
8
9
  import { fileURLToPath, pathToFileURL } from "node:url";
9
- import { and, asc, eq, inArray, lt, lte, or, sql } from "drizzle-orm";
10
+ import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
10
11
  import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
11
12
  import { bigserial, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
12
13
  import { existsSync, readFileSync } from "node:fs";
13
14
  import { AsyncLocalStorage } from "node:async_hooks";
14
15
  import { Elysia } from "elysia";
15
- import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
16
16
  import { websocket } from "elysia/websocket";
17
17
  // src/plugin-types.ts
18
18
  /** Where a plugin route mounts: under the app prefix, its service, or its resource. */
@@ -307,6 +307,59 @@ function buildErrorEnvelope(err, context) {
307
307
  };
308
308
  }
309
309
  // src/typebox.ts
310
+ /**
311
+ * Any JSON value: null, boolean, number, string, or an array or object of
312
+ * JSON values.
313
+ */
314
+ 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)
322
+ ]), options);
323
+ }
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. */
326
+ function File(options = {}) {
327
+ return Type.Unsafe({
328
+ [Kind]: "File",
329
+ type: "string",
330
+ format: "binary",
331
+ ...options
332
+ });
333
+ }
334
+ /** Several files under one form field. */
335
+ function Files(options = {}) {
336
+ const { minItems, maxItems, ...file } = options;
337
+ return Type.Array(File(file), {
338
+ minItems,
339
+ maxItems
340
+ });
341
+ }
342
+ /** TypeBox's `Type` plus Brick's `Json`, `File` and `Files`. */
343
+ const Type$1 = Object.assign({}, Type, {
344
+ Json,
345
+ File,
346
+ Files
347
+ });
348
+ function fileFields(schema) {
349
+ const fields = [];
350
+ const properties = schema?.properties;
351
+ for (const [key, prop] of Object.entries(properties ?? {})) {
352
+ const file = prop[Kind] === "File" ? prop : prop.items;
353
+ if (file?.[Kind] !== "File") continue;
354
+ const count = file === prop ? 1 : prop.maxItems;
355
+ const maxBytes = file.maxSize === void 0 || count === void 0 ? void 0 : file.maxSize * count;
356
+ fields.push({
357
+ key,
358
+ maxBytes
359
+ });
360
+ }
361
+ return fields;
362
+ }
310
363
  const compilerCache = /* @__PURE__ */ new WeakMap();
311
364
  /**
312
365
  * The compiled validator for a TypeBox schema. Compiling is slow and checking
@@ -446,6 +499,69 @@ const DEFAULT_LOG_PREFIXES = {
446
499
  error: "[ERROR]",
447
500
  debug: "[DEBUG]"
448
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];
515
+ }
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");
523
+ }
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());
528
+ }
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")}`;
537
+ }
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
+ }
555
+ }
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;
564
+ }
449
565
  // src/context.ts
450
566
  const DEFAULT_REQUEST = new Request("http://localhost");
451
567
  const EMPTY = Object.freeze({});
@@ -481,7 +597,8 @@ function baseContext(fields) {
481
597
  requestId: fields.requestId ?? newId("req"),
482
598
  services: fields.services ?? EMPTY,
483
599
  metadata: fields.metadata ?? EMPTY,
484
- deps: fields.deps ?? EMPTY
600
+ deps: fields.deps ?? EMPTY,
601
+ dashboard: fields.dashboard ?? dashboardIdentity(fields.request)
485
602
  };
486
603
  }
487
604
  function pickContextEnvelope(context) {
@@ -492,6 +609,7 @@ function pickContextEnvelope(context) {
492
609
  if (context.traceId !== void 0) envelope.traceId = context.traceId;
493
610
  if (context.requestId !== void 0) envelope.requestId = context.requestId;
494
611
  if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
612
+ if (context.dashboard !== void 0) envelope.dashboard = context.dashboard;
495
613
  return envelope;
496
614
  }
497
615
  // src/compiler/runtime.ts
@@ -508,28 +626,47 @@ function mergeInput(first, second, third) {
508
626
  if (c && !a && !b) return third;
509
627
  if (a || b || c) return Object.assign({}, first, second, third);
510
628
  }
511
- function coerceQueryValue(value, type, request, key) {
629
+ function coerceScalar(value, type) {
630
+ if (typeof value !== "string") return value;
512
631
  if (type === "number") {
513
632
  const number = Number(value);
514
633
  return Number.isNaN(number) ? value : number;
515
634
  }
516
- if (type === "array") {
517
- const values = request ? new URL(request.url).searchParams.getAll(key) : [];
518
- return values.length ? values : Array.isArray(value) ? value : [value];
635
+ if (type === "boolean") {
636
+ if (value === "true" || value === "1") return true;
637
+ if (value === "false" || value === "0") return false;
638
+ }
639
+ if (type === "json") try {
640
+ return JSON.parse(value);
641
+ } catch {
642
+ return value;
519
643
  }
520
- if (value === "true" || value === "1") return true;
521
- if (value === "false" || value === "0") return false;
522
644
  return value;
523
645
  }
646
+ function coerceQueryValue(value, { key, type, items }, request) {
647
+ if (type !== "array") return coerceScalar(value, type);
648
+ const values = request ? new URL(request.url).searchParams.getAll(key) : [];
649
+ return (values.length ? values : Array.isArray(value) ? value : [value]).map((item) => coerceScalar(item, items));
650
+ }
651
+ const BODY_TOO_LARGE = Symbol("brick.bodyTooLarge");
652
+ function bodyLimitParser(limit) {
653
+ return ({ request }) => Number(request.headers.get("content-length")) > limit ? BODY_TOO_LARGE : void 0;
654
+ }
524
655
  /** The action's input from the path, query and body, coerced by its schema. */
525
656
  function readInput(route, { params, body, query, request }) {
657
+ if (body === BODY_TOO_LARGE) throw new ActionExecutionError("PAYLOAD_TOO_LARGE", `Request body exceeds ${route.bodyLimit} bytes`, 413);
526
658
  if (!route.input) return void 0;
527
659
  let coercedQuery = query;
528
660
  let coercedParams = params;
661
+ let coercedBody = body;
529
662
  if (route.coercions.length) {
530
663
  if (query) {
531
664
  coercedQuery = { ...query };
532
- for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
665
+ for (const coercion of route.coercions) if (query[coercion.key] !== void 0) coercedQuery[coercion.key] = coerceQueryValue(query[coercion.key], coercion, request);
666
+ }
667
+ if (body && request?.headers.get("content-type")?.startsWith("multipart/form-data")) {
668
+ coercedBody = { ...body };
669
+ for (const coercion of route.coercions) if (body[coercion.key] !== void 0) coercedBody[coercion.key] = coerceQueryValue(body[coercion.key], coercion, void 0);
533
670
  }
534
671
  for (const { key, type } of route.coercions) {
535
672
  if (type !== "number" || typeof params?.[key] !== "string") continue;
@@ -539,7 +676,7 @@ function readInput(route, { params, body, query, request }) {
539
676
  coercedParams[key] = value;
540
677
  }
541
678
  }
542
- const input = route.readLike ? mergeInput(coercedQuery, coercedParams, body) : mergeInput(coercedParams, body, coercedQuery);
679
+ const input = route.readLike ? mergeInput(coercedQuery, coercedParams, coercedBody) : mergeInput(coercedParams, coercedBody, coercedQuery);
543
680
  return input === void 0 && route.inputSchema?.type === "object" ? {} : input;
544
681
  }
545
682
  const MAX_INPUT_DEPTH = 128;
@@ -597,6 +734,7 @@ async function authorizeCall(authorize, ctx, input, action) {
597
734
  }
598
735
  /** The stage order of every call, over HTTP and in-process: check input → authorize → execute → check output. */
599
736
  async function runStages(stages, input, ctx) {
737
+ if (stages.dashboardOnly && !ctx.dashboard) throw new ActionExecutionError("UNAUTHORIZED", `Action '${stages.name}' is only for the dashboard`, 401);
600
738
  stages.checkInput(input);
601
739
  await authorizeCall(stages.authorize, ctx, input, stages.name);
602
740
  return stages.checkOutput(await stages.execute({
@@ -628,6 +766,7 @@ function bindRoute(plan) {
628
766
  const name = route.action;
629
767
  const stages = {
630
768
  name,
769
+ dashboardOnly: plan.action.config.dashboard === true,
631
770
  checkInput: (input) => {
632
771
  if (inputChecker) validateInput(inputChecker, input, name, checkInput);
633
772
  },
@@ -639,10 +778,10 @@ function bindRoute(plan) {
639
778
  return result;
640
779
  }
641
780
  };
642
- if (contextHook || authorize) return async function brickAction(context) {
643
- const input = readInput(route, context);
781
+ if (contextHook || authorize || stages.dashboardOnly) return async function brickAction(context) {
644
782
  const ctx = requestContext(plan, context);
645
783
  try {
784
+ const input = readInput(route, context);
646
785
  if (contextHook) {
647
786
  const extra = await contextHook(ctx);
648
787
  if (extra) Object.assign(ctx, extra);
@@ -654,9 +793,9 @@ function bindRoute(plan) {
654
793
  }
655
794
  };
656
795
  return function brickAction(context) {
657
- const input = readInput(route, context);
658
796
  const ctx = requestContext(plan, context);
659
797
  try {
798
+ const input = readInput(route, context);
660
799
  stages.checkInput(input);
661
800
  const result = execute({
662
801
  input,
@@ -726,6 +865,7 @@ function defineAction(config) {
726
865
  };
727
866
  const stages = {
728
867
  name: config.name,
868
+ dashboardOnly: config.dashboard === true,
729
869
  checkInput: (input) => {
730
870
  if (!config.input) return;
731
871
  const checked = actionFn.validateInput(input);
@@ -1268,6 +1408,13 @@ function claimName(sites, label, name, site) {
1268
1408
  sites.set(name, site);
1269
1409
  }
1270
1410
  // src/compiler/ir.ts
1411
+ const FORM_FIELDS_AND_FRAMING_BYTES = 1048576;
1412
+ function coercionOf(schema) {
1413
+ if (schema?.type === "number" || schema?.type === "integer") return "number";
1414
+ if (schema?.type === "boolean") return "boolean";
1415
+ if (schema?.type === "array") return "array";
1416
+ if (schema?.type === "object") return "json";
1417
+ }
1271
1418
  function freezeIR(value) {
1272
1419
  if (value && typeof value === "object" && !Object.isFrozen(value)) {
1273
1420
  for (const child of Object.values(value)) freezeIR(child);
@@ -1356,19 +1503,22 @@ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1356
1503
  /** What the compiler records about one action route. */
1357
1504
  function describeRoute(service, action, method, path) {
1358
1505
  const coercions = [];
1359
- for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
1360
- key,
1361
- type: "number"
1362
- });
1363
- else if (prop.type === "boolean") coercions.push({
1364
- key,
1365
- type: "boolean"
1366
- });
1367
- else if (prop.type === "array") coercions.push({
1368
- key,
1369
- type: "array"
1370
- });
1506
+ for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) {
1507
+ const type = coercionOf(prop);
1508
+ if (!type) continue;
1509
+ const items = type === "array" ? coercionOf(prop.items) : void 0;
1510
+ coercions.push(items && items !== "array" ? {
1511
+ key,
1512
+ type,
1513
+ items
1514
+ } : {
1515
+ key,
1516
+ type
1517
+ });
1518
+ }
1371
1519
  const plugin = actionMeta(action).route?.plugin;
1520
+ 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;
1372
1522
  return {
1373
1523
  method,
1374
1524
  path,
@@ -1383,6 +1533,7 @@ function describeRoute(service, action, method, path) {
1383
1533
  readLike: isReadLike(method, action.name),
1384
1534
  inputSource: inputSource(method),
1385
1535
  coercions,
1536
+ ...bodyLimit === void 0 ? {} : { bodyLimit },
1386
1537
  inputSchema: schemaSnapshot(action.config.input),
1387
1538
  outputSchema: schemaSnapshot(action.config.output)
1388
1539
  };
@@ -1631,6 +1782,19 @@ var WorkflowRuntime = class {
1631
1782
  });
1632
1783
  }
1633
1784
  /**
1785
+ * Start the workflow of a schedule's run. The workflow run is named after
1786
+ * the run key, so a run that is tried again does not start another.
1787
+ */
1788
+ async startScheduled(schedule, run) {
1789
+ const sdk = await this.ensure();
1790
+ const { attempt: _attempt, ...workflowRun } = run;
1791
+ await sdk.start(schedule.workflow, [workflowRun], {
1792
+ world: this.world,
1793
+ runKey: `schedule:${run.runKey}`,
1794
+ runKeyTime: Date.parse(run.slot)
1795
+ });
1796
+ }
1797
+ /**
1634
1798
  * Answer a request to a webhook a workflow created with `createWebhook`, by
1635
1799
  * resuming the workflow that waits on it. Needs the world but not the queue
1636
1800
  * consumer, so a process that only records events (`dispatch: false`) serves
@@ -2055,6 +2219,7 @@ function generateOpenApiSpec(options = {}) {
2055
2219
  addError("UNAUTHORIZED", 401, "Authentication required");
2056
2220
  addError("FORBIDDEN", 403, "Access denied");
2057
2221
  }
2222
+ if (action.config.dashboard === true) addError("UNAUTHORIZED", 401, "Only for the dashboard");
2058
2223
  if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
2059
2224
  const def = errorDef;
2060
2225
  addError(code, def.status || 400, def.message || code, def.details);
@@ -2087,14 +2252,17 @@ function generateOpenApiSpec(options = {}) {
2087
2252
  schema
2088
2253
  });
2089
2254
  }
2090
- else if (inputSchema) operation.requestBody = {
2091
- required: true,
2092
- content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
2255
+ else if (inputSchema) {
2256
+ const bodySchema = pathParams.length && inputSchema.properties ? {
2093
2257
  ...inputSchema,
2094
2258
  properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
2095
2259
  required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
2096
- } : inputSchema } }
2097
- };
2260
+ } : inputSchema;
2261
+ operation.requestBody = {
2262
+ required: true,
2263
+ content: { [fileFields(inputSchema).length ? "multipart/form-data" : "application/json"]: { schema: bodySchema } }
2264
+ };
2265
+ }
2098
2266
  if (parameters.length) operation.parameters = parameters;
2099
2267
  if (hasAuth) operation.security = [{ bearerAuth: [] }];
2100
2268
  paths[actionPath][method] = operation;
@@ -2358,10 +2526,11 @@ function requestLoggingPlugin(opts = {}) {
2358
2526
  const markStarted = ({ request }) => {
2359
2527
  startedAt.set(request, Date.now());
2360
2528
  };
2361
- const logSuccess = ({ request, set }) => {
2529
+ const logSuccess = ({ request, set, responseValue }) => {
2362
2530
  const start = startedAt.get(request) ?? Date.now();
2363
2531
  const path = new URL(request.url).pathname;
2364
- logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
2532
+ const status = responseValue instanceof Response ? responseValue.status : set.status ?? 200;
2533
+ logger(formatLog(request.method, path, status, Date.now() - start));
2365
2534
  };
2366
2535
  const logError = ({ request, set, error }) => {
2367
2536
  if (request) {
@@ -3039,6 +3208,609 @@ var Dispatcher = class {
3039
3208
  await this.db.delete(t).where(and(eq(t.status, "delivered"), lt(t.deliveredAt, new Date(now - keep))));
3040
3209
  }
3041
3210
  };
3211
+ // src/schedules/cron.ts
3212
+ const MACROS = {
3213
+ "@yearly": "0 0 1 1 *",
3214
+ "@annually": "0 0 1 1 *",
3215
+ "@monthly": "0 0 1 * *",
3216
+ "@weekly": "0 0 * * 0",
3217
+ "@daily": "0 0 * * *",
3218
+ "@midnight": "0 0 * * *",
3219
+ "@hourly": "0 * * * *"
3220
+ };
3221
+ const MONTH_NAMES = "jan feb mar apr may jun jul aug sep oct nov dec".split(" ");
3222
+ const DAY_NAMES = "sun mon tue wed thu fri sat".split(" ");
3223
+ function parseField(field, min, max, names = [], nameBase = 0) {
3224
+ const value = (text) => {
3225
+ const named = names.indexOf(text.toLowerCase());
3226
+ if (named >= 0) return named + nameBase;
3227
+ if (!/^\d+$/.test(text)) throw new Error(`'${text}' is not a number`);
3228
+ const number = Number(text);
3229
+ if (number < min || number > max) throw new Error(`${number} is outside ${min}-${max}`);
3230
+ return number;
3231
+ };
3232
+ const values = /* @__PURE__ */ new Set();
3233
+ for (const part of field.split(",")) {
3234
+ const [range, stepText, extra] = part.split("/");
3235
+ if (extra !== void 0 || !range) throw new Error(`'${part}' is not a valid field`);
3236
+ const step = stepText === void 0 ? 1 : Number(stepText);
3237
+ if (!Number.isInteger(step) || step < 1) throw new Error(`'${stepText}' is not a valid step`);
3238
+ let from;
3239
+ let to;
3240
+ if (range === "*") [from, to] = [min, max];
3241
+ else if (range.includes("-")) {
3242
+ const [a, b, extra] = range.split("-");
3243
+ if (extra !== void 0) throw new Error(`'${range}' is not a valid range`);
3244
+ [from, to] = [value(a), value(b)];
3245
+ if (from > to) throw new Error(`'${range}' runs backwards`);
3246
+ } else {
3247
+ from = value(range);
3248
+ to = stepText === void 0 ? from : max;
3249
+ }
3250
+ for (let v = from; v <= to; v += step) values.add(v);
3251
+ }
3252
+ return {
3253
+ values,
3254
+ star: field.startsWith("*") || field.startsWith("?")
3255
+ };
3256
+ }
3257
+ /**
3258
+ * Parse a cron expression.
3259
+ *
3260
+ * @throws When the expression is malformed.
3261
+ */
3262
+ function parseCron(expression) {
3263
+ const source = expression.trim();
3264
+ const fields = (MACROS[source.toLowerCase()] ?? source).split(/\s+/);
3265
+ if (fields.length === 5) fields.unshift("0");
3266
+ if (fields.length !== 6) throw new Error(`Cron expression '${expression}' needs 5 fields (minute hour day month weekday), or 6 with seconds first`);
3267
+ const [sec, min, hour, day, month, weekday] = fields;
3268
+ try {
3269
+ const days = parseField(day.replace("?", "*"), 1, 31);
3270
+ const weekdays = parseField(weekday.replace("?", "*"), 0, 7, DAY_NAMES);
3271
+ if (weekdays.values.delete(7)) weekdays.values.add(0);
3272
+ return {
3273
+ source,
3274
+ seconds: parseField(sec, 0, 59).values,
3275
+ minutes: parseField(min, 0, 59).values,
3276
+ hours: parseField(hour, 0, 23).values,
3277
+ days: days.values,
3278
+ months: parseField(month, 1, 12, MONTH_NAMES, 1).values,
3279
+ weekdays: weekdays.values,
3280
+ eitherDay: !days.star && !weekdays.star
3281
+ };
3282
+ } catch (error) {
3283
+ throw new Error(`Cron expression '${expression}': ${error.message}`);
3284
+ }
3285
+ }
3286
+ const formatters = /* @__PURE__ */ new Map();
3287
+ /**
3288
+ * @throws When `timeZone` is not an IANA time zone this runtime knows.
3289
+ */
3290
+ function checkTimeZone(timeZone) {
3291
+ formatter(timeZone);
3292
+ }
3293
+ function formatter(timeZone) {
3294
+ let found = formatters.get(timeZone);
3295
+ if (!found) {
3296
+ try {
3297
+ found = new Intl.DateTimeFormat("en-US", {
3298
+ timeZone,
3299
+ hourCycle: "h23",
3300
+ year: "numeric",
3301
+ month: "numeric",
3302
+ day: "numeric",
3303
+ hour: "numeric",
3304
+ minute: "numeric",
3305
+ second: "numeric"
3306
+ });
3307
+ } catch {
3308
+ throw new Error(`Unknown time zone '${timeZone}'`);
3309
+ }
3310
+ formatters.set(timeZone, found);
3311
+ }
3312
+ return found;
3313
+ }
3314
+ /** The wall-clock time at `instant` in `timeZone`, as if it were UTC (whole seconds). */
3315
+ function wallClock(instant, timeZone) {
3316
+ const parts = {};
3317
+ for (const part of formatter(timeZone).formatToParts(instant)) if (part.type !== "literal") parts[part.type] = Number(part.value);
3318
+ return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
3319
+ }
3320
+ const DAY_MS = 864e5;
3321
+ /** The offset of `timeZone` from UTC at `instant`, in milliseconds. */
3322
+ const offsetAt = (instant, timeZone) => wallClock(instant, timeZone) - Math.floor(instant / 1e3) * 1e3;
3323
+ /**
3324
+ * The first instant whose wall-clock time in `timeZone` is `wall`, or, when
3325
+ * a DST change skips `wall`, the instant the clocks jump past it, shifted by
3326
+ * the gap.
3327
+ */
3328
+ function instantOf(wall, timeZone) {
3329
+ const before = wall - offsetAt(wall - DAY_MS, timeZone);
3330
+ const valid = [before, wall - offsetAt(wall + DAY_MS, timeZone)].filter((instant) => wallClock(instant, timeZone) === wall);
3331
+ return valid.length ? Math.min(...valid) : before;
3332
+ }
3333
+ function dayMatches(cron, date) {
3334
+ const day = cron.days.has(date.getUTCDate());
3335
+ const weekday = cron.weekdays.has(date.getUTCDay());
3336
+ return cron.eitherDay ? day || weekday : day && weekday;
3337
+ }
3338
+ /** The first wall-clock time at or after `wall` that the expression matches, or undefined within eight years. */
3339
+ function nextWall(cron, wall) {
3340
+ const d = new Date(wall);
3341
+ const limit = d.getUTCFullYear() + 8;
3342
+ while (d.getUTCFullYear() <= limit) if (!cron.months.has(d.getUTCMonth() + 1)) {
3343
+ d.setUTCMonth(d.getUTCMonth() + 1, 1);
3344
+ d.setUTCHours(0, 0, 0);
3345
+ } else if (!dayMatches(cron, d)) {
3346
+ d.setUTCDate(d.getUTCDate() + 1);
3347
+ d.setUTCHours(0, 0, 0);
3348
+ } else if (!cron.hours.has(d.getUTCHours())) d.setUTCHours(d.getUTCHours() + 1, 0, 0);
3349
+ else if (!cron.minutes.has(d.getUTCMinutes())) d.setUTCMinutes(d.getUTCMinutes() + 1, 0);
3350
+ else if (!cron.seconds.has(d.getUTCSeconds())) d.setUTCSeconds(d.getUTCSeconds() + 1);
3351
+ else return d.getTime();
3352
+ }
3353
+ /**
3354
+ * The first time after `after` that the expression fires in `timeZone`.
3355
+ *
3356
+ * @returns The instant, or `undefined` when it never fires (`0 0 31 2 *`).
3357
+ */
3358
+ function nextCron(cron, after, timeZone = "UTC") {
3359
+ const from = after.getTime();
3360
+ let wall = wallClock(from, timeZone) + 1e3;
3361
+ for (;;) {
3362
+ const found = nextWall(cron, wall);
3363
+ if (found === void 0) return void 0;
3364
+ const instant = instantOf(found, timeZone);
3365
+ if (instant > from) return new Date(instant);
3366
+ wall = found + 1e3;
3367
+ }
3368
+ }
3369
+ /** A century: well inside what a `Date` can hold after any due time. */
3370
+ const MAX_DURATION_MS = 36600 * DAY_MS;
3371
+ const UNITS = {
3372
+ ms: 1,
3373
+ s: 1e3,
3374
+ m: 6e4,
3375
+ h: 36e5,
3376
+ d: DAY_MS
3377
+ };
3378
+ /**
3379
+ * A duration in milliseconds: a number of milliseconds, or text such as
3380
+ * `"90s"`, `"15m"`, `"6h"`, `"1d"` or `"1h30m"`.
3381
+ *
3382
+ * @throws When it is not a positive duration (or zero, with `allowZero`), or
3383
+ * is longer than a century.
3384
+ */
3385
+ function parseDuration(duration, options = {}) {
3386
+ let ms = 0;
3387
+ if (typeof duration === "number") ms = duration;
3388
+ else {
3389
+ const text = duration.replace(/\s+/g, "");
3390
+ const pattern = /(\d+(?:\.\d+)?)(ms|s|m|h|d)/gy;
3391
+ let match;
3392
+ let read = 0;
3393
+ while (match = pattern.exec(text)) {
3394
+ ms += Number(match[1]) * UNITS[match[2]];
3395
+ read = pattern.lastIndex;
3396
+ }
3397
+ if (!text || read !== text.length) ms = NaN;
3398
+ }
3399
+ const rounded = Math.round(ms);
3400
+ if (!Number.isFinite(rounded) || rounded < (options.allowZero ? 0 : 1) || rounded > MAX_DURATION_MS) throw new Error(`'${duration}' is not a duration: use milliseconds or text such as "15m", "6h" or "1h30m"`);
3401
+ return rounded;
3402
+ }
3403
+ // src/schedules/schedule.ts
3404
+ /**
3405
+ * Define a schedule: code that runs at set times, in one process among all
3406
+ * those that run the app. Pass it to `brick({ events: { schedules } })`.
3407
+ *
3408
+ * It runs either on a `cron` expression, at fixed wall-clock times in a time
3409
+ * zone, or `every` so long, counted from the end of the last successful run.
3410
+ * State lives in the app's `scheduleTable()`, so a due time runs once however
3411
+ * many processes there are, and a restart or deploy carries on where it
3412
+ * stopped. A due time counts as done only once its run succeeds: a run that
3413
+ * throws is retried with a growing delay, and one whose process died is taken
3414
+ * over by another process. A run is never started while the last one is still
3415
+ * running; due times that pass in the meantime are skipped.
3416
+ *
3417
+ * @param config - `name`, `cron` (and `timeZone`) or `every`, `run` or
3418
+ * `workflow`, and optionally `catchUp`, `maxAttempts`, `backoff`, `jitter` and
3419
+ * `enabled`.
3420
+ * @returns The schedule.
3421
+ * @throws When the name is empty or contains `:`, the cron expression or time
3422
+ * zone is invalid, or the schedule has both or neither of `cron` and `every`,
3423
+ * or of `run` and `workflow`.
3424
+ * @example
3425
+ * import { brick, defineSchedule } from "@brickkit/core";
3426
+ *
3427
+ * const backup = defineSchedule({
3428
+ * name: "db-backup",
3429
+ * cron: "0 *\/6 * * *",
3430
+ * timeZone: "Europe/Berlin",
3431
+ * run: () => backupDatabase(),
3432
+ * });
3433
+ *
3434
+ * export default brick({ services, events: { schedules: [backup] } });
3435
+ */
3436
+ function defineSchedule(config) {
3437
+ const { name } = config;
3438
+ if (typeof name !== "string" || !name) throw new Error("A schedule needs a name");
3439
+ if (name.includes(":")) throw new Error(`Schedule name '${name}' must not contain ':'`);
3440
+ const fail = (message) => {
3441
+ throw new Error(`Schedule '${name}': ${message}`);
3442
+ };
3443
+ const attempt = (fn) => {
3444
+ try {
3445
+ return fn();
3446
+ } catch (error) {
3447
+ return fail(error.message);
3448
+ }
3449
+ };
3450
+ /** A duration that may also be 0: none. */
3451
+ const optionalDuration = (value, fallback) => value === void 0 ? fallback : attempt(() => parseDuration(value, { allowZero: true }));
3452
+ if (config.cron === void 0 === (config.every === void 0)) fail("give it a cron expression or an interval (every), not both");
3453
+ if (config.run === void 0 === (config.workflow === void 0)) fail("give it a run handler or a workflow, not both");
3454
+ if (config.run !== void 0 && typeof config.run !== "function") fail("run must be a function");
3455
+ if (config.workflow !== void 0 && typeof config.workflow !== "function") fail("workflow must be a function marked \"use workflow\"");
3456
+ const maxAttempts = config.maxAttempts ?? 3;
3457
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) fail("maxAttempts must be a positive integer");
3458
+ if (config.catchUp !== void 0 && !["once", "skip"].includes(config.catchUp)) fail("catchUp must be \"once\" or \"skip\"");
3459
+ let when;
3460
+ if (config.cron !== void 0) {
3461
+ const timeZone = config.timeZone ?? "UTC";
3462
+ const cron = attempt(() => parseCron(config.cron));
3463
+ attempt(() => checkTimeZone(timeZone));
3464
+ if (!nextCron(cron, /* @__PURE__ */ new Date(), timeZone)) fail(`cron expression '${config.cron}' never fires`);
3465
+ when = {
3466
+ cron,
3467
+ timeZone,
3468
+ spec: `cron ${cron.source} ${timeZone}`
3469
+ };
3470
+ } else {
3471
+ const every = attempt(() => parseDuration(config.every));
3472
+ when = {
3473
+ every,
3474
+ spec: `every ${every}`
3475
+ };
3476
+ }
3477
+ return Object.freeze({
3478
+ name,
3479
+ ...when,
3480
+ catchUp: config.catchUp ?? "once",
3481
+ maxAttempts,
3482
+ backoffMs: optionalDuration(config.backoff, 6e4),
3483
+ jitterMs: optionalDuration(config.jitter, 0),
3484
+ enabled: config.enabled ?? true,
3485
+ ...config.run ? { run: config.run } : {},
3486
+ ...config.workflow ? { workflow: config.workflow } : {}
3487
+ });
3488
+ }
3489
+ /**
3490
+ * The first due time of `schedule` after `after`, before jitter: the next
3491
+ * cron time, or `after` plus the interval. `undefined` when the cron
3492
+ * expression fires no more.
3493
+ */
3494
+ function nextDue(schedule, after) {
3495
+ return schedule.cron ? nextCron(schedule.cron, after, schedule.timeZone) : new Date(after.getTime() + schedule.every);
3496
+ }
3497
+ // src/schedules/scheduler.ts
3498
+ /** A due time this late, on its first try, counts as missed for `catchUp: "skip"`. */
3499
+ const MISSED_AFTER_MS = 6e4;
3500
+ /** Runs kept per schedule. */
3501
+ const KEEP_RUNS = 20;
3502
+ const ABANDONED = "The process running it stopped before it finished";
3503
+ /**
3504
+ * Runs an app's schedules from one schedule table, shared by every process
3505
+ * that runs the app.
3506
+ *
3507
+ * Each schedule has one row. A process claims a due row with a conditional
3508
+ * update (due, and not held by a live claim), so one process wins each due
3509
+ * time, on Postgres and SQLite alike. While it runs, the process renews its
3510
+ * claim; a process that dies stops renewing, and after `claimTimeoutMs`
3511
+ * another process takes the due time over. On Postgres claims are timed by
3512
+ * the database's clock, so hosts whose clocks disagree still agree on them. Only success (or giving up after
3513
+ * `maxAttempts`) moves the row to the next due time.
3514
+ */
3515
+ var Scheduler = class {
3516
+ db;
3517
+ table;
3518
+ runner;
3519
+ options;
3520
+ byName;
3521
+ inFlight = /* @__PURE__ */ new Map();
3522
+ timer;
3523
+ tickQueue;
3524
+ synced;
3525
+ postgres;
3526
+ constructor(db, table, schedules, runner, options) {
3527
+ this.db = db;
3528
+ this.table = table;
3529
+ this.runner = runner;
3530
+ this.options = options;
3531
+ this.byName = new Map(schedules.map((s) => [s.name, s]));
3532
+ this.postgres = !isSqliteDatabase(db);
3533
+ }
3534
+ start() {
3535
+ if (this.timer || !this.options.timer) return;
3536
+ this.timer = setInterval(() => void this.tick(), this.options.intervalMs);
3537
+ this.timer.unref?.();
3538
+ this.tick();
3539
+ }
3540
+ /** Stop the timer and wait for the runs in progress. */
3541
+ async stop() {
3542
+ if (this.timer) clearInterval(this.timer);
3543
+ this.timer = void 0;
3544
+ await this.tickQueue;
3545
+ await Promise.allSettled(this.inFlight.values());
3546
+ }
3547
+ /**
3548
+ * Run what is due now and wait for it. Retries that are not due yet are not
3549
+ * waited for. For tests and for workers driven by hand.
3550
+ *
3551
+ * @returns How many runs it started.
3552
+ */
3553
+ async drain() {
3554
+ let total = 0;
3555
+ for (;;) {
3556
+ const started = await this.tick();
3557
+ await Promise.allSettled(this.inFlight.values());
3558
+ if (started === 0) return total;
3559
+ total += started;
3560
+ }
3561
+ }
3562
+ /** Every schedule with its state. */
3563
+ async list(now = /* @__PURE__ */ new Date()) {
3564
+ const t = this.table;
3565
+ const rows = await this.db.select().from(t);
3566
+ const byName = new Map(rows.map((row) => [row.name, row]));
3567
+ return [...this.byName.values()].map((schedule) => {
3568
+ const row = byName.get(schedule.name);
3569
+ return {
3570
+ name: schedule.name,
3571
+ kind: schedule.workflow ? "workflow" : "handler",
3572
+ ...schedule.cron ? {
3573
+ cron: schedule.cron.source,
3574
+ timeZone: schedule.timeZone
3575
+ } : { every: schedule.every },
3576
+ enabled: schedule.enabled,
3577
+ nextRunAt: row ? row.nextAt.toISOString() : null,
3578
+ running: Boolean(row?.runId && row.leaseUntil && row.leaseUntil > now),
3579
+ attempts: row?.runId ? row.attempts : row?.attempts ?? 0,
3580
+ lastSuccessAt: row?.lastSuccessAt?.toISOString() ?? null,
3581
+ runs: row?.runs ?? []
3582
+ };
3583
+ });
3584
+ }
3585
+ /**
3586
+ * Make a schedule due now, as a manual run. Whichever process runs the
3587
+ * schedules picks it up; this one at once if it does.
3588
+ *
3589
+ * @returns `false` when the schedule is running now.
3590
+ * @throws When no schedule has that name.
3591
+ */
3592
+ async trigger(name) {
3593
+ if (!this.byName.has(name)) throw new Error(`No schedule named '${name}'`);
3594
+ await this.sync();
3595
+ const now = /* @__PURE__ */ new Date();
3596
+ if (!await this.reset(name, now, {
3597
+ slot: now,
3598
+ nextAt: now,
3599
+ attempts: 0,
3600
+ trigger: "manual"
3601
+ })) return false;
3602
+ if (this.timer) setTimeout(() => void this.tick(), 0).unref?.();
3603
+ return true;
3604
+ }
3605
+ /**
3606
+ * Set a schedule's row afresh, unless a live claim holds it. A claim whose
3607
+ * process died is recorded first, as a failed run of its own due time.
3608
+ *
3609
+ * @returns Whether the row was set.
3610
+ */
3611
+ async reset(name, now, values) {
3612
+ const t = this.table;
3613
+ const [row] = await this.db.select().from(t).where(eq(t.name, name));
3614
+ if (!row) return false;
3615
+ return (await this.db.update(t).set({
3616
+ ...values,
3617
+ runId: null,
3618
+ startedAt: null,
3619
+ leaseUntil: null,
3620
+ ...row.runId ? { runs: [this.record(row, row.startedAt, "failed", ABANDONED), ...row.runs].slice(0, KEEP_RUNS) } : {}
3621
+ }).where(and(eq(t.name, name), this.unchanged(row.runId), this.free(now))).returning({ name: t.name })).length > 0;
3622
+ }
3623
+ /** Not held by a live claim. */
3624
+ free(now) {
3625
+ const t = this.table;
3626
+ return or(isNull(t.runId), lt(t.leaseUntil, this.clock(now)));
3627
+ }
3628
+ /** Still held by the claim `runId`, or by none when it is null. */
3629
+ unchanged(runId) {
3630
+ const t = this.table;
3631
+ return runId ? eq(t.runId, runId) : isNull(t.runId);
3632
+ }
3633
+ /** Now, for claims: the database's clock on Postgres, this host's on SQLite (one host). */
3634
+ clock(now) {
3635
+ return this.postgres ? sql`now()` : now;
3636
+ }
3637
+ /** When a claim made or renewed now runs out. */
3638
+ leaseFrom(now) {
3639
+ const ms = this.options.claimTimeoutMs;
3640
+ return this.postgres ? sql`now() + make_interval(secs => ${ms / 1e3})` : new Date(now.getTime() + ms);
3641
+ }
3642
+ /** A row due at the schedule's first time from now: an interval at once, a cron schedule at its next time. */
3643
+ fresh(schedule, now) {
3644
+ const slot = schedule.cron ? nextDue(schedule, now) : now;
3645
+ return slot && {
3646
+ spec: schedule.spec,
3647
+ slot,
3648
+ nextAt: this.jittered(schedule, slot),
3649
+ attempts: 0,
3650
+ trigger: "schedule"
3651
+ };
3652
+ }
3653
+ /**
3654
+ * Give each schedule its row, and work its next due time out again when what
3655
+ * decides it changed (an edited cron expression). Once per scheduler.
3656
+ */
3657
+ sync() {
3658
+ this.synced ??= this.writeRows().catch((error) => {
3659
+ this.synced = void 0;
3660
+ throw error;
3661
+ });
3662
+ return this.synced;
3663
+ }
3664
+ async writeRows() {
3665
+ const t = this.table;
3666
+ const now = /* @__PURE__ */ new Date();
3667
+ for (const schedule of this.byName.values()) {
3668
+ const fresh = this.fresh(schedule, now);
3669
+ if (!fresh) continue;
3670
+ await this.db.insert(t).values({
3671
+ name: schedule.name,
3672
+ runs: [],
3673
+ ...fresh
3674
+ }).onConflictDoNothing();
3675
+ const [row] = await this.db.select({ spec: t.spec }).from(t).where(eq(t.name, schedule.name));
3676
+ if (row && row.spec !== schedule.spec) await this.reset(schedule.name, now, fresh);
3677
+ }
3678
+ }
3679
+ tick() {
3680
+ this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(() => this.claimAndRun(), () => this.claimAndRun());
3681
+ return this.tickQueue;
3682
+ }
3683
+ async claimAndRun() {
3684
+ try {
3685
+ await this.sync();
3686
+ const t = this.table;
3687
+ const now = /* @__PURE__ */ new Date();
3688
+ const due = await this.db.select({
3689
+ name: t.name,
3690
+ spec: t.spec,
3691
+ trigger: t.trigger,
3692
+ runId: t.runId,
3693
+ startedAt: t.startedAt
3694
+ }).from(t).where(and(inArray(t.name, [...this.byName.keys()]), lte(t.nextAt, now), this.free(now)));
3695
+ let started = 0;
3696
+ for (const candidate of due) {
3697
+ const schedule = this.byName.get(candidate.name);
3698
+ if (this.inFlight.has(schedule.name)) continue;
3699
+ if (!schedule.enabled && candidate.trigger !== "manual") continue;
3700
+ if (candidate.spec !== schedule.spec) {
3701
+ const fresh = this.fresh(schedule, now);
3702
+ if (fresh) await this.reset(schedule.name, now, fresh);
3703
+ continue;
3704
+ }
3705
+ const runId = crypto.randomUUID();
3706
+ const [row] = await this.db.update(t).set({
3707
+ runId,
3708
+ startedAt: now,
3709
+ leaseUntil: this.leaseFrom(now),
3710
+ attempts: sql`${t.attempts} + 1`
3711
+ }).where(and(eq(t.name, schedule.name), lte(t.nextAt, now), this.free(now), this.unchanged(candidate.runId))).returning();
3712
+ if (!row) continue;
3713
+ started++;
3714
+ const run = this.execute(schedule, row, candidate.runId === null ? void 0 : candidate.startedAt).catch((error) => this.logError(error)).finally(() => this.inFlight.delete(schedule.name));
3715
+ this.inFlight.set(schedule.name, run);
3716
+ }
3717
+ return started;
3718
+ } catch (error) {
3719
+ this.logError(error);
3720
+ return 0;
3721
+ }
3722
+ }
3723
+ async execute(schedule, row, abandonedAt) {
3724
+ const runs = [...row.runs];
3725
+ const startedAt = row.startedAt;
3726
+ const attempt = row.attempts;
3727
+ if (abandonedAt) runs.unshift(this.record({
3728
+ ...row,
3729
+ attempts: attempt - 1
3730
+ }, abandonedAt, "failed", ABANDONED));
3731
+ const now = () => /* @__PURE__ */ new Date();
3732
+ if (attempt === 1 && row.trigger === "schedule" && schedule.cron && schedule.catchUp === "skip" && startedAt.getTime() - row.nextAt.getTime() > MISSED_AFTER_MS) {
3733
+ runs.unshift(this.record(row, startedAt, "skipped"));
3734
+ return this.advance(schedule, row, runs, now(), false);
3735
+ }
3736
+ if (attempt > schedule.maxAttempts) return this.advance(schedule, row, runs, now(), false);
3737
+ const heartbeat = setInterval(() => void this.renew(row).catch((error) => this.logError(error)), Math.max(10, Math.floor(this.options.claimTimeoutMs / 3)));
3738
+ heartbeat.unref?.();
3739
+ const slot = row.slot.toISOString();
3740
+ try {
3741
+ await this.runner(schedule, {
3742
+ schedule: schedule.name,
3743
+ slot,
3744
+ trigger: row.trigger,
3745
+ attempt,
3746
+ runKey: `${schedule.name}:${slot}`
3747
+ });
3748
+ } catch (error) {
3749
+ clearInterval(heartbeat);
3750
+ const message = error instanceof Error ? error.message : String(error);
3751
+ runs.unshift(this.record(row, startedAt, "failed", message));
3752
+ return this.retry(schedule, row, runs, now());
3753
+ }
3754
+ clearInterval(heartbeat);
3755
+ runs.unshift(this.record(row, startedAt, "succeeded"));
3756
+ return this.advance(schedule, row, runs, now(), true);
3757
+ }
3758
+ async renew(row) {
3759
+ const t = this.table;
3760
+ if (!(await this.db.update(t).set({ leaseUntil: this.leaseFrom(/* @__PURE__ */ new Date()) }).where(and(eq(t.name, row.name), eq(t.runId, row.runId))).returning({ name: t.name })).length) console.warn(`[Brick-TS schedules] Schedule '${row.name}' lost its claim while running; another process may run it too.`);
3761
+ }
3762
+ /** After a failure: try the same due time again later, unless the tries ran out or the next due time comes first. */
3763
+ async retry(schedule, row, runs, now) {
3764
+ const retryAt = new Date(now.getTime() + schedule.backoffMs * 2 ** (row.attempts - 1));
3765
+ const next = schedule.cron ? nextDue(schedule, now) : void 0;
3766
+ if (row.attempts >= schedule.maxAttempts || next && next <= retryAt) return this.advance(schedule, row, runs, now, false);
3767
+ await this.release(row, {
3768
+ nextAt: retryAt,
3769
+ runs
3770
+ });
3771
+ }
3772
+ /** Done with this due time: on to the next one. */
3773
+ async advance(schedule, row, runs, now, succeeded) {
3774
+ const slot = nextDue(schedule, now);
3775
+ await this.release(row, {
3776
+ spec: schedule.spec,
3777
+ ...slot ? {
3778
+ slot,
3779
+ nextAt: this.jittered(schedule, slot)
3780
+ } : { nextAt: /* @__PURE__ */ new Date(864e13) },
3781
+ attempts: 0,
3782
+ trigger: "schedule",
3783
+ runs,
3784
+ ...succeeded ? { lastSuccessAt: now } : {}
3785
+ });
3786
+ }
3787
+ async release(row, values) {
3788
+ const t = this.table;
3789
+ if (!(await this.db.update(t).set({
3790
+ ...values,
3791
+ runs: values.runs?.slice(0, KEEP_RUNS),
3792
+ runId: null,
3793
+ leaseUntil: null
3794
+ }).where(and(eq(t.name, row.name), eq(t.runId, row.runId))).returning({ name: t.name })).length) console.warn(`[Brick-TS schedules] Schedule '${row.name}': another process took the run over, so this outcome is not recorded.`);
3795
+ }
3796
+ record(row, startedAt, outcome, error) {
3797
+ return {
3798
+ slot: row.slot.toISOString(),
3799
+ trigger: row.trigger,
3800
+ attempt: row.attempts,
3801
+ startedAt: startedAt.toISOString(),
3802
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
3803
+ outcome,
3804
+ ...error !== void 0 ? { error } : {}
3805
+ };
3806
+ }
3807
+ jittered(schedule, slot) {
3808
+ return schedule.jitterMs ? new Date(slot.getTime() + Math.floor(Math.random() * schedule.jitterMs)) : slot;
3809
+ }
3810
+ logError(error) {
3811
+ console.error("[Brick-TS schedules]", error);
3812
+ }
3813
+ };
3042
3814
  // src/events/hub.ts
3043
3815
  function matchesEvent(pattern, name) {
3044
3816
  if (pattern === "*") return true;
@@ -3070,6 +3842,8 @@ var EventsHub = class {
3070
3842
  dispatchOptions;
3071
3843
  runtime;
3072
3844
  recorderNames = [];
3845
+ scheduleList = [];
3846
+ scheduler;
3073
3847
  started = false;
3074
3848
  stopping;
3075
3849
  /**
@@ -3084,9 +3858,15 @@ var EventsHub = class {
3084
3858
  if (this.byName.has(listener.name)) throw new DuplicateNameError(`Duplicate event listener '${listener.name}'`);
3085
3859
  this.byName.set(listener.name, listener);
3086
3860
  }
3087
- const workflowListeners = [...this.byName.values()].filter((listener) => listener.workflow);
3861
+ const scheduleNames = /* @__PURE__ */ new Set();
3862
+ for (const schedule of options.schedules ?? []) {
3863
+ if (scheduleNames.has(schedule.name)) throw new DuplicateNameError(`Duplicate schedule '${schedule.name}'`);
3864
+ scheduleNames.add(schedule.name);
3865
+ this.scheduleList.push(schedule);
3866
+ }
3867
+ const workflowListeners = [...this.byName.values(), ...this.scheduleList].filter((listener) => listener.workflow);
3088
3868
  if (workflowListeners.length) {
3089
- if (!options.world) throw new Error(`Event listener '${workflowListeners[0].name}' runs a workflow, so events needs a world: brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.`);
3869
+ if (!options.world) throw new Error(`${"on" in workflowListeners[0] ? "Event listener" : "Schedule"} '${workflowListeners[0].name}' runs a workflow, so events needs a world: brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.`);
3090
3870
  this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners, deps);
3091
3871
  }
3092
3872
  this.dispatchOptions = options.dispatch === false ? false : options.dispatch === true || options.dispatch === void 0 ? {} : options.dispatch;
@@ -3109,6 +3889,7 @@ var EventsHub = class {
3109
3889
  if (db && typeof db === "object") recordingServices.set(db, service);
3110
3890
  if (!this.dispatchers.has(table)) this.dispatchers.set(table, new Dispatcher(db, table, (name) => this.deliverable(name), this.dispatchOptions || {}));
3111
3891
  }
3892
+ if (this.scheduleList.length) this.attachSchedules(services);
3112
3893
  if (this.recorderNames.length === 0 && this.byName.size > 0) console.warn("[Brick-TS] events are configured, but no service database has an outbox table. Add outboxTable() to a database's tables so its writes can record events.");
3113
3894
  return this;
3114
3895
  }
@@ -3125,9 +3906,48 @@ var EventsHub = class {
3125
3906
  kind: listener.workflow ? "workflow" : "handler"
3126
3907
  })),
3127
3908
  dispatch: this.dispatchOptions !== false,
3128
- recorders: [...this.recorderNames]
3909
+ recorders: [...this.recorderNames],
3910
+ ...this.scheduleList.length ? { schedules: this.scheduleList.map((schedule) => ({
3911
+ name: schedule.name,
3912
+ kind: schedule.workflow ? "workflow" : "handler",
3913
+ ...schedule.cron ? {
3914
+ cron: schedule.cron.source,
3915
+ timeZone: schedule.timeZone
3916
+ } : { every: schedule.every },
3917
+ enabled: schedule.enabled
3918
+ })) } : {}
3129
3919
  };
3130
3920
  }
3921
+ /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */
3922
+ get schedules() {
3923
+ const scheduler = this.scheduler;
3924
+ return scheduler && {
3925
+ list: () => scheduler.list(),
3926
+ trigger: (name) => scheduler.trigger(name),
3927
+ drain: () => scheduler.drain()
3928
+ };
3929
+ }
3930
+ /**
3931
+ * Find the one schedule table among the services' databases.
3932
+ *
3933
+ * @throws When none holds one, or more than one does: a schedule must have
3934
+ * one place where its state lives.
3935
+ */
3936
+ attachSchedules(services) {
3937
+ const found = /* @__PURE__ */ new Map();
3938
+ for (const service of services.map(portOf)) {
3939
+ const table = service.getScheduleTable();
3940
+ if (table && !found.has(table)) found.set(table, service.getDb());
3941
+ }
3942
+ if (found.size !== 1) throw new Error(found.size ? "Brick: schedules need exactly one scheduleTable(), but several databases hold one." : "Brick: schedules keep their state in a scheduleTable(), and no service database holds one. Add scheduleTable() to a database's tables.");
3943
+ const [[table, db]] = [...found];
3944
+ const options = this.dispatchOptions || {};
3945
+ this.scheduler = new Scheduler(db, table, this.scheduleList, (schedule, run) => schedule.workflow ? this.runtime.startScheduled(schedule, run) : runWithDeps(this.deps, async () => schedule.run(run)), {
3946
+ timer: options.timer ?? true,
3947
+ intervalMs: options.intervalMs ?? 1e3,
3948
+ claimTimeoutMs: options.claimTimeoutMs ?? 6e4
3949
+ });
3950
+ }
3131
3951
  /**
3132
3952
  * Where the workflow bundle is read from, the project it is built from, and
3133
3953
  * the world the workflows run on. Only set when a listener runs a workflow.
@@ -3162,6 +3982,7 @@ var EventsHub = class {
3162
3982
  startedHubs.add(this);
3163
3983
  this.runtime?.warmUp();
3164
3984
  for (const dispatcher of this.dispatchers.values()) dispatcher.start();
3985
+ this.scheduler?.start();
3165
3986
  }
3166
3987
  /**
3167
3988
  * Stop delivering, wait for the deliveries that are running, and close the
@@ -3176,7 +3997,7 @@ var EventsHub = class {
3176
3997
  }
3177
3998
  async shutDown() {
3178
3999
  this.started = false;
3179
- await Promise.all([...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()));
4000
+ await Promise.all([...[...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()), this.scheduler?.stop()]);
3180
4001
  await this.runtime?.close();
3181
4002
  }
3182
4003
  /**
@@ -3395,8 +4216,8 @@ function defineServiceSocket(service, config, resolve) {
3395
4216
  if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
3396
4217
  const replay = config.replay && { ...config.replay };
3397
4218
  if (replay && !(Number.isInteger(replay.keep) && replay.keep > 0 && replay.maxAgeMs > 0 && Number.isFinite(replay.maxAgeMs))) throw new Error("Socket replay needs a positive integer keep and a positive finite maxAgeMs");
3398
- for (const schema of [...Object.values(input), ...Object.values(output)]) {
3399
- serializeSocketSchema(schema);
4219
+ for (const [path, schema] of [...Object.entries(input).map(([k, v]) => [`input.${k}`, v]), ...Object.entries(output).map(([k, v]) => [`output.${k}`, v])]) {
4220
+ serializeSocketSchema(schema, path);
3400
4221
  getCompiledCheck(schema);
3401
4222
  }
3402
4223
  const typed = (socket) => socket;
@@ -3829,6 +4650,7 @@ function brick(options = {}) {
3829
4650
  if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
3830
4651
  const services = options.services ?? getGlobalRegistry().list();
3831
4652
  const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
4653
+ app.onRequest(({ request }) => markDashboardArrival(request));
3832
4654
  if (options.cors) app.onRequest(corsHook(options.cors));
3833
4655
  for (const handler of plugins.middleware) app.onRequest(handler);
3834
4656
  const registeredRoutes = /* @__PURE__ */ new Map();
@@ -3898,14 +4720,15 @@ function brick(options = {}) {
3898
4720
  if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new DuplicateNameError(`Brick: duplicate socket route '${socket.path}'`);
3899
4721
  socketRoutes.add(key);
3900
4722
  }
3901
- const mountRoute = (method, path, handler, plugin = false) => {
4723
+ const mountRoute = (method, path, handler, plugin = false, hook) => {
3902
4724
  const key = routeKey(method, path);
3903
4725
  if (socketRoutes.has(key)) throw new DuplicateNameError(`Brick: route '${method} ${path}' conflicts with a socket`);
3904
4726
  if (registeredRoutes.has(key)) {
3905
4727
  if (plugin || registeredRoutes.get(key)) throw new DuplicateNameError(`Brick: duplicate plugin route '${method} ${path}'`);
3906
4728
  return false;
3907
4729
  }
3908
- app.route(method, path, handler);
4730
+ if (hook) app.route(method, path, hook, handler);
4731
+ else app.route(method, path, handler);
3909
4732
  registeredRoutes.set(key, plugin);
3910
4733
  return true;
3911
4734
  };
@@ -3954,7 +4777,7 @@ function brick(options = {}) {
3954
4777
  }, () => route.handler(context)) : route.handler(context);
3955
4778
  return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
3956
4779
  };
3957
- if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin))) mountedRoutes.push(route.ir);
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);
3958
4781
  }
3959
4782
  mountSockets(app, sockets, options.sockets?.broker ?? localBroker(), options.sockets?.secret);
3960
4783
  const definition = Object.freeze({
@@ -4038,6 +4861,6 @@ function cachedJsonRoute(build, revision) {
4038
4861
  return json;
4039
4862
  };
4040
4863
  }
4041
- export { validateName as $, resolveWorkflowPaths as A, createActionHandler as B, setActionAccess as C, compileBrickApplication as D, bindCompiledApplication as E, crudEventSource as F, useDeps as G, definitionSite as H, eventRefs as I, getPluginEndpoints as J, defineResourcePlugin as K, isCrudEvent as L, checkEvent as M, checkPayload as N, loadCompiledBrickApp as O, crudEventName as P, segmentClaimant as Q, isBrickApp as R, getActionAccess as S, resetGlobalRegistry as T, INTERNALS as U, claimName as V, port as W, installPlugin as X, hasPlugin as Y, isInstallingPlugin as Z, listSecrets as _, Dispatcher as a, baseContext as at, resolveSecrets as b, isOutboxTable as c, t as ct, registerReferenceRoute as d, withCallSpan as dt, portOf as et, scalarDocsHTML as f, PLUGIN_COMMIT as ft, envSource as g, defineSecret as h, stopAllEvents as i, deny as it, defineListener as j, WORKFLOW_BUNDLE as k, outboxTable as l, validateWithSchema as lt, SecretRef as m, defineServiceSocket as n, defineAction as nt, onTransactionCommit as o, pickContextEnvelope as ot, requestLoggingPlugin as p, PLUGIN_KIND as pt, defineServicePlugin as q, recordingServices as r, errorsOf as rt, runInTransaction as s, Type as st, brick as t, buildErrorHelpers as tt, referencePlugin as u, traceRoute as ut, overrideSecret as v, getGlobalRegistry as w, generateOpenApiSpec as x, resetSecrets as y, requireBrickApp as z };
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 };
4042
4865
 
4043
4866
  //# sourceMappingURL=server.js.map