@brickkit/core 0.13.2 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1450,247 +1450,552 @@ function requireBrickApp(app) {
1450
1450
  if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
1451
1451
  return app;
1452
1452
  }
1453
- // src/compiler.ts
1454
- /** @throws When the services no longer analyze to `ir`, so the build is stale. */
1455
- function analyzeMatching(services, ir) {
1456
- const analyzed = analyzeApplication(services, ir.prefix);
1457
- if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
1458
- return analyzed;
1453
+ // src/events/catalog.ts
1454
+ function isEventRef(value) {
1455
+ return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.service === "string" && typeof value.schema === "object";
1456
+ }
1457
+ /** Build `service.events` from its catalog. */
1458
+ function eventRefs(service, catalog) {
1459
+ const refs = Object.create(null);
1460
+ for (const [key, schema] of Object.entries(catalog ?? {})) {
1461
+ 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`);
1462
+ if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
1463
+ refs[key] = Object.freeze({
1464
+ name: `${service}.${key}`,
1465
+ service,
1466
+ schema
1467
+ });
1468
+ }
1469
+ return Object.freeze(refs);
1470
+ }
1471
+ /** @throws When the payload does not match the event's schema. */
1472
+ function checkPayload(ref, payload) {
1473
+ const result = validateWithSchema(ref.schema, payload);
1474
+ if (!result.success) throw new Error(`Event "${ref.name}" payload does not match its schema: ${result.errors.map((error) => `${error.path || "/"} ${error.message}`).join("; ")}`);
1475
+ }
1476
+ /** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
1477
+ const CRUD_EVENT_OPERATIONS = [
1478
+ "create",
1479
+ "update",
1480
+ "delete"
1481
+ ];
1482
+ /** The event a CRUD write records: `<resource>.<operation>`. */
1483
+ const crudEventName = (resource, operation) => `${resource}.${operation}`;
1484
+ /** The `source` of a resource's events: `<service>.<resource>`. */
1485
+ const crudEventSource = (service, resource) => `${service}.${resource}`;
1486
+ /** Whether `name` is the CRUD event of one of `resources`. */
1487
+ function isCrudEvent(name, resources) {
1488
+ const dot = name.indexOf(".");
1489
+ return dot > 0 && CRUD_EVENT_OPERATIONS.includes(name.slice(dot + 1)) && resources.includes(name.slice(0, dot));
1459
1490
  }
1460
1491
  /**
1461
- * Build artifact bootstrap: import the bundled app. It is not re-analyzed
1462
- * against the IR: the bundle and its IR come from one build (#107).
1492
+ * Check an event against the catalog of the service recording it. Without a
1493
+ * catalog any name goes. With one, the name must be `<service>.<event>` from it
1494
+ * (the payload is checked against its schema) or a CRUD event of one of the
1495
+ * service's resources (`<resource>.create|update|delete`).
1463
1496
  *
1464
- * @param _ir Ignored; kept so existing callers still type-check.
1497
+ * @throws When the name is not declared or the payload does not match.
1465
1498
  */
1466
- async function loadCompiledBrickApp(load, _ir) {
1467
- return requireBrickApp((await load()).default);
1499
+ function checkEvent(service, name, payload) {
1500
+ const prefix = `${service.name}.`;
1501
+ const ref = name.startsWith(prefix) ? service.events[name.slice(prefix.length)] : void 0;
1502
+ if (ref) return checkPayload(ref, payload);
1503
+ if (!service.hasCatalog) return;
1504
+ if (isCrudEvent(name, service.listResources().map((r) => r.name))) return;
1505
+ throw new Error(`Event "${name}" is not in the event catalog of service "${service.name}" (declared: ${Object.values(service.events).map((ref) => ref.name).join(", ") || "none"})`);
1468
1506
  }
1469
- function bindAnalyzed(ir, bindings, bind = bindRoute) {
1470
- const routes = ir.routes.map((route, index) => {
1471
- const { service, action } = bindings[index];
1472
- const plan = Object.freeze(planRoute(route, service, action));
1473
- return Object.freeze({
1474
- ir: route,
1475
- handler: bind(plan, index)
1476
- });
1507
+ // src/events/listener.ts
1508
+ function defineListener(config) {
1509
+ const on = (Array.isArray(config.on) ? config.on : [config.on]).map((item) => isEventRef(item) ? item.name : item);
1510
+ validateListener({
1511
+ ...config,
1512
+ on
1477
1513
  });
1514
+ const helpers = buildErrorHelpers(config.errors);
1478
1515
  return Object.freeze({
1479
- ir: freezeIR(ir),
1480
- routes: Object.freeze(routes)
1516
+ name: config.name,
1517
+ on: Object.freeze(on),
1518
+ ...config.run !== void 0 ? { run: ((delivery) => config.run(delivery, { error: helpers })) } : {},
1519
+ ...config.errors ? { errors: config.errors } : {},
1520
+ ...config.retry ? { retry: config.retry } : {},
1521
+ ...config.workflow !== void 0 ? { workflow: config.workflow } : {},
1522
+ ...config.maxAttempts !== void 0 ? { maxAttempts: config.maxAttempts } : {}
1481
1523
  });
1482
1524
  }
1483
- /** Startup compiler: analyzes once, then binds live callbacks. */
1484
- function compileBrickApplication(options) {
1485
- const { ir, bindings } = analyzeApplication(options.services, options.prefix);
1486
- if (options.mode !== "generic") for (const service of options.services) portOf(service).prepareContributions();
1487
- return bindAnalyzed(ir, bindings);
1488
- }
1489
1525
  /**
1490
- * Build artifact binder: consumes emitted functions, with no runtime handler code generation.
1491
- *
1492
- * @deprecated `brick build` no longer emits handler factories; built servers
1493
- * use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as
1494
- * `brick({ compilation })` instead.
1526
+ * @throws When the name is empty or contains `:`, `on` is empty, `maxAttempts`
1527
+ * is not a positive integer, or the listener has both or neither of `run` and
1528
+ * `workflow`.
1495
1529
  */
1496
- function bindCompiledApplication(ir, services, factories) {
1497
- if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
1498
- const analyzed = analyzeMatching(services, ir);
1499
- if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
1500
- for (const service of services) portOf(service).prepareContributions();
1501
- return bindAnalyzed(ir, analyzed.bindings, (plan, index) => factories[index](plan, compilerRuntime));
1530
+ function validateListener(listener) {
1531
+ const { name, on, maxAttempts, run, workflow } = listener;
1532
+ if (typeof name !== "string" || !name) throw new Error("An event listener needs a name");
1533
+ if (name.includes(":")) throw new Error(`Event listener name '${name}' must not contain ':'`);
1534
+ if (!Array.isArray(on) || !on.length || on.some((pattern) => !pattern || typeof pattern !== "string")) throw new Error(`Event listener '${name}' listens for nothing`);
1535
+ if (maxAttempts !== void 0 && (!Number.isInteger(maxAttempts) || maxAttempts < 1)) throw new Error(`Event listener '${name}': maxAttempts must be a positive integer`);
1536
+ if (run !== void 0 && workflow !== void 0) throw new Error(`Event listener '${name}' has both run and workflow; give it one`);
1537
+ if (run === void 0 && workflow === void 0) throw new Error(`Event listener '${name}' needs a run handler or a workflow`);
1538
+ if (run !== void 0 && typeof run !== "function") throw new Error(`Event listener '${name}': run must be a function`);
1539
+ if (workflow !== void 0 && typeof workflow !== "function") throw new Error(`Event listener '${name}': workflow must be a function marked "use workflow"`);
1502
1540
  }
1503
- // src/registry.ts
1504
- var ServiceRegistry = class {
1505
- _revision = 0;
1506
- /** Definition revision for invalidating serialized architecture snapshots. */
1507
- get revision() {
1508
- return this._revision;
1509
- }
1510
- touch() {
1511
- this._revision++;
1512
- }
1513
- services = /* @__PURE__ */ new Map();
1514
- sites = /* @__PURE__ */ new Map();
1515
- /** @throws When a different file already registered a service with this name. */
1516
- register(service, site = definitionSite()) {
1517
- claimName(this.sites, `service "${service.name}"`, service.name, site);
1518
- this.services.set(service.name, service);
1519
- this.touch();
1520
- }
1521
- get(name) {
1522
- return this.services.get(name);
1523
- }
1524
- has(name) {
1525
- return this.services.has(name);
1526
- }
1527
- list() {
1528
- return Array.from(this.services.values());
1529
- }
1530
- /**
1531
- * The architecture of an app (`app.definition`): its mounted routes. Without
1532
- * one, every registered service with its default routes under `/api`.
1533
- */
1534
- exportArchitecture(application) {
1535
- return {
1536
- version: "1.0.0",
1537
- ...application?.events ? { events: application.events } : {},
1538
- ...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
1539
- services: (application?.services ?? this.list()).map((service) => {
1540
- const byAction = new Map(application ? application.routes.filter((route) => route.service === service.name).map((route) => [route.action, route]) : service.listActions().flatMap((action) => {
1541
- const route = getActionRoute(action);
1542
- return route ? [[action.name, route]] : [];
1543
- }));
1544
- const schema = service.introspect();
1545
- return {
1546
- ...schema,
1547
- ...application?.sockets ? { sockets: application.sockets.filter((socket) => socket.service === service.name) } : {},
1548
- actions: schema.actions.map((action) => {
1549
- const route = byAction.get(action.name);
1550
- return route ? {
1551
- ...action,
1552
- method: route.method,
1553
- path: route.path
1554
- } : action;
1555
- })
1556
- };
1557
- })
1558
- };
1559
- }
1541
+ /** The deps a plugin's listener runs with, set by the plugin install; `undefined` for the app's own. */
1542
+ const listenerDeps = (listener) => listener[PLUGIN_DEPS];
1543
+ // src/events/workflows.ts
1544
+ /** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */
1545
+ const WORKFLOW_BUNDLE = {
1546
+ dir: ".well-known/workflow/v1",
1547
+ flow: "flow.mjs",
1548
+ steps: "__step_registrations.mjs",
1549
+ webhook: "webhook.mjs",
1550
+ manifest: "manifest.json"
1560
1551
  };
1561
- let globalRegistry = new ServiceRegistry();
1562
- /**
1563
- * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
1564
- * generator, `useService`, and the dashboard find services by name.
1565
- *
1566
- * @returns The current global registry.
1567
- */
1568
- function getGlobalRegistry() {
1569
- return globalRegistry;
1570
- }
1571
- /**
1572
- * Start over with an empty global registry. For tests, which define the same
1573
- * services again in each case; an application never needs it.
1574
- */
1575
- function resetGlobalRegistry() {
1576
- globalRegistry = new ServiceRegistry();
1577
- }
1578
- // src/access.ts
1552
+ /** From the Workflow SDK: the queue a workflow run goes to (`getQueueTopicPrefix("workflow")` in `@workflow/world`), and the header a world names it in. */
1553
+ const WORKFLOW_QUEUE = {
1554
+ prefix: "__wkf_workflow_",
1555
+ header: "x-vqs-queue-name"
1556
+ };
1557
+ const STOPPED = "The events were stopped, so workflows can no longer run";
1558
+ const NOT_BUILT = "brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.";
1559
+ /** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */
1560
+ const WEBHOOK_ROUTE = `/${WORKFLOW_BUNDLE.dir}/webhook/*`;
1561
+ /** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */
1562
+ const STEP_REGISTRY = Symbol.for("@workflow/core//registeredSteps");
1579
1563
  /**
1580
- * Record how an action is protected, for tools that cannot read it from the
1581
- * configuration: plugins such as `crud` enforce access inside `execute`, so the
1582
- * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
1583
- * read what is recorded here.
1564
+ * Where the workflow bundle is read from, and the project it is built from.
1584
1565
  *
1585
- * @param action - The action to describe.
1586
- * @param info - Whether it checks authorization and whether it scopes queries,
1587
- * and the resulting policy.
1566
+ * @param options - The `events.workflows` option.
1567
+ * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the
1568
+ * builder finds the SDK from where it writes, and skips only this directory when it
1569
+ * looks for workflows.
1588
1570
  */
1589
- function setActionAccess(action, info) {
1590
- actionMeta(action).access = {
1591
- hasAuthorize: info.hasAuthorize,
1592
- hasScope: info.hasScope,
1593
- policy: info.policy
1571
+ function resolveWorkflowPaths(options = {}) {
1572
+ const root = resolve(options.root ?? process.cwd());
1573
+ return {
1574
+ root,
1575
+ dir: shippedBundle ?? join(root, WORKFLOW_BUNDLE.dir)
1594
1576
  };
1595
1577
  }
1578
+ /** The bundle `brick build` shipped beside a compiled server, which reads it instead of building one. */
1579
+ let shippedBundle;
1580
+ /** @internal Called by a compiled server before it loads its app. */
1581
+ function setShippedWorkflowBundle(dir) {
1582
+ shippedBundle = resolve(dir);
1583
+ }
1584
+ /** Whether this process runs a compiled server that reads the bundle shipped beside it. */
1585
+ const isWorkflowBundleShipped = () => shippedBundle !== void 0;
1596
1586
  /**
1597
- * How an action is protected: `"public"` when nothing checks the caller,
1598
- * `"authorized"` when an `authorize` does, and `"scoped"` when the action also
1599
- * limits what rows the caller can reach. It reads what a plugin recorded with
1600
- * `setActionAccess`, else the action's own `authorize`, and keeps the policy
1601
- * consistent with the flags.
1587
+ * Runs workflow listeners: wires the world into the Workflow SDK, serves the
1588
+ * built bundle from this process, and starts one run for each delivery.
1602
1589
  *
1603
- * @param action - An action, or any object a plugin described.
1604
- * @returns `hasAuthorize`, `hasScope`, and `policy`.
1590
+ * Nothing is loaded until it is needed, so an app without workflow listeners
1591
+ * never imports the SDK.
1605
1592
  */
1606
- function getActionAccess(action) {
1607
- const meta = actionMeta(action).access;
1608
- const configAuthorize = typeof action.config?.authorize === "function";
1609
- if (!meta) return {
1610
- hasAuthorize: configAuthorize,
1611
- hasScope: false,
1612
- policy: configAuthorize ? "authorized" : "public"
1613
- };
1614
- const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
1615
- const hasScope = Boolean(meta.hasScope);
1616
- let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
1617
- if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
1618
- else if (policy !== "public" && !hasAuthorize) policy = "public";
1619
- else if (policy === "scoped" && !hasScope) policy = "authorized";
1620
- return {
1621
- hasAuthorize,
1622
- hasScope,
1623
- policy
1624
- };
1625
- }
1626
- // src/openapi.ts
1627
- /** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */
1628
- const OPENAPI_DEFAULTS = Object.freeze({
1629
- title: "Brick-TS API Mesh",
1630
- version: "1.0.0",
1631
- path: "/openapi.json"
1632
- });
1633
- function isAnchor(node) {
1634
- return typeof node === "object" && node !== null && typeof node.$id === "string";
1635
- }
1636
- function isBareRef(node) {
1637
- return typeof node === "object" && node !== null && typeof node.$ref === "string" && !node.$ref.startsWith("#");
1638
- }
1639
- function toComponentKey(id) {
1640
- return id.replace(/[^A-Za-z0-9.\-_]+/g, "_");
1593
+ var WorkflowRuntime = class {
1594
+ world;
1595
+ listeners;
1596
+ deps;
1597
+ root;
1598
+ ready;
1599
+ connected;
1600
+ closed = false;
1601
+ constructor(world, options, listeners, deps = {}) {
1602
+ this.world = world;
1603
+ this.listeners = listeners;
1604
+ this.deps = deps;
1605
+ this.root = resolveWorkflowPaths(options).root;
1606
+ }
1607
+ /** Read when used, in case a bundler evaluates the app before the compiled server names its shipped bundle. */
1608
+ get dir() {
1609
+ return resolveWorkflowPaths({ root: this.root }).dir;
1610
+ }
1611
+ /** Begin loading the runtime now rather than at the first delivery. */
1612
+ warmUp() {
1613
+ this.ensure().catch((error) => console.error(`[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`));
1614
+ }
1615
+ /**
1616
+ * Start the run for a delivery.
1617
+ *
1618
+ * The run is named after the delivery id, so a delivery that is tried again
1619
+ * finds the run it already started instead of starting another.
1620
+ *
1621
+ * @param listener - The workflow listener the delivery is for.
1622
+ * @param delivery - The delivery.
1623
+ */
1624
+ async startRun(listener, delivery) {
1625
+ const sdk = await this.ensure();
1626
+ const { attempt: _attempt, ...event } = delivery;
1627
+ await sdk.start(listener.workflow, [event], {
1628
+ world: this.world,
1629
+ runKey: delivery.deliveryId,
1630
+ runKeyTime: Date.parse(delivery.occurredAt)
1631
+ });
1632
+ }
1633
+ /**
1634
+ * Answer a request to a webhook a workflow created with `createWebhook`, by
1635
+ * resuming the workflow that waits on it. Needs the world but not the queue
1636
+ * consumer, so a process that only records events (`dispatch: false`) serves
1637
+ * webhooks too.
1638
+ *
1639
+ * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.
1640
+ * @returns The response the bundle's webhook handler gives.
1641
+ */
1642
+ async handleWebhook(request) {
1643
+ await this.connect();
1644
+ const file = join(this.dir, WORKFLOW_BUNDLE.webhook);
1645
+ if (!existsSync(file)) throw new Error(`No webhook bundle at ${file}. ${NOT_BUILT}`);
1646
+ const handler = (await import(pathToFileURL(file).href))[request.method];
1647
+ if (typeof handler !== "function") return new Response(null, { status: 405 });
1648
+ return handler(request);
1649
+ }
1650
+ /** Stop the world. The runtime cannot be started again afterwards. */
1651
+ async close() {
1652
+ this.closed = true;
1653
+ await this.ready?.catch(() => {});
1654
+ await this.connected?.catch(() => {});
1655
+ await this.world.close?.();
1656
+ }
1657
+ ensure() {
1658
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
1659
+ this.ready ??= this.initialize().catch((error) => {
1660
+ this.ready = void 0;
1661
+ throw error;
1662
+ });
1663
+ return this.ready;
1664
+ }
1665
+ /** Load the SDK and give it the world: all a webhook needs. */
1666
+ connect() {
1667
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
1668
+ this.connected ??= this.loadSdk().then((sdk) => {
1669
+ sdk.setWorld(this.world);
1670
+ return sdk;
1671
+ }).catch((error) => {
1672
+ this.connected = void 0;
1673
+ throw error;
1674
+ });
1675
+ return this.connected;
1676
+ }
1677
+ async initialize() {
1678
+ if (typeof this.world.createRunId !== "function") throw new Error("This world cannot name a run after its key, so an event delivered twice would start two runs. Use the world from @brickkit/redis-world or @brickkit/bullmq-world.");
1679
+ const sdk = await this.connect();
1680
+ const flow = join(this.dir, WORKFLOW_BUNDLE.flow);
1681
+ if (!existsSync(flow)) throw new Error(`No workflow bundle at ${flow}. ${NOT_BUILT}`);
1682
+ const manifest = this.readManifest();
1683
+ const depsOf = this.checkListeners(manifest);
1684
+ const bundle = await this.loadBundle(flow);
1685
+ if (typeof bundle.POST !== "function") throw new Error(`${flow} does not export a POST handler`);
1686
+ const post = bundle.POST;
1687
+ this.world.registerHandler?.(WORKFLOW_QUEUE.prefix, (request) => {
1688
+ const queue = request.headers.get(WORKFLOW_QUEUE.header) ?? "";
1689
+ return runWithDeps(depsOf.get(queue.slice(WORKFLOW_QUEUE.prefix.length)) ?? this.deps, () => post(request));
1690
+ });
1691
+ await this.world.start?.();
1692
+ return sdk;
1693
+ }
1694
+ async loadSdk() {
1695
+ const from = [this.root, this.dir].map((dir) => createRequire(join(dir, "package.json")));
1696
+ const load = async (specifier) => {
1697
+ let path;
1698
+ for (const require of from) try {
1699
+ path ??= require.resolve(specifier);
1700
+ } catch {}
1701
+ if (!path) throw new Error(`The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`);
1702
+ return import(pathToFileURL(path).href);
1703
+ };
1704
+ const [api, runtime] = await Promise.all([load("workflow/api"), load("workflow/runtime")]);
1705
+ return {
1706
+ start: api.start,
1707
+ setWorld: runtime.setWorld
1708
+ };
1709
+ }
1710
+ /**
1711
+ * The bundle holds its own copy of every step and registers them all when it
1712
+ * loads, replacing the ones the app registered. A copy has its own module state:
1713
+ * a step would find no database connection, no config, none of what the app set
1714
+ * up. So the app's steps are put back, and the bundle's copies serve only the
1715
+ * steps the app never loaded.
1716
+ */
1717
+ async loadBundle(flow) {
1718
+ const registry = () => globalThis[STEP_REGISTRY];
1719
+ const app = new Map(registry());
1720
+ const bundle = await import(pathToFileURL(flow).href);
1721
+ const registered = registry();
1722
+ if (registered) for (const [id, step] of app) registered.set(id, step);
1723
+ return bundle;
1724
+ }
1725
+ readManifest() {
1726
+ const path = join(this.dir, WORKFLOW_BUNDLE.manifest);
1727
+ if (!existsSync(path)) return void 0;
1728
+ return JSON.parse(readFileSync(path, "utf8"));
1729
+ }
1730
+ /**
1731
+ * A listener's workflow must carry the id the transform gives it, and the bundle
1732
+ * must know that id: a function that was never transformed, or a bundle built
1733
+ * before the workflow existed, would fail on its first delivery with a less
1734
+ * helpful message.
1735
+ *
1736
+ * @returns The deps each workflow's steps run with, by workflow id.
1737
+ * @throws When one workflow is run by listeners with different deps (an app
1738
+ * and a plugin, or two plugin installs): its steps could see only one set.
1739
+ */
1740
+ checkListeners(manifest) {
1741
+ const depsOf = /* @__PURE__ */ new Map();
1742
+ const known = /* @__PURE__ */ new Set();
1743
+ for (const file of Object.values(manifest?.workflows ?? {})) for (const entry of Object.values(file)) if (entry.workflowId) known.add(entry.workflowId);
1744
+ for (const listener of this.listeners) {
1745
+ const id = listener.workflow?.workflowId;
1746
+ if (typeof id !== "string") throw new Error(`The workflow of listener '${listener.name}' was not transformed. Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.`);
1747
+ if (manifest && !known.has(id)) throw new Error(`The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`);
1748
+ const deps = listenerDeps(listener) ?? this.deps;
1749
+ if ((depsOf.get(id) ?? deps) !== deps) throw new Error(`Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`);
1750
+ depsOf.set(id, deps);
1751
+ }
1752
+ return depsOf;
1753
+ }
1754
+ };
1755
+ // src/compiler.ts
1756
+ /** @throws When the services no longer analyze to `ir`, so the build is stale. */
1757
+ function analyzeMatching(services, ir) {
1758
+ const analyzed = analyzeApplication(services, ir.prefix);
1759
+ if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
1760
+ return analyzed;
1641
1761
  }
1642
1762
  /**
1643
- * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors
1644
- * (`{ $id: "T0", ..., { $ref: "T0" } }`). OpenAPI interprets a bare `$ref`
1645
- * as an external file reference, so downstream tooling tries to load a
1646
- * file named `T0` and fails. Hoist every anchored subschema into
1647
- * `#/components/schemas/` and rewrite the refs to local pointers.
1648
- * First definition wins when one `$id` is declared twice.
1763
+ * Build artifact bootstrap: import the bundled app. It is not re-analyzed
1764
+ * against the IR: the bundle and its IR come from one build (#107).
1765
+ *
1766
+ * @param _ir Ignored; kept so existing callers still type-check.
1767
+ * @param options `workflows`: the workflow bundle `brick build` shipped beside
1768
+ * the server, read instead of `<root>/.well-known/workflow/v1`.
1649
1769
  */
1650
- function hoistAnchoredSchemas(spec) {
1651
- const anchored = /* @__PURE__ */ new Map();
1652
- const collect = (node) => {
1653
- if (Array.isArray(node)) return node.map(collect);
1654
- if (typeof node !== "object" || node === null) return node;
1655
- if (isAnchor(node)) {
1656
- const id = node.$id;
1657
- const { $id: _dropped, ...rest } = node;
1658
- const collected = collect(rest);
1659
- if (!anchored.has(id)) anchored.set(id, collected);
1660
- return { $ref: `#/components/schemas/${toComponentKey(id)}` };
1661
- }
1662
- for (const key of Object.keys(node)) node[key] = collect(node[key]);
1663
- return node;
1664
- };
1665
- const rewrite = (node) => {
1666
- if (Array.isArray(node)) {
1667
- for (const child of node) rewrite(child);
1668
- return;
1669
- }
1670
- if (typeof node !== "object" || node === null) return;
1671
- if (isBareRef(node)) node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;
1672
- for (const key of Object.keys(node)) rewrite(node[key]);
1673
- };
1674
- collect(spec);
1675
- const components = spec.components ??= {};
1676
- const schemas = components.schemas ??= {};
1677
- for (const [id, schema] of anchored) schemas[toComponentKey(id)] = schema;
1678
- rewrite(spec);
1770
+ async function loadCompiledBrickApp(load, _ir, options = {}) {
1771
+ if (options.workflows) setShippedWorkflowBundle(options.workflows);
1772
+ return requireBrickApp((await load()).default);
1773
+ }
1774
+ function bindAnalyzed(ir, bindings, bind = bindRoute) {
1775
+ const routes = ir.routes.map((route, index) => {
1776
+ const { service, action } = bindings[index];
1777
+ const plan = Object.freeze(planRoute(route, service, action));
1778
+ return Object.freeze({
1779
+ ir: route,
1780
+ handler: bind(plan, index)
1781
+ });
1782
+ });
1783
+ return Object.freeze({
1784
+ ir: freezeIR(ir),
1785
+ routes: Object.freeze(routes)
1786
+ });
1787
+ }
1788
+ /** Startup compiler: analyzes once, then binds live callbacks. */
1789
+ function compileBrickApplication(options) {
1790
+ const { ir, bindings } = analyzeApplication(options.services, options.prefix);
1791
+ if (options.mode !== "generic") for (const service of options.services) portOf(service).prepareContributions();
1792
+ return bindAnalyzed(ir, bindings);
1679
1793
  }
1680
1794
  /**
1681
- * Build the OpenAPI 3.1 document for the services: one path per action route,
1682
- * with request and response schemas from the actions' TypeBox schemas, their
1683
- * declared errors, tags by service, and a bearer security scheme where any
1684
- * action needs authorization. Declared events are listed under `x-brick-events`,
1685
- * by wire name, with their service and payload schema.
1686
- *
1687
- * `brick()` calls this for `/openapi.json`; call it yourself to write the
1688
- * document to a file or feed another tool.
1795
+ * Build artifact binder: consumes emitted functions, with no runtime handler code generation.
1689
1796
  *
1690
- * @param options - `title`, `version`, and `description` for the `info` block,
1691
- * `prefix` (default `/api`), and the `services` to describe (the global
1692
- * registry's by default).
1693
- * @returns The document as a plain object.
1797
+ * @deprecated `brick build` no longer emits handler factories; built servers
1798
+ * use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as
1799
+ * `brick({ compilation })` instead.
1800
+ */
1801
+ function bindCompiledApplication(ir, services, factories) {
1802
+ if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
1803
+ const analyzed = analyzeMatching(services, ir);
1804
+ if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
1805
+ for (const service of services) portOf(service).prepareContributions();
1806
+ return bindAnalyzed(ir, analyzed.bindings, (plan, index) => factories[index](plan, compilerRuntime));
1807
+ }
1808
+ // src/registry.ts
1809
+ var ServiceRegistry = class {
1810
+ _revision = 0;
1811
+ /** Definition revision for invalidating serialized architecture snapshots. */
1812
+ get revision() {
1813
+ return this._revision;
1814
+ }
1815
+ touch() {
1816
+ this._revision++;
1817
+ }
1818
+ services = /* @__PURE__ */ new Map();
1819
+ sites = /* @__PURE__ */ new Map();
1820
+ /** @throws When a different file already registered a service with this name. */
1821
+ register(service, site = definitionSite()) {
1822
+ claimName(this.sites, `service "${service.name}"`, service.name, site);
1823
+ this.services.set(service.name, service);
1824
+ this.touch();
1825
+ }
1826
+ get(name) {
1827
+ return this.services.get(name);
1828
+ }
1829
+ has(name) {
1830
+ return this.services.has(name);
1831
+ }
1832
+ list() {
1833
+ return Array.from(this.services.values());
1834
+ }
1835
+ /**
1836
+ * The architecture of an app (`app.definition`): its mounted routes. Without
1837
+ * one, every registered service with its default routes under `/api`.
1838
+ */
1839
+ exportArchitecture(application) {
1840
+ return {
1841
+ version: "1.0.0",
1842
+ ...application?.events ? { events: application.events } : {},
1843
+ ...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
1844
+ services: (application?.services ?? this.list()).map((service) => {
1845
+ const byAction = new Map(application ? application.routes.filter((route) => route.service === service.name).map((route) => [route.action, route]) : service.listActions().flatMap((action) => {
1846
+ const route = getActionRoute(action);
1847
+ return route ? [[action.name, route]] : [];
1848
+ }));
1849
+ const schema = service.introspect();
1850
+ return {
1851
+ ...schema,
1852
+ ...application?.sockets ? { sockets: application.sockets.filter((socket) => socket.service === service.name) } : {},
1853
+ actions: schema.actions.map((action) => {
1854
+ const route = byAction.get(action.name);
1855
+ return route ? {
1856
+ ...action,
1857
+ method: route.method,
1858
+ path: route.path
1859
+ } : action;
1860
+ })
1861
+ };
1862
+ })
1863
+ };
1864
+ }
1865
+ };
1866
+ let globalRegistry = new ServiceRegistry();
1867
+ /**
1868
+ * The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
1869
+ * generator, `useService`, and the dashboard find services by name.
1870
+ *
1871
+ * @returns The current global registry.
1872
+ */
1873
+ function getGlobalRegistry() {
1874
+ return globalRegistry;
1875
+ }
1876
+ /**
1877
+ * Start over with an empty global registry. For tests, which define the same
1878
+ * services again in each case; an application never needs it.
1879
+ */
1880
+ function resetGlobalRegistry() {
1881
+ globalRegistry = new ServiceRegistry();
1882
+ }
1883
+ // src/access.ts
1884
+ /**
1885
+ * Record how an action is protected, for tools that cannot read it from the
1886
+ * configuration: plugins such as `crud` enforce access inside `execute`, so the
1887
+ * action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
1888
+ * read what is recorded here.
1889
+ *
1890
+ * @param action - The action to describe.
1891
+ * @param info - Whether it checks authorization and whether it scopes queries,
1892
+ * and the resulting policy.
1893
+ */
1894
+ function setActionAccess(action, info) {
1895
+ actionMeta(action).access = {
1896
+ hasAuthorize: info.hasAuthorize,
1897
+ hasScope: info.hasScope,
1898
+ policy: info.policy
1899
+ };
1900
+ }
1901
+ /**
1902
+ * How an action is protected: `"public"` when nothing checks the caller,
1903
+ * `"authorized"` when an `authorize` does, and `"scoped"` when the action also
1904
+ * limits what rows the caller can reach. It reads what a plugin recorded with
1905
+ * `setActionAccess`, else the action's own `authorize`, and keeps the policy
1906
+ * consistent with the flags.
1907
+ *
1908
+ * @param action - An action, or any object a plugin described.
1909
+ * @returns `hasAuthorize`, `hasScope`, and `policy`.
1910
+ */
1911
+ function getActionAccess(action) {
1912
+ const meta = actionMeta(action).access;
1913
+ const configAuthorize = typeof action.config?.authorize === "function";
1914
+ if (!meta) return {
1915
+ hasAuthorize: configAuthorize,
1916
+ hasScope: false,
1917
+ policy: configAuthorize ? "authorized" : "public"
1918
+ };
1919
+ const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
1920
+ const hasScope = Boolean(meta.hasScope);
1921
+ let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
1922
+ if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
1923
+ else if (policy !== "public" && !hasAuthorize) policy = "public";
1924
+ else if (policy === "scoped" && !hasScope) policy = "authorized";
1925
+ return {
1926
+ hasAuthorize,
1927
+ hasScope,
1928
+ policy
1929
+ };
1930
+ }
1931
+ // src/openapi.ts
1932
+ /** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */
1933
+ const OPENAPI_DEFAULTS = Object.freeze({
1934
+ title: "Brick-TS API Mesh",
1935
+ version: "1.0.0",
1936
+ path: "/openapi.json"
1937
+ });
1938
+ function isAnchor(node) {
1939
+ return typeof node === "object" && node !== null && typeof node.$id === "string";
1940
+ }
1941
+ function isBareRef(node) {
1942
+ return typeof node === "object" && node !== null && typeof node.$ref === "string" && !node.$ref.startsWith("#");
1943
+ }
1944
+ function toComponentKey(id) {
1945
+ return id.replace(/[^A-Za-z0-9.\-_]+/g, "_");
1946
+ }
1947
+ /**
1948
+ * TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors
1949
+ * (`{ $id: "T0", ..., { $ref: "T0" } }`). OpenAPI interprets a bare `$ref`
1950
+ * as an external file reference, so downstream tooling tries to load a
1951
+ * file named `T0` and fails. Hoist every anchored subschema into
1952
+ * `#/components/schemas/` and rewrite the refs to local pointers.
1953
+ * First definition wins when one `$id` is declared twice.
1954
+ */
1955
+ function hoistAnchoredSchemas(spec) {
1956
+ const anchored = /* @__PURE__ */ new Map();
1957
+ const collect = (node) => {
1958
+ if (Array.isArray(node)) return node.map(collect);
1959
+ if (typeof node !== "object" || node === null) return node;
1960
+ if (isAnchor(node)) {
1961
+ const id = node.$id;
1962
+ const { $id: _dropped, ...rest } = node;
1963
+ const collected = collect(rest);
1964
+ if (!anchored.has(id)) anchored.set(id, collected);
1965
+ return { $ref: `#/components/schemas/${toComponentKey(id)}` };
1966
+ }
1967
+ for (const key of Object.keys(node)) node[key] = collect(node[key]);
1968
+ return node;
1969
+ };
1970
+ const rewrite = (node) => {
1971
+ if (Array.isArray(node)) {
1972
+ for (const child of node) rewrite(child);
1973
+ return;
1974
+ }
1975
+ if (typeof node !== "object" || node === null) return;
1976
+ if (isBareRef(node)) node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;
1977
+ for (const key of Object.keys(node)) rewrite(node[key]);
1978
+ };
1979
+ collect(spec);
1980
+ const components = spec.components ??= {};
1981
+ const schemas = components.schemas ??= {};
1982
+ for (const [id, schema] of anchored) schemas[toComponentKey(id)] = schema;
1983
+ rewrite(spec);
1984
+ }
1985
+ /**
1986
+ * Build the OpenAPI 3.1 document for the services: one path per action route,
1987
+ * with request and response schemas from the actions' TypeBox schemas, their
1988
+ * declared errors, tags by service, and a bearer security scheme where any
1989
+ * action needs authorization. Declared events are listed under `x-brick-events`,
1990
+ * by wire name, with their service and payload schema.
1991
+ *
1992
+ * `brick()` calls this for `/openapi.json`; call it yourself to write the
1993
+ * document to a file or feed another tool.
1994
+ *
1995
+ * @param options - `title`, `version`, and `description` for the `info` block,
1996
+ * `prefix` (default `/api`), and the `services` to describe (the global
1997
+ * registry's by default).
1998
+ * @returns The document as a plain object.
1694
1999
  */
1695
2000
  function generateOpenApiSpec(options = {}) {
1696
2001
  const title = options.title ?? OPENAPI_DEFAULTS.title;
@@ -2183,847 +2488,555 @@ function normalizeDashboard(options) {
2183
2488
  const secrets = Object.freeze({
2184
2489
  ...tokens ? { token: Object.freeze(tokens) } : {},
2185
2490
  ...auth.authorize ? { authorize: auth.authorize } : {}
2186
- });
2187
- Object.defineProperty(normalized, "auth", {
2188
- enumerable: false,
2189
- get: () => secrets
2190
- });
2191
- }
2192
- return Object.freeze(normalized);
2193
- }
2194
- // src/endpoints.ts
2195
- /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
2196
- function resolveEndpointDb(service, services) {
2197
- if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb();
2198
- for (const svc of services) {
2199
- const db = svc.getDb();
2200
- if (db) return db;
2201
- }
2202
- }
2203
- /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
2204
- function createEndpointHandler(def, services) {
2205
- const logger = createLogger(`[${`endpoint:${def.method} ${def.path}`}]`);
2206
- return async ({ params, body, query, headers, request, set }) => {
2207
- const { traceId, requestId } = requestIds(headers, set);
2208
- const ctx = {
2209
- body,
2210
- db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
2211
- headers: headers ?? {},
2212
- logger,
2213
- params: params ?? {},
2214
- query: query ?? {},
2215
- request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
2216
- headers: new Headers(headers ?? {}),
2217
- method: def.method
2218
- }),
2219
- requestId,
2220
- set,
2221
- traceId
2222
- };
2223
- try {
2224
- return await def.handler(ctx);
2225
- } catch (err) {
2226
- const response = toErrorResponse(!(err instanceof ActionExecutionError || err instanceof ValidationError) && err !== null && typeof err === "object" && "status" in err && typeof err.status === "number" && Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? new ActionExecutionError("HTTP_ERROR", "message" in err && typeof err.message === "string" ? err.message : "Endpoint error", err.status, void 0, { cause: err }) : err, {
2227
- logger: ctx.logger,
2228
- requestId
2229
- });
2230
- set.status = response.status;
2231
- return response;
2232
- }
2233
- };
2234
- }
2235
- /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
2236
- function endpointPaths(defs) {
2237
- const paths = {};
2238
- for (const def of defs) {
2239
- const openApiPath = toOpenApiPath(def.path);
2240
- if (!paths[openApiPath]) paths[openApiPath] = {};
2241
- const params = pathParamNames(def.path).map((name) => ({
2242
- in: "path",
2243
- name,
2244
- required: true,
2245
- schema: { type: "string" }
2246
- }));
2247
- paths[openApiPath][def.method.toLowerCase()] = {
2248
- ...def.summary ? { summary: def.summary } : {},
2249
- ...def.description ? { description: def.description } : {},
2250
- ...def.tags ? { tags: def.tags } : {},
2251
- ...def.plugin ? { "x-brick-plugin": def.plugin } : {},
2252
- ...params.length > 0 ? { parameters: params } : {},
2253
- responses: { 200: { description: "Successful response" } }
2254
- };
2255
- }
2256
- return paths;
2257
- }
2258
- // src/events/id.ts
2259
- const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
2260
- function newEventId(now = Date.now()) {
2261
- let time = "";
2262
- let remaining = now;
2263
- for (let index = 0; index < 10; index++) {
2264
- time = ALPHABET[remaining % 32] + time;
2265
- remaining = Math.floor(remaining / 32);
2266
- }
2267
- let random = "";
2268
- for (const byte of crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))) random += ALPHABET[byte % 32];
2269
- return `evt_${time}${random}`;
2270
- }
2271
- /**
2272
- * A delivery's id: `<event id>:<listener>`, which is why a listener name cannot
2273
- * contain `:`.
2274
- */
2275
- const deliveryId = (eventId, listener) => `${eventId}:${listener}`;
2276
- // src/events/outbox.ts
2277
- const OUTBOX = Symbol.for("brick.outbox");
2278
- const OUTBOX_STATUSES = [
2279
- "pending",
2280
- "claimed",
2281
- "delivered",
2282
- "dead"
2283
- ];
2284
- function sqliteOutbox(name) {
2285
- const timestampMs = (column) => integer(column, { mode: "timestamp_ms" });
2286
- return sqliteTable(name, {
2287
- seq: integer("seq").primaryKey({ autoIncrement: true }),
2288
- id: text("id").notNull().unique(),
2289
- eventId: text("event_id").notNull(),
2290
- listener: text("listener").notNull(),
2291
- name: text("name").notNull(),
2292
- payload: text("payload", { mode: "json" }).notNull(),
2293
- traceId: text("trace_id"),
2294
- source: text("source"),
2295
- occurredAt: timestampMs("occurred_at").notNull(),
2296
- status: text("status").$type().notNull(),
2297
- attempts: integer("attempts").notNull().default(0),
2298
- lastError: text("last_error"),
2299
- availableAt: timestampMs("available_at").notNull(),
2300
- claimedAt: timestampMs("claimed_at"),
2301
- deliveredAt: timestampMs("delivered_at")
2302
- }, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
2303
- }
2304
- function postgresOutbox(name) {
2305
- const at = (column) => timestamp(column, { withTimezone: true });
2306
- return pgTable(name, {
2307
- seq: bigserial("seq", { mode: "number" }).primaryKey(),
2308
- id: text$1("id").notNull().unique(),
2309
- eventId: text$1("event_id").notNull(),
2310
- listener: text$1("listener").notNull(),
2311
- name: text$1("name").notNull(),
2312
- payload: jsonb("payload").notNull(),
2313
- traceId: text$1("trace_id"),
2314
- source: text$1("source"),
2315
- occurredAt: at("occurred_at").notNull(),
2316
- status: text$1("status").$type().notNull(),
2317
- attempts: integer$1("attempts").notNull().default(0),
2318
- lastError: text$1("last_error"),
2319
- availableAt: at("available_at").notNull(),
2320
- claimedAt: at("claimed_at"),
2321
- deliveredAt: at("delivered_at")
2322
- }, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
2323
- }
2324
- function outboxTable(engine, options = {}) {
2325
- const name = options.name ?? "brick_outbox";
2326
- const table = engine === "sqlite" ? sqliteOutbox(name) : postgresOutbox(name);
2327
- Object.defineProperty(table, OUTBOX, { value: { engine } });
2328
- return table;
2329
- }
2330
- /**
2331
- * Whether a value is an outbox table made by `outboxTable`.
2332
- *
2333
- * @param value - Anything.
2334
- * @returns `true` for an outbox table, narrowing its type.
2335
- */
2336
- function isOutboxTable(value) {
2337
- return typeof value === "object" && value !== null && OUTBOX in value;
2338
- }
2339
- /** The rows that record an event: one per listener, due now. */
2340
- function outboxRows(event, listeners) {
2341
- return listeners.map((listener) => ({
2342
- id: deliveryId(event.id, listener),
2343
- eventId: event.id,
2344
- listener,
2345
- name: event.name,
2346
- payload: event.payload,
2347
- traceId: event.traceId ?? null,
2348
- source: event.source ?? null,
2349
- occurredAt: event.occurredAt,
2350
- status: "pending",
2351
- attempts: 0,
2352
- availableAt: event.occurredAt
2353
- }));
2354
- }
2355
- /** The delivery a row of `outboxRows` is. */
2356
- function deliveryOf(row) {
2357
- return {
2358
- id: row.eventId,
2359
- name: row.name,
2360
- payload: row.payload,
2361
- occurredAt: row.occurredAt.toISOString(),
2362
- ...row.traceId ? { traceId: row.traceId } : {},
2363
- ...row.source ? { source: row.source } : {},
2364
- listener: row.listener,
2365
- deliveryId: row.id,
2366
- attempt: row.attempts
2367
- };
2368
- }
2369
- function outboxEngine(table) {
2370
- return table[OUTBOX].engine;
2371
- }
2372
- // src/events/transaction.ts
2373
- const sqliteQueues = /* @__PURE__ */ new WeakMap();
2374
- const active = new AsyncLocalStorage();
2375
- function joined(db) {
2376
- const open = active.getStore();
2377
- return open?.open && open.handles.has(db) ? open : void 0;
2378
- }
2379
- function isSqliteDatabase(db) {
2380
- return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
2381
- }
2382
- function rollbackQuietly(db, statement = "ROLLBACK") {
2383
- try {
2384
- db.$client.run(statement);
2385
- } catch {
2386
- return;
2387
- }
2388
- }
2389
- async function nested(db, open, fn) {
2390
- const commits = open.commits.length;
2391
- try {
2392
- if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
2393
- open.handles.add(tx);
2394
- return fn(tx);
2395
- });
2396
- const name = `brick_${++open.savepoints}`;
2397
- db.$client.run(`SAVEPOINT ${name}`);
2398
- try {
2399
- const result = await fn(db);
2400
- db.$client.run(`RELEASE ${name}`);
2401
- return result;
2402
- } catch (error) {
2403
- rollbackQuietly(db, `ROLLBACK TO ${name}`);
2404
- rollbackQuietly(db, `RELEASE ${name}`);
2405
- throw error;
2406
- }
2407
- } catch (error) {
2408
- open.commits.length = commits;
2409
- throw error;
2410
- }
2411
- }
2412
- /**
2413
- * Run `fn` in a database transaction: everything it writes through the `tx` it is
2414
- * given is committed together when it returns, or undone if it throws.
2415
- *
2416
- * Postgres uses a real transaction on one connection. SQLite has one connection
2417
- * and a synchronous driver, which Drizzle's own `transaction` cannot use with an
2418
- * async callback (it would commit before the callback finished). So transactions
2419
- * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
2420
- * A write made elsewhere in the process during that time, outside this helper,
2421
- * would join the transaction; use Postgres where that matters.
2422
- *
2423
- * A call made inside `fn` with the `tx` it was given (on SQLite, the database
2424
- * itself) joins the open transaction as a savepoint instead of waiting for it: a
2425
- * nested failure undoes only the nested work, and the outer transaction decides
2426
- * the commit. Nested calls must run one at a time.
2427
- *
2428
- * @param db - A Drizzle database, from `service.getDb()`.
2429
- * @param fn - Receives the transaction handle to run queries on.
2430
- * @returns What `fn` returned.
2431
- * @throws What `fn` threw, after rolling back.
2432
- */
2433
- async function runInTransaction(db, fn) {
2434
- const outer = joined(db);
2435
- if (outer) return nested(db, outer, fn);
2436
- const open = {
2437
- handles: /* @__PURE__ */ new Set(),
2438
- commits: [],
2439
- open: true,
2440
- savepoints: 0
2441
- };
2442
- let result;
2443
- try {
2444
- result = await active.run(open, () => begin(db, open, fn));
2445
- } finally {
2446
- open.open = false;
2447
- }
2448
- for (const commit of open.commits) await commit();
2449
- return result;
2450
- }
2451
- async function begin(db, open, fn) {
2452
- if (!isSqliteDatabase(db)) return db.transaction((tx) => {
2453
- open.handles.add(tx);
2454
- return fn(tx);
2455
- });
2456
- open.handles.add(db);
2457
- const previous = sqliteQueues.get(db) ?? Promise.resolve();
2458
- let release;
2459
- const turn = new Promise((resolve) => {
2460
- release = resolve;
2461
- });
2462
- sqliteQueues.set(db, previous.then(() => turn));
2463
- await previous;
2464
- try {
2465
- db.$client.run("BEGIN IMMEDIATE");
2466
- try {
2467
- const result = await fn(db);
2468
- db.$client.run("COMMIT");
2469
- return result;
2470
- } catch (error) {
2471
- rollbackQuietly(db);
2472
- throw error;
2473
- }
2474
- } finally {
2475
- release();
2476
- }
2477
- }
2478
- /** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
2479
- function inTransaction(db) {
2480
- return joined(db) !== void 0;
2481
- }
2482
- /**
2483
- * Run `fn` once the transaction that `db` belongs to has committed, or now when
2484
- * `db` is not in one opened by `runInTransaction`. It never runs when that
2485
- * transaction, or the savepoint it was queued in, rolls back. An error it throws
2486
- * reaches the caller of the outermost `runInTransaction`, after the commit.
2487
- *
2488
- * @param db - The handle the work ran on: a `tx`, or a database.
2489
- * @param fn - The side effect, such as clearing a cache.
2490
- */
2491
- async function onTransactionCommit(db, fn) {
2492
- const open = joined(db);
2493
- if (open) open.commits.push(fn);
2494
- else await fn();
2495
- }
2496
- // src/events/dispatcher.ts
2497
- function resolveDispatchOptions(options) {
2498
- return {
2499
- timer: options.timer ?? true,
2500
- intervalMs: options.intervalMs ?? 1e3,
2501
- batchSize: options.batchSize ?? 50,
2502
- maxAttempts: options.maxAttempts ?? 8,
2503
- claimTimeoutMs: options.claimTimeoutMs ?? 6e4,
2504
- maxBackoffMs: options.maxBackoffMs ?? 3e5,
2505
- retainDeliveredMs: options.retainDeliveredMs ?? 864e5
2506
- };
2507
- }
2508
- const PURGE_INTERVAL_MS = 6e4;
2509
- /** Listeners whose `retry` threw, logged once each. */
2510
- const brokenRetry = /* @__PURE__ */ new WeakSet();
2511
- /** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry", and is logged once. */
2512
- function decideRetry(name, listener, error) {
2513
- if (!listener.retry) return "retry";
2514
- try {
2515
- return listener.retry(error instanceof ActionExecutionError && listener.errors?.[error.code] ? {
2516
- code: error.code,
2517
- message: error.message,
2518
- details: error.details
2519
- } : {
2520
- code: "UNKNOWN",
2521
- message: error instanceof Error ? error.message : String(error),
2522
- cause: error
2523
- });
2524
- } catch (thrown) {
2525
- if (!brokenRetry.has(listener)) {
2526
- brokenRetry.add(listener);
2527
- console.error(`[Brick-TS events] Listener '${name}': its retry() threw, so the failure is retried. Later throws are not logged.`, thrown);
2528
- }
2529
- return "retry";
2530
- }
2531
- }
2532
- function backoffMs(attempt, maxBackoffMs) {
2533
- return Math.min(1e3 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);
2534
- }
2535
- /**
2536
- * Delivers the events recorded in one outbox table to the app's listeners.
2537
- *
2538
- * It claims a batch of due rows, runs each listener, and marks the row delivered.
2539
- * A listener that throws is retried later with a growing delay, and parked as
2540
- * dead after its attempts run out. Several dispatchers can share a table: on
2541
- * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
2542
- * finished within `claimTimeoutMs` (the process died) is taken by another.
2543
- * Delivery is at least once, so a listener should tolerate running twice for the
2544
- * same `deliveryId`.
2545
- */
2546
- var Dispatcher = class {
2547
- db;
2548
- table;
2549
- listeners;
2550
- engine;
2551
- options;
2552
- inFlight = /* @__PURE__ */ new Set();
2553
- timer;
2554
- tickQueue;
2555
- lastPurge = 0;
2556
- constructor(db, table, listeners, options = {}) {
2557
- this.db = db;
2558
- this.table = table;
2559
- this.listeners = listeners;
2560
- this.engine = outboxEngine(table);
2561
- this.options = resolveDispatchOptions(options);
2562
- }
2563
- /** Start looking for due deliveries on a timer. Does nothing if it already is. */
2564
- start() {
2565
- if (this.timer || !this.options.timer) return;
2566
- this.timer = setInterval(() => void this.tick(), this.options.intervalMs);
2567
- this.timer.unref?.();
2568
- this.tick();
2569
- }
2570
- /** Stop the timer and wait for the deliveries that are running to finish. */
2571
- async stop() {
2572
- if (this.timer) clearInterval(this.timer);
2573
- this.timer = void 0;
2574
- await this.tickQueue;
2575
- await Promise.allSettled(this.inFlight);
2576
- }
2577
- /** Look for work soon, without waiting for the timer. Safe to call often. */
2578
- notify() {
2579
- if (!this.timer) return;
2580
- setTimeout(() => void this.tick(), 0).unref?.();
2581
- }
2582
- /** Claim what is due and run it, once. @returns How many deliveries it started. */
2583
- tick() {
2584
- this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(() => this.claimAndRun(), () => this.claimAndRun());
2585
- return this.tickQueue;
2586
- }
2587
- /**
2588
- * Deliver everything that is due now and wait until those deliveries are done.
2589
- * Deliveries that fail and are rescheduled are not waited for again.
2590
- *
2591
- * @returns How many deliveries it ran.
2592
- */
2593
- async drain() {
2594
- let total = 0;
2595
- for (;;) {
2596
- const started = await this.tick();
2597
- await Promise.allSettled(this.inFlight);
2598
- if (started === 0) return total;
2599
- total += started;
2600
- }
2601
- }
2602
- async counts() {
2603
- const t = this.table;
2604
- const rows = await this.db.select({
2605
- status: t.status,
2606
- count: sql`count(*)`
2607
- }).from(t).groupBy(t.status);
2608
- const counts = Object.fromEntries(OUTBOX_STATUSES.map((status) => [status, 0]));
2609
- for (const row of rows) counts[row.status] = Number(row.count);
2610
- return counts;
2611
- }
2612
- /**
2613
- * Put parked deliveries back in line, with their attempts reset.
2614
- *
2615
- * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
2616
- * @returns How many deliveries were put back.
2617
- */
2618
- async retryDead(deliveryId) {
2619
- const t = this.table;
2620
- const rows = await this.db.update(t).set({
2621
- status: "pending",
2622
- attempts: 0,
2623
- availableAt: /* @__PURE__ */ new Date()
2624
- }).where(deliveryId ? and(eq(t.status, "dead"), eq(t.id, deliveryId)) : eq(t.status, "dead")).returning({ id: t.id });
2625
- if (rows.length) this.notify();
2626
- return rows.length;
2627
- }
2628
- async claimAndRun() {
2629
- try {
2630
- const room = this.options.batchSize - this.inFlight.size;
2631
- if (room <= 0) return 0;
2632
- const rows = await this.claim(room);
2633
- for (const row of rows) {
2634
- const run = this.deliver(row).finally(() => {
2635
- this.inFlight.delete(run);
2636
- });
2637
- this.inFlight.add(run);
2638
- }
2639
- await this.purgeDelivered();
2640
- return rows.length;
2641
- } catch (error) {
2642
- this.logError(error);
2643
- return 0;
2644
- }
2645
- }
2646
- async claim(limit) {
2647
- const t = this.table;
2648
- const now = /* @__PURE__ */ new Date();
2649
- const stale = new Date(now.getTime() - this.options.claimTimeoutMs);
2650
- const due = or(and(eq(t.status, "pending"), lte(t.availableAt, now)), and(eq(t.status, "claimed"), lt(t.claimedAt, stale)));
2651
- const claimIn = async (tx) => {
2652
- let select = tx.select().from(t).where(due).orderBy(asc(t.seq)).limit(limit);
2653
- if (this.engine === "postgres") select = select.for("update", { skipLocked: true });
2654
- const picked = await select;
2655
- if (!picked.length) return [];
2656
- await tx.update(t).set({
2657
- status: "claimed",
2658
- claimedAt: now,
2659
- attempts: sql`${t.attempts} + 1`
2660
- }).where(inArray(t.seq, picked.map((row) => row.seq)));
2661
- return picked.map((row) => ({
2662
- ...row,
2663
- attempts: row.attempts + 1
2664
- }));
2665
- };
2666
- return this.engine === "postgres" ? this.db.transaction(claimIn) : runInTransaction(this.db, claimIn);
2667
- }
2668
- async deliver(row) {
2669
- const listener = this.listeners(row.listener);
2670
- if (!listener) {
2671
- await this.park(row, `No listener named '${row.listener}' is registered`);
2672
- return;
2673
- }
2674
- try {
2675
- await listener.run(deliveryOf(row));
2676
- } catch (error) {
2677
- await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(row.listener, listener, error));
2678
- return;
2679
- }
2680
- await this.markDelivered(row);
2681
- }
2682
- async markDelivered(row) {
2683
- const t = this.table;
2684
- try {
2685
- if (this.options.retainDeliveredMs === 0) await this.db.delete(t).where(eq(t.seq, row.seq));
2686
- else await this.db.update(t).set({
2687
- status: "delivered",
2688
- deliveredAt: /* @__PURE__ */ new Date(),
2689
- lastError: null
2690
- }).where(eq(t.seq, row.seq));
2691
- } catch (error) {
2692
- this.logError(error);
2693
- }
2694
- }
2695
- async fail(row, error, maxAttempts, decision) {
2696
- const message = error instanceof Error ? error.message : String(error);
2697
- if (decision === "dead" || row.attempts >= maxAttempts) {
2698
- await this.park(row, message);
2699
- return;
2700
- }
2701
- const t = this.table;
2702
- try {
2703
- await this.db.update(t).set({
2704
- status: "pending",
2705
- lastError: message,
2706
- claimedAt: null,
2707
- availableAt: new Date(Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs))
2708
- }).where(eq(t.seq, row.seq));
2709
- } catch (writeError) {
2710
- this.logError(writeError);
2711
- }
2491
+ });
2492
+ Object.defineProperty(normalized, "auth", {
2493
+ enumerable: false,
2494
+ get: () => secrets
2495
+ });
2712
2496
  }
2713
- async park(row, message) {
2714
- const t = this.table;
2497
+ return Object.freeze(normalized);
2498
+ }
2499
+ // src/endpoints.ts
2500
+ /** Resolve the db for an endpoint: explicit service first, else first service holding one. */
2501
+ function resolveEndpointDb(service, services) {
2502
+ if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb();
2503
+ for (const svc of services) {
2504
+ const db = svc.getDb();
2505
+ if (db) return db;
2506
+ }
2507
+ }
2508
+ /** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
2509
+ function createEndpointHandler(def, services) {
2510
+ const logger = createLogger(`[${`endpoint:${def.method} ${def.path}`}]`);
2511
+ return async ({ params, body, query, headers, request, set }) => {
2512
+ const { traceId, requestId } = requestIds(headers, set);
2513
+ const ctx = {
2514
+ body,
2515
+ db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
2516
+ headers: headers ?? {},
2517
+ logger,
2518
+ params: params ?? {},
2519
+ query: query ?? {},
2520
+ request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
2521
+ headers: new Headers(headers ?? {}),
2522
+ method: def.method
2523
+ }),
2524
+ requestId,
2525
+ set,
2526
+ traceId
2527
+ };
2715
2528
  try {
2716
- await this.db.update(t).set({
2717
- status: "dead",
2718
- lastError: message,
2719
- claimedAt: null
2720
- }).where(eq(t.seq, row.seq));
2721
- } catch (error) {
2722
- this.logError(error);
2529
+ return await def.handler(ctx);
2530
+ } catch (err) {
2531
+ const response = toErrorResponse(!(err instanceof ActionExecutionError || err instanceof ValidationError) && err !== null && typeof err === "object" && "status" in err && typeof err.status === "number" && Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? new ActionExecutionError("HTTP_ERROR", "message" in err && typeof err.message === "string" ? err.message : "Endpoint error", err.status, void 0, { cause: err }) : err, {
2532
+ logger: ctx.logger,
2533
+ requestId
2534
+ });
2535
+ set.status = response.status;
2536
+ return response;
2723
2537
  }
2724
- }
2725
- logError(error) {
2726
- console.error("[Brick-TS events]", error);
2727
- }
2728
- async purgeDelivered() {
2729
- const keep = this.options.retainDeliveredMs;
2730
- const now = Date.now();
2731
- if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;
2732
- this.lastPurge = now;
2733
- const t = this.table;
2734
- await this.db.delete(t).where(and(eq(t.status, "delivered"), lt(t.deliveredAt, new Date(now - keep))));
2735
- }
2736
- };
2737
- // src/events/catalog.ts
2738
- function isEventRef(value) {
2739
- return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.service === "string" && typeof value.schema === "object";
2538
+ };
2740
2539
  }
2741
- /** Build `service.events` from its catalog. */
2742
- function eventRefs(service, catalog) {
2743
- const refs = Object.create(null);
2744
- for (const [key, schema] of Object.entries(catalog ?? {})) {
2745
- 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`);
2746
- if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
2747
- refs[key] = Object.freeze({
2748
- name: `${service}.${key}`,
2749
- service,
2750
- schema
2751
- });
2540
+ /** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
2541
+ function endpointPaths(defs) {
2542
+ const paths = {};
2543
+ for (const def of defs) {
2544
+ const openApiPath = toOpenApiPath(def.path);
2545
+ if (!paths[openApiPath]) paths[openApiPath] = {};
2546
+ const params = pathParamNames(def.path).map((name) => ({
2547
+ in: "path",
2548
+ name,
2549
+ required: true,
2550
+ schema: { type: "string" }
2551
+ }));
2552
+ paths[openApiPath][def.method.toLowerCase()] = {
2553
+ ...def.summary ? { summary: def.summary } : {},
2554
+ ...def.description ? { description: def.description } : {},
2555
+ ...def.tags ? { tags: def.tags } : {},
2556
+ ...def.plugin ? { "x-brick-plugin": def.plugin } : {},
2557
+ ...params.length > 0 ? { parameters: params } : {},
2558
+ responses: { 200: { description: "Successful response" } }
2559
+ };
2752
2560
  }
2753
- return Object.freeze(refs);
2561
+ return paths;
2754
2562
  }
2755
- /** @throws When the payload does not match the event's schema. */
2756
- function checkPayload(ref, payload) {
2757
- const result = validateWithSchema(ref.schema, payload);
2758
- if (!result.success) throw new Error(`Event "${ref.name}" payload does not match its schema: ${result.errors.map((error) => `${error.path || "/"} ${error.message}`).join("; ")}`);
2563
+ // src/events/id.ts
2564
+ const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
2565
+ function newEventId(now = Date.now()) {
2566
+ let time = "";
2567
+ let remaining = now;
2568
+ for (let index = 0; index < 10; index++) {
2569
+ time = ALPHABET[remaining % 32] + time;
2570
+ remaining = Math.floor(remaining / 32);
2571
+ }
2572
+ let random = "";
2573
+ for (const byte of crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))) random += ALPHABET[byte % 32];
2574
+ return `evt_${time}${random}`;
2759
2575
  }
2760
- /** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
2761
- const CRUD_EVENT_OPERATIONS = [
2762
- "create",
2763
- "update",
2764
- "delete"
2576
+ /**
2577
+ * A delivery's id: `<event id>:<listener>`, which is why a listener name cannot
2578
+ * contain `:`.
2579
+ */
2580
+ const deliveryId = (eventId, listener) => `${eventId}:${listener}`;
2581
+ // src/events/outbox.ts
2582
+ const OUTBOX = Symbol.for("brick.outbox");
2583
+ const OUTBOX_STATUSES = [
2584
+ "pending",
2585
+ "claimed",
2586
+ "delivered",
2587
+ "dead"
2765
2588
  ];
2766
- /** The event a CRUD write records: `<resource>.<operation>`. */
2767
- const crudEventName = (resource, operation) => `${resource}.${operation}`;
2768
- /** The `source` of a resource's events: `<service>.<resource>`. */
2769
- const crudEventSource = (service, resource) => `${service}.${resource}`;
2770
- /** Whether `name` is the CRUD event of one of `resources`. */
2771
- function isCrudEvent(name, resources) {
2772
- const dot = name.indexOf(".");
2773
- return dot > 0 && CRUD_EVENT_OPERATIONS.includes(name.slice(dot + 1)) && resources.includes(name.slice(0, dot));
2589
+ function sqliteOutbox(name) {
2590
+ const timestampMs = (column) => integer(column, { mode: "timestamp_ms" });
2591
+ return sqliteTable(name, {
2592
+ seq: integer("seq").primaryKey({ autoIncrement: true }),
2593
+ id: text("id").notNull().unique(),
2594
+ eventId: text("event_id").notNull(),
2595
+ listener: text("listener").notNull(),
2596
+ name: text("name").notNull(),
2597
+ payload: text("payload", { mode: "json" }).notNull(),
2598
+ traceId: text("trace_id"),
2599
+ source: text("source"),
2600
+ occurredAt: timestampMs("occurred_at").notNull(),
2601
+ status: text("status").$type().notNull(),
2602
+ attempts: integer("attempts").notNull().default(0),
2603
+ lastError: text("last_error"),
2604
+ availableAt: timestampMs("available_at").notNull(),
2605
+ claimedAt: timestampMs("claimed_at"),
2606
+ deliveredAt: timestampMs("delivered_at")
2607
+ }, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
2608
+ }
2609
+ function postgresOutbox(name) {
2610
+ const at = (column) => timestamp(column, { withTimezone: true });
2611
+ return pgTable(name, {
2612
+ seq: bigserial("seq", { mode: "number" }).primaryKey(),
2613
+ id: text$1("id").notNull().unique(),
2614
+ eventId: text$1("event_id").notNull(),
2615
+ listener: text$1("listener").notNull(),
2616
+ name: text$1("name").notNull(),
2617
+ payload: jsonb("payload").notNull(),
2618
+ traceId: text$1("trace_id"),
2619
+ source: text$1("source"),
2620
+ occurredAt: at("occurred_at").notNull(),
2621
+ status: text$1("status").$type().notNull(),
2622
+ attempts: integer$1("attempts").notNull().default(0),
2623
+ lastError: text$1("last_error"),
2624
+ availableAt: at("available_at").notNull(),
2625
+ claimedAt: at("claimed_at"),
2626
+ deliveredAt: at("delivered_at")
2627
+ }, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
2628
+ }
2629
+ function outboxTable(engine, options = {}) {
2630
+ const name = options.name ?? "brick_outbox";
2631
+ const table = engine === "sqlite" ? sqliteOutbox(name) : postgresOutbox(name);
2632
+ Object.defineProperty(table, OUTBOX, { value: { engine } });
2633
+ return table;
2634
+ }
2635
+ /**
2636
+ * Whether a value is an outbox table made by `outboxTable`.
2637
+ *
2638
+ * @param value - Anything.
2639
+ * @returns `true` for an outbox table, narrowing its type.
2640
+ */
2641
+ function isOutboxTable(value) {
2642
+ return typeof value === "object" && value !== null && OUTBOX in value;
2643
+ }
2644
+ /** The rows that record an event: one per listener, due now. */
2645
+ function outboxRows(event, listeners) {
2646
+ return listeners.map((listener) => ({
2647
+ id: deliveryId(event.id, listener),
2648
+ eventId: event.id,
2649
+ listener,
2650
+ name: event.name,
2651
+ payload: event.payload,
2652
+ traceId: event.traceId ?? null,
2653
+ source: event.source ?? null,
2654
+ occurredAt: event.occurredAt,
2655
+ status: "pending",
2656
+ attempts: 0,
2657
+ availableAt: event.occurredAt
2658
+ }));
2659
+ }
2660
+ /** The delivery a row of `outboxRows` is. */
2661
+ function deliveryOf(row) {
2662
+ return {
2663
+ id: row.eventId,
2664
+ name: row.name,
2665
+ payload: row.payload,
2666
+ occurredAt: row.occurredAt.toISOString(),
2667
+ ...row.traceId ? { traceId: row.traceId } : {},
2668
+ ...row.source ? { source: row.source } : {},
2669
+ listener: row.listener,
2670
+ deliveryId: row.id,
2671
+ attempt: row.attempts
2672
+ };
2673
+ }
2674
+ function outboxEngine(table) {
2675
+ return table[OUTBOX].engine;
2676
+ }
2677
+ // src/events/transaction.ts
2678
+ const sqliteQueues = /* @__PURE__ */ new WeakMap();
2679
+ const active = new AsyncLocalStorage();
2680
+ function joined(db) {
2681
+ const open = active.getStore();
2682
+ return open?.open && open.handles.has(db) ? open : void 0;
2683
+ }
2684
+ function isSqliteDatabase(db) {
2685
+ return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
2686
+ }
2687
+ function rollbackQuietly(db, statement = "ROLLBACK") {
2688
+ try {
2689
+ db.$client.run(statement);
2690
+ } catch {
2691
+ return;
2692
+ }
2693
+ }
2694
+ async function nested(db, open, fn) {
2695
+ const commits = open.commits.length;
2696
+ try {
2697
+ if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
2698
+ open.handles.add(tx);
2699
+ return fn(tx);
2700
+ });
2701
+ const name = `brick_${++open.savepoints}`;
2702
+ db.$client.run(`SAVEPOINT ${name}`);
2703
+ try {
2704
+ const result = await fn(db);
2705
+ db.$client.run(`RELEASE ${name}`);
2706
+ return result;
2707
+ } catch (error) {
2708
+ rollbackQuietly(db, `ROLLBACK TO ${name}`);
2709
+ rollbackQuietly(db, `RELEASE ${name}`);
2710
+ throw error;
2711
+ }
2712
+ } catch (error) {
2713
+ open.commits.length = commits;
2714
+ throw error;
2715
+ }
2774
2716
  }
2775
2717
  /**
2776
- * Check an event against the catalog of the service recording it. Without a
2777
- * catalog any name goes. With one, the name must be `<service>.<event>` from it
2778
- * (the payload is checked against its schema) or a CRUD event of one of the
2779
- * service's resources (`<resource>.create|update|delete`).
2718
+ * Run `fn` in a database transaction: everything it writes through the `tx` it is
2719
+ * given is committed together when it returns, or undone if it throws.
2780
2720
  *
2781
- * @throws When the name is not declared or the payload does not match.
2721
+ * Postgres uses a real transaction on one connection. SQLite has one connection
2722
+ * and a synchronous driver, which Drizzle's own `transaction` cannot use with an
2723
+ * async callback (it would commit before the callback finished). So transactions
2724
+ * on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
2725
+ * A write made elsewhere in the process during that time, outside this helper,
2726
+ * would join the transaction; use Postgres where that matters.
2727
+ *
2728
+ * A call made inside `fn` with the `tx` it was given (on SQLite, the database
2729
+ * itself) joins the open transaction as a savepoint instead of waiting for it: a
2730
+ * nested failure undoes only the nested work, and the outer transaction decides
2731
+ * the commit. Nested calls must run one at a time.
2732
+ *
2733
+ * @param db - A Drizzle database, from `service.getDb()`.
2734
+ * @param fn - Receives the transaction handle to run queries on.
2735
+ * @returns What `fn` returned.
2736
+ * @throws What `fn` threw, after rolling back.
2782
2737
  */
2783
- function checkEvent(service, name, payload) {
2784
- const prefix = `${service.name}.`;
2785
- const ref = name.startsWith(prefix) ? service.events[name.slice(prefix.length)] : void 0;
2786
- if (ref) return checkPayload(ref, payload);
2787
- if (!service.hasCatalog) return;
2788
- if (isCrudEvent(name, service.listResources().map((r) => r.name))) return;
2789
- throw new Error(`Event "${name}" is not in the event catalog of service "${service.name}" (declared: ${Object.values(service.events).map((ref) => ref.name).join(", ") || "none"})`);
2738
+ async function runInTransaction(db, fn) {
2739
+ const outer = joined(db);
2740
+ if (outer) return nested(db, outer, fn);
2741
+ const open = {
2742
+ handles: /* @__PURE__ */ new Set(),
2743
+ commits: [],
2744
+ open: true,
2745
+ savepoints: 0
2746
+ };
2747
+ let result;
2748
+ try {
2749
+ result = await active.run(open, () => begin(db, open, fn));
2750
+ } finally {
2751
+ open.open = false;
2752
+ }
2753
+ for (const commit of open.commits) await commit();
2754
+ return result;
2790
2755
  }
2791
- // src/events/listener.ts
2792
- function defineListener(config) {
2793
- const on = (Array.isArray(config.on) ? config.on : [config.on]).map((item) => isEventRef(item) ? item.name : item);
2794
- validateListener({
2795
- ...config,
2796
- on
2756
+ async function begin(db, open, fn) {
2757
+ if (!isSqliteDatabase(db)) return db.transaction((tx) => {
2758
+ open.handles.add(tx);
2759
+ return fn(tx);
2797
2760
  });
2798
- const helpers = buildErrorHelpers(config.errors);
2799
- return Object.freeze({
2800
- name: config.name,
2801
- on: Object.freeze(on),
2802
- ...config.run !== void 0 ? { run: ((delivery) => config.run(delivery, { error: helpers })) } : {},
2803
- ...config.errors ? { errors: config.errors } : {},
2804
- ...config.retry ? { retry: config.retry } : {},
2805
- ...config.workflow !== void 0 ? { workflow: config.workflow } : {},
2806
- ...config.maxAttempts !== void 0 ? { maxAttempts: config.maxAttempts } : {}
2761
+ open.handles.add(db);
2762
+ const previous = sqliteQueues.get(db) ?? Promise.resolve();
2763
+ let release;
2764
+ const turn = new Promise((resolve) => {
2765
+ release = resolve;
2807
2766
  });
2767
+ sqliteQueues.set(db, previous.then(() => turn));
2768
+ await previous;
2769
+ try {
2770
+ db.$client.run("BEGIN IMMEDIATE");
2771
+ try {
2772
+ const result = await fn(db);
2773
+ db.$client.run("COMMIT");
2774
+ return result;
2775
+ } catch (error) {
2776
+ rollbackQuietly(db);
2777
+ throw error;
2778
+ }
2779
+ } finally {
2780
+ release();
2781
+ }
2808
2782
  }
2809
- /**
2810
- * @throws When the name is empty or contains `:`, `on` is empty, `maxAttempts`
2811
- * is not a positive integer, or the listener has both or neither of `run` and
2812
- * `workflow`.
2813
- */
2814
- function validateListener(listener) {
2815
- const { name, on, maxAttempts, run, workflow } = listener;
2816
- if (typeof name !== "string" || !name) throw new Error("An event listener needs a name");
2817
- if (name.includes(":")) throw new Error(`Event listener name '${name}' must not contain ':'`);
2818
- if (!Array.isArray(on) || !on.length || on.some((pattern) => !pattern || typeof pattern !== "string")) throw new Error(`Event listener '${name}' listens for nothing`);
2819
- if (maxAttempts !== void 0 && (!Number.isInteger(maxAttempts) || maxAttempts < 1)) throw new Error(`Event listener '${name}': maxAttempts must be a positive integer`);
2820
- if (run !== void 0 && workflow !== void 0) throw new Error(`Event listener '${name}' has both run and workflow; give it one`);
2821
- if (run === void 0 && workflow === void 0) throw new Error(`Event listener '${name}' needs a run handler or a workflow`);
2822
- if (run !== void 0 && typeof run !== "function") throw new Error(`Event listener '${name}': run must be a function`);
2823
- if (workflow !== void 0 && typeof workflow !== "function") throw new Error(`Event listener '${name}': workflow must be a function marked "use workflow"`);
2783
+ /** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
2784
+ function inTransaction(db) {
2785
+ return joined(db) !== void 0;
2824
2786
  }
2825
- /** The deps a plugin's listener runs with, set by the plugin install; `undefined` for the app's own. */
2826
- const listenerDeps = (listener) => listener[PLUGIN_DEPS];
2827
- // src/events/workflows.ts
2828
- /** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */
2829
- const WORKFLOW_BUNDLE = {
2830
- dir: ".well-known/workflow/v1",
2831
- flow: "flow.mjs",
2832
- steps: "__step_registrations.mjs",
2833
- webhook: "webhook.mjs",
2834
- manifest: "manifest.json"
2835
- };
2836
- /** From the Workflow SDK: the queue a workflow run goes to (`getQueueTopicPrefix("workflow")` in `@workflow/world`), and the header a world names it in. */
2837
- const WORKFLOW_QUEUE = {
2838
- prefix: "__wkf_workflow_",
2839
- header: "x-vqs-queue-name"
2840
- };
2841
- const STOPPED = "The events were stopped, so workflows can no longer run";
2842
- const NOT_BUILT = "brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.";
2843
- /** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */
2844
- const WEBHOOK_ROUTE = `/${WORKFLOW_BUNDLE.dir}/webhook/*`;
2845
- /** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */
2846
- const STEP_REGISTRY = Symbol.for("@workflow/core//registeredSteps");
2847
2787
  /**
2848
- * Where the workflow bundle is read from, and the project it is built from.
2788
+ * Run `fn` once the transaction that `db` belongs to has committed, or now when
2789
+ * `db` is not in one opened by `runInTransaction`. It never runs when that
2790
+ * transaction, or the savepoint it was queued in, rolls back. An error it throws
2791
+ * reaches the caller of the outermost `runInTransaction`, after the commit.
2849
2792
  *
2850
- * @param options - The `events.workflows` option.
2851
- * @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the
2852
- * builder finds the SDK from where it writes, and skips only this directory when it
2853
- * looks for workflows.
2793
+ * @param db - The handle the work ran on: a `tx`, or a database.
2794
+ * @param fn - The side effect, such as clearing a cache.
2854
2795
  */
2855
- function resolveWorkflowPaths(options = {}) {
2856
- const root = resolve(options.root ?? process.cwd());
2796
+ async function onTransactionCommit(db, fn) {
2797
+ const open = joined(db);
2798
+ if (open) open.commits.push(fn);
2799
+ else await fn();
2800
+ }
2801
+ // src/events/dispatcher.ts
2802
+ function resolveDispatchOptions(options) {
2857
2803
  return {
2858
- root,
2859
- dir: join(root, WORKFLOW_BUNDLE.dir)
2804
+ timer: options.timer ?? true,
2805
+ intervalMs: options.intervalMs ?? 1e3,
2806
+ batchSize: options.batchSize ?? 50,
2807
+ maxAttempts: options.maxAttempts ?? 8,
2808
+ claimTimeoutMs: options.claimTimeoutMs ?? 6e4,
2809
+ maxBackoffMs: options.maxBackoffMs ?? 3e5,
2810
+ retainDeliveredMs: options.retainDeliveredMs ?? 864e5
2860
2811
  };
2861
2812
  }
2813
+ const PURGE_INTERVAL_MS = 6e4;
2814
+ /** Listeners whose `retry` threw, logged once each. */
2815
+ const brokenRetry = /* @__PURE__ */ new WeakSet();
2816
+ /** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry", and is logged once. */
2817
+ function decideRetry(name, listener, error) {
2818
+ if (!listener.retry) return "retry";
2819
+ try {
2820
+ return listener.retry(error instanceof ActionExecutionError && listener.errors?.[error.code] ? {
2821
+ code: error.code,
2822
+ message: error.message,
2823
+ details: error.details
2824
+ } : {
2825
+ code: "UNKNOWN",
2826
+ message: error instanceof Error ? error.message : String(error),
2827
+ cause: error
2828
+ });
2829
+ } catch (thrown) {
2830
+ if (!brokenRetry.has(listener)) {
2831
+ brokenRetry.add(listener);
2832
+ console.error(`[Brick-TS events] Listener '${name}': its retry() threw, so the failure is retried. Later throws are not logged.`, thrown);
2833
+ }
2834
+ return "retry";
2835
+ }
2836
+ }
2837
+ function backoffMs(attempt, maxBackoffMs) {
2838
+ return Math.min(1e3 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);
2839
+ }
2862
2840
  /**
2863
- * Runs workflow listeners: wires the world into the Workflow SDK, serves the
2864
- * built bundle from this process, and starts one run for each delivery.
2841
+ * Delivers the events recorded in one outbox table to the app's listeners.
2865
2842
  *
2866
- * Nothing is loaded until it is needed, so an app without workflow listeners
2867
- * never imports the SDK.
2843
+ * It claims a batch of due rows, runs each listener, and marks the row delivered.
2844
+ * A listener that throws is retried later with a growing delay, and parked as
2845
+ * dead after its attempts run out. Several dispatchers can share a table: on
2846
+ * Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
2847
+ * finished within `claimTimeoutMs` (the process died) is taken by another.
2848
+ * Delivery is at least once, so a listener should tolerate running twice for the
2849
+ * same `deliveryId`.
2868
2850
  */
2869
- var WorkflowRuntime = class {
2870
- world;
2851
+ var Dispatcher = class {
2852
+ db;
2853
+ table;
2871
2854
  listeners;
2872
- deps;
2873
- root;
2874
- dir;
2875
- ready;
2876
- connected;
2877
- closed = false;
2878
- constructor(world, options, listeners, deps = {}) {
2879
- this.world = world;
2855
+ engine;
2856
+ options;
2857
+ inFlight = /* @__PURE__ */ new Set();
2858
+ timer;
2859
+ tickQueue;
2860
+ lastPurge = 0;
2861
+ constructor(db, table, listeners, options = {}) {
2862
+ this.db = db;
2863
+ this.table = table;
2880
2864
  this.listeners = listeners;
2881
- this.deps = deps;
2882
- ({root: this.root, dir: this.dir} = resolveWorkflowPaths(options));
2865
+ this.engine = outboxEngine(table);
2866
+ this.options = resolveDispatchOptions(options);
2883
2867
  }
2884
- /** Begin loading the runtime now rather than at the first delivery. */
2885
- warmUp() {
2886
- this.ensure().catch((error) => console.error(`[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`));
2868
+ /** Start looking for due deliveries on a timer. Does nothing if it already is. */
2869
+ start() {
2870
+ if (this.timer || !this.options.timer) return;
2871
+ this.timer = setInterval(() => void this.tick(), this.options.intervalMs);
2872
+ this.timer.unref?.();
2873
+ this.tick();
2874
+ }
2875
+ /** Stop the timer and wait for the deliveries that are running to finish. */
2876
+ async stop() {
2877
+ if (this.timer) clearInterval(this.timer);
2878
+ this.timer = void 0;
2879
+ await this.tickQueue;
2880
+ await Promise.allSettled(this.inFlight);
2881
+ }
2882
+ /** Look for work soon, without waiting for the timer. Safe to call often. */
2883
+ notify() {
2884
+ if (!this.timer) return;
2885
+ setTimeout(() => void this.tick(), 0).unref?.();
2886
+ }
2887
+ /** Claim what is due and run it, once. @returns How many deliveries it started. */
2888
+ tick() {
2889
+ this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(() => this.claimAndRun(), () => this.claimAndRun());
2890
+ return this.tickQueue;
2887
2891
  }
2888
2892
  /**
2889
- * Start the run for a delivery.
2890
- *
2891
- * The run is named after the delivery id, so a delivery that is tried again
2892
- * finds the run it already started instead of starting another.
2893
+ * Deliver everything that is due now and wait until those deliveries are done.
2894
+ * Deliveries that fail and are rescheduled are not waited for again.
2893
2895
  *
2894
- * @param listener - The workflow listener the delivery is for.
2895
- * @param delivery - The delivery.
2896
+ * @returns How many deliveries it ran.
2896
2897
  */
2897
- async startRun(listener, delivery) {
2898
- const sdk = await this.ensure();
2899
- const { attempt: _attempt, ...event } = delivery;
2900
- await sdk.start(listener.workflow, [event], {
2901
- world: this.world,
2902
- runKey: delivery.deliveryId,
2903
- runKeyTime: Date.parse(delivery.occurredAt)
2904
- });
2898
+ async drain() {
2899
+ let total = 0;
2900
+ for (;;) {
2901
+ const started = await this.tick();
2902
+ await Promise.allSettled(this.inFlight);
2903
+ if (started === 0) return total;
2904
+ total += started;
2905
+ }
2906
+ }
2907
+ async counts() {
2908
+ const t = this.table;
2909
+ const rows = await this.db.select({
2910
+ status: t.status,
2911
+ count: sql`count(*)`
2912
+ }).from(t).groupBy(t.status);
2913
+ const counts = Object.fromEntries(OUTBOX_STATUSES.map((status) => [status, 0]));
2914
+ for (const row of rows) counts[row.status] = Number(row.count);
2915
+ return counts;
2905
2916
  }
2906
2917
  /**
2907
- * Answer a request to a webhook a workflow created with `createWebhook`, by
2908
- * resuming the workflow that waits on it. Needs the world but not the queue
2909
- * consumer, so a process that only records events (`dispatch: false`) serves
2910
- * webhooks too.
2918
+ * Put parked deliveries back in line, with their attempts reset.
2911
2919
  *
2912
- * @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.
2913
- * @returns The response the bundle's webhook handler gives.
2920
+ * @param deliveryId - One delivery to retry. Omit it to retry every dead one.
2921
+ * @returns How many deliveries were put back.
2914
2922
  */
2915
- async handleWebhook(request) {
2916
- await this.connect();
2917
- const file = join(this.dir, WORKFLOW_BUNDLE.webhook);
2918
- if (!existsSync(file)) throw new Error(`No webhook bundle at ${file}. ${NOT_BUILT}`);
2919
- const handler = (await import(pathToFileURL(file).href))[request.method];
2920
- if (typeof handler !== "function") return new Response(null, { status: 405 });
2921
- return handler(request);
2923
+ async retryDead(deliveryId) {
2924
+ const t = this.table;
2925
+ const rows = await this.db.update(t).set({
2926
+ status: "pending",
2927
+ attempts: 0,
2928
+ availableAt: /* @__PURE__ */ new Date()
2929
+ }).where(deliveryId ? and(eq(t.status, "dead"), eq(t.id, deliveryId)) : eq(t.status, "dead")).returning({ id: t.id });
2930
+ if (rows.length) this.notify();
2931
+ return rows.length;
2922
2932
  }
2923
- /** Stop the world. The runtime cannot be started again afterwards. */
2924
- async close() {
2925
- this.closed = true;
2926
- await this.ready?.catch(() => {});
2927
- await this.connected?.catch(() => {});
2928
- await this.world.close?.();
2933
+ async claimAndRun() {
2934
+ try {
2935
+ const room = this.options.batchSize - this.inFlight.size;
2936
+ if (room <= 0) return 0;
2937
+ const rows = await this.claim(room);
2938
+ for (const row of rows) {
2939
+ const run = this.deliver(row).finally(() => {
2940
+ this.inFlight.delete(run);
2941
+ });
2942
+ this.inFlight.add(run);
2943
+ }
2944
+ await this.purgeDelivered();
2945
+ return rows.length;
2946
+ } catch (error) {
2947
+ this.logError(error);
2948
+ return 0;
2949
+ }
2929
2950
  }
2930
- ensure() {
2931
- if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
2932
- this.ready ??= this.initialize().catch((error) => {
2933
- this.ready = void 0;
2934
- throw error;
2935
- });
2936
- return this.ready;
2951
+ async claim(limit) {
2952
+ const t = this.table;
2953
+ const now = /* @__PURE__ */ new Date();
2954
+ const stale = new Date(now.getTime() - this.options.claimTimeoutMs);
2955
+ const due = or(and(eq(t.status, "pending"), lte(t.availableAt, now)), and(eq(t.status, "claimed"), lt(t.claimedAt, stale)));
2956
+ const claimIn = async (tx) => {
2957
+ let select = tx.select().from(t).where(due).orderBy(asc(t.seq)).limit(limit);
2958
+ if (this.engine === "postgres") select = select.for("update", { skipLocked: true });
2959
+ const picked = await select;
2960
+ if (!picked.length) return [];
2961
+ await tx.update(t).set({
2962
+ status: "claimed",
2963
+ claimedAt: now,
2964
+ attempts: sql`${t.attempts} + 1`
2965
+ }).where(inArray(t.seq, picked.map((row) => row.seq)));
2966
+ return picked.map((row) => ({
2967
+ ...row,
2968
+ attempts: row.attempts + 1
2969
+ }));
2970
+ };
2971
+ return this.engine === "postgres" ? this.db.transaction(claimIn) : runInTransaction(this.db, claimIn);
2937
2972
  }
2938
- /** Load the SDK and give it the world: all a webhook needs. */
2939
- connect() {
2940
- if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
2941
- this.connected ??= this.loadSdk().then((sdk) => {
2942
- sdk.setWorld(this.world);
2943
- return sdk;
2944
- }).catch((error) => {
2945
- this.connected = void 0;
2946
- throw error;
2947
- });
2948
- return this.connected;
2973
+ async deliver(row) {
2974
+ const listener = this.listeners(row.listener);
2975
+ if (!listener) {
2976
+ await this.park(row, `No listener named '${row.listener}' is registered`);
2977
+ return;
2978
+ }
2979
+ try {
2980
+ await listener.run(deliveryOf(row));
2981
+ } catch (error) {
2982
+ await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(row.listener, listener, error));
2983
+ return;
2984
+ }
2985
+ await this.markDelivered(row);
2949
2986
  }
2950
- async initialize() {
2951
- if (typeof this.world.createRunId !== "function") throw new Error("This world cannot name a run after its key, so an event delivered twice would start two runs. Use the world from @brickkit/redis-world or @brickkit/bullmq-world.");
2952
- const sdk = await this.connect();
2953
- const flow = join(this.dir, WORKFLOW_BUNDLE.flow);
2954
- if (!existsSync(flow)) throw new Error(`No workflow bundle at ${flow}. ${NOT_BUILT}`);
2955
- const manifest = this.readManifest();
2956
- const depsOf = this.checkListeners(manifest);
2957
- const bundle = await this.loadBundle(flow);
2958
- if (typeof bundle.POST !== "function") throw new Error(`${flow} does not export a POST handler`);
2959
- const post = bundle.POST;
2960
- this.world.registerHandler?.(WORKFLOW_QUEUE.prefix, (request) => {
2961
- const queue = request.headers.get(WORKFLOW_QUEUE.header) ?? "";
2962
- return runWithDeps(depsOf.get(queue.slice(WORKFLOW_QUEUE.prefix.length)) ?? this.deps, () => post(request));
2963
- });
2964
- await this.world.start?.();
2965
- return sdk;
2987
+ async markDelivered(row) {
2988
+ const t = this.table;
2989
+ try {
2990
+ if (this.options.retainDeliveredMs === 0) await this.db.delete(t).where(eq(t.seq, row.seq));
2991
+ else await this.db.update(t).set({
2992
+ status: "delivered",
2993
+ deliveredAt: /* @__PURE__ */ new Date(),
2994
+ lastError: null
2995
+ }).where(eq(t.seq, row.seq));
2996
+ } catch (error) {
2997
+ this.logError(error);
2998
+ }
2966
2999
  }
2967
- async loadSdk() {
2968
- const from = createRequire(join(this.root, "package.json"));
2969
- const load = async (specifier) => {
2970
- let path;
2971
- try {
2972
- path = from.resolve(specifier);
2973
- } catch {
2974
- throw new Error(`The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`);
2975
- }
2976
- return import(pathToFileURL(path).href);
2977
- };
2978
- const [api, runtime] = await Promise.all([load("workflow/api"), load("workflow/runtime")]);
2979
- return {
2980
- start: api.start,
2981
- setWorld: runtime.setWorld
2982
- };
3000
+ async fail(row, error, maxAttempts, decision) {
3001
+ const message = error instanceof Error ? error.message : String(error);
3002
+ if (decision === "dead" || row.attempts >= maxAttempts) {
3003
+ await this.park(row, message);
3004
+ return;
3005
+ }
3006
+ const t = this.table;
3007
+ try {
3008
+ await this.db.update(t).set({
3009
+ status: "pending",
3010
+ lastError: message,
3011
+ claimedAt: null,
3012
+ availableAt: new Date(Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs))
3013
+ }).where(eq(t.seq, row.seq));
3014
+ } catch (writeError) {
3015
+ this.logError(writeError);
3016
+ }
2983
3017
  }
2984
- /**
2985
- * The bundle holds its own copy of every step and registers them all when it
2986
- * loads, replacing the ones the app registered. A copy has its own module state:
2987
- * a step would find no database connection, no config, none of what the app set
2988
- * up. So the app's steps are put back, and the bundle's copies serve only the
2989
- * steps the app never loaded.
2990
- */
2991
- async loadBundle(flow) {
2992
- const registry = () => globalThis[STEP_REGISTRY];
2993
- const app = new Map(registry());
2994
- const bundle = await import(pathToFileURL(flow).href);
2995
- const registered = registry();
2996
- if (registered) for (const [id, step] of app) registered.set(id, step);
2997
- return bundle;
3018
+ async park(row, message) {
3019
+ const t = this.table;
3020
+ try {
3021
+ await this.db.update(t).set({
3022
+ status: "dead",
3023
+ lastError: message,
3024
+ claimedAt: null
3025
+ }).where(eq(t.seq, row.seq));
3026
+ } catch (error) {
3027
+ this.logError(error);
3028
+ }
2998
3029
  }
2999
- readManifest() {
3000
- const path = join(this.dir, WORKFLOW_BUNDLE.manifest);
3001
- if (!existsSync(path)) return void 0;
3002
- return JSON.parse(readFileSync(path, "utf8"));
3030
+ logError(error) {
3031
+ console.error("[Brick-TS events]", error);
3003
3032
  }
3004
- /**
3005
- * A listener's workflow must carry the id the transform gives it, and the bundle
3006
- * must know that id: a function that was never transformed, or a bundle built
3007
- * before the workflow existed, would fail on its first delivery with a less
3008
- * helpful message.
3009
- *
3010
- * @returns The deps each workflow's steps run with, by workflow id.
3011
- * @throws When one workflow is run by listeners with different deps (an app
3012
- * and a plugin, or two plugin installs): its steps could see only one set.
3013
- */
3014
- checkListeners(manifest) {
3015
- const depsOf = /* @__PURE__ */ new Map();
3016
- const known = /* @__PURE__ */ new Set();
3017
- for (const file of Object.values(manifest?.workflows ?? {})) for (const entry of Object.values(file)) if (entry.workflowId) known.add(entry.workflowId);
3018
- for (const listener of this.listeners) {
3019
- const id = listener.workflow?.workflowId;
3020
- if (typeof id !== "string") throw new Error(`The workflow of listener '${listener.name}' was not transformed. Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.`);
3021
- if (manifest && !known.has(id)) throw new Error(`The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`);
3022
- const deps = listenerDeps(listener) ?? this.deps;
3023
- if ((depsOf.get(id) ?? deps) !== deps) throw new Error(`Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`);
3024
- depsOf.set(id, deps);
3025
- }
3026
- return depsOf;
3033
+ async purgeDelivered() {
3034
+ const keep = this.options.retainDeliveredMs;
3035
+ const now = Date.now();
3036
+ if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;
3037
+ this.lastPurge = now;
3038
+ const t = this.table;
3039
+ await this.db.delete(t).where(and(eq(t.status, "delivered"), lt(t.deliveredAt, new Date(now - keep))));
3027
3040
  }
3028
3041
  };
3029
3042
  // src/events/hub.ts
@@ -3119,13 +3132,15 @@ var EventsHub = class {
3119
3132
  * Where the workflow bundle is read from, the project it is built from, and
3120
3133
  * the world the workflows run on. Only set when a listener runs a workflow.
3121
3134
  * The CLI builds the bundle there before events start, and shows the world's
3122
- * runs in the dev dashboard.
3135
+ * runs in the dev dashboard. `shipped`: a compiled server reads the bundle
3136
+ * `brick build` shipped beside it, so there is nothing to build.
3123
3137
  */
3124
3138
  get workflows() {
3125
3139
  return this.runtime && {
3126
3140
  root: this.runtime.root,
3127
3141
  dir: this.runtime.dir,
3128
- world: this.runtime.world
3142
+ world: this.runtime.world,
3143
+ shipped: isWorkflowBundleShipped()
3129
3144
  };
3130
3145
  }
3131
3146
  /**
@@ -4023,6 +4038,6 @@ function cachedJsonRoute(build, revision) {
4023
4038
  return json;
4024
4039
  };
4025
4040
  }
4026
- export { validateName as $, generateOpenApiSpec as A, createActionHandler as B, SecretRef as C, overrideSecret as D, listSecrets as E, bindCompiledApplication as F, useDeps as G, definitionSite as H, compileBrickApplication as I, getPluginEndpoints as J, defineResourcePlugin as K, loadCompiledBrickApp as L, setActionAccess as M, getGlobalRegistry as N, resetSecrets as O, resetGlobalRegistry as P, segmentClaimant as Q, isBrickApp as R, requestLoggingPlugin as S, envSource as T, INTERNALS as U, claimName as V, port as W, installPlugin as X, hasPlugin as Y, isInstallingPlugin as Z, isOutboxTable as _, WORKFLOW_BUNDLE as a, baseContext as at, registerReferenceRoute as b, checkEvent as c, t as ct, crudEventSource as d, withCallSpan as dt, portOf as et, eventRefs as f, PLUGIN_COMMIT as ft, runInTransaction as g, onTransactionCommit as h, stopAllEvents as i, deny as it, getActionAccess as j, resolveSecrets as k, checkPayload as l, validateWithSchema as lt, Dispatcher as m, defineServiceSocket as n, defineAction as nt, resolveWorkflowPaths as o, pickContextEnvelope as ot, isCrudEvent as p, PLUGIN_KIND as pt, defineServicePlugin as q, recordingServices as r, errorsOf as rt, defineListener as s, Type as st, brick as t, buildErrorHelpers as tt, crudEventName as u, traceRoute as ut, outboxTable as v, defineSecret as w, scalarDocsHTML as x, referencePlugin as y, requireBrickApp as z };
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 };
4027
4042
 
4028
4043
  //# sourceMappingURL=server.js.map