@dudousxd/nestjs-durable 0.0.0-beta-20260701163515

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.cjs ADDED
@@ -0,0 +1,1345 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ CONTEXT_ACCESSOR: () => CONTEXT_ACCESSOR,
25
+ DEAD_LETTER_METADATA: () => DEAD_LETTER_METADATA,
26
+ DURABLE_STEP_METADATA: () => DURABLE_STEP_METADATA,
27
+ DURABLE_WORKER_OPTIONS: () => DURABLE_WORKER_OPTIONS,
28
+ DURABLE_WORKER_RUNNERS: () => DURABLE_WORKER_RUNNERS,
29
+ DeadLetter: () => DeadLetter,
30
+ DurableControlPlaneModule: () => DurableControlPlaneModule,
31
+ DurableModule: () => DurableModule,
32
+ DurableStep: () => DurableStep,
33
+ DurableWorkerModule: () => DurableWorkerModule,
34
+ ENTITY_METADATA: () => ENTITY_METADATA,
35
+ ENTITY_ON_METADATA: () => ENTITY_ON_METADATA,
36
+ Entity: () => Entity,
37
+ EntityService: () => EntityService,
38
+ IN_APP_RUN_REDIS_WORKER: () => IN_APP_RUN_REDIS_WORKER,
39
+ IN_APP_WORKER_BINDING: () => IN_APP_WORKER_BINDING,
40
+ IN_APP_WORKER_OPTIONS: () => IN_APP_WORKER_OPTIONS,
41
+ IN_APP_WORKER_RUNNERS: () => IN_APP_WORKER_RUNNERS,
42
+ IN_APP_WORKER_RUNTIME: () => IN_APP_WORKER_RUNTIME,
43
+ InAppWorkerBootstrap: () => InAppWorkerBootstrap,
44
+ ON_EVENT_METADATA: () => ON_EVENT_METADATA,
45
+ On: () => On,
46
+ OnEvent: () => OnEvent,
47
+ RUN_REDIS_WORKER: () => RUN_REDIS_WORKER,
48
+ STEP_INTERCEPTOR_METADATA: () => STEP_INTERCEPTOR_METADATA,
49
+ Step: () => Step,
50
+ StepInterceptor: () => StepInterceptor,
51
+ ThinStepRegistrar: () => ThinStepRegistrar,
52
+ ThinWorkerBootstrap: () => ThinWorkerBootstrap,
53
+ ThinWorkflowRegistrar: () => ThinWorkflowRegistrar,
54
+ WORKFLOW_METADATA: () => WORKFLOW_METADATA,
55
+ Workflow: () => Workflow,
56
+ WorkflowService: () => WorkflowService,
57
+ entityConfigFor: () => entityConfigFor,
58
+ getDurableStepMeta: () => getDurableStepMeta,
59
+ getEntityMeta: () => getEntityMeta,
60
+ getOnEvents: () => getOnEvents,
61
+ getWorkflowMeta: () => getWorkflowMeta,
62
+ inAppWorkerProviders: () => inAppWorkerProviders,
63
+ isDeadLetterHandler: () => isDeadLetterHandler,
64
+ isStepInterceptor: () => isStepInterceptor
65
+ });
66
+ module.exports = __toCommonJS(index_exports);
67
+
68
+ // src/decorators.ts
69
+ var import_nestjs_durable_core = require("@dudousxd/nestjs-durable-core");
70
+ var import_reflect_metadata = require("reflect-metadata");
71
+ var WORKFLOW_METADATA = Symbol("nestjs-durable:workflow");
72
+ function Workflow(options) {
73
+ return (target) => {
74
+ const meta = {
75
+ name: options.name,
76
+ version: options.version ?? "1",
77
+ deadLetterWorkflow: options.deadLetterWorkflow,
78
+ tags: options.tags,
79
+ singleton: options.singleton,
80
+ executionTimeout: options.executionTimeout,
81
+ inputSchema: options.inputSchema,
82
+ validateInput: options.validateInput,
83
+ onEvent: options.onEvent,
84
+ debounce: options.debounce,
85
+ batch: options.batch
86
+ };
87
+ Reflect.defineMetadata(WORKFLOW_METADATA, meta, target);
88
+ Object.defineProperty(target, import_nestjs_durable_core.WORKFLOW_NAME_KEY, {
89
+ value: options.name,
90
+ configurable: true
91
+ });
92
+ };
93
+ }
94
+ __name(Workflow, "Workflow");
95
+ function getWorkflowMeta(target) {
96
+ return Reflect.getMetadata(WORKFLOW_METADATA, target);
97
+ }
98
+ __name(getWorkflowMeta, "getWorkflowMeta");
99
+ var DURABLE_STEP_METADATA = Symbol("nestjs-durable:step-handler");
100
+ function Step(name) {
101
+ return (_target, _propertyKey, descriptor) => {
102
+ const meta = {
103
+ name
104
+ };
105
+ Reflect.defineMetadata(DURABLE_STEP_METADATA, meta, descriptor.value);
106
+ return descriptor;
107
+ };
108
+ }
109
+ __name(Step, "Step");
110
+ var DurableStep = Step;
111
+ function getDurableStepMeta(method) {
112
+ return Reflect.getMetadata(DURABLE_STEP_METADATA, method);
113
+ }
114
+ __name(getDurableStepMeta, "getDurableStepMeta");
115
+ var DEAD_LETTER_METADATA = Symbol("nestjs-durable:dead-letter");
116
+ function DeadLetter() {
117
+ return (_target, _propertyKey, descriptor) => {
118
+ Reflect.defineMetadata(DEAD_LETTER_METADATA, true, descriptor.value);
119
+ return descriptor;
120
+ };
121
+ }
122
+ __name(DeadLetter, "DeadLetter");
123
+ function isDeadLetterHandler(method) {
124
+ return Reflect.getMetadata(DEAD_LETTER_METADATA, method) === true;
125
+ }
126
+ __name(isDeadLetterHandler, "isDeadLetterHandler");
127
+ var ON_EVENT_METADATA = Symbol("nestjs-durable:on-event");
128
+ function OnEvent(...events) {
129
+ return (target) => {
130
+ const existing = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
131
+ Reflect.defineMetadata(ON_EVENT_METADATA, [
132
+ ...existing,
133
+ ...events
134
+ ], target);
135
+ };
136
+ }
137
+ __name(OnEvent, "OnEvent");
138
+ function getOnEvents(meta, target) {
139
+ const fromDecorator = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
140
+ return [
141
+ .../* @__PURE__ */ new Set([
142
+ ...meta.onEvent ?? [],
143
+ ...fromDecorator
144
+ ])
145
+ ];
146
+ }
147
+ __name(getOnEvents, "getOnEvents");
148
+
149
+ // src/durable-worker.module.ts
150
+ var import_durable_worker = require("@dudousxd/durable-worker");
151
+ var import_nestjs_durable_core2 = require("@dudousxd/nestjs-durable-core");
152
+ var import_common = require("@nestjs/common");
153
+ var import_core = require("@nestjs/core");
154
+
155
+ // src/discovery-helpers.ts
156
+ function scanWorkflows(discovery, register) {
157
+ for (const wrapper of discovery.getProviders()) {
158
+ const { instance } = wrapper;
159
+ if (!instance || typeof instance !== "object") continue;
160
+ const meta = getWorkflowMeta(instance.constructor);
161
+ if (!meta) continue;
162
+ const workflow = instance;
163
+ if (typeof workflow.run !== "function") {
164
+ throw new Error(`@Workflow ${meta.name} must define a run(ctx, input) method`);
165
+ }
166
+ register(meta, workflow);
167
+ }
168
+ }
169
+ __name(scanWorkflows, "scanWorkflows");
170
+ function scanSteps(discovery, scanner, register) {
171
+ for (const wrapper of discovery.getProviders()) {
172
+ const { instance } = wrapper;
173
+ if (!instance || typeof instance !== "object") continue;
174
+ const prototype = Object.getPrototypeOf(instance);
175
+ for (const methodName of scanner.getAllMethodNames(prototype)) {
176
+ const method = instance[methodName];
177
+ if (typeof method !== "function") continue;
178
+ const meta = getDurableStepMeta(method);
179
+ if (!meta) continue;
180
+ const handler = /* @__PURE__ */ __name((input, log) => method.call(instance, input, log), "handler");
181
+ register(meta, handler);
182
+ }
183
+ }
184
+ }
185
+ __name(scanSteps, "scanSteps");
186
+
187
+ // src/durable-worker.module.ts
188
+ function _ts_decorate(decorators, target, key, desc) {
189
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
190
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
191
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
192
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
193
+ }
194
+ __name(_ts_decorate, "_ts_decorate");
195
+ function _ts_metadata(k, v) {
196
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
197
+ }
198
+ __name(_ts_metadata, "_ts_metadata");
199
+ function _ts_param(paramIndex, decorator) {
200
+ return function(target, key) {
201
+ decorator(target, key, paramIndex);
202
+ };
203
+ }
204
+ __name(_ts_param, "_ts_param");
205
+ var DURABLE_WORKER_OPTIONS = Symbol("nestjs-durable:worker-options");
206
+ var RUN_REDIS_WORKER = Symbol("nestjs-durable:run-redis-worker");
207
+ var DURABLE_WORKER_RUNNERS = Symbol("nestjs-durable:worker-runners");
208
+ var ThinWorkflowRegistrar = class {
209
+ static {
210
+ __name(this, "ThinWorkflowRegistrar");
211
+ }
212
+ discovery;
213
+ runtime;
214
+ constructor(discovery, runtime) {
215
+ this.discovery = discovery;
216
+ this.runtime = runtime;
217
+ }
218
+ onModuleInit() {
219
+ scanWorkflows(this.discovery, (meta, instance) => this.runtime.registerWorkflow(meta.name, (ctx, input) => instance.run(ctx, input)));
220
+ }
221
+ };
222
+ ThinWorkflowRegistrar = _ts_decorate([
223
+ (0, import_common.Injectable)(),
224
+ _ts_metadata("design:type", Function),
225
+ _ts_metadata("design:paramtypes", [
226
+ typeof import_core.DiscoveryService === "undefined" ? Object : import_core.DiscoveryService,
227
+ typeof import_durable_worker.DurableWorkerRuntime === "undefined" ? Object : import_durable_worker.DurableWorkerRuntime
228
+ ])
229
+ ], ThinWorkflowRegistrar);
230
+ var ThinStepRegistrar = class {
231
+ static {
232
+ __name(this, "ThinStepRegistrar");
233
+ }
234
+ discovery;
235
+ metadataScanner;
236
+ runtime;
237
+ constructor(discovery, metadataScanner, runtime) {
238
+ this.discovery = discovery;
239
+ this.metadataScanner = metadataScanner;
240
+ this.runtime = runtime;
241
+ }
242
+ onModuleInit() {
243
+ scanSteps(this.discovery, this.metadataScanner, (meta, handler) => this.runtime.registerStep(meta.name, handler));
244
+ }
245
+ };
246
+ ThinStepRegistrar = _ts_decorate([
247
+ (0, import_common.Injectable)(),
248
+ _ts_metadata("design:type", Function),
249
+ _ts_metadata("design:paramtypes", [
250
+ typeof import_core.DiscoveryService === "undefined" ? Object : import_core.DiscoveryService,
251
+ typeof import_core.MetadataScanner === "undefined" ? Object : import_core.MetadataScanner,
252
+ typeof import_durable_worker.DurableWorkerRuntime === "undefined" ? Object : import_durable_worker.DurableWorkerRuntime
253
+ ])
254
+ ], ThinStepRegistrar);
255
+ var ThinWorkerBootstrap = class {
256
+ static {
257
+ __name(this, "ThinWorkerBootstrap");
258
+ }
259
+ runtime;
260
+ options;
261
+ runRedisWorker;
262
+ runnersSink;
263
+ runners = [];
264
+ constructor(runtime, options, runRedisWorker, runnersSink) {
265
+ this.runtime = runtime;
266
+ this.options = options;
267
+ this.runRedisWorker = runRedisWorker;
268
+ this.runnersSink = runnersSink;
269
+ }
270
+ async onApplicationBootstrap() {
271
+ for (const group of this.options.groups) {
272
+ const handle = await this.runRedisWorker({
273
+ runtime: this.runtime,
274
+ group: (0, import_nestjs_durable_core2.tenantGroup)(group, this.options.tenant),
275
+ connection: this.options.connection,
276
+ ...this.options.prefix !== void 0 ? {
277
+ prefix: this.options.prefix
278
+ } : {},
279
+ ...this.options.instanceId !== void 0 ? {
280
+ instanceId: this.options.instanceId
281
+ } : {},
282
+ ...(this.options.concurrencyByGroup?.[group] ?? this.options.concurrency) !== void 0 ? {
283
+ concurrency: this.options.concurrencyByGroup?.[group] ?? this.options.concurrency
284
+ } : {}
285
+ });
286
+ this.runners.push(handle);
287
+ this.runnersSink.push(handle);
288
+ }
289
+ }
290
+ async onApplicationShutdown() {
291
+ await Promise.allSettled(this.runners.map((h) => h.close()));
292
+ }
293
+ };
294
+ ThinWorkerBootstrap = _ts_decorate([
295
+ (0, import_common.Injectable)(),
296
+ _ts_param(1, (0, import_common.Inject)(DURABLE_WORKER_OPTIONS)),
297
+ _ts_param(2, (0, import_common.Inject)(RUN_REDIS_WORKER)),
298
+ _ts_param(3, (0, import_common.Inject)(DURABLE_WORKER_RUNNERS)),
299
+ _ts_metadata("design:type", Function),
300
+ _ts_metadata("design:paramtypes", [
301
+ typeof import_durable_worker.DurableWorkerRuntime === "undefined" ? Object : import_durable_worker.DurableWorkerRuntime,
302
+ typeof DurableWorkerModuleOptions === "undefined" ? Object : DurableWorkerModuleOptions,
303
+ typeof RunRedisWorkerFn === "undefined" ? Object : RunRedisWorkerFn,
304
+ Array
305
+ ])
306
+ ], ThinWorkerBootstrap);
307
+ var DurableWorkerModule = class _DurableWorkerModule {
308
+ static {
309
+ __name(this, "DurableWorkerModule");
310
+ }
311
+ static forRoot(options) {
312
+ return _DurableWorkerModule.build({
313
+ provide: DURABLE_WORKER_OPTIONS,
314
+ useValue: options
315
+ });
316
+ }
317
+ static forRootAsync(options) {
318
+ return _DurableWorkerModule.build({
319
+ provide: DURABLE_WORKER_OPTIONS,
320
+ useFactory: options.useFactory,
321
+ inject: options.inject ?? []
322
+ });
323
+ }
324
+ static build(optionsProvider) {
325
+ return {
326
+ module: _DurableWorkerModule,
327
+ imports: [
328
+ import_core.DiscoveryModule
329
+ ],
330
+ providers: [
331
+ optionsProvider,
332
+ {
333
+ provide: import_durable_worker.DurableWorkerRuntime,
334
+ useFactory: /* @__PURE__ */ __name(() => new import_durable_worker.DurableWorkerRuntime(), "useFactory")
335
+ },
336
+ {
337
+ provide: RUN_REDIS_WORKER,
338
+ useValue: import_durable_worker.runRedisWorker
339
+ },
340
+ {
341
+ provide: DURABLE_WORKER_RUNNERS,
342
+ useValue: []
343
+ },
344
+ ThinWorkflowRegistrar,
345
+ ThinStepRegistrar,
346
+ ThinWorkerBootstrap
347
+ ],
348
+ exports: [
349
+ import_durable_worker.DurableWorkerRuntime
350
+ ]
351
+ };
352
+ }
353
+ };
354
+ DurableWorkerModule = _ts_decorate([
355
+ (0, import_common.Module)({})
356
+ ], DurableWorkerModule);
357
+
358
+ // src/durable.module.ts
359
+ var import_nestjs_durable_core10 = require("@dudousxd/nestjs-durable-core");
360
+ var import_common9 = require("@nestjs/common");
361
+ var import_core5 = require("@nestjs/core");
362
+
363
+ // src/durable-step.registrar.ts
364
+ var import_nestjs_durable_core3 = require("@dudousxd/nestjs-durable-core");
365
+ var import_common2 = require("@nestjs/common");
366
+ var import_core2 = require("@nestjs/core");
367
+ function _ts_decorate2(decorators, target, key, desc) {
368
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
369
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
370
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
371
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
372
+ }
373
+ __name(_ts_decorate2, "_ts_decorate");
374
+ function _ts_metadata2(k, v) {
375
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
376
+ }
377
+ __name(_ts_metadata2, "_ts_metadata");
378
+ function _ts_param2(paramIndex, decorator) {
379
+ return function(target, key) {
380
+ decorator(target, key, paramIndex);
381
+ };
382
+ }
383
+ __name(_ts_param2, "_ts_param");
384
+ function supportsHandle(transport) {
385
+ return typeof transport?.handle === "function";
386
+ }
387
+ __name(supportsHandle, "supportsHandle");
388
+ var DurableStepRegistrar = class {
389
+ static {
390
+ __name(this, "DurableStepRegistrar");
391
+ }
392
+ discovery;
393
+ metadataScanner;
394
+ transport;
395
+ options;
396
+ constructor(discovery, metadataScanner, transport, options) {
397
+ this.discovery = discovery;
398
+ this.metadataScanner = metadataScanner;
399
+ this.transport = transport;
400
+ this.options = options;
401
+ }
402
+ onModuleInit() {
403
+ if (this.options.worker === false) return;
404
+ if (!supportsHandle(this.transport)) return;
405
+ const transport = this.transport;
406
+ scanSteps(this.discovery, this.metadataScanner, (meta, handler) => transport.handle(meta.name, handler));
407
+ }
408
+ };
409
+ DurableStepRegistrar = _ts_decorate2([
410
+ (0, import_common2.Injectable)(),
411
+ _ts_param2(2, (0, import_common2.Inject)(import_nestjs_durable_core3.TRANSPORT_CANONICAL)),
412
+ _ts_param2(3, (0, import_common2.Inject)(import_nestjs_durable_core3.DURABLE_OPTIONS_CANONICAL)),
413
+ _ts_metadata2("design:type", Function),
414
+ _ts_metadata2("design:paramtypes", [
415
+ typeof import_core2.DiscoveryService === "undefined" ? Object : import_core2.DiscoveryService,
416
+ typeof import_core2.MetadataScanner === "undefined" ? Object : import_core2.MetadataScanner,
417
+ Object,
418
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
419
+ ])
420
+ ], DurableStepRegistrar);
421
+
422
+ // src/entity.ts
423
+ var import_nestjs_durable_core4 = require("@dudousxd/nestjs-durable-core");
424
+ var import_common3 = require("@nestjs/common");
425
+ var import_reflect_metadata2 = require("reflect-metadata");
426
+ function _ts_decorate3(decorators, target, key, desc) {
427
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
428
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
429
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
430
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
431
+ }
432
+ __name(_ts_decorate3, "_ts_decorate");
433
+ function _ts_metadata3(k, v) {
434
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
435
+ }
436
+ __name(_ts_metadata3, "_ts_metadata");
437
+ var ENTITY_METADATA = Symbol("nestjs-durable:entity");
438
+ var ENTITY_ON_METADATA = Symbol("nestjs-durable:entity-on");
439
+ function Entity(options) {
440
+ return (target) => {
441
+ Reflect.defineMetadata(ENTITY_METADATA, options, target);
442
+ };
443
+ }
444
+ __name(Entity, "Entity");
445
+ function On(op) {
446
+ return (target, propertyKey) => {
447
+ const ctor = target.constructor;
448
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
449
+ ops.set(op, propertyKey);
450
+ Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);
451
+ };
452
+ }
453
+ __name(On, "On");
454
+ function getEntityMeta(target) {
455
+ return Reflect.getMetadata(ENTITY_METADATA, target);
456
+ }
457
+ __name(getEntityMeta, "getEntityMeta");
458
+ function entityConfigFor(ctor) {
459
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
460
+ const Cls = ctor;
461
+ const handlers = {};
462
+ for (const [op, method] of ops) {
463
+ handlers[op] = (state, arg) => {
464
+ Object.setPrototypeOf(state, Cls.prototype);
465
+ const fn = state[method];
466
+ if (typeof fn !== "function") throw new Error(`entity handler "${method}" is not a method`);
467
+ return fn.call(state, arg);
468
+ };
469
+ }
470
+ return {
471
+ initialState: /* @__PURE__ */ __name(() => new Cls(), "initialState"),
472
+ handlers
473
+ };
474
+ }
475
+ __name(entityConfigFor, "entityConfigFor");
476
+ var EntityService = class {
477
+ static {
478
+ __name(this, "EntityService");
479
+ }
480
+ engine;
481
+ constructor(engine) {
482
+ this.engine = engine;
483
+ }
484
+ /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */
485
+ signal(name, key, op, arg) {
486
+ return this.engine.signalEntity(name, key, op, arg);
487
+ }
488
+ /** Read an entity's current durable state (or undefined if it has none yet). */
489
+ getState(name, key) {
490
+ return this.engine.getEntityState(name, key);
491
+ }
492
+ };
493
+ EntityService = _ts_decorate3([
494
+ (0, import_common3.Injectable)(),
495
+ _ts_metadata3("design:type", Function),
496
+ _ts_metadata3("design:paramtypes", [
497
+ typeof import_nestjs_durable_core4.WorkflowEngine === "undefined" ? Object : import_nestjs_durable_core4.WorkflowEngine
498
+ ])
499
+ ], EntityService);
500
+
501
+ // src/in-app-worker.ts
502
+ var import_durable_worker2 = require("@dudousxd/durable-worker");
503
+ var import_nestjs_durable_core5 = require("@dudousxd/nestjs-durable-core");
504
+ var import_common4 = require("@nestjs/common");
505
+ var import_core3 = require("@nestjs/core");
506
+ function _ts_decorate4(decorators, target, key, desc) {
507
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
508
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
509
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
510
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
511
+ }
512
+ __name(_ts_decorate4, "_ts_decorate");
513
+ function _ts_metadata4(k, v) {
514
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
515
+ }
516
+ __name(_ts_metadata4, "_ts_metadata");
517
+ function _ts_param3(paramIndex, decorator) {
518
+ return function(target, key) {
519
+ decorator(target, key, paramIndex);
520
+ };
521
+ }
522
+ __name(_ts_param3, "_ts_param");
523
+ var IN_APP_WORKER_OPTIONS = Symbol("nestjs-durable:in-app-worker-options");
524
+ var IN_APP_WORKER_BINDING = Symbol("nestjs-durable:in-app-worker-binding");
525
+ var IN_APP_WORKER_RUNTIME = Symbol("nestjs-durable:in-app-worker-runtime");
526
+ var IN_APP_RUN_REDIS_WORKER = Symbol("nestjs-durable:in-app-run-redis-worker");
527
+ var IN_APP_WORKER_RUNNERS = Symbol("nestjs-durable:in-app-worker-runners");
528
+ function inAppWorkerBinding(transport, options) {
529
+ if (!options) return null;
530
+ if (!transport?.dispatchWorkflowTask || !transport.onDecision) {
531
+ throw new Error("inAppWorker requires a transport that carries workflow tasks (dispatchWorkflowTask + onDecision), e.g. BullMQTransport. An in-process transport cannot serve a group-served workflow.");
532
+ }
533
+ return {
534
+ group: options.group,
535
+ executor: new import_nestjs_durable_core5.RemoteWorkflowExecutor(transport, options.group)
536
+ };
537
+ }
538
+ __name(inAppWorkerBinding, "inAppWorkerBinding");
539
+ var InAppWorkerBootstrap = class {
540
+ static {
541
+ __name(this, "InAppWorkerBootstrap");
542
+ }
543
+ discovery;
544
+ metadataScanner;
545
+ options;
546
+ runtime;
547
+ runRedisWorker;
548
+ runnersSink;
549
+ runners = [];
550
+ constructor(discovery, metadataScanner, options, runtime, runRedisWorker, runnersSink) {
551
+ this.discovery = discovery;
552
+ this.metadataScanner = metadataScanner;
553
+ this.options = options;
554
+ this.runtime = runtime;
555
+ this.runRedisWorker = runRedisWorker;
556
+ this.runnersSink = runnersSink;
557
+ }
558
+ onModuleInit() {
559
+ if (!this.options) return;
560
+ scanWorkflows(this.discovery, (meta, instance) => this.runtime.registerWorkflow(meta.name, (ctx, input) => instance.run(ctx, input)));
561
+ scanSteps(this.discovery, this.metadataScanner, (meta, handler) => this.runtime.registerStep(meta.name, handler));
562
+ }
563
+ async onApplicationBootstrap() {
564
+ if (!this.options) return;
565
+ const handle = await this.runRedisWorker({
566
+ runtime: this.runtime,
567
+ group: this.options.group,
568
+ connection: this.options.connection,
569
+ ...this.options.prefix !== void 0 ? {
570
+ prefix: this.options.prefix
571
+ } : {},
572
+ ...this.options.instanceId !== void 0 ? {
573
+ instanceId: this.options.instanceId
574
+ } : {},
575
+ ...this.options.concurrency !== void 0 ? {
576
+ concurrency: this.options.concurrency
577
+ } : {}
578
+ });
579
+ this.runners.push(handle);
580
+ this.runnersSink.push(handle);
581
+ }
582
+ async onApplicationShutdown() {
583
+ await Promise.allSettled(this.runners.map((handle) => handle.close()));
584
+ }
585
+ };
586
+ InAppWorkerBootstrap = _ts_decorate4([
587
+ (0, import_common4.Injectable)(),
588
+ _ts_param3(2, (0, import_common4.Inject)(IN_APP_WORKER_OPTIONS)),
589
+ _ts_param3(3, (0, import_common4.Inject)(IN_APP_WORKER_RUNTIME)),
590
+ _ts_param3(4, (0, import_common4.Inject)(IN_APP_RUN_REDIS_WORKER)),
591
+ _ts_param3(5, (0, import_common4.Inject)(IN_APP_WORKER_RUNNERS)),
592
+ _ts_metadata4("design:type", Function),
593
+ _ts_metadata4("design:paramtypes", [
594
+ typeof import_core3.DiscoveryService === "undefined" ? Object : import_core3.DiscoveryService,
595
+ typeof import_core3.MetadataScanner === "undefined" ? Object : import_core3.MetadataScanner,
596
+ Object,
597
+ typeof import_durable_worker2.DurableWorkerRuntime === "undefined" ? Object : import_durable_worker2.DurableWorkerRuntime,
598
+ typeof RunRedisWorkerFn === "undefined" ? Object : RunRedisWorkerFn,
599
+ Array
600
+ ])
601
+ ], InAppWorkerBootstrap);
602
+ function inAppWorkerProviders() {
603
+ return [
604
+ {
605
+ provide: IN_APP_WORKER_BINDING,
606
+ useFactory: /* @__PURE__ */ __name((transport, options) => inAppWorkerBinding(transport, options.inAppWorker ?? null), "useFactory"),
607
+ inject: [
608
+ import_nestjs_durable_core5.TRANSPORT_CANONICAL,
609
+ import_nestjs_durable_core5.DURABLE_OPTIONS_CANONICAL
610
+ ]
611
+ },
612
+ {
613
+ provide: IN_APP_WORKER_OPTIONS,
614
+ useFactory: /* @__PURE__ */ __name((options) => options.inAppWorker ?? null, "useFactory"),
615
+ inject: [
616
+ import_nestjs_durable_core5.DURABLE_OPTIONS_CANONICAL
617
+ ]
618
+ },
619
+ {
620
+ provide: IN_APP_WORKER_RUNTIME,
621
+ useFactory: /* @__PURE__ */ __name(() => new import_durable_worker2.DurableWorkerRuntime(), "useFactory")
622
+ },
623
+ {
624
+ provide: IN_APP_RUN_REDIS_WORKER,
625
+ useValue: import_durable_worker2.runRedisWorker
626
+ },
627
+ {
628
+ provide: IN_APP_WORKER_RUNNERS,
629
+ useValue: []
630
+ },
631
+ InAppWorkerBootstrap
632
+ ];
633
+ }
634
+ __name(inAppWorkerProviders, "inAppWorkerProviders");
635
+
636
+ // src/retention-poller.ts
637
+ var import_nestjs_durable_core6 = require("@dudousxd/nestjs-durable-core");
638
+ var import_common5 = require("@nestjs/common");
639
+ function _ts_decorate5(decorators, target, key, desc) {
640
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
641
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
642
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
643
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
644
+ }
645
+ __name(_ts_decorate5, "_ts_decorate");
646
+ function _ts_metadata5(k, v) {
647
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
648
+ }
649
+ __name(_ts_metadata5, "_ts_metadata");
650
+ function _ts_param4(paramIndex, decorator) {
651
+ return function(target, key) {
652
+ decorator(target, key, paramIndex);
653
+ };
654
+ }
655
+ __name(_ts_param4, "_ts_param");
656
+ var DEFAULT_SWEEP_INTERVAL_MS = 6e4;
657
+ var DEFAULT_BATCH_SIZE = 1e3;
658
+ var MAX_BATCHES_PER_POLICY = 100;
659
+ function validateRetention(retention) {
660
+ const seen = /* @__PURE__ */ new Set();
661
+ for (const policy of retention.policies) {
662
+ if (policy.statuses.length === 0) {
663
+ throw new Error("durable retention: each policy must list at least one status");
664
+ }
665
+ if (policy.maxAge == null && policy.maxCount == null) {
666
+ throw new Error("durable retention: each policy must set maxAge and/or maxCount");
667
+ }
668
+ if (policy.maxAge != null) (0, import_nestjs_durable_core6.parseDuration)(policy.maxAge);
669
+ for (const status of policy.statuses) {
670
+ if (!import_nestjs_durable_core6.TERMINAL_RUN_STATUSES.includes(status)) {
671
+ throw new Error(`durable retention: status "${status}" is not terminal; only ${import_nestjs_durable_core6.TERMINAL_RUN_STATUSES.join(", ")} can be pruned`);
672
+ }
673
+ if (seen.has(status)) {
674
+ throw new Error(`durable retention: status "${status}" appears in more than one policy; status sets must be disjoint`);
675
+ }
676
+ seen.add(status);
677
+ }
678
+ }
679
+ }
680
+ __name(validateRetention, "validateRetention");
681
+ var RetentionPoller = class {
682
+ static {
683
+ __name(this, "RetentionPoller");
684
+ }
685
+ store;
686
+ options;
687
+ timer;
688
+ sweeping = false;
689
+ constructor(store, options) {
690
+ this.store = store;
691
+ this.options = options;
692
+ }
693
+ async onApplicationBootstrap() {
694
+ if (this.options.worker === false) return;
695
+ const retention = this.options.retention;
696
+ if (!retention || retention.policies.length === 0) return;
697
+ validateRetention(retention);
698
+ if (typeof this.store.pruneTerminalRuns !== "function") {
699
+ console.warn("[nestjs-durable] `retention` is configured but the store adapter does not implement pruneTerminalRuns; retention is disabled.");
700
+ return;
701
+ }
702
+ await this.sweep();
703
+ const intervalMs = retention.sweepInterval != null ? (0, import_nestjs_durable_core6.parseDuration)(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
704
+ if (intervalMs > 0) {
705
+ this.timer = setInterval(() => void this.sweep(), intervalMs);
706
+ this.timer.unref?.();
707
+ }
708
+ }
709
+ onModuleDestroy() {
710
+ if (this.timer) clearInterval(this.timer);
711
+ }
712
+ async sweep() {
713
+ if (this.sweeping) return;
714
+ const retention = this.options.retention;
715
+ const prune = this.store.pruneTerminalRuns;
716
+ if (!retention || typeof prune !== "function") return;
717
+ this.sweeping = true;
718
+ try {
719
+ const batchSize = retention.batchSize ?? DEFAULT_BATCH_SIZE;
720
+ const now = Date.now();
721
+ for (const policy of retention.policies) {
722
+ for (let batch = 0; batch < MAX_BATCHES_PER_POLICY; batch++) {
723
+ const deleted = await prune.call(this.store, policy, now, batchSize);
724
+ if (deleted < batchSize) break;
725
+ }
726
+ }
727
+ } finally {
728
+ this.sweeping = false;
729
+ }
730
+ }
731
+ };
732
+ RetentionPoller = _ts_decorate5([
733
+ (0, import_common5.Injectable)(),
734
+ _ts_param4(0, (0, import_common5.Inject)(import_nestjs_durable_core6.STATE_STORE_CANONICAL)),
735
+ _ts_param4(1, (0, import_common5.Inject)(import_nestjs_durable_core6.DURABLE_OPTIONS_CANONICAL)),
736
+ _ts_metadata5("design:type", Function),
737
+ _ts_metadata5("design:paramtypes", [
738
+ typeof StateStore === "undefined" ? Object : StateStore,
739
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
740
+ ])
741
+ ], RetentionPoller);
742
+
743
+ // src/timer-poller.ts
744
+ var import_nestjs_durable_core7 = require("@dudousxd/nestjs-durable-core");
745
+ var import_common6 = require("@nestjs/common");
746
+ function _ts_decorate6(decorators, target, key, desc) {
747
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
748
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
749
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
750
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
751
+ }
752
+ __name(_ts_decorate6, "_ts_decorate");
753
+ function _ts_metadata6(k, v) {
754
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
755
+ }
756
+ __name(_ts_metadata6, "_ts_metadata");
757
+ function _ts_param5(paramIndex, decorator) {
758
+ return function(target, key) {
759
+ decorator(target, key, paramIndex);
760
+ };
761
+ }
762
+ __name(_ts_param5, "_ts_param");
763
+ var TimerPoller = class {
764
+ static {
765
+ __name(this, "TimerPoller");
766
+ }
767
+ engine;
768
+ options;
769
+ timer;
770
+ polling = false;
771
+ unsubscribeEnqueued;
772
+ constructor(engine, options) {
773
+ this.engine = engine;
774
+ this.options = options;
775
+ }
776
+ async onApplicationBootstrap() {
777
+ const drive = this.options.drive ?? this.options.worker !== false;
778
+ if (!drive) return;
779
+ this.unsubscribeEnqueued = this.engine.onEnqueued((runId) => void this.engine.runOne(runId));
780
+ await this.poll();
781
+ const intervalMs = this.options.timerPollMs ?? 1e3;
782
+ if (intervalMs > 0) {
783
+ this.timer = setInterval(() => void this.poll(), intervalMs);
784
+ this.timer.unref?.();
785
+ }
786
+ }
787
+ onModuleDestroy() {
788
+ if (this.timer) clearInterval(this.timer);
789
+ this.unsubscribeEnqueued?.();
790
+ }
791
+ async poll() {
792
+ if (this.polling) return;
793
+ this.polling = true;
794
+ try {
795
+ await this.engine.runPending();
796
+ await this.engine.recoverIncomplete();
797
+ await this.engine.resumeDueTimers();
798
+ await this.engine.sweepTimeouts();
799
+ const schedules = this.options.schedules;
800
+ if (schedules && schedules.length > 0) {
801
+ await (0, import_nestjs_durable_core7.runSchedules)(this.engine, schedules, Date.now());
802
+ }
803
+ } finally {
804
+ this.polling = false;
805
+ }
806
+ }
807
+ };
808
+ TimerPoller = _ts_decorate6([
809
+ (0, import_common6.Injectable)(),
810
+ _ts_param5(1, (0, import_common6.Inject)(import_nestjs_durable_core7.DURABLE_OPTIONS_CANONICAL)),
811
+ _ts_metadata6("design:type", Function),
812
+ _ts_metadata6("design:paramtypes", [
813
+ typeof import_nestjs_durable_core7.WorkflowEngine === "undefined" ? Object : import_nestjs_durable_core7.WorkflowEngine,
814
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
815
+ ])
816
+ ], TimerPoller);
817
+
818
+ // src/tokens.ts
819
+ var CONTEXT_ACCESSOR = Symbol.for("@dudousxd/nestjs-context:accessor");
820
+
821
+ // src/workflow.registrar.ts
822
+ var import_nestjs_durable_core8 = require("@dudousxd/nestjs-durable-core");
823
+ var import_common7 = require("@nestjs/common");
824
+ var import_core4 = require("@nestjs/core");
825
+
826
+ // src/input-validation.ts
827
+ function classValidatorInput(cls) {
828
+ let cv;
829
+ let ct;
830
+ try {
831
+ cv = require("class-validator");
832
+ ct = require("class-transformer");
833
+ } catch {
834
+ throw new Error('@Workflow({ inputSchema }) needs the optional peers "class-validator" and "class-transformer" \u2014 install them, or pass a `validateInput` function instead.');
835
+ }
836
+ return async (input) => {
837
+ const instance = ct.plainToInstance(cls, input);
838
+ const errors = await cv.validate(instance, {
839
+ whitelist: true
840
+ });
841
+ if (errors.length > 0) {
842
+ const message = errors.map((e) => Object.values(e.constraints ?? {
843
+ _: e.property
844
+ }).join(", ")).join("; ");
845
+ throw new Error(`invalid input for workflow: ${message}`);
846
+ }
847
+ };
848
+ }
849
+ __name(classValidatorInput, "classValidatorInput");
850
+
851
+ // src/step-interceptor.ts
852
+ var import_reflect_metadata3 = require("reflect-metadata");
853
+ var STEP_INTERCEPTOR_METADATA = Symbol("nestjs-durable:step-interceptor");
854
+ function StepInterceptor() {
855
+ return (target) => {
856
+ Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);
857
+ };
858
+ }
859
+ __name(StepInterceptor, "StepInterceptor");
860
+ function isStepInterceptor(target) {
861
+ return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;
862
+ }
863
+ __name(isStepInterceptor, "isStepInterceptor");
864
+
865
+ // src/workflow.registrar.ts
866
+ function _ts_decorate7(decorators, target, key, desc) {
867
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
868
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
869
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
870
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
871
+ }
872
+ __name(_ts_decorate7, "_ts_decorate");
873
+ function _ts_metadata7(k, v) {
874
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
875
+ }
876
+ __name(_ts_metadata7, "_ts_metadata");
877
+ function _ts_param6(paramIndex, decorator) {
878
+ return function(target, key) {
879
+ decorator(target, key, paramIndex);
880
+ };
881
+ }
882
+ __name(_ts_param6, "_ts_param");
883
+ var WorkflowRegistrar = class {
884
+ static {
885
+ __name(this, "WorkflowRegistrar");
886
+ }
887
+ discovery;
888
+ metadataScanner;
889
+ engine;
890
+ store;
891
+ options;
892
+ inAppWorker;
893
+ constructor(discovery, metadataScanner, engine, store, options, inAppWorker) {
894
+ this.discovery = discovery;
895
+ this.metadataScanner = metadataScanner;
896
+ this.engine = engine;
897
+ this.store = store;
898
+ this.options = options;
899
+ this.inAppWorker = inAppWorker;
900
+ }
901
+ async onApplicationBootstrap() {
902
+ const drive = this.options.drive ?? this.options.worker !== false;
903
+ if (!drive) return;
904
+ await this.engine.recoverIncomplete();
905
+ }
906
+ /** On deploy/shutdown: stop picking up new runs and wait for in-flight ones to settle, then close
907
+ * the transport(s) so the broker workers stop consuming and connections are released. Closing
908
+ * AFTER the drain keeps the transport alive while in-flight runs dispatch/await their remote steps. */
909
+ async onApplicationShutdown() {
910
+ await this.engine.drain(this.options.shutdownTimeoutMs);
911
+ const transports = [
912
+ this.options.transport,
913
+ ...(this.options.transports ?? []).map((t) => t.transport)
914
+ ];
915
+ await Promise.allSettled(transports.map((t) => t?.close?.()));
916
+ }
917
+ async onModuleInit() {
918
+ if (this.options.autoSchema !== false) {
919
+ await this.store.ensureSchema?.();
920
+ }
921
+ const deadLetterByWorkflow = /* @__PURE__ */ new Map();
922
+ for (const wrapper of this.discovery.getProviders()) {
923
+ const { instance } = wrapper;
924
+ if (!instance || typeof instance !== "object") continue;
925
+ if (isStepInterceptor(instance.constructor)) {
926
+ const interceptor = instance;
927
+ this.engine.use((invocation, next) => interceptor.intercept(invocation, next));
928
+ }
929
+ const entityMeta = getEntityMeta(instance.constructor);
930
+ if (entityMeta) {
931
+ this.engine.registerEntity(entityMeta.name, entityConfigFor(instance.constructor));
932
+ }
933
+ }
934
+ scanWorkflows(this.discovery, (meta, workflow) => {
935
+ const validateInput = meta.validateInput ?? (meta.inputSchema ? classValidatorInput(meta.inputSchema) : void 0);
936
+ const eventBatch = meta.debounce ? {
937
+ mode: "debounce",
938
+ windowMs: (0, import_nestjs_durable_core8.parseDuration)(meta.debounce)
939
+ } : meta.batch ? {
940
+ mode: "batch",
941
+ maxSize: meta.batch.maxSize,
942
+ windowMs: (0, import_nestjs_durable_core8.parseDuration)(meta.batch.within)
943
+ } : void 0;
944
+ const workflowCtor = workflow.constructor;
945
+ this.engine.register(meta.name, meta.version, (ctx, input) => workflow.run(ctx, input), {
946
+ tags: meta.tags,
947
+ singleton: meta.singleton,
948
+ executionTimeout: meta.executionTimeout,
949
+ validateInput,
950
+ onEvent: getOnEvents(meta, workflowCtor),
951
+ eventBatch,
952
+ // Uniform dispatch (opt-in): when an in-app worker is configured, register the body GROUP-SERVED
953
+ // so the engine dispatches its turns to the app's own group instead of running it inline; the
954
+ // co-located worker consumer replays the same body. Absent → the inline fast path (unchanged).
955
+ ...this.inAppWorker ? {
956
+ group: this.inAppWorker.group,
957
+ executor: this.inAppWorker.executor
958
+ } : {}
959
+ });
960
+ const inline = this.findDeadLetterHandler(workflow);
961
+ if (inline && meta.deadLetterWorkflow) {
962
+ throw new Error(`@Workflow ${meta.name} declares both an inline @DeadLetter() method and a deadLetterWorkflow option. Use one: the inline handler, or the reference.`);
963
+ }
964
+ if (inline) {
965
+ const dlqName = `${meta.name}.dlq`;
966
+ this.engine.register(dlqName, meta.version, inline);
967
+ deadLetterByWorkflow.set(meta.name, dlqName);
968
+ } else if (meta.deadLetterWorkflow) {
969
+ deadLetterByWorkflow.set(meta.name, (0, import_nestjs_durable_core8.workflowName)(meta.deadLetterWorkflow));
970
+ }
971
+ });
972
+ this.installDeadLetterRouting(deadLetterByWorkflow);
973
+ }
974
+ /** Returns the instance's `@DeadLetter()` method bound to the instance, or undefined if none. */
975
+ findDeadLetterHandler(instance) {
976
+ const prototype = Object.getPrototypeOf(instance);
977
+ for (const methodName of this.metadataScanner.getAllMethodNames(prototype)) {
978
+ const method = instance[methodName];
979
+ if (typeof method === "function" && isDeadLetterHandler(method)) {
980
+ return (ctx, input) => method.call(instance, ctx, input);
981
+ }
982
+ }
983
+ return void 0;
984
+ }
985
+ /**
986
+ * Installs a single onDead listener that routes a dead run to its workflow's handler (from the
987
+ * map) or the module-level `deadLetterWorkflow` default. The handler is started idempotently with
988
+ * a `dlq:<runId>` id, so re-recovery never double-dispatches.
989
+ */
990
+ installDeadLetterRouting(byWorkflow) {
991
+ const fallback = this.options.deadLetterWorkflow ? (0, import_nestjs_durable_core8.workflowName)(this.options.deadLetterWorkflow) : void 0;
992
+ if (byWorkflow.size === 0 && !fallback) return;
993
+ this.engine.onDead((run) => {
994
+ const target = byWorkflow.get(run.workflow) ?? fallback;
995
+ if (!target) return;
996
+ void this.engine.start(
997
+ target,
998
+ {
999
+ deadRunId: run.id,
1000
+ workflow: run.workflow,
1001
+ input: run.input,
1002
+ error: run.error
1003
+ },
1004
+ `dlq:${run.id}`,
1005
+ // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to
1006
+ // that tenant's worker group (`target@<tenant>`), not the bare group.
1007
+ {
1008
+ namespace: run.namespace
1009
+ }
1010
+ ).catch(() => void 0);
1011
+ });
1012
+ }
1013
+ };
1014
+ WorkflowRegistrar = _ts_decorate7([
1015
+ (0, import_common7.Injectable)(),
1016
+ _ts_param6(3, (0, import_common7.Inject)(import_nestjs_durable_core8.STATE_STORE_CANONICAL)),
1017
+ _ts_param6(4, (0, import_common7.Inject)(import_nestjs_durable_core8.DURABLE_OPTIONS_CANONICAL)),
1018
+ _ts_param6(5, (0, import_common7.Inject)(IN_APP_WORKER_BINDING)),
1019
+ _ts_metadata7("design:type", Function),
1020
+ _ts_metadata7("design:paramtypes", [
1021
+ typeof import_core4.DiscoveryService === "undefined" ? Object : import_core4.DiscoveryService,
1022
+ typeof import_core4.MetadataScanner === "undefined" ? Object : import_core4.MetadataScanner,
1023
+ typeof import_nestjs_durable_core8.WorkflowEngine === "undefined" ? Object : import_nestjs_durable_core8.WorkflowEngine,
1024
+ typeof StateStore === "undefined" ? Object : StateStore,
1025
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
1026
+ Object
1027
+ ])
1028
+ ], WorkflowRegistrar);
1029
+
1030
+ // src/workflow.service.ts
1031
+ var import_node_crypto = require("crypto");
1032
+ var import_nestjs_durable_core9 = require("@dudousxd/nestjs-durable-core");
1033
+ var import_common8 = require("@nestjs/common");
1034
+ function _ts_decorate8(decorators, target, key, desc) {
1035
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1036
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1037
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1038
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1039
+ }
1040
+ __name(_ts_decorate8, "_ts_decorate");
1041
+ function _ts_metadata8(k, v) {
1042
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1043
+ }
1044
+ __name(_ts_metadata8, "_ts_metadata");
1045
+ var WorkflowService = class {
1046
+ static {
1047
+ __name(this, "WorkflowService");
1048
+ }
1049
+ engine;
1050
+ constructor(engine) {
1051
+ this.engine = engine;
1052
+ }
1053
+ start(workflow, input, runId = (0, import_node_crypto.randomUUID)(), opts) {
1054
+ return this.engine.start(workflow, input, runId, opts);
1055
+ }
1056
+ resume(runId) {
1057
+ return this.engine.resume(runId);
1058
+ }
1059
+ /**
1060
+ * Resolve once a run settles — terminal (completed/failed/cancelled/dead) or suspended. `start`
1061
+ * only enqueues (a worker runs the body), so pair them when a request needs the outcome:
1062
+ * `const { runId } = await svc.start(...); const result = await svc.waitForRun(runId)`.
1063
+ */
1064
+ waitForRun(runId, opts) {
1065
+ return this.engine.waitForRun(runId, opts);
1066
+ }
1067
+ /** Deliver an external signal (e.g. from a webhook) to the run waiting on `token`. */
1068
+ signal(token, payload) {
1069
+ return this.engine.signal(token, payload);
1070
+ }
1071
+ signalWithStart(workflow, input, runId, signal, opts) {
1072
+ return this.engine.signalWithStart(workflow, input, runId, signal, opts);
1073
+ }
1074
+ /**
1075
+ * Publish a named event. Resumes runs waiting on it via `ctx.waitForEvent(name, { match })` and
1076
+ * starts a fresh run of every workflow subscribed via `@Workflow({ onEvent })` / `@OnEvent` (the
1077
+ * payload becomes its input). Pass `opts.id` to dedupe redeliveries. Returns how many runs it
1078
+ * touched (resumed + started).
1079
+ */
1080
+ publishEvent(name, payload, opts) {
1081
+ return this.engine.publishEvent(name, payload, opts);
1082
+ }
1083
+ };
1084
+ WorkflowService = _ts_decorate8([
1085
+ (0, import_common8.Injectable)(),
1086
+ _ts_metadata8("design:type", Function),
1087
+ _ts_metadata8("design:paramtypes", [
1088
+ typeof import_nestjs_durable_core9.WorkflowEngine === "undefined" ? Object : import_nestjs_durable_core9.WorkflowEngine
1089
+ ])
1090
+ ], WorkflowService);
1091
+
1092
+ // src/durable.module.ts
1093
+ function _ts_decorate9(decorators, target, key, desc) {
1094
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1095
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1096
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1097
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1098
+ }
1099
+ __name(_ts_decorate9, "_ts_decorate");
1100
+ function resolveAccessor(moduleRef) {
1101
+ try {
1102
+ return moduleRef.get(CONTEXT_ACCESSOR, {
1103
+ strict: false
1104
+ });
1105
+ } catch {
1106
+ return void 0;
1107
+ }
1108
+ }
1109
+ __name(resolveAccessor, "resolveAccessor");
1110
+ function carrierFromAccessor(accessor) {
1111
+ const carrier = {};
1112
+ const traceId = accessor.traceId();
1113
+ if (traceId !== void 0) carrier.traceId = traceId;
1114
+ const tenantId = accessor.tenantId();
1115
+ if (tenantId !== void 0) carrier.tenantId = tenantId;
1116
+ const userRef = accessor.userRef();
1117
+ if (userRef !== void 0) carrier.userRef = userRef;
1118
+ return carrier;
1119
+ }
1120
+ __name(carrierFromAccessor, "carrierFromAccessor");
1121
+ function isContextRuntime(x) {
1122
+ return !!x && typeof x.deserialize === "function";
1123
+ }
1124
+ __name(isContextRuntime, "isContextRuntime");
1125
+ async function resolveContextRuntime() {
1126
+ try {
1127
+ const specifier = "@dudousxd/nestjs-context";
1128
+ const mod = await import(specifier);
1129
+ return isContextRuntime(mod.Context) ? mod.Context : void 0;
1130
+ } catch {
1131
+ return void 0;
1132
+ }
1133
+ }
1134
+ __name(resolveContextRuntime, "resolveContextRuntime");
1135
+ function isControlPlane(x) {
1136
+ return !!x && typeof x.publishControl === "function" && typeof x.onControl === "function";
1137
+ }
1138
+ __name(isControlPlane, "isControlPlane");
1139
+ function isScopeableStore(store) {
1140
+ return typeof store.withScope === "function";
1141
+ }
1142
+ __name(isScopeableStore, "isScopeableStore");
1143
+ function scopedStore(options) {
1144
+ if (options.scopeReads !== true || options.namespace === void 0) return options.store;
1145
+ if (!isScopeableStore(options.store)) return options.store;
1146
+ return options.store.withScope({
1147
+ namespace: options.namespace
1148
+ });
1149
+ }
1150
+ __name(scopedStore, "scopedStore");
1151
+ var DurableModule = class _DurableModule {
1152
+ static {
1153
+ __name(this, "DurableModule");
1154
+ }
1155
+ static forRoot(options) {
1156
+ return _DurableModule.build({
1157
+ provide: import_nestjs_durable_core10.DURABLE_OPTIONS_CANONICAL,
1158
+ useValue: options
1159
+ });
1160
+ }
1161
+ static forRootAsync(options) {
1162
+ return _DurableModule.build({
1163
+ provide: import_nestjs_durable_core10.DURABLE_OPTIONS_CANONICAL,
1164
+ useFactory: options.useFactory,
1165
+ inject: options.inject ?? []
1166
+ });
1167
+ }
1168
+ static build(optionsProvider) {
1169
+ return {
1170
+ module: _DurableModule,
1171
+ global: true,
1172
+ imports: [
1173
+ import_core5.DiscoveryModule
1174
+ ],
1175
+ providers: [
1176
+ optionsProvider,
1177
+ {
1178
+ provide: import_nestjs_durable_core10.STATE_STORE_CANONICAL,
1179
+ useFactory: /* @__PURE__ */ __name((options) => scopedStore(options), "useFactory"),
1180
+ inject: [
1181
+ import_nestjs_durable_core10.DURABLE_OPTIONS_CANONICAL
1182
+ ]
1183
+ },
1184
+ {
1185
+ provide: import_nestjs_durable_core10.TRANSPORT_CANONICAL,
1186
+ useFactory: /* @__PURE__ */ __name((options) => options.transport ?? null, "useFactory"),
1187
+ inject: [
1188
+ import_nestjs_durable_core10.DURABLE_OPTIONS_CANONICAL
1189
+ ]
1190
+ },
1191
+ // Legacy back-compat aliases (deprecated tokens still resolve to the same instances):
1192
+ {
1193
+ provide: import_nestjs_durable_core10.STATE_STORE,
1194
+ useExisting: import_nestjs_durable_core10.STATE_STORE_CANONICAL
1195
+ },
1196
+ {
1197
+ provide: import_nestjs_durable_core10.TRANSPORT,
1198
+ useExisting: import_nestjs_durable_core10.TRANSPORT_CANONICAL
1199
+ },
1200
+ {
1201
+ provide: import_nestjs_durable_core10.DURABLE_OPTIONS,
1202
+ useExisting: import_nestjs_durable_core10.DURABLE_OPTIONS_CANONICAL
1203
+ },
1204
+ {
1205
+ provide: import_nestjs_durable_core10.WorkflowEngine,
1206
+ useFactory: /* @__PURE__ */ __name(async (store, transport, opts, moduleRef) => {
1207
+ const primary = transport ?? opts.transports?.[0]?.transport;
1208
+ const accessor = resolveAccessor(moduleRef);
1209
+ const context = opts.context ?? (accessor ? () => carrierFromAccessor(accessor) : void 0);
1210
+ const runtime = accessor ? await resolveContextRuntime() : void 0;
1211
+ const rehydrate = runtime && ((carrier, fn) => carrier && Object.keys(carrier).length > 0 ? runtime.deserialize(carrier, fn) : fn());
1212
+ const engine = new import_nestjs_durable_core10.WorkflowEngine({
1213
+ store,
1214
+ transport: transport ?? void 0,
1215
+ transports: opts.transports,
1216
+ controlPlane: opts.controlPlane ?? (isControlPlane(primary) ? primary : void 0),
1217
+ leaseMs: opts.leaseMs,
1218
+ admission: opts.admission,
1219
+ maxRecoveryAttempts: opts.maxRecoveryAttempts,
1220
+ remoteAdvanceSilenceMs: opts.remoteAdvanceSilenceMs,
1221
+ instanceId: opts.instanceId,
1222
+ namespace: opts.namespace,
1223
+ remoteByConvention: opts.remoteByConvention,
1224
+ webhookUrl: opts.webhookUrl,
1225
+ traceparent: opts.traceparent,
1226
+ context,
1227
+ rehydrate: rehydrate || void 0,
1228
+ compensationRetries: opts.compensationRetries,
1229
+ // A non-worker, non-driving (plain API/dashboard) instance must not run workflows:
1230
+ // enqueue-only, leaving each `pending` run in the store for a DRIVING instance's poll.
1231
+ // Workers AND driving control planes (`drive:true` — see `DurableControlPlaneModule`)
1232
+ // get the engine's default in-process dispatcher: for a worker that executes the body
1233
+ // locally, and for a driving-only control plane that has no local registration, the
1234
+ // SAME default dispatcher routes it out remotely via `remoteByConvention` instead.
1235
+ runDispatcher: opts.worker === false && opts.drive !== true ? {
1236
+ dispatch: /* @__PURE__ */ __name(() => {
1237
+ }, "dispatch")
1238
+ } : void 0
1239
+ });
1240
+ for (const queue of opts.queues ?? []) engine.registerQueue(queue);
1241
+ return engine;
1242
+ }, "useFactory"),
1243
+ inject: [
1244
+ import_nestjs_durable_core10.STATE_STORE_CANONICAL,
1245
+ import_nestjs_durable_core10.TRANSPORT_CANONICAL,
1246
+ import_nestjs_durable_core10.DURABLE_OPTIONS_CANONICAL,
1247
+ import_core5.ModuleRef
1248
+ ]
1249
+ },
1250
+ WorkflowService,
1251
+ EntityService,
1252
+ WorkflowRegistrar,
1253
+ DurableStepRegistrar,
1254
+ TimerPoller,
1255
+ RetentionPoller,
1256
+ // In-app worker (uniform dispatch, opt-in): inert when `inAppWorker` is unset — the binding
1257
+ // resolves to null and the bootstrap no-ops, so a plain DurableModule is unchanged.
1258
+ ...inAppWorkerProviders()
1259
+ ],
1260
+ exports: [
1261
+ WorkflowService,
1262
+ EntityService,
1263
+ import_nestjs_durable_core10.WorkflowEngine,
1264
+ import_nestjs_durable_core10.STATE_STORE,
1265
+ import_nestjs_durable_core10.STATE_STORE_CANONICAL,
1266
+ import_nestjs_durable_core10.TRANSPORT,
1267
+ import_nestjs_durable_core10.TRANSPORT_CANONICAL,
1268
+ import_nestjs_durable_core10.DURABLE_OPTIONS_CANONICAL
1269
+ ]
1270
+ };
1271
+ }
1272
+ };
1273
+ DurableModule = _ts_decorate9([
1274
+ (0, import_common9.Module)({})
1275
+ ], DurableModule);
1276
+ var DurableControlPlaneModule = class {
1277
+ static {
1278
+ __name(this, "DurableControlPlaneModule");
1279
+ }
1280
+ static forRoot(options) {
1281
+ return DurableModule.forRoot({
1282
+ ...options,
1283
+ worker: false,
1284
+ drive: true
1285
+ });
1286
+ }
1287
+ static forRootAsync(options) {
1288
+ return DurableModule.forRootAsync({
1289
+ ...options,
1290
+ useFactory: /* @__PURE__ */ __name(async (...args) => ({
1291
+ ...await options.useFactory(...args),
1292
+ worker: false,
1293
+ drive: true
1294
+ }), "useFactory")
1295
+ });
1296
+ }
1297
+ };
1298
+ DurableControlPlaneModule = _ts_decorate9([
1299
+ (0, import_common9.Module)({})
1300
+ ], DurableControlPlaneModule);
1301
+ // Annotate the CommonJS export names for ESM import in node:
1302
+ 0 && (module.exports = {
1303
+ CONTEXT_ACCESSOR,
1304
+ DEAD_LETTER_METADATA,
1305
+ DURABLE_STEP_METADATA,
1306
+ DURABLE_WORKER_OPTIONS,
1307
+ DURABLE_WORKER_RUNNERS,
1308
+ DeadLetter,
1309
+ DurableControlPlaneModule,
1310
+ DurableModule,
1311
+ DurableStep,
1312
+ DurableWorkerModule,
1313
+ ENTITY_METADATA,
1314
+ ENTITY_ON_METADATA,
1315
+ Entity,
1316
+ EntityService,
1317
+ IN_APP_RUN_REDIS_WORKER,
1318
+ IN_APP_WORKER_BINDING,
1319
+ IN_APP_WORKER_OPTIONS,
1320
+ IN_APP_WORKER_RUNNERS,
1321
+ IN_APP_WORKER_RUNTIME,
1322
+ InAppWorkerBootstrap,
1323
+ ON_EVENT_METADATA,
1324
+ On,
1325
+ OnEvent,
1326
+ RUN_REDIS_WORKER,
1327
+ STEP_INTERCEPTOR_METADATA,
1328
+ Step,
1329
+ StepInterceptor,
1330
+ ThinStepRegistrar,
1331
+ ThinWorkerBootstrap,
1332
+ ThinWorkflowRegistrar,
1333
+ WORKFLOW_METADATA,
1334
+ Workflow,
1335
+ WorkflowService,
1336
+ entityConfigFor,
1337
+ getDurableStepMeta,
1338
+ getEntityMeta,
1339
+ getOnEvents,
1340
+ getWorkflowMeta,
1341
+ inAppWorkerProviders,
1342
+ isDeadLetterHandler,
1343
+ isStepInterceptor
1344
+ });
1345
+ //# sourceMappingURL=index.cjs.map