@dudousxd/nestjs-durable 0.64.0 → 0.66.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
@@ -127,6 +127,8 @@ function Workflow(options) {
127
127
  deadLetterWorkflow: options.deadLetterWorkflow,
128
128
  onError: options.onError,
129
129
  tags: options.tags,
130
+ // The typed callbacks are stored erased: the engine calls them with the parsed input, which is
131
+ // exactly the type `S` gave them (see `workflowIo`).
130
132
  singleton: options.singleton,
131
133
  concurrency: options.concurrency,
132
134
  executionTimeout: options.executionTimeout,
@@ -343,7 +345,7 @@ function attributesOf(workflow, run) {
343
345
  __name(attributesOf, "attributesOf");
344
346
 
345
347
  // src/durable-start-client.ts
346
- import { resolveTenantToken, workflowName } from "@dudousxd/nestjs-durable-core";
348
+ import { acceptingSubscription, resolveConcurrency, resolveTenantToken, toEventSubscription, workflowName } from "@dudousxd/nestjs-durable-core";
347
349
  import { Injectable } from "@nestjs/common";
348
350
 
349
351
  // src/tenancy.ts
@@ -699,95 +701,217 @@ var DurableStartClient = class {
699
701
  options;
700
702
  deps;
701
703
  accessor;
704
+ requests;
702
705
  tenant;
703
706
  tenantToken;
704
- constructor(options, deps, accessor) {
707
+ policies = /* @__PURE__ */ new Map();
708
+ warnedCoalescing = /* @__PURE__ */ new Set();
709
+ constructor(options, deps, accessor, requests) {
705
710
  this.options = options;
706
711
  this.deps = deps;
707
712
  this.accessor = accessor;
713
+ this.requests = requests;
708
714
  this.tenant = options.partition ?? "default";
709
715
  this.tenantToken = resolveTenantTokenSource(options.tenantToken);
710
716
  }
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 : {
717
+ /**
718
+ * Apply `policy` to every start of `workflow` from this process (see
719
+ * {@link TenantWorkflowStartPolicy}). Called by `ThinWorkflowRegistrar` at boot.
720
+ */
721
+ declareWorkflow(workflow, policy) {
722
+ this.policies.set(workflow, policy);
723
+ }
724
+ /**
725
+ * The start-run fields a declared policy adds for `input`: it validates the input (throwing), and
726
+ * evaluates the singleton key and the default quota against the parsed input. A per-start `concurrency` wins over the
727
+ * workflow's.
728
+ */
729
+ async applyPolicy(workflow, input, opts) {
730
+ const policy = this.policies.get(workflow);
731
+ if (!policy) return opts?.concurrency !== void 0 ? {
732
+ concurrency: opts.concurrency
733
+ } : {};
734
+ const keyInput = policy.parseInput ? await policy.parseInput(input) : input;
735
+ await policy.validateInput?.(keyInput);
736
+ const concurrency = await resolveConcurrency(opts?.concurrency, policy.concurrency, keyInput);
737
+ const singleton = policy.singleton ? {
738
+ key: policy.singleton.key(keyInput),
739
+ ...policy.singleton.limit !== void 0 ? {
740
+ limit: policy.singleton.limit
741
+ } : {},
742
+ ...policy.singleton.maxQueueDepth !== void 0 ? {
743
+ maxQueueDepth: policy.singleton.maxQueueDepth
744
+ } : {}
745
+ } : void 0;
746
+ return {
747
+ ...singleton ? {
748
+ singleton
749
+ } : {},
750
+ ...concurrency ? {
751
+ concurrency
752
+ } : {}
753
+ };
754
+ }
755
+ /** The wire `tenant`: the signed token when configured, else the partition. */
756
+ async wireTenant() {
757
+ return this.tenantToken !== void 0 ? await resolveTenantToken(this.tenantToken) : this.tenant;
758
+ }
759
+ /**
760
+ * The customer tenant a start claims: an explicit `tenantId` (`null` = none), else the request's
761
+ * tenant when tenancy is on.
762
+ */
763
+ claimedTenant(opts) {
764
+ return opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
714
765
  id: opts.tenantId,
715
- kind: opts.tenantKind
766
+ ...opts.tenantKind !== void 0 ? {
767
+ kind: opts.tenantKind
768
+ } : {}
716
769
  } : currentTenant(this.options.tenancy, this.accessor);
770
+ }
771
+ async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
772
+ const message = await this.startMessage(workflowName(workflow), input, runId, opts);
717
773
  await startRun(this.options.connection, {
718
774
  // The signed token (when configured) rides in the `tenant` field, as on every run request; an
719
775
  // 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,
776
+ tenant: await this.wireTenant(),
777
+ ...message,
724
778
  // Option B: DO NOT pass `namespace` — the start-run queue stays the shared
725
779
  // `durable-start-run` the operator consumes; tenant rides only as message data.
726
780
  ...this.options.prefix !== void 0 ? {
727
781
  prefix: this.options.prefix
728
782
  } : {},
783
+ ...this.deps !== void 0 ? {
784
+ deps: this.deps
785
+ } : {}
786
+ });
787
+ const startAtMs = message.startAt;
788
+ return {
789
+ runId,
790
+ status: startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > Date.now() ? "suspended" : "pending"
791
+ };
792
+ }
793
+ /**
794
+ * The start-run a start of `name` sends (everything but the wire `tenant`): the start options the
795
+ * control plane applies (version pin, priority, delayed start, quota), the singleton key and the
796
+ * customer tenant this run claims. Applies the workflow's declared policy first, so a rejected
797
+ * input throws before anything is published, as `engine.start` does.
798
+ */
799
+ async startMessage(name, input, runId, opts) {
800
+ const tenant = this.claimedTenant(opts);
801
+ const policy = await this.applyPolicy(name, input, opts);
802
+ const startAt = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
803
+ return {
804
+ workflow: name,
805
+ input,
806
+ runId,
729
807
  ...opts?.tags !== void 0 ? {
730
808
  tags: opts.tags
731
809
  } : {},
732
810
  ...opts?.searchAttributes !== void 0 ? {
733
811
  searchAttributes: opts.searchAttributes
734
812
  } : {},
735
- // The start options the control plane applies (version pin, priority, delayed start, quota).
736
813
  ...opts?.version !== void 0 ? {
737
814
  version: opts.version
738
815
  } : {},
739
816
  ...opts?.priority !== void 0 ? {
740
817
  priority: opts.priority
741
818
  } : {},
742
- ...opts?.startAt !== void 0 ? {
743
- startAt: opts.startAt
819
+ ...startAt !== void 0 ? {
820
+ startAt
821
+ } : {},
822
+ ...policy.concurrency !== void 0 ? {
823
+ concurrency: policy.concurrency
744
824
  } : {},
745
- ...opts?.concurrency !== void 0 ? {
746
- concurrency: opts.concurrency
825
+ ...policy.singleton !== void 0 ? {
826
+ singleton: policy.singleton
747
827
  } : {},
748
828
  ...tenant ? {
749
829
  tenantId: tenant.id,
750
830
  ...tenant.kind !== void 0 ? {
751
831
  tenantKind: tenant.kind
752
832
  } : {}
753
- } : {},
754
- ...this.deps !== void 0 ? {
755
- deps: this.deps
756
833
  } : {}
757
- });
758
- const startAtMs = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
834
+ };
835
+ }
836
+ /** The control plane's run requests, or a clear error naming what is missing. */
837
+ runRequests(method) {
838
+ const requests = this.requests?.();
839
+ if (!requests) {
840
+ 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).`);
841
+ }
842
+ return requests;
843
+ }
844
+ /**
845
+ * Signal the run of this tenant's partition waiting on `token`, through the control plane.
846
+ * Resolves the resumed run, or null when no run of this partition waits on it: unlike
847
+ * `engine.signal` on a control plane, a tenant's signal is NOT buffered for a wait opened later
848
+ * (another partition's run could open it). Use `signalWithStart` to signal a run that may not wait
849
+ * yet. `opts.id` deduplicates like `engine.signal`.
850
+ */
851
+ async signal(token, payload, opts) {
852
+ return this.runRequests("signal").signal(token, payload, opts);
853
+ }
854
+ async signalWithStart(workflow, input, runId, signal, opts) {
855
+ const requests = this.runRequests("signalWithStart");
856
+ const start = await this.startMessage(workflowName(workflow), input, runId, opts);
857
+ const result = await requests.signalWithStart(start, signal);
759
858
  return {
760
- runId,
761
- status: startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > Date.now() ? "suspended" : "pending"
859
+ runId: result.runId
762
860
  };
763
861
  }
862
+ /**
863
+ * Publish event `name` from this tenant. Starts this app's own `onEvent` subscribers (each one
864
+ * whose `where` accepts the payload, with its `input` mapping) as runs of this partition, by the
865
+ * start path ({@link start}, run id `evt:<id>:<workflow>`), and has the control plane resume the
866
+ * runs of this partition waiting on it (`ctx.waitForEvent`). Resolves how many runs it started or
867
+ * resumed; a subscriber that throws is warned about and skipped. Unlike a control plane's
868
+ * `publishEvent`, an event nobody received is not buffered (there is no `buffer` option), and
869
+ * a subscriber's `debounce`/`batch` is not applied (it starts once per event, with a warning).
870
+ */
871
+ async publishEvent(name, payload, opts) {
872
+ const requests = this.runRequests("publishEvent");
873
+ const eventId = opts?.id ?? globalThis.crypto.randomUUID();
874
+ let started = 0;
875
+ for (const [workflow, policy] of this.policies) {
876
+ try {
877
+ const subscriptions = (policy.onEvent ?? []).map(toEventSubscription).filter((sub) => sub.event === name);
878
+ const { accepted, errors } = acceptingSubscription(subscriptions, payload);
879
+ if (!accepted) {
880
+ if (errors.length > 0) throw errors[0];
881
+ continue;
882
+ }
883
+ if (policy.coalesces && !this.warnedCoalescing.has(workflow)) {
884
+ this.warnedCoalescing.add(workflow);
885
+ console.warn(`[nestjs-durable] ${workflow} debounces/batches its events, which a tenant's publishEvent does not apply: it starts once per event.`);
886
+ }
887
+ const input = accepted.input ? accepted.input(payload) : payload;
888
+ await this.start(workflow, input, `evt:${eventId}:${workflow}`);
889
+ started += 1;
890
+ } catch (error) {
891
+ console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error);
892
+ }
893
+ }
894
+ const resumed = await requests.publishEvent(name, payload, {
895
+ id: eventId
896
+ });
897
+ return started + resumed;
898
+ }
764
899
  cancel(_runId) {
765
900
  return tenantUnsupported("cancel");
766
901
  }
767
902
  deleteRun(_runId) {
768
903
  return tenantUnsupported("deleteRun");
769
904
  }
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.
905
+ // — everything below rejects: a tenant worker holds no store/driver. —
906
+ // `resume`/`waitForRun` need the store or driver a tenant does not have. They exist so a mistaken
907
+ // call fails with a CLEAR, named tenant error instead of a cryptic `this.engine.X is not a
908
+ // function`. Params mirror the WorkflowEngine surface; every method rejects without reading them.
776
909
  resume(_runId) {
777
910
  return tenantUnsupported("resume");
778
911
  }
779
912
  waitForRun(_runId, _opts) {
780
913
  return tenantUnsupported("waitForRun");
781
914
  }
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
915
  };
792
916
  DurableStartClient = _ts_decorate([
793
917
  Injectable(),
@@ -795,7 +919,8 @@ DurableStartClient = _ts_decorate([
795
919
  _ts_metadata("design:paramtypes", [
796
920
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
797
921
  typeof StartRunDeps === "undefined" ? Object : StartRunDeps,
798
- typeof ContextAccessor === "undefined" ? Object : ContextAccessor
922
+ typeof ContextAccessor === "undefined" ? Object : ContextAccessor,
923
+ Function
799
924
  ])
800
925
  ], DurableStartClient);
801
926
  function tenantUnsupported(method) {
@@ -804,8 +929,8 @@ function tenantUnsupported(method) {
804
929
  __name(tenantUnsupported, "tenantUnsupported");
805
930
 
806
931
  // 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";
932
+ import { DURABLE_OPTIONS_CANONICAL, WorkflowEngine as WorkflowEngine2, bindWorkflowClass, resolveTenantToken as resolveTenantToken2, workflowName as workflowName3 } from "@dudousxd/nestjs-durable-core";
933
+ import { Inject, Injectable as Injectable3 } from "@nestjs/common";
809
934
  import { DiscoveryService, MetadataScanner } from "@nestjs/core";
810
935
 
811
936
  // src/schema-parse.ts
@@ -916,6 +1041,97 @@ function scanSteps(discovery, scanner, register) {
916
1041
  }
917
1042
  __name(scanSteps, "scanSteps");
918
1043
 
1044
+ // src/entity.ts
1045
+ import { WorkflowEngine } from "@dudousxd/nestjs-durable-core";
1046
+ import { Injectable as Injectable2 } from "@nestjs/common";
1047
+ import "reflect-metadata";
1048
+ function _ts_decorate2(decorators, target, key, desc) {
1049
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1050
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1051
+ r = Reflect.decorate(decorators, target, key, desc);
1052
+ } else {
1053
+ for (var i = decorators.length - 1; i >= 0; i--) {
1054
+ if (d = decorators[i]) {
1055
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1056
+ }
1057
+ }
1058
+ }
1059
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1060
+ }
1061
+ __name(_ts_decorate2, "_ts_decorate");
1062
+ function _ts_metadata2(metadataKey, metadataValue) {
1063
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1064
+ return Reflect.metadata(metadataKey, metadataValue);
1065
+ }
1066
+ }
1067
+ __name(_ts_metadata2, "_ts_metadata");
1068
+ var ENTITY_METADATA = Symbol("nestjs-durable:entity");
1069
+ var ENTITY_ON_METADATA = Symbol("nestjs-durable:entity-on");
1070
+ function Entity(options) {
1071
+ return (target) => {
1072
+ Reflect.defineMetadata(ENTITY_METADATA, options, target);
1073
+ };
1074
+ }
1075
+ __name(Entity, "Entity");
1076
+ function On(op) {
1077
+ return (target, propertyKey) => {
1078
+ const ctor = target.constructor;
1079
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1080
+ ops.set(op, propertyKey);
1081
+ Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);
1082
+ };
1083
+ }
1084
+ __name(On, "On");
1085
+ function getEntityMeta(target) {
1086
+ return Reflect.getMetadata(ENTITY_METADATA, target);
1087
+ }
1088
+ __name(getEntityMeta, "getEntityMeta");
1089
+ function entityConfigFor(ctor) {
1090
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1091
+ const Cls = ctor;
1092
+ const handlers = {};
1093
+ for (const [op, method] of ops) {
1094
+ handlers[op] = (state, arg) => {
1095
+ Object.setPrototypeOf(state, Cls.prototype);
1096
+ const fn = state[method];
1097
+ if (typeof fn !== "function") throw new Error(`entity handler "${method}" is not a method`);
1098
+ return fn.call(state, arg);
1099
+ };
1100
+ }
1101
+ return {
1102
+ initialState: /* @__PURE__ */ __name(() => new Cls(), "initialState"),
1103
+ handlers
1104
+ };
1105
+ }
1106
+ __name(entityConfigFor, "entityConfigFor");
1107
+ var EntityService = class {
1108
+ static {
1109
+ __name(this, "EntityService");
1110
+ }
1111
+ engine;
1112
+ constructor(engine) {
1113
+ this.engine = engine;
1114
+ }
1115
+ /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */
1116
+ signal(name, key, op, arg) {
1117
+ return this.engine.signalEntity(name, key, op, arg);
1118
+ }
1119
+ /** Read an entity's current durable state (or undefined if it has none yet). */
1120
+ getState(name, key) {
1121
+ return this.engine.getEntityState(name, key);
1122
+ }
1123
+ };
1124
+ EntityService = _ts_decorate2([
1125
+ Injectable2(),
1126
+ _ts_metadata2("design:type", Function),
1127
+ _ts_metadata2("design:paramtypes", [
1128
+ typeof WorkflowEngine === "undefined" ? Object : WorkflowEngine
1129
+ ])
1130
+ ], EntityService);
1131
+
1132
+ // src/runtime-registration.ts
1133
+ import { parseDuration as parseDuration2 } from "@dudousxd/nestjs-durable-core";
1134
+
919
1135
  // src/on-error-handlers.ts
920
1136
  import { workflowName as workflowName2 } from "@dudousxd/nestjs-durable-core";
921
1137
  function onErrorHandlersOf(meta, instance, scanner) {
@@ -954,10 +1170,8 @@ function workflowIo(meta) {
954
1170
  const parseOutput = meta.output && schemaParser(meta.output, "output", `workflow "${meta.name}" output`);
955
1171
  const validateInput = meta.validateInput;
956
1172
  return {
957
- validateAtStart: parseInput || validateInput ? async (input) => {
958
- const parsed = parseInput ? await parseInput(input) : input;
959
- await validateInput?.(parsed);
960
- } : void 0,
1173
+ parseInput: parseInput || void 0,
1174
+ validateParsed: validateInput,
961
1175
  wrap: /* @__PURE__ */ __name((body) => !parseInput && !parseOutput ? body : async (ctx, input) => {
962
1176
  const output = await body(ctx, parseInput ? await parseInput(input) : input);
963
1177
  return parseOutput ? parseOutput(output) : output;
@@ -967,7 +1181,7 @@ function workflowIo(meta) {
967
1181
  __name(workflowIo, "workflowIo");
968
1182
 
969
1183
  // src/runtime-registration.ts
970
- function registerOnRuntime(runtime, scanner, meta, instance, origin) {
1184
+ function registerOnRuntime(runtime, scanner, meta, instance, origin, deadLetter) {
971
1185
  const { handlers, routes } = onErrorHandlersOf(meta, instance, scanner);
972
1186
  const announced = {
973
1187
  version: meta.version,
@@ -995,11 +1209,52 @@ function registerOnRuntime(runtime, scanner, meta, instance, origin) {
995
1209
  } : {},
996
1210
  ...subscribes.length > 0 ? {
997
1211
  subscribes
1212
+ } : {},
1213
+ ...announcedOptions(meta),
1214
+ ...deadLetter !== void 0 ? {
1215
+ deadLetter
998
1216
  } : {}
999
1217
  });
1000
1218
  for (const [name, fn] of handlers) runtime.registerWorkflow(name, fn, announced);
1001
1219
  }
1002
1220
  __name(registerOnRuntime, "registerOnRuntime");
1221
+ function announcedOptions(meta) {
1222
+ const options = {};
1223
+ if (meta.tags !== void 0 && meta.tags.length > 0) options.tags = [
1224
+ ...meta.tags
1225
+ ];
1226
+ if (meta.executionTimeout !== void 0) {
1227
+ options.executionTimeoutMs = parseDuration2(meta.executionTimeout);
1228
+ }
1229
+ if (meta.singleton !== void 0) {
1230
+ options.singleton = {
1231
+ ...meta.singleton.limit !== void 0 ? {
1232
+ limit: meta.singleton.limit
1233
+ } : {},
1234
+ ...meta.singleton.maxQueueDepth !== void 0 ? {
1235
+ maxQueueDepth: meta.singleton.maxQueueDepth
1236
+ } : {}
1237
+ };
1238
+ }
1239
+ return Object.keys(options).length > 0 ? {
1240
+ options
1241
+ } : {};
1242
+ }
1243
+ __name(announcedOptions, "announcedOptions");
1244
+
1245
+ // src/step-interceptor.ts
1246
+ import "reflect-metadata";
1247
+ var STEP_INTERCEPTOR_METADATA = Symbol("nestjs-durable:step-interceptor");
1248
+ function StepInterceptor() {
1249
+ return (target) => {
1250
+ Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);
1251
+ };
1252
+ }
1253
+ __name(StepInterceptor, "StepInterceptor");
1254
+ function isStepInterceptor(target) {
1255
+ return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;
1256
+ }
1257
+ __name(isStepInterceptor, "isStepInterceptor");
1003
1258
 
1004
1259
  // src/tokens.ts
1005
1260
  import { RunGateway } from "@dudousxd/nestjs-durable-core";
@@ -1008,7 +1263,7 @@ var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
1008
1263
  var RUN_GATEWAY = RunGateway;
1009
1264
 
1010
1265
  // src/durable-worker.module.ts
1011
- function _ts_decorate2(decorators, target, key, desc) {
1266
+ function _ts_decorate3(decorators, target, key, desc) {
1012
1267
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1013
1268
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1014
1269
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1021,19 +1276,29 @@ function _ts_decorate2(decorators, target, key, desc) {
1021
1276
  }
1022
1277
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1023
1278
  }
1024
- __name(_ts_decorate2, "_ts_decorate");
1025
- function _ts_metadata2(metadataKey, metadataValue) {
1279
+ __name(_ts_decorate3, "_ts_decorate");
1280
+ function _ts_metadata3(metadataKey, metadataValue) {
1026
1281
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1027
1282
  return Reflect.metadata(metadataKey, metadataValue);
1028
1283
  }
1029
1284
  }
1030
- __name(_ts_metadata2, "_ts_metadata");
1285
+ __name(_ts_metadata3, "_ts_metadata");
1031
1286
  function _ts_param(paramIndex, decorator) {
1032
1287
  return function(target, key) {
1033
1288
  decorator(target, key, paramIndex);
1034
1289
  };
1035
1290
  }
1036
1291
  __name(_ts_param, "_ts_param");
1292
+ function deadLetterHandlerOf(instance, scanner) {
1293
+ for (const name of scanner.getAllMethodNames(Object.getPrototypeOf(instance))) {
1294
+ const method = instance[name];
1295
+ if (typeof method === "function" && isDeadLetterHandler(method)) {
1296
+ return (ctx, input) => method.call(instance, ctx, input);
1297
+ }
1298
+ }
1299
+ return void 0;
1300
+ }
1301
+ __name(deadLetterHandlerOf, "deadLetterHandlerOf");
1037
1302
  var RUN_REDIS_WORKER = Symbol("nestjs-durable:run-redis-worker");
1038
1303
  var DURABLE_WORKER_RUNTIME = Symbol("nestjs-durable:worker-runtime");
1039
1304
  var DURABLE_WORKER_RUNNERS = Symbol("nestjs-durable:worker-runners");
@@ -1061,21 +1326,80 @@ var ThinWorkflowRegistrar = class {
1061
1326
  const runtime = this.runtime;
1062
1327
  if (runtime === null || !isPureThinWorker(this.options)) return;
1063
1328
  const starter = this.starter;
1329
+ this.assertNoEntities();
1330
+ this.useInterceptors(runtime);
1331
+ const fallback = this.options.deadLetterWorkflow ? workflowName3(this.options.deadLetterWorkflow) : void 0;
1064
1332
  scanWorkflows(this.discovery, (meta, instance, origin) => {
1065
- registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin);
1333
+ const inline = deadLetterHandlerOf(instance, this.metadataScanner);
1334
+ if (inline && meta.deadLetterWorkflow) {
1335
+ throw new Error(`@Workflow ${meta.name} declares both an inline @DeadLetter() method and a deadLetterWorkflow option. Use one: the inline handler, or the reference.`);
1336
+ }
1337
+ const deadLetter = inline ? `${meta.name}.dlq` : meta.deadLetterWorkflow ? workflowName3(meta.deadLetterWorkflow) : fallback;
1338
+ registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin, deadLetter);
1339
+ if (inline) {
1340
+ runtime.registerWorkflow(`${meta.name}.dlq`, inline, {
1341
+ version: meta.version,
1342
+ ...origin !== void 0 ? {
1343
+ origin
1344
+ } : {}
1345
+ });
1346
+ }
1347
+ const declare = starter.declareWorkflow;
1348
+ if (typeof declare === "function") {
1349
+ const io = workflowIo(meta);
1350
+ const policy = {
1351
+ validateInput: io.validateParsed,
1352
+ parseInput: io.parseInput,
1353
+ singleton: meta.singleton,
1354
+ concurrency: meta.concurrency,
1355
+ onEvent: getOnEvents(meta, instance.constructor),
1356
+ coalesces: eventBatchOf(meta, instance.constructor) !== void 0
1357
+ };
1358
+ declare.call(starter, meta.name, policy);
1359
+ }
1066
1360
  bindWorkflowClass(instance.constructor, {
1067
1361
  start: /* @__PURE__ */ __name((name, input, runId, opts) => starter.start(name, input, runId, opts), "start")
1068
1362
  });
1069
1363
  });
1070
1364
  }
1365
+ /**
1366
+ * `@Entity` providers are refused on a tenant, at boot: an entity's state is a run on the store
1367
+ * and its `@On` handlers run inside the engine that owns that store (`EntityService` and
1368
+ * `ctx.callEntity`/`signalEntity` read and serialize it there). A tenant has no store and no
1369
+ * engine, so an entity declared here would never run. Declare it on the control plane.
1370
+ */
1371
+ assertNoEntities() {
1372
+ const entities = this.discovery.getProviders().map((w) => w.instance).filter((i) => !!i && typeof i === "object" && !!getEntityMeta(i.constructor)).map((i) => getEntityMeta(i.constructor)?.name);
1373
+ if (entities.length === 0) return;
1374
+ 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.`);
1375
+ }
1376
+ /**
1377
+ * `@StepInterceptor()` providers wrap every step this tenant runs (each `ctx.step` its workers
1378
+ * execute), as `engine.use` does on an engine. A `@durable-worker` too old to take interceptors
1379
+ * says so instead of dropping them silently.
1380
+ */
1381
+ useInterceptors(runtime) {
1382
+ for (const wrapper of this.discovery.getProviders()) {
1383
+ const instance = wrapper.instance;
1384
+ if (!instance || typeof instance !== "object" || !isStepInterceptor(instance.constructor)) {
1385
+ continue;
1386
+ }
1387
+ const interceptor = instance;
1388
+ if (typeof runtime.use !== "function") {
1389
+ console.warn(`[nestjs-durable] @StepInterceptor ${instance.constructor.name} is not applied: this @dudousxd/durable-worker predates step interceptors on a tenant; upgrade it.`);
1390
+ continue;
1391
+ }
1392
+ runtime.use((invocation, next) => interceptor.intercept(invocation, next));
1393
+ }
1394
+ }
1071
1395
  };
1072
- ThinWorkflowRegistrar = _ts_decorate2([
1073
- Injectable2(),
1396
+ ThinWorkflowRegistrar = _ts_decorate3([
1397
+ Injectable3(),
1074
1398
  _ts_param(2, Inject(DURABLE_WORKER_RUNTIME)),
1075
1399
  _ts_param(3, Inject(DURABLE_OPTIONS_CANONICAL)),
1076
- _ts_param(4, Inject(WorkflowEngine)),
1077
- _ts_metadata2("design:type", Function),
1078
- _ts_metadata2("design:paramtypes", [
1400
+ _ts_param(4, Inject(WorkflowEngine2)),
1401
+ _ts_metadata3("design:type", Function),
1402
+ _ts_metadata3("design:paramtypes", [
1079
1403
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1080
1404
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1081
1405
  Object,
@@ -1103,12 +1427,12 @@ var ThinStepRegistrar = class {
1103
1427
  scanSteps(this.discovery, this.metadataScanner, (meta, handler) => runtime.registerStep(meta.name, handler));
1104
1428
  }
1105
1429
  };
1106
- ThinStepRegistrar = _ts_decorate2([
1107
- Injectable2(),
1430
+ ThinStepRegistrar = _ts_decorate3([
1431
+ Injectable3(),
1108
1432
  _ts_param(2, Inject(DURABLE_WORKER_RUNTIME)),
1109
1433
  _ts_param(3, Inject(DURABLE_OPTIONS_CANONICAL)),
1110
- _ts_metadata2("design:type", Function),
1111
- _ts_metadata2("design:paramtypes", [
1434
+ _ts_metadata3("design:type", Function),
1435
+ _ts_metadata3("design:paramtypes", [
1112
1436
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1113
1437
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1114
1438
  Object,
@@ -1168,15 +1492,15 @@ var ThinWorkerBootstrap = class {
1168
1492
  await Promise.allSettled(this.runners.map((h) => h.close()));
1169
1493
  }
1170
1494
  };
1171
- ThinWorkerBootstrap = _ts_decorate2([
1172
- Injectable2(),
1495
+ ThinWorkerBootstrap = _ts_decorate3([
1496
+ Injectable3(),
1173
1497
  _ts_param(0, Inject(DURABLE_WORKER_RUNTIME)),
1174
1498
  _ts_param(1, Inject(DURABLE_OPTIONS_CANONICAL)),
1175
1499
  _ts_param(2, Inject(RUN_REDIS_WORKER)),
1176
1500
  _ts_param(3, Inject(DURABLE_WORKER_RUNNERS)),
1177
1501
  _ts_param(4, Inject(TENANT_AUTH)),
1178
- _ts_metadata2("design:type", Function),
1179
- _ts_metadata2("design:paramtypes", [
1502
+ _ts_metadata3("design:type", Function),
1503
+ _ts_metadata3("design:paramtypes", [
1180
1504
  Object,
1181
1505
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
1182
1506
  typeof RunRedisWorkerFn === "undefined" ? Object : RunRedisWorkerFn,
@@ -1195,12 +1519,21 @@ async function tenantScheduleAnnouncement(options, tenantToken) {
1195
1519
  return {
1196
1520
  schedules: {
1197
1521
  tenant,
1198
- items: (options.schedules ?? []).map(announcedSchedule)
1522
+ items: await Promise.all((options.schedules ?? []).map(announcedSchedule))
1199
1523
  }
1200
1524
  };
1201
1525
  }
1202
1526
  __name(tenantScheduleAnnouncement, "tenantScheduleAnnouncement");
1203
- function announcedSchedule(s) {
1527
+ async function scheduleKeyInput(parseInput, input) {
1528
+ if (!parseInput) return input;
1529
+ try {
1530
+ return await parseInput(input);
1531
+ } catch {
1532
+ return input;
1533
+ }
1534
+ }
1535
+ __name(scheduleKeyInput, "scheduleKeyInput");
1536
+ async function announcedSchedule(s) {
1204
1537
  const item = {
1205
1538
  key: s.key,
1206
1539
  workflow: workflowName3(s.workflow)
@@ -1212,6 +1545,20 @@ function announcedSchedule(s) {
1212
1545
  if (s.paused === true) item.paused = true;
1213
1546
  if (s.overlap !== void 0) item.overlap = s.overlap;
1214
1547
  if (s.jitter !== void 0 && s.jitter > 0) item.jitterMs = s.jitter;
1548
+ const meta = typeof s.workflow === "function" ? getWorkflowMeta(s.workflow) : void 0;
1549
+ const singleton = meta?.singleton;
1550
+ if (meta && singleton) {
1551
+ const parseInput = workflowIo(meta).parseInput;
1552
+ item.singleton = {
1553
+ key: singleton.key(await scheduleKeyInput(parseInput, s.input)),
1554
+ ...singleton.limit !== void 0 ? {
1555
+ limit: singleton.limit
1556
+ } : {},
1557
+ ...singleton.maxQueueDepth !== void 0 ? {
1558
+ maxQueueDepth: singleton.maxQueueDepth
1559
+ } : {}
1560
+ };
1561
+ }
1215
1562
  return item;
1216
1563
  }
1217
1564
  __name(announcedSchedule, "announcedSchedule");
@@ -1310,7 +1657,7 @@ import { DiscoveryModule, ModuleRef as ModuleRef2 } from "@nestjs/core";
1310
1657
 
1311
1658
  // src/durable-step.registrar.ts
1312
1659
  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";
1660
+ import { Inject as Inject2, Injectable as Injectable4 } from "@nestjs/common";
1314
1661
  import { DiscoveryService as DiscoveryService2, MetadataScanner as MetadataScanner2 } from "@nestjs/core";
1315
1662
 
1316
1663
  // src/role.ts
@@ -1324,7 +1671,7 @@ function isDrivingOperator(options) {
1324
1671
  __name(isDrivingOperator, "isDrivingOperator");
1325
1672
 
1326
1673
  // src/durable-step.registrar.ts
1327
- function _ts_decorate3(decorators, target, key, desc) {
1674
+ function _ts_decorate4(decorators, target, key, desc) {
1328
1675
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1329
1676
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1330
1677
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1337,13 +1684,13 @@ function _ts_decorate3(decorators, target, key, desc) {
1337
1684
  }
1338
1685
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1339
1686
  }
1340
- __name(_ts_decorate3, "_ts_decorate");
1341
- function _ts_metadata3(metadataKey, metadataValue) {
1687
+ __name(_ts_decorate4, "_ts_decorate");
1688
+ function _ts_metadata4(metadataKey, metadataValue) {
1342
1689
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1343
1690
  return Reflect.metadata(metadataKey, metadataValue);
1344
1691
  }
1345
1692
  }
1346
- __name(_ts_metadata3, "_ts_metadata");
1693
+ __name(_ts_metadata4, "_ts_metadata");
1347
1694
  function _ts_param2(paramIndex, decorator) {
1348
1695
  return function(target, key) {
1349
1696
  decorator(target, key, paramIndex);
@@ -1375,12 +1722,12 @@ var DurableStepRegistrar = class {
1375
1722
  scanSteps(this.discovery, this.metadataScanner, (meta, handler) => transport.handle(meta.name, handler, this.options.partition));
1376
1723
  }
1377
1724
  };
1378
- DurableStepRegistrar = _ts_decorate3([
1379
- Injectable3(),
1725
+ DurableStepRegistrar = _ts_decorate4([
1726
+ Injectable4(),
1380
1727
  _ts_param2(2, Inject2(TRANSPORT_CANONICAL)),
1381
1728
  _ts_param2(3, Inject2(DURABLE_OPTIONS_CANONICAL2)),
1382
- _ts_metadata3("design:type", Function),
1383
- _ts_metadata3("design:paramtypes", [
1729
+ _ts_metadata4("design:type", Function),
1730
+ _ts_metadata4("design:paramtypes", [
1384
1731
  typeof DiscoveryService2 === "undefined" ? Object : DiscoveryService2,
1385
1732
  typeof MetadataScanner2 === "undefined" ? Object : MetadataScanner2,
1386
1733
  Object,
@@ -1388,94 +1735,6 @@ DurableStepRegistrar = _ts_decorate3([
1388
1735
  ])
1389
1736
  ], DurableStepRegistrar);
1390
1737
 
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
1738
  // src/in-app-worker.ts
1480
1739
  import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL3, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL2 } from "@dudousxd/nestjs-durable-core";
1481
1740
  import { Inject as Inject3, Injectable as Injectable5 } from "@nestjs/common";
@@ -1644,7 +1903,7 @@ import { SUMMARY_CHILD_LIMIT, childIdsOf, pageFan, resolveTenantToken as resolve
1644
1903
  import { Injectable as Injectable6 } from "@nestjs/common";
1645
1904
 
1646
1905
  // src/run-request-responder.ts
1647
- import { lifecycleKindOf, resolveWireTenant } from "@dudousxd/nestjs-durable-core";
1906
+ import { grantsClientTenant, lifecycleKindOf, verifyWireTenant } from "@dudousxd/nestjs-durable-core";
1648
1907
  var UNSUPPORTED_RUN_REQUEST = "unsupported-request";
1649
1908
  var BAD_RUN_REQUEST = "bad-request";
1650
1909
  var TENANT_REPUBLISH_MAX_LIMIT = 1e3;
@@ -1665,7 +1924,9 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1665
1924
  "republishLifecycle",
1666
1925
  "workflowLifecycle",
1667
1926
  "signal",
1668
- "schedule"
1927
+ "schedule",
1928
+ "signalWithStart",
1929
+ "publishEvent"
1669
1930
  ]);
1670
1931
  function wireDate(value) {
1671
1932
  if (value === void 0 || value === null) return void 0;
@@ -1741,7 +2002,8 @@ var RunRequestResponder = class {
1741
2002
  });
1742
2003
  }
1743
2004
  async handle(wire) {
1744
- const tenant = await resolveWireTenant(wire.tenant, this.verifyTenant);
2005
+ const verified = await verifyWireTenant(wire.tenant, this.verifyTenant);
2006
+ const tenant = verified?.tenant ?? null;
1745
2007
  if (tenant === null) {
1746
2008
  return {
1747
2009
  requestId: wire.requestId,
@@ -1919,7 +2181,18 @@ var RunRequestResponder = class {
1919
2181
  }
1920
2182
  };
1921
2183
  }
1922
- return this.answer(msg.requestId, () => signal.call(this.gateway, body.token, body.payload));
2184
+ 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));
2185
+ }
2186
+ if (body.kind === "signalWithStart") {
2187
+ return this.signalWithStart(msg.requestId, body, msg.tenant, verified);
2188
+ }
2189
+ if (body.kind === "publishEvent") {
2190
+ const { publishEventForTenant } = this.gateway;
2191
+ if (!publishEventForTenant) return unsupported(msg.requestId, body.kind);
2192
+ if (typeof body.name !== "string" || body.name === "") {
2193
+ return badRequest(msg.requestId, "publishEvent needs an event name");
2194
+ }
2195
+ return this.answer(msg.requestId, () => publishEventForTenant.call(this.gateway, body.name, body.payload, msg.tenant));
1923
2196
  }
1924
2197
  if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1925
2198
  return unsupported(msg.requestId, body.kind);
@@ -1994,6 +2267,50 @@ var RunRequestResponder = class {
1994
2267
  };
1995
2268
  }
1996
2269
  }
2270
+ /**
2271
+ * A tenant's `signalWithStart`: the run it names must be the requester's when it exists, and so
2272
+ * must a run already waiting on the token; anything else is refused `cross-tenant` before the
2273
+ * gateway is called. The run is started in the requester's namespace (a customer tenant it claims
2274
+ * is kept only when its verified token grants it, as for a start-run).
2275
+ */
2276
+ async signalWithStart(requestId, body, tenant, verified) {
2277
+ const { signalWithStartForTenant, signalWaiter } = this.gateway;
2278
+ if (!signalWithStartForTenant) return unsupported(requestId, body.kind);
2279
+ const start = body.start;
2280
+ if (!start || typeof start.runId !== "string" || start.runId === "" || typeof start.workflow !== "string" || start.workflow === "" || typeof body.signal?.token !== "string" || body.signal.token === "") {
2281
+ return badRequest(requestId, "signalWithStart needs a workflow, a run id and a signal token");
2282
+ }
2283
+ const crossTenant = {
2284
+ requestId,
2285
+ result: {
2286
+ ok: false,
2287
+ error: {
2288
+ message: "run belongs to another tenant",
2289
+ code: "cross-tenant"
2290
+ }
2291
+ }
2292
+ };
2293
+ const existing = await this.runOf(start.runId);
2294
+ if (existing && existing.namespace !== tenant) return crossTenant;
2295
+ const waiterRunId = signalWaiter ? await signalWaiter.call(this.gateway, body.signal.token) : null;
2296
+ const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;
2297
+ if (waiter && waiter.namespace !== tenant) return crossTenant;
2298
+ const claim = start.tenantId !== void 0 ? grantsClientTenant(verified, start.tenantId) ? {
2299
+ tenantId: start.tenantId,
2300
+ ...start.tenantKind !== void 0 ? {
2301
+ tenantKind: start.tenantKind
2302
+ } : {}
2303
+ } : {
2304
+ tenantId: null
2305
+ } : {};
2306
+ return this.answer(requestId, () => signalWithStartForTenant.call(this.gateway, {
2307
+ ...start,
2308
+ tenant
2309
+ }, tenant, claim, {
2310
+ token: body.signal.token,
2311
+ payload: body.signal.payload
2312
+ }));
2313
+ }
1997
2314
  /** The run alone (`getRun`, else from its detail), or null when it does not exist. */
1998
2315
  async runOf(runId) {
1999
2316
  return this.gateway.getRun ? this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run ?? null;
@@ -2162,6 +2479,10 @@ var RunGatewayError = class extends Error {
2162
2479
  this.code = code;
2163
2480
  }
2164
2481
  };
2482
+ function unsupportedVerb(kind) {
2483
+ return new RunGatewayError(`${kind} is not supported by this server: the control plane is older than this tenant`, UNSUPPORTED_RUN_REQUEST);
2484
+ }
2485
+ __name(unsupportedVerb, "unsupportedVerb");
2165
2486
  var UnsupportedRunRequestError = class UnsupportedRunRequestError2 extends RunGatewayError {
2166
2487
  static {
2167
2488
  __name(this, "UnsupportedRunRequestError");
@@ -2467,7 +2788,7 @@ var ProxyRunGateway = class {
2467
2788
  * {@link RunGatewayError} with code {@link UNSUPPORTED_RUN_REQUEST}.
2468
2789
  */
2469
2790
  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");
2791
+ const notSupported = /* @__PURE__ */ __name(() => unsupportedVerb(body.kind), "notSupported");
2471
2792
  if (this.knownUnsupported(body.kind)) throw notSupported();
2472
2793
  let data;
2473
2794
  try {
@@ -2479,6 +2800,62 @@ var ProxyRunGateway = class {
2479
2800
  this.unsupportedUntil.set(body.kind, Date.now() + this.capabilityTtlMs);
2480
2801
  throw notSupported();
2481
2802
  }
2803
+ /**
2804
+ * Signal the run of this tenant's namespace waiting on `token` (`engine.signal`). Resolves null
2805
+ * when no run of this namespace waits on it: the control plane does NOT buffer a tenant's signal
2806
+ * for a wait opened later (another namespace's run could open it). A control plane that predates
2807
+ * the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error.
2808
+ */
2809
+ async signal(token, payload, opts) {
2810
+ if (this.knownUnsupported("signal")) throw unsupportedVerb("signal");
2811
+ let data;
2812
+ try {
2813
+ data = await this.request(opts === void 0 ? {
2814
+ kind: "signal",
2815
+ token,
2816
+ payload
2817
+ } : {
2818
+ kind: "signal",
2819
+ token,
2820
+ payload,
2821
+ opts
2822
+ });
2823
+ } catch (err) {
2824
+ if (!isUnsupported(err)) throw err;
2825
+ }
2826
+ if (data !== void 0) return data;
2827
+ this.unsupportedUntil.set("signal", Date.now() + this.capabilityTtlMs);
2828
+ throw unsupportedVerb("signal");
2829
+ }
2830
+ /**
2831
+ * `engine.signalWithStart` for this tenant: the control plane starts `start` in this tenant's
2832
+ * namespace unless its run exists, then signals it (buffered until the run waits, when the token
2833
+ * names the run id). See the responder for the authorization rule.
2834
+ */
2835
+ signalWithStart(start, signal) {
2836
+ return this.requestNewVerb({
2837
+ kind: "signalWithStart",
2838
+ start,
2839
+ signal
2840
+ });
2841
+ }
2842
+ /**
2843
+ * Resume the runs of this tenant's namespace waiting on event `name` (`ctx.waitForEvent`).
2844
+ * Resolves how many it resumed. The tenant's own `onEvent` subscribers are started by the caller
2845
+ * (`DurableStartClient.publishEvent`), not here.
2846
+ */
2847
+ publishEvent(name, payload, opts) {
2848
+ return this.requestNewVerb({
2849
+ kind: "publishEvent",
2850
+ name,
2851
+ payload,
2852
+ ...opts?.id !== void 0 ? {
2853
+ opts: {
2854
+ id: opts.id
2855
+ }
2856
+ } : {}
2857
+ });
2858
+ }
2482
2859
  subscribe(runId, onEvent) {
2483
2860
  const unsubscribe = this.transport.onTenantEvent?.(this.tenant, (evt) => {
2484
2861
  if (evt.event.runId === runId) onEvent(evt.event);
@@ -2501,7 +2878,7 @@ ProxyRunGateway = _ts_decorate6([
2501
2878
  ], ProxyRunGateway);
2502
2879
 
2503
2880
  // 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";
2881
+ import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL5, STATE_STORE_CANONICAL, TERMINAL_RUN_STATUSES, parseDuration as parseDuration3 } from "@dudousxd/nestjs-durable-core";
2505
2882
  import { Inject as Inject5, Injectable as Injectable8, Optional as Optional2 } from "@nestjs/common";
2506
2883
 
2507
2884
  // src/settle-within.ts
@@ -2674,7 +3051,7 @@ function validateRetention(retention) {
2674
3051
  if (policy.maxAge == null && policy.maxCount == null) {
2675
3052
  throw new Error("durable retention: each policy must set maxAge and/or maxCount");
2676
3053
  }
2677
- if (policy.maxAge != null) parseDuration2(policy.maxAge);
3054
+ if (policy.maxAge != null) parseDuration3(policy.maxAge);
2678
3055
  for (const status of policy.statuses) {
2679
3056
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
2680
3057
  throw new Error(`durable retention: status "${status}" is not terminal; only ${TERMINAL_RUN_STATUSES.join(", ")} can be pruned`);
@@ -2731,7 +3108,7 @@ var RetentionPoller = class {
2731
3108
  return;
2732
3109
  }
2733
3110
  void this.sweep();
2734
- const intervalMs = retention.sweepInterval != null ? parseDuration2(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
3111
+ const intervalMs = retention.sweepInterval != null ? parseDuration3(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
2735
3112
  if (intervalMs > 0) {
2736
3113
  this.timer = setInterval(() => void this.sweep(), intervalMs);
2737
3114
  this.timer.unref?.();
@@ -3167,8 +3544,14 @@ var StoreRunGateway = class {
3167
3544
  if (action === "trigger") return this.engine.schedules.trigger(id);
3168
3545
  return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
3169
3546
  }
3170
- signal(token, payload) {
3171
- return this.engine.signal(token, payload);
3547
+ signal(token, payload, opts) {
3548
+ return this.engine.signal(token, payload, opts);
3549
+ }
3550
+ signalWithStartForTenant(start, namespace, clientTenant, signal) {
3551
+ return this.engine.signalWithStartForTenant(start, namespace, clientTenant, signal);
3552
+ }
3553
+ publishEventForTenant(name, payload, namespace) {
3554
+ return this.engine.publishEventForTenant(name, payload, namespace);
3172
3555
  }
3173
3556
  async signalWaiter(token) {
3174
3557
  const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
@@ -3575,22 +3958,6 @@ TimerPoller = _ts_decorate10([
3575
3958
  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
3959
  import { Inject as Inject8, Injectable as Injectable11 } from "@nestjs/common";
3577
3960
  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
3961
  function _ts_decorate11(decorators, target, key, desc) {
3595
3962
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3596
3963
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -3698,7 +4065,8 @@ var WorkflowRegistrar = class {
3698
4065
  concurrency: meta.concurrency,
3699
4066
  executionTimeout: meta.executionTimeout,
3700
4067
  requires: meta.requires,
3701
- validateInput: io.validateAtStart,
4068
+ validateInput: io.validateParsed,
4069
+ parseInput: io.parseInput,
3702
4070
  searchAttributesSchema: meta.searchAttributes,
3703
4071
  onEvent: getOnEvents(meta, workflowCtor),
3704
4072
  eventBatch,
@@ -3783,25 +4151,33 @@ var WorkflowRegistrar = class {
3783
4151
  const fallback = this.options.deadLetterWorkflow ? workflowName5(this.options.deadLetterWorkflow) : void 0;
3784
4152
  if (byWorkflow.size === 0 && !fallback) return;
3785
4153
  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);
4154
+ void this.routeDead(run, byWorkflow, fallback).catch(() => void 0);
3803
4155
  });
3804
4156
  }
4157
+ /** {@link installDeadLetterRouting}'s routing of one dead run. */
4158
+ async routeDead(run, byWorkflow, fallback) {
4159
+ let target = byWorkflow.get(run.workflow);
4160
+ if (!target && fallback) {
4161
+ if (await this.engine.announcedDeadLetter?.(run).catch(() => void 0)) return;
4162
+ target = fallback;
4163
+ }
4164
+ if (!target) return;
4165
+ await this.engine.start(
4166
+ target,
4167
+ {
4168
+ deadRunId: run.id,
4169
+ workflow: run.workflow,
4170
+ input: run.input,
4171
+ error: run.error
4172
+ },
4173
+ `dlq:${run.id}`,
4174
+ // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to
4175
+ // that tenant's worker group (`target@<tenant>`), not the bare group.
4176
+ {
4177
+ namespace: run.namespace
4178
+ }
4179
+ ).catch(() => void 0);
4180
+ }
3805
4181
  };
3806
4182
  WorkflowRegistrar = _ts_decorate11([
3807
4183
  Injectable11(),
@@ -4273,12 +4649,29 @@ var DurableModule = class _DurableModule {
4273
4649
  provide: WorkflowEngine7,
4274
4650
  useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
4275
4651
  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));
4652
+ return new DurableStartClient(
4653
+ {
4654
+ ...options,
4655
+ ...auth.tenantToken !== void 0 ? {
4656
+ tenantToken: auth.tenantToken
4657
+ } : {}
4658
+ },
4659
+ void 0,
4660
+ resolveAccessor(moduleRef),
4661
+ // `signal`/`signalWithStart`/`publishEvent` go to the control plane as run requests,
4662
+ // over the one `ProxyRunGateway` bound under `RunGateway` (it owns the reply
4663
+ // subscription). Resolved lazily: that gateway is built after this facade.
4664
+ () => {
4665
+ try {
4666
+ const gateway = moduleRef.get(RunGateway2, {
4667
+ strict: false
4668
+ });
4669
+ return gateway instanceof ProxyRunGateway ? gateway : void 0;
4670
+ } catch {
4671
+ return void 0;
4672
+ }
4673
+ }
4674
+ );
4282
4675
  }
4283
4676
  if (!store) {
4284
4677
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");