@dudousxd/nestjs-durable 0.64.0 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -343,7 +343,7 @@ function attributesOf(workflow, run) {
343
343
  __name(attributesOf, "attributesOf");
344
344
 
345
345
  // src/durable-start-client.ts
346
- import { resolveTenantToken, workflowName } from "@dudousxd/nestjs-durable-core";
346
+ import { acceptingSubscription, resolveConcurrency, resolveTenantToken, toEventSubscription, workflowName } from "@dudousxd/nestjs-durable-core";
347
347
  import { Injectable } from "@nestjs/common";
348
348
 
349
349
  // src/tenancy.ts
@@ -699,95 +699,216 @@ var DurableStartClient = class {
699
699
  options;
700
700
  deps;
701
701
  accessor;
702
+ requests;
702
703
  tenant;
703
704
  tenantToken;
704
- constructor(options, deps, accessor) {
705
+ policies = /* @__PURE__ */ new Map();
706
+ warnedCoalescing = /* @__PURE__ */ new Set();
707
+ constructor(options, deps, accessor, requests) {
705
708
  this.options = options;
706
709
  this.deps = deps;
707
710
  this.accessor = accessor;
711
+ this.requests = requests;
708
712
  this.tenant = options.partition ?? "default";
709
713
  this.tenantToken = resolveTenantTokenSource(options.tenantToken);
710
714
  }
711
- async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
712
- const name = workflowName(workflow);
713
- const tenant = opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
715
+ /**
716
+ * Apply `policy` to every start of `workflow` from this process (see
717
+ * {@link TenantWorkflowStartPolicy}). Called by `ThinWorkflowRegistrar` at boot.
718
+ */
719
+ declareWorkflow(workflow, policy) {
720
+ this.policies.set(workflow, policy);
721
+ }
722
+ /**
723
+ * The start-run fields a declared policy adds for `input`: it validates the input (throwing), and
724
+ * evaluates the singleton key and the default quota. A per-start `concurrency` wins over the
725
+ * workflow's.
726
+ */
727
+ async applyPolicy(workflow, input, opts) {
728
+ const policy = this.policies.get(workflow);
729
+ if (!policy) return opts?.concurrency !== void 0 ? {
730
+ concurrency: opts.concurrency
731
+ } : {};
732
+ await policy.validateInput?.(input);
733
+ const concurrency = await resolveConcurrency(opts?.concurrency, policy.concurrency, input);
734
+ const singleton = policy.singleton ? {
735
+ key: policy.singleton.key(input),
736
+ ...policy.singleton.limit !== void 0 ? {
737
+ limit: policy.singleton.limit
738
+ } : {},
739
+ ...policy.singleton.maxQueueDepth !== void 0 ? {
740
+ maxQueueDepth: policy.singleton.maxQueueDepth
741
+ } : {}
742
+ } : void 0;
743
+ return {
744
+ ...singleton ? {
745
+ singleton
746
+ } : {},
747
+ ...concurrency ? {
748
+ concurrency
749
+ } : {}
750
+ };
751
+ }
752
+ /** The wire `tenant`: the signed token when configured, else the partition. */
753
+ async wireTenant() {
754
+ return this.tenantToken !== void 0 ? await resolveTenantToken(this.tenantToken) : this.tenant;
755
+ }
756
+ /**
757
+ * The customer tenant a start claims: an explicit `tenantId` (`null` = none), else the request's
758
+ * tenant when tenancy is on.
759
+ */
760
+ claimedTenant(opts) {
761
+ return opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
714
762
  id: opts.tenantId,
715
- kind: opts.tenantKind
763
+ ...opts.tenantKind !== void 0 ? {
764
+ kind: opts.tenantKind
765
+ } : {}
716
766
  } : currentTenant(this.options.tenancy, this.accessor);
767
+ }
768
+ async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
769
+ const message = await this.startMessage(workflowName(workflow), input, runId, opts);
717
770
  await startRun(this.options.connection, {
718
771
  // The signed token (when configured) rides in the `tenant` field, as on every run request; an
719
772
  // operator with `verifyTenant` derives the run's namespace from it.
720
- tenant: this.tenantToken !== void 0 ? await resolveTenantToken(this.tenantToken) : this.tenant,
721
- workflow: name,
722
- input,
723
- runId,
773
+ tenant: await this.wireTenant(),
774
+ ...message,
724
775
  // Option B: DO NOT pass `namespace` — the start-run queue stays the shared
725
776
  // `durable-start-run` the operator consumes; tenant rides only as message data.
726
777
  ...this.options.prefix !== void 0 ? {
727
778
  prefix: this.options.prefix
728
779
  } : {},
780
+ ...this.deps !== void 0 ? {
781
+ deps: this.deps
782
+ } : {}
783
+ });
784
+ const startAtMs = message.startAt;
785
+ return {
786
+ runId,
787
+ status: startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > Date.now() ? "suspended" : "pending"
788
+ };
789
+ }
790
+ /**
791
+ * The start-run a start of `name` sends (everything but the wire `tenant`): the start options the
792
+ * control plane applies (version pin, priority, delayed start, quota), the singleton key and the
793
+ * customer tenant this run claims. Applies the workflow's declared policy first, so a rejected
794
+ * input throws before anything is published, as `engine.start` does.
795
+ */
796
+ async startMessage(name, input, runId, opts) {
797
+ const tenant = this.claimedTenant(opts);
798
+ const policy = await this.applyPolicy(name, input, opts);
799
+ const startAt = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
800
+ return {
801
+ workflow: name,
802
+ input,
803
+ runId,
729
804
  ...opts?.tags !== void 0 ? {
730
805
  tags: opts.tags
731
806
  } : {},
732
807
  ...opts?.searchAttributes !== void 0 ? {
733
808
  searchAttributes: opts.searchAttributes
734
809
  } : {},
735
- // The start options the control plane applies (version pin, priority, delayed start, quota).
736
810
  ...opts?.version !== void 0 ? {
737
811
  version: opts.version
738
812
  } : {},
739
813
  ...opts?.priority !== void 0 ? {
740
814
  priority: opts.priority
741
815
  } : {},
742
- ...opts?.startAt !== void 0 ? {
743
- startAt: opts.startAt
816
+ ...startAt !== void 0 ? {
817
+ startAt
744
818
  } : {},
745
- ...opts?.concurrency !== void 0 ? {
746
- concurrency: opts.concurrency
819
+ ...policy.concurrency !== void 0 ? {
820
+ concurrency: policy.concurrency
821
+ } : {},
822
+ ...policy.singleton !== void 0 ? {
823
+ singleton: policy.singleton
747
824
  } : {},
748
825
  ...tenant ? {
749
826
  tenantId: tenant.id,
750
827
  ...tenant.kind !== void 0 ? {
751
828
  tenantKind: tenant.kind
752
829
  } : {}
753
- } : {},
754
- ...this.deps !== void 0 ? {
755
- deps: this.deps
756
830
  } : {}
757
- });
758
- const startAtMs = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
831
+ };
832
+ }
833
+ /** The control plane's run requests, or a clear error naming what is missing. */
834
+ runRequests(method) {
835
+ const requests = this.requests?.();
836
+ if (!requests) {
837
+ throw new Error(`${method}() on a tenant is sent to the control plane as a run request, which needs \`transport\` on DurableModule.forRoot (the tenant's BullMQTransport).`);
838
+ }
839
+ return requests;
840
+ }
841
+ /**
842
+ * Signal the run of this tenant's partition waiting on `token`, through the control plane.
843
+ * Resolves the resumed run, or null when no run of this partition waits on it: unlike
844
+ * `engine.signal` on a control plane, a tenant's signal is NOT buffered for a wait opened later
845
+ * (another partition's run could open it). Use `signalWithStart` to signal a run that may not wait
846
+ * yet. `opts.id` deduplicates like `engine.signal`.
847
+ */
848
+ async signal(token, payload, opts) {
849
+ return this.runRequests("signal").signal(token, payload, opts);
850
+ }
851
+ async signalWithStart(workflow, input, runId, signal, opts) {
852
+ const requests = this.runRequests("signalWithStart");
853
+ const start = await this.startMessage(workflowName(workflow), input, runId, opts);
854
+ const result = await requests.signalWithStart(start, signal);
759
855
  return {
760
- runId,
761
- status: startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > Date.now() ? "suspended" : "pending"
856
+ runId: result.runId
762
857
  };
763
858
  }
859
+ /**
860
+ * Publish event `name` from this tenant. Starts this app's own `onEvent` subscribers (each one
861
+ * whose `where` accepts the payload, with its `input` mapping) as runs of this partition, by the
862
+ * start path ({@link start}, run id `evt:<id>:<workflow>`), and has the control plane resume the
863
+ * runs of this partition waiting on it (`ctx.waitForEvent`). Resolves how many runs it started or
864
+ * resumed; a subscriber that throws is warned about and skipped. Unlike a control plane's
865
+ * `publishEvent`, an event nobody received is not buffered (there is no `buffer` option), and
866
+ * a subscriber's `debounce`/`batch` is not applied (it starts once per event, with a warning).
867
+ */
868
+ async publishEvent(name, payload, opts) {
869
+ const requests = this.runRequests("publishEvent");
870
+ const eventId = opts?.id ?? globalThis.crypto.randomUUID();
871
+ let started = 0;
872
+ for (const [workflow, policy] of this.policies) {
873
+ try {
874
+ const subscriptions = (policy.onEvent ?? []).map(toEventSubscription).filter((sub) => sub.event === name);
875
+ const { accepted, errors } = acceptingSubscription(subscriptions, payload);
876
+ if (!accepted) {
877
+ if (errors.length > 0) throw errors[0];
878
+ continue;
879
+ }
880
+ if (policy.coalesces && !this.warnedCoalescing.has(workflow)) {
881
+ this.warnedCoalescing.add(workflow);
882
+ console.warn(`[nestjs-durable] ${workflow} debounces/batches its events, which a tenant's publishEvent does not apply: it starts once per event.`);
883
+ }
884
+ const input = accepted.input ? accepted.input(payload) : payload;
885
+ await this.start(workflow, input, `evt:${eventId}:${workflow}`);
886
+ started += 1;
887
+ } catch (error) {
888
+ console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error);
889
+ }
890
+ }
891
+ const resumed = await requests.publishEvent(name, payload, {
892
+ id: eventId
893
+ });
894
+ return started + resumed;
895
+ }
764
896
  cancel(_runId) {
765
897
  return tenantUnsupported("cancel");
766
898
  }
767
899
  deleteRun(_runId) {
768
900
  return tenantUnsupported("deleteRun");
769
901
  }
770
- // — everything below rejects: a tenant worker holds no store/driver, only the start channel. —
771
- // The remaining WorkflowEngine surface WorkflowService delegates to (resume/waitForRun/signal/
772
- // signalWithStart/publishEvent) all need the store or driver a tenant does not have. A tenant only
773
- // ever calls `start`; these exist so a mistaken call fails with a CLEAR, named tenant error instead
774
- // of a cryptic `this.engine.X is not a function` — the facade is honest about what it cannot do.
775
- // Params mirror the WorkflowEngine surface being faced; every method rejects without reading them.
902
+ // — everything below rejects: a tenant worker holds no store/driver. —
903
+ // `resume`/`waitForRun` need the store or driver a tenant does not have. They exist so a mistaken
904
+ // call fails with a CLEAR, named tenant error instead of a cryptic `this.engine.X is not a
905
+ // function`. Params mirror the WorkflowEngine surface; every method rejects without reading them.
776
906
  resume(_runId) {
777
907
  return tenantUnsupported("resume");
778
908
  }
779
909
  waitForRun(_runId, _opts) {
780
910
  return tenantUnsupported("waitForRun");
781
911
  }
782
- signal(_token, _payload) {
783
- return tenantUnsupported("signal");
784
- }
785
- signalWithStart(_workflow, _input, _runId, _signal, _opts) {
786
- return tenantUnsupported("signalWithStart");
787
- }
788
- publishEvent(_name, _payload, _opts) {
789
- return tenantUnsupported("publishEvent");
790
- }
791
912
  };
792
913
  DurableStartClient = _ts_decorate([
793
914
  Injectable(),
@@ -795,7 +916,8 @@ DurableStartClient = _ts_decorate([
795
916
  _ts_metadata("design:paramtypes", [
796
917
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
797
918
  typeof StartRunDeps === "undefined" ? Object : StartRunDeps,
798
- typeof ContextAccessor === "undefined" ? Object : ContextAccessor
919
+ typeof ContextAccessor === "undefined" ? Object : ContextAccessor,
920
+ Function
799
921
  ])
800
922
  ], DurableStartClient);
801
923
  function tenantUnsupported(method) {
@@ -804,8 +926,8 @@ function tenantUnsupported(method) {
804
926
  __name(tenantUnsupported, "tenantUnsupported");
805
927
 
806
928
  // src/durable-worker.module.ts
807
- import { DURABLE_OPTIONS_CANONICAL, WorkflowEngine, bindWorkflowClass, resolveTenantToken as resolveTenantToken2, workflowName as workflowName3 } from "@dudousxd/nestjs-durable-core";
808
- import { Inject, Injectable as Injectable2 } from "@nestjs/common";
929
+ import { DURABLE_OPTIONS_CANONICAL, WorkflowEngine as WorkflowEngine2, bindWorkflowClass, resolveTenantToken as resolveTenantToken2, workflowName as workflowName3 } from "@dudousxd/nestjs-durable-core";
930
+ import { Inject, Injectable as Injectable3 } from "@nestjs/common";
809
931
  import { DiscoveryService, MetadataScanner } from "@nestjs/core";
810
932
 
811
933
  // src/schema-parse.ts
@@ -916,6 +1038,97 @@ function scanSteps(discovery, scanner, register) {
916
1038
  }
917
1039
  __name(scanSteps, "scanSteps");
918
1040
 
1041
+ // src/entity.ts
1042
+ import { WorkflowEngine } from "@dudousxd/nestjs-durable-core";
1043
+ import { Injectable as Injectable2 } from "@nestjs/common";
1044
+ import "reflect-metadata";
1045
+ function _ts_decorate2(decorators, target, key, desc) {
1046
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1047
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1048
+ r = Reflect.decorate(decorators, target, key, desc);
1049
+ } else {
1050
+ for (var i = decorators.length - 1; i >= 0; i--) {
1051
+ if (d = decorators[i]) {
1052
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1053
+ }
1054
+ }
1055
+ }
1056
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1057
+ }
1058
+ __name(_ts_decorate2, "_ts_decorate");
1059
+ function _ts_metadata2(metadataKey, metadataValue) {
1060
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1061
+ return Reflect.metadata(metadataKey, metadataValue);
1062
+ }
1063
+ }
1064
+ __name(_ts_metadata2, "_ts_metadata");
1065
+ var ENTITY_METADATA = Symbol("nestjs-durable:entity");
1066
+ var ENTITY_ON_METADATA = Symbol("nestjs-durable:entity-on");
1067
+ function Entity(options) {
1068
+ return (target) => {
1069
+ Reflect.defineMetadata(ENTITY_METADATA, options, target);
1070
+ };
1071
+ }
1072
+ __name(Entity, "Entity");
1073
+ function On(op) {
1074
+ return (target, propertyKey) => {
1075
+ const ctor = target.constructor;
1076
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1077
+ ops.set(op, propertyKey);
1078
+ Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);
1079
+ };
1080
+ }
1081
+ __name(On, "On");
1082
+ function getEntityMeta(target) {
1083
+ return Reflect.getMetadata(ENTITY_METADATA, target);
1084
+ }
1085
+ __name(getEntityMeta, "getEntityMeta");
1086
+ function entityConfigFor(ctor) {
1087
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1088
+ const Cls = ctor;
1089
+ const handlers = {};
1090
+ for (const [op, method] of ops) {
1091
+ handlers[op] = (state, arg) => {
1092
+ Object.setPrototypeOf(state, Cls.prototype);
1093
+ const fn = state[method];
1094
+ if (typeof fn !== "function") throw new Error(`entity handler "${method}" is not a method`);
1095
+ return fn.call(state, arg);
1096
+ };
1097
+ }
1098
+ return {
1099
+ initialState: /* @__PURE__ */ __name(() => new Cls(), "initialState"),
1100
+ handlers
1101
+ };
1102
+ }
1103
+ __name(entityConfigFor, "entityConfigFor");
1104
+ var EntityService = class {
1105
+ static {
1106
+ __name(this, "EntityService");
1107
+ }
1108
+ engine;
1109
+ constructor(engine) {
1110
+ this.engine = engine;
1111
+ }
1112
+ /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */
1113
+ signal(name, key, op, arg) {
1114
+ return this.engine.signalEntity(name, key, op, arg);
1115
+ }
1116
+ /** Read an entity's current durable state (or undefined if it has none yet). */
1117
+ getState(name, key) {
1118
+ return this.engine.getEntityState(name, key);
1119
+ }
1120
+ };
1121
+ EntityService = _ts_decorate2([
1122
+ Injectable2(),
1123
+ _ts_metadata2("design:type", Function),
1124
+ _ts_metadata2("design:paramtypes", [
1125
+ typeof WorkflowEngine === "undefined" ? Object : WorkflowEngine
1126
+ ])
1127
+ ], EntityService);
1128
+
1129
+ // src/runtime-registration.ts
1130
+ import { parseDuration as parseDuration2 } from "@dudousxd/nestjs-durable-core";
1131
+
919
1132
  // src/on-error-handlers.ts
920
1133
  import { workflowName as workflowName2 } from "@dudousxd/nestjs-durable-core";
921
1134
  function onErrorHandlersOf(meta, instance, scanner) {
@@ -967,7 +1180,7 @@ function workflowIo(meta) {
967
1180
  __name(workflowIo, "workflowIo");
968
1181
 
969
1182
  // src/runtime-registration.ts
970
- function registerOnRuntime(runtime, scanner, meta, instance, origin) {
1183
+ function registerOnRuntime(runtime, scanner, meta, instance, origin, deadLetter) {
971
1184
  const { handlers, routes } = onErrorHandlersOf(meta, instance, scanner);
972
1185
  const announced = {
973
1186
  version: meta.version,
@@ -995,11 +1208,52 @@ function registerOnRuntime(runtime, scanner, meta, instance, origin) {
995
1208
  } : {},
996
1209
  ...subscribes.length > 0 ? {
997
1210
  subscribes
1211
+ } : {},
1212
+ ...announcedOptions(meta),
1213
+ ...deadLetter !== void 0 ? {
1214
+ deadLetter
998
1215
  } : {}
999
1216
  });
1000
1217
  for (const [name, fn] of handlers) runtime.registerWorkflow(name, fn, announced);
1001
1218
  }
1002
1219
  __name(registerOnRuntime, "registerOnRuntime");
1220
+ function announcedOptions(meta) {
1221
+ const options = {};
1222
+ if (meta.tags !== void 0 && meta.tags.length > 0) options.tags = [
1223
+ ...meta.tags
1224
+ ];
1225
+ if (meta.executionTimeout !== void 0) {
1226
+ options.executionTimeoutMs = parseDuration2(meta.executionTimeout);
1227
+ }
1228
+ if (meta.singleton !== void 0) {
1229
+ options.singleton = {
1230
+ ...meta.singleton.limit !== void 0 ? {
1231
+ limit: meta.singleton.limit
1232
+ } : {},
1233
+ ...meta.singleton.maxQueueDepth !== void 0 ? {
1234
+ maxQueueDepth: meta.singleton.maxQueueDepth
1235
+ } : {}
1236
+ };
1237
+ }
1238
+ return Object.keys(options).length > 0 ? {
1239
+ options
1240
+ } : {};
1241
+ }
1242
+ __name(announcedOptions, "announcedOptions");
1243
+
1244
+ // src/step-interceptor.ts
1245
+ import "reflect-metadata";
1246
+ var STEP_INTERCEPTOR_METADATA = Symbol("nestjs-durable:step-interceptor");
1247
+ function StepInterceptor() {
1248
+ return (target) => {
1249
+ Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);
1250
+ };
1251
+ }
1252
+ __name(StepInterceptor, "StepInterceptor");
1253
+ function isStepInterceptor(target) {
1254
+ return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;
1255
+ }
1256
+ __name(isStepInterceptor, "isStepInterceptor");
1003
1257
 
1004
1258
  // src/tokens.ts
1005
1259
  import { RunGateway } from "@dudousxd/nestjs-durable-core";
@@ -1008,7 +1262,7 @@ var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
1008
1262
  var RUN_GATEWAY = RunGateway;
1009
1263
 
1010
1264
  // src/durable-worker.module.ts
1011
- function _ts_decorate2(decorators, target, key, desc) {
1265
+ function _ts_decorate3(decorators, target, key, desc) {
1012
1266
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1013
1267
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1014
1268
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1021,19 +1275,29 @@ function _ts_decorate2(decorators, target, key, desc) {
1021
1275
  }
1022
1276
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1023
1277
  }
1024
- __name(_ts_decorate2, "_ts_decorate");
1025
- function _ts_metadata2(metadataKey, metadataValue) {
1278
+ __name(_ts_decorate3, "_ts_decorate");
1279
+ function _ts_metadata3(metadataKey, metadataValue) {
1026
1280
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1027
1281
  return Reflect.metadata(metadataKey, metadataValue);
1028
1282
  }
1029
1283
  }
1030
- __name(_ts_metadata2, "_ts_metadata");
1284
+ __name(_ts_metadata3, "_ts_metadata");
1031
1285
  function _ts_param(paramIndex, decorator) {
1032
1286
  return function(target, key) {
1033
1287
  decorator(target, key, paramIndex);
1034
1288
  };
1035
1289
  }
1036
1290
  __name(_ts_param, "_ts_param");
1291
+ function deadLetterHandlerOf(instance, scanner) {
1292
+ for (const name of scanner.getAllMethodNames(Object.getPrototypeOf(instance))) {
1293
+ const method = instance[name];
1294
+ if (typeof method === "function" && isDeadLetterHandler(method)) {
1295
+ return (ctx, input) => method.call(instance, ctx, input);
1296
+ }
1297
+ }
1298
+ return void 0;
1299
+ }
1300
+ __name(deadLetterHandlerOf, "deadLetterHandlerOf");
1037
1301
  var RUN_REDIS_WORKER = Symbol("nestjs-durable:run-redis-worker");
1038
1302
  var DURABLE_WORKER_RUNTIME = Symbol("nestjs-durable:worker-runtime");
1039
1303
  var DURABLE_WORKER_RUNNERS = Symbol("nestjs-durable:worker-runners");
@@ -1061,21 +1325,78 @@ var ThinWorkflowRegistrar = class {
1061
1325
  const runtime = this.runtime;
1062
1326
  if (runtime === null || !isPureThinWorker(this.options)) return;
1063
1327
  const starter = this.starter;
1328
+ this.assertNoEntities();
1329
+ this.useInterceptors(runtime);
1330
+ const fallback = this.options.deadLetterWorkflow ? workflowName3(this.options.deadLetterWorkflow) : void 0;
1064
1331
  scanWorkflows(this.discovery, (meta, instance, origin) => {
1065
- registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin);
1332
+ const inline = deadLetterHandlerOf(instance, this.metadataScanner);
1333
+ if (inline && meta.deadLetterWorkflow) {
1334
+ throw new Error(`@Workflow ${meta.name} declares both an inline @DeadLetter() method and a deadLetterWorkflow option. Use one: the inline handler, or the reference.`);
1335
+ }
1336
+ const deadLetter = inline ? `${meta.name}.dlq` : meta.deadLetterWorkflow ? workflowName3(meta.deadLetterWorkflow) : fallback;
1337
+ registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin, deadLetter);
1338
+ if (inline) {
1339
+ runtime.registerWorkflow(`${meta.name}.dlq`, inline, {
1340
+ version: meta.version,
1341
+ ...origin !== void 0 ? {
1342
+ origin
1343
+ } : {}
1344
+ });
1345
+ }
1346
+ const declare = starter.declareWorkflow;
1347
+ if (typeof declare === "function") {
1348
+ const policy = {
1349
+ validateInput: workflowIo(meta).validateAtStart,
1350
+ singleton: meta.singleton,
1351
+ concurrency: meta.concurrency,
1352
+ onEvent: getOnEvents(meta, instance.constructor),
1353
+ coalesces: eventBatchOf(meta, instance.constructor) !== void 0
1354
+ };
1355
+ declare.call(starter, meta.name, policy);
1356
+ }
1066
1357
  bindWorkflowClass(instance.constructor, {
1067
1358
  start: /* @__PURE__ */ __name((name, input, runId, opts) => starter.start(name, input, runId, opts), "start")
1068
1359
  });
1069
1360
  });
1070
1361
  }
1362
+ /**
1363
+ * `@Entity` providers are refused on a tenant, at boot: an entity's state is a run on the store
1364
+ * and its `@On` handlers run inside the engine that owns that store (`EntityService` and
1365
+ * `ctx.callEntity`/`signalEntity` read and serialize it there). A tenant has no store and no
1366
+ * engine, so an entity declared here would never run. Declare it on the control plane.
1367
+ */
1368
+ assertNoEntities() {
1369
+ const entities = this.discovery.getProviders().map((w) => w.instance).filter((i) => !!i && typeof i === "object" && !!getEntityMeta(i.constructor)).map((i) => getEntityMeta(i.constructor)?.name);
1370
+ if (entities.length === 0) return;
1371
+ throw new Error(`@Entity ${entities.join(", ")} cannot be declared on a DurableModule tenant (connection, no store): an entity's state and handlers live in the engine that owns the store. Declare it on the control plane.`);
1372
+ }
1373
+ /**
1374
+ * `@StepInterceptor()` providers wrap every step this tenant runs (each `ctx.step` its workers
1375
+ * execute), as `engine.use` does on an engine. A `@durable-worker` too old to take interceptors
1376
+ * says so instead of dropping them silently.
1377
+ */
1378
+ useInterceptors(runtime) {
1379
+ for (const wrapper of this.discovery.getProviders()) {
1380
+ const instance = wrapper.instance;
1381
+ if (!instance || typeof instance !== "object" || !isStepInterceptor(instance.constructor)) {
1382
+ continue;
1383
+ }
1384
+ const interceptor = instance;
1385
+ if (typeof runtime.use !== "function") {
1386
+ console.warn(`[nestjs-durable] @StepInterceptor ${instance.constructor.name} is not applied: this @dudousxd/durable-worker predates step interceptors on a tenant; upgrade it.`);
1387
+ continue;
1388
+ }
1389
+ runtime.use((invocation, next) => interceptor.intercept(invocation, next));
1390
+ }
1391
+ }
1071
1392
  };
1072
- ThinWorkflowRegistrar = _ts_decorate2([
1073
- Injectable2(),
1393
+ ThinWorkflowRegistrar = _ts_decorate3([
1394
+ Injectable3(),
1074
1395
  _ts_param(2, Inject(DURABLE_WORKER_RUNTIME)),
1075
1396
  _ts_param(3, Inject(DURABLE_OPTIONS_CANONICAL)),
1076
- _ts_param(4, Inject(WorkflowEngine)),
1077
- _ts_metadata2("design:type", Function),
1078
- _ts_metadata2("design:paramtypes", [
1397
+ _ts_param(4, Inject(WorkflowEngine2)),
1398
+ _ts_metadata3("design:type", Function),
1399
+ _ts_metadata3("design:paramtypes", [
1079
1400
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1080
1401
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1081
1402
  Object,
@@ -1103,12 +1424,12 @@ var ThinStepRegistrar = class {
1103
1424
  scanSteps(this.discovery, this.metadataScanner, (meta, handler) => runtime.registerStep(meta.name, handler));
1104
1425
  }
1105
1426
  };
1106
- ThinStepRegistrar = _ts_decorate2([
1107
- Injectable2(),
1427
+ ThinStepRegistrar = _ts_decorate3([
1428
+ Injectable3(),
1108
1429
  _ts_param(2, Inject(DURABLE_WORKER_RUNTIME)),
1109
1430
  _ts_param(3, Inject(DURABLE_OPTIONS_CANONICAL)),
1110
- _ts_metadata2("design:type", Function),
1111
- _ts_metadata2("design:paramtypes", [
1431
+ _ts_metadata3("design:type", Function),
1432
+ _ts_metadata3("design:paramtypes", [
1112
1433
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1113
1434
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1114
1435
  Object,
@@ -1168,15 +1489,15 @@ var ThinWorkerBootstrap = class {
1168
1489
  await Promise.allSettled(this.runners.map((h) => h.close()));
1169
1490
  }
1170
1491
  };
1171
- ThinWorkerBootstrap = _ts_decorate2([
1172
- Injectable2(),
1492
+ ThinWorkerBootstrap = _ts_decorate3([
1493
+ Injectable3(),
1173
1494
  _ts_param(0, Inject(DURABLE_WORKER_RUNTIME)),
1174
1495
  _ts_param(1, Inject(DURABLE_OPTIONS_CANONICAL)),
1175
1496
  _ts_param(2, Inject(RUN_REDIS_WORKER)),
1176
1497
  _ts_param(3, Inject(DURABLE_WORKER_RUNNERS)),
1177
1498
  _ts_param(4, Inject(TENANT_AUTH)),
1178
- _ts_metadata2("design:type", Function),
1179
- _ts_metadata2("design:paramtypes", [
1499
+ _ts_metadata3("design:type", Function),
1500
+ _ts_metadata3("design:paramtypes", [
1180
1501
  Object,
1181
1502
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
1182
1503
  typeof RunRedisWorkerFn === "undefined" ? Object : RunRedisWorkerFn,
@@ -1212,6 +1533,18 @@ function announcedSchedule(s) {
1212
1533
  if (s.paused === true) item.paused = true;
1213
1534
  if (s.overlap !== void 0) item.overlap = s.overlap;
1214
1535
  if (s.jitter !== void 0 && s.jitter > 0) item.jitterMs = s.jitter;
1536
+ const singleton = typeof s.workflow === "function" ? getWorkflowMeta(s.workflow)?.singleton : void 0;
1537
+ if (singleton) {
1538
+ item.singleton = {
1539
+ key: singleton.key(s.input),
1540
+ ...singleton.limit !== void 0 ? {
1541
+ limit: singleton.limit
1542
+ } : {},
1543
+ ...singleton.maxQueueDepth !== void 0 ? {
1544
+ maxQueueDepth: singleton.maxQueueDepth
1545
+ } : {}
1546
+ };
1547
+ }
1215
1548
  return item;
1216
1549
  }
1217
1550
  __name(announcedSchedule, "announcedSchedule");
@@ -1310,7 +1643,7 @@ import { DiscoveryModule, ModuleRef as ModuleRef2 } from "@nestjs/core";
1310
1643
 
1311
1644
  // src/durable-step.registrar.ts
1312
1645
  import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL2, TRANSPORT_CANONICAL } from "@dudousxd/nestjs-durable-core";
1313
- import { Inject as Inject2, Injectable as Injectable3 } from "@nestjs/common";
1646
+ import { Inject as Inject2, Injectable as Injectable4 } from "@nestjs/common";
1314
1647
  import { DiscoveryService as DiscoveryService2, MetadataScanner as MetadataScanner2 } from "@nestjs/core";
1315
1648
 
1316
1649
  // src/role.ts
@@ -1324,7 +1657,7 @@ function isDrivingOperator(options) {
1324
1657
  __name(isDrivingOperator, "isDrivingOperator");
1325
1658
 
1326
1659
  // src/durable-step.registrar.ts
1327
- function _ts_decorate3(decorators, target, key, desc) {
1660
+ function _ts_decorate4(decorators, target, key, desc) {
1328
1661
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1329
1662
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1330
1663
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1337,13 +1670,13 @@ function _ts_decorate3(decorators, target, key, desc) {
1337
1670
  }
1338
1671
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1339
1672
  }
1340
- __name(_ts_decorate3, "_ts_decorate");
1341
- function _ts_metadata3(metadataKey, metadataValue) {
1673
+ __name(_ts_decorate4, "_ts_decorate");
1674
+ function _ts_metadata4(metadataKey, metadataValue) {
1342
1675
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1343
1676
  return Reflect.metadata(metadataKey, metadataValue);
1344
1677
  }
1345
1678
  }
1346
- __name(_ts_metadata3, "_ts_metadata");
1679
+ __name(_ts_metadata4, "_ts_metadata");
1347
1680
  function _ts_param2(paramIndex, decorator) {
1348
1681
  return function(target, key) {
1349
1682
  decorator(target, key, paramIndex);
@@ -1375,12 +1708,12 @@ var DurableStepRegistrar = class {
1375
1708
  scanSteps(this.discovery, this.metadataScanner, (meta, handler) => transport.handle(meta.name, handler, this.options.partition));
1376
1709
  }
1377
1710
  };
1378
- DurableStepRegistrar = _ts_decorate3([
1379
- Injectable3(),
1711
+ DurableStepRegistrar = _ts_decorate4([
1712
+ Injectable4(),
1380
1713
  _ts_param2(2, Inject2(TRANSPORT_CANONICAL)),
1381
1714
  _ts_param2(3, Inject2(DURABLE_OPTIONS_CANONICAL2)),
1382
- _ts_metadata3("design:type", Function),
1383
- _ts_metadata3("design:paramtypes", [
1715
+ _ts_metadata4("design:type", Function),
1716
+ _ts_metadata4("design:paramtypes", [
1384
1717
  typeof DiscoveryService2 === "undefined" ? Object : DiscoveryService2,
1385
1718
  typeof MetadataScanner2 === "undefined" ? Object : MetadataScanner2,
1386
1719
  Object,
@@ -1388,94 +1721,6 @@ DurableStepRegistrar = _ts_decorate3([
1388
1721
  ])
1389
1722
  ], DurableStepRegistrar);
1390
1723
 
1391
- // src/entity.ts
1392
- import { WorkflowEngine as WorkflowEngine2 } from "@dudousxd/nestjs-durable-core";
1393
- import { Injectable as Injectable4 } from "@nestjs/common";
1394
- import "reflect-metadata";
1395
- function _ts_decorate4(decorators, target, key, desc) {
1396
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1397
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1398
- r = Reflect.decorate(decorators, target, key, desc);
1399
- } else {
1400
- for (var i = decorators.length - 1; i >= 0; i--) {
1401
- if (d = decorators[i]) {
1402
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1403
- }
1404
- }
1405
- }
1406
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1407
- }
1408
- __name(_ts_decorate4, "_ts_decorate");
1409
- function _ts_metadata4(metadataKey, metadataValue) {
1410
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1411
- return Reflect.metadata(metadataKey, metadataValue);
1412
- }
1413
- }
1414
- __name(_ts_metadata4, "_ts_metadata");
1415
- var ENTITY_METADATA = Symbol("nestjs-durable:entity");
1416
- var ENTITY_ON_METADATA = Symbol("nestjs-durable:entity-on");
1417
- function Entity(options) {
1418
- return (target) => {
1419
- Reflect.defineMetadata(ENTITY_METADATA, options, target);
1420
- };
1421
- }
1422
- __name(Entity, "Entity");
1423
- function On(op) {
1424
- return (target, propertyKey) => {
1425
- const ctor = target.constructor;
1426
- const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1427
- ops.set(op, propertyKey);
1428
- Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);
1429
- };
1430
- }
1431
- __name(On, "On");
1432
- function getEntityMeta(target) {
1433
- return Reflect.getMetadata(ENTITY_METADATA, target);
1434
- }
1435
- __name(getEntityMeta, "getEntityMeta");
1436
- function entityConfigFor(ctor) {
1437
- const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1438
- const Cls = ctor;
1439
- const handlers = {};
1440
- for (const [op, method] of ops) {
1441
- handlers[op] = (state, arg) => {
1442
- Object.setPrototypeOf(state, Cls.prototype);
1443
- const fn = state[method];
1444
- if (typeof fn !== "function") throw new Error(`entity handler "${method}" is not a method`);
1445
- return fn.call(state, arg);
1446
- };
1447
- }
1448
- return {
1449
- initialState: /* @__PURE__ */ __name(() => new Cls(), "initialState"),
1450
- handlers
1451
- };
1452
- }
1453
- __name(entityConfigFor, "entityConfigFor");
1454
- var EntityService = class {
1455
- static {
1456
- __name(this, "EntityService");
1457
- }
1458
- engine;
1459
- constructor(engine) {
1460
- this.engine = engine;
1461
- }
1462
- /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */
1463
- signal(name, key, op, arg) {
1464
- return this.engine.signalEntity(name, key, op, arg);
1465
- }
1466
- /** Read an entity's current durable state (or undefined if it has none yet). */
1467
- getState(name, key) {
1468
- return this.engine.getEntityState(name, key);
1469
- }
1470
- };
1471
- EntityService = _ts_decorate4([
1472
- Injectable4(),
1473
- _ts_metadata4("design:type", Function),
1474
- _ts_metadata4("design:paramtypes", [
1475
- typeof WorkflowEngine2 === "undefined" ? Object : WorkflowEngine2
1476
- ])
1477
- ], EntityService);
1478
-
1479
1724
  // src/in-app-worker.ts
1480
1725
  import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL3, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL2 } from "@dudousxd/nestjs-durable-core";
1481
1726
  import { Inject as Inject3, Injectable as Injectable5 } from "@nestjs/common";
@@ -1644,7 +1889,7 @@ import { SUMMARY_CHILD_LIMIT, childIdsOf, pageFan, resolveTenantToken as resolve
1644
1889
  import { Injectable as Injectable6 } from "@nestjs/common";
1645
1890
 
1646
1891
  // src/run-request-responder.ts
1647
- import { lifecycleKindOf, resolveWireTenant } from "@dudousxd/nestjs-durable-core";
1892
+ import { grantsClientTenant, lifecycleKindOf, verifyWireTenant } from "@dudousxd/nestjs-durable-core";
1648
1893
  var UNSUPPORTED_RUN_REQUEST = "unsupported-request";
1649
1894
  var BAD_RUN_REQUEST = "bad-request";
1650
1895
  var TENANT_REPUBLISH_MAX_LIMIT = 1e3;
@@ -1665,7 +1910,9 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1665
1910
  "republishLifecycle",
1666
1911
  "workflowLifecycle",
1667
1912
  "signal",
1668
- "schedule"
1913
+ "schedule",
1914
+ "signalWithStart",
1915
+ "publishEvent"
1669
1916
  ]);
1670
1917
  function wireDate(value) {
1671
1918
  if (value === void 0 || value === null) return void 0;
@@ -1741,7 +1988,8 @@ var RunRequestResponder = class {
1741
1988
  });
1742
1989
  }
1743
1990
  async handle(wire) {
1744
- const tenant = await resolveWireTenant(wire.tenant, this.verifyTenant);
1991
+ const verified = await verifyWireTenant(wire.tenant, this.verifyTenant);
1992
+ const tenant = verified?.tenant ?? null;
1745
1993
  if (tenant === null) {
1746
1994
  return {
1747
1995
  requestId: wire.requestId,
@@ -1919,7 +2167,18 @@ var RunRequestResponder = class {
1919
2167
  }
1920
2168
  };
1921
2169
  }
1922
- return this.answer(msg.requestId, () => signal.call(this.gateway, body.token, body.payload));
2170
+ return this.answer(msg.requestId, () => body.opts === void 0 ? signal.call(this.gateway, body.token, body.payload) : signal.call(this.gateway, body.token, body.payload, body.opts));
2171
+ }
2172
+ if (body.kind === "signalWithStart") {
2173
+ return this.signalWithStart(msg.requestId, body, msg.tenant, verified);
2174
+ }
2175
+ if (body.kind === "publishEvent") {
2176
+ const { publishEventForTenant } = this.gateway;
2177
+ if (!publishEventForTenant) return unsupported(msg.requestId, body.kind);
2178
+ if (typeof body.name !== "string" || body.name === "") {
2179
+ return badRequest(msg.requestId, "publishEvent needs an event name");
2180
+ }
2181
+ return this.answer(msg.requestId, () => publishEventForTenant.call(this.gateway, body.name, body.payload, msg.tenant));
1923
2182
  }
1924
2183
  if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1925
2184
  return unsupported(msg.requestId, body.kind);
@@ -1994,6 +2253,50 @@ var RunRequestResponder = class {
1994
2253
  };
1995
2254
  }
1996
2255
  }
2256
+ /**
2257
+ * A tenant's `signalWithStart`: the run it names must be the requester's when it exists, and so
2258
+ * must a run already waiting on the token; anything else is refused `cross-tenant` before the
2259
+ * gateway is called. The run is started in the requester's namespace (a customer tenant it claims
2260
+ * is kept only when its verified token grants it, as for a start-run).
2261
+ */
2262
+ async signalWithStart(requestId, body, tenant, verified) {
2263
+ const { signalWithStartForTenant, signalWaiter } = this.gateway;
2264
+ if (!signalWithStartForTenant) return unsupported(requestId, body.kind);
2265
+ const start = body.start;
2266
+ if (!start || typeof start.runId !== "string" || start.runId === "" || typeof start.workflow !== "string" || start.workflow === "" || typeof body.signal?.token !== "string" || body.signal.token === "") {
2267
+ return badRequest(requestId, "signalWithStart needs a workflow, a run id and a signal token");
2268
+ }
2269
+ const crossTenant = {
2270
+ requestId,
2271
+ result: {
2272
+ ok: false,
2273
+ error: {
2274
+ message: "run belongs to another tenant",
2275
+ code: "cross-tenant"
2276
+ }
2277
+ }
2278
+ };
2279
+ const existing = await this.runOf(start.runId);
2280
+ if (existing && existing.namespace !== tenant) return crossTenant;
2281
+ const waiterRunId = signalWaiter ? await signalWaiter.call(this.gateway, body.signal.token) : null;
2282
+ const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;
2283
+ if (waiter && waiter.namespace !== tenant) return crossTenant;
2284
+ const claim = start.tenantId !== void 0 ? grantsClientTenant(verified, start.tenantId) ? {
2285
+ tenantId: start.tenantId,
2286
+ ...start.tenantKind !== void 0 ? {
2287
+ tenantKind: start.tenantKind
2288
+ } : {}
2289
+ } : {
2290
+ tenantId: null
2291
+ } : {};
2292
+ return this.answer(requestId, () => signalWithStartForTenant.call(this.gateway, {
2293
+ ...start,
2294
+ tenant
2295
+ }, tenant, claim, {
2296
+ token: body.signal.token,
2297
+ payload: body.signal.payload
2298
+ }));
2299
+ }
1997
2300
  /** The run alone (`getRun`, else from its detail), or null when it does not exist. */
1998
2301
  async runOf(runId) {
1999
2302
  return this.gateway.getRun ? this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run ?? null;
@@ -2162,6 +2465,10 @@ var RunGatewayError = class extends Error {
2162
2465
  this.code = code;
2163
2466
  }
2164
2467
  };
2468
+ function unsupportedVerb(kind) {
2469
+ return new RunGatewayError(`${kind} is not supported by this server: the control plane is older than this tenant`, UNSUPPORTED_RUN_REQUEST);
2470
+ }
2471
+ __name(unsupportedVerb, "unsupportedVerb");
2165
2472
  var UnsupportedRunRequestError = class UnsupportedRunRequestError2 extends RunGatewayError {
2166
2473
  static {
2167
2474
  __name(this, "UnsupportedRunRequestError");
@@ -2467,7 +2774,7 @@ var ProxyRunGateway = class {
2467
2774
  * {@link RunGatewayError} with code {@link UNSUPPORTED_RUN_REQUEST}.
2468
2775
  */
2469
2776
  async requestNewVerb(body) {
2470
- const notSupported = /* @__PURE__ */ __name(() => new RunGatewayError(`${body.kind} is not supported by this server: the control plane is older than this tenant`, UNSUPPORTED_RUN_REQUEST), "notSupported");
2777
+ const notSupported = /* @__PURE__ */ __name(() => unsupportedVerb(body.kind), "notSupported");
2471
2778
  if (this.knownUnsupported(body.kind)) throw notSupported();
2472
2779
  let data;
2473
2780
  try {
@@ -2479,6 +2786,62 @@ var ProxyRunGateway = class {
2479
2786
  this.unsupportedUntil.set(body.kind, Date.now() + this.capabilityTtlMs);
2480
2787
  throw notSupported();
2481
2788
  }
2789
+ /**
2790
+ * Signal the run of this tenant's namespace waiting on `token` (`engine.signal`). Resolves null
2791
+ * when no run of this namespace waits on it: the control plane does NOT buffer a tenant's signal
2792
+ * for a wait opened later (another namespace's run could open it). A control plane that predates
2793
+ * the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error.
2794
+ */
2795
+ async signal(token, payload, opts) {
2796
+ if (this.knownUnsupported("signal")) throw unsupportedVerb("signal");
2797
+ let data;
2798
+ try {
2799
+ data = await this.request(opts === void 0 ? {
2800
+ kind: "signal",
2801
+ token,
2802
+ payload
2803
+ } : {
2804
+ kind: "signal",
2805
+ token,
2806
+ payload,
2807
+ opts
2808
+ });
2809
+ } catch (err) {
2810
+ if (!isUnsupported(err)) throw err;
2811
+ }
2812
+ if (data !== void 0) return data;
2813
+ this.unsupportedUntil.set("signal", Date.now() + this.capabilityTtlMs);
2814
+ throw unsupportedVerb("signal");
2815
+ }
2816
+ /**
2817
+ * `engine.signalWithStart` for this tenant: the control plane starts `start` in this tenant's
2818
+ * namespace unless its run exists, then signals it (buffered until the run waits, when the token
2819
+ * names the run id). See the responder for the authorization rule.
2820
+ */
2821
+ signalWithStart(start, signal) {
2822
+ return this.requestNewVerb({
2823
+ kind: "signalWithStart",
2824
+ start,
2825
+ signal
2826
+ });
2827
+ }
2828
+ /**
2829
+ * Resume the runs of this tenant's namespace waiting on event `name` (`ctx.waitForEvent`).
2830
+ * Resolves how many it resumed. The tenant's own `onEvent` subscribers are started by the caller
2831
+ * (`DurableStartClient.publishEvent`), not here.
2832
+ */
2833
+ publishEvent(name, payload, opts) {
2834
+ return this.requestNewVerb({
2835
+ kind: "publishEvent",
2836
+ name,
2837
+ payload,
2838
+ ...opts?.id !== void 0 ? {
2839
+ opts: {
2840
+ id: opts.id
2841
+ }
2842
+ } : {}
2843
+ });
2844
+ }
2482
2845
  subscribe(runId, onEvent) {
2483
2846
  const unsubscribe = this.transport.onTenantEvent?.(this.tenant, (evt) => {
2484
2847
  if (evt.event.runId === runId) onEvent(evt.event);
@@ -2501,7 +2864,7 @@ ProxyRunGateway = _ts_decorate6([
2501
2864
  ], ProxyRunGateway);
2502
2865
 
2503
2866
  // src/retention-poller.ts
2504
- import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL5, STATE_STORE_CANONICAL, TERMINAL_RUN_STATUSES, parseDuration as parseDuration2 } from "@dudousxd/nestjs-durable-core";
2867
+ import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL5, STATE_STORE_CANONICAL, TERMINAL_RUN_STATUSES, parseDuration as parseDuration3 } from "@dudousxd/nestjs-durable-core";
2505
2868
  import { Inject as Inject5, Injectable as Injectable8, Optional as Optional2 } from "@nestjs/common";
2506
2869
 
2507
2870
  // src/settle-within.ts
@@ -2674,7 +3037,7 @@ function validateRetention(retention) {
2674
3037
  if (policy.maxAge == null && policy.maxCount == null) {
2675
3038
  throw new Error("durable retention: each policy must set maxAge and/or maxCount");
2676
3039
  }
2677
- if (policy.maxAge != null) parseDuration2(policy.maxAge);
3040
+ if (policy.maxAge != null) parseDuration3(policy.maxAge);
2678
3041
  for (const status of policy.statuses) {
2679
3042
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
2680
3043
  throw new Error(`durable retention: status "${status}" is not terminal; only ${TERMINAL_RUN_STATUSES.join(", ")} can be pruned`);
@@ -2731,7 +3094,7 @@ var RetentionPoller = class {
2731
3094
  return;
2732
3095
  }
2733
3096
  void this.sweep();
2734
- const intervalMs = retention.sweepInterval != null ? parseDuration2(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
3097
+ const intervalMs = retention.sweepInterval != null ? parseDuration3(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
2735
3098
  if (intervalMs > 0) {
2736
3099
  this.timer = setInterval(() => void this.sweep(), intervalMs);
2737
3100
  this.timer.unref?.();
@@ -3167,8 +3530,14 @@ var StoreRunGateway = class {
3167
3530
  if (action === "trigger") return this.engine.schedules.trigger(id);
3168
3531
  return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
3169
3532
  }
3170
- signal(token, payload) {
3171
- return this.engine.signal(token, payload);
3533
+ signal(token, payload, opts) {
3534
+ return this.engine.signal(token, payload, opts);
3535
+ }
3536
+ signalWithStartForTenant(start, namespace, clientTenant, signal) {
3537
+ return this.engine.signalWithStartForTenant(start, namespace, clientTenant, signal);
3538
+ }
3539
+ publishEventForTenant(name, payload, namespace) {
3540
+ return this.engine.publishEventForTenant(name, payload, namespace);
3172
3541
  }
3173
3542
  async signalWaiter(token) {
3174
3543
  const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
@@ -3575,22 +3944,6 @@ TimerPoller = _ts_decorate10([
3575
3944
  import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL7, RemoteWorkflowExecutor, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL3, WorkflowEngine as WorkflowEngine5, bindWorkflowClass as bindWorkflowClass2, sanitizeQueueToken, tenantGroup, workflowName as workflowName5 } from "@dudousxd/nestjs-durable-core";
3576
3945
  import { Inject as Inject8, Injectable as Injectable11 } from "@nestjs/common";
3577
3946
  import { DiscoveryService as DiscoveryService4, MetadataScanner as MetadataScanner4 } from "@nestjs/core";
3578
-
3579
- // src/step-interceptor.ts
3580
- import "reflect-metadata";
3581
- var STEP_INTERCEPTOR_METADATA = Symbol("nestjs-durable:step-interceptor");
3582
- function StepInterceptor() {
3583
- return (target) => {
3584
- Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);
3585
- };
3586
- }
3587
- __name(StepInterceptor, "StepInterceptor");
3588
- function isStepInterceptor(target) {
3589
- return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;
3590
- }
3591
- __name(isStepInterceptor, "isStepInterceptor");
3592
-
3593
- // src/workflow.registrar.ts
3594
3947
  function _ts_decorate11(decorators, target, key, desc) {
3595
3948
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3596
3949
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -3783,25 +4136,33 @@ var WorkflowRegistrar = class {
3783
4136
  const fallback = this.options.deadLetterWorkflow ? workflowName5(this.options.deadLetterWorkflow) : void 0;
3784
4137
  if (byWorkflow.size === 0 && !fallback) return;
3785
4138
  this.engine.onDead((run) => {
3786
- const target = byWorkflow.get(run.workflow) ?? fallback;
3787
- if (!target) return;
3788
- void this.engine.start(
3789
- target,
3790
- {
3791
- deadRunId: run.id,
3792
- workflow: run.workflow,
3793
- input: run.input,
3794
- error: run.error
3795
- },
3796
- `dlq:${run.id}`,
3797
- // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to
3798
- // that tenant's worker group (`target@<tenant>`), not the bare group.
3799
- {
3800
- namespace: run.namespace
3801
- }
3802
- ).catch(() => void 0);
4139
+ void this.routeDead(run, byWorkflow, fallback).catch(() => void 0);
3803
4140
  });
3804
4141
  }
4142
+ /** {@link installDeadLetterRouting}'s routing of one dead run. */
4143
+ async routeDead(run, byWorkflow, fallback) {
4144
+ let target = byWorkflow.get(run.workflow);
4145
+ if (!target && fallback) {
4146
+ if (await this.engine.announcedDeadLetter?.(run).catch(() => void 0)) return;
4147
+ target = fallback;
4148
+ }
4149
+ if (!target) return;
4150
+ await this.engine.start(
4151
+ target,
4152
+ {
4153
+ deadRunId: run.id,
4154
+ workflow: run.workflow,
4155
+ input: run.input,
4156
+ error: run.error
4157
+ },
4158
+ `dlq:${run.id}`,
4159
+ // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to
4160
+ // that tenant's worker group (`target@<tenant>`), not the bare group.
4161
+ {
4162
+ namespace: run.namespace
4163
+ }
4164
+ ).catch(() => void 0);
4165
+ }
3805
4166
  };
3806
4167
  WorkflowRegistrar = _ts_decorate11([
3807
4168
  Injectable11(),
@@ -4273,12 +4634,29 @@ var DurableModule = class _DurableModule {
4273
4634
  provide: WorkflowEngine7,
4274
4635
  useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
4275
4636
  if (options.store === void 0) {
4276
- return new DurableStartClient({
4277
- ...options,
4278
- ...auth.tenantToken !== void 0 ? {
4279
- tenantToken: auth.tenantToken
4280
- } : {}
4281
- }, void 0, resolveAccessor(moduleRef));
4637
+ return new DurableStartClient(
4638
+ {
4639
+ ...options,
4640
+ ...auth.tenantToken !== void 0 ? {
4641
+ tenantToken: auth.tenantToken
4642
+ } : {}
4643
+ },
4644
+ void 0,
4645
+ resolveAccessor(moduleRef),
4646
+ // `signal`/`signalWithStart`/`publishEvent` go to the control plane as run requests,
4647
+ // over the one `ProxyRunGateway` bound under `RunGateway` (it owns the reply
4648
+ // subscription). Resolved lazily: that gateway is built after this facade.
4649
+ () => {
4650
+ try {
4651
+ const gateway = moduleRef.get(RunGateway2, {
4652
+ strict: false
4653
+ });
4654
+ return gateway instanceof ProxyRunGateway ? gateway : void 0;
4655
+ } catch {
4656
+ return void 0;
4657
+ }
4658
+ }
4659
+ );
4282
4660
  }
4283
4661
  if (!store) {
4284
4662
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");