@rotorsoft/act 1.32.30 → 1.33.1

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.
Files changed (123) hide show
  1. package/README.md +0 -1
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/@types/act.d.ts +96 -385
  4. package/dist/@types/act.d.ts.map +1 -1
  5. package/dist/@types/adapters/in-memory-store.d.ts.map +1 -1
  6. package/dist/@types/builders/act-builder.d.ts +2 -115
  7. package/dist/@types/builders/act-builder.d.ts.map +1 -1
  8. package/dist/@types/builders/builder-utils.d.ts +1 -1
  9. package/dist/@types/builders/builder-utils.d.ts.map +1 -1
  10. package/dist/@types/builders/event-builder.d.ts +5 -5
  11. package/dist/@types/builders/event-builder.d.ts.map +1 -1
  12. package/dist/@types/builders/merge.d.ts +1 -1
  13. package/dist/@types/builders/merge.d.ts.map +1 -1
  14. package/dist/@types/builders/projection-builder.d.ts +2 -144
  15. package/dist/@types/builders/projection-builder.d.ts.map +1 -1
  16. package/dist/@types/builders/slice-builder.d.ts +2 -71
  17. package/dist/@types/builders/slice-builder.d.ts.map +1 -1
  18. package/dist/@types/builders/state-builder.d.ts +2 -376
  19. package/dist/@types/builders/state-builder.d.ts.map +1 -1
  20. package/dist/@types/config.d.ts +6 -43
  21. package/dist/@types/config.d.ts.map +1 -1
  22. package/dist/@types/csv.d.ts +1 -15
  23. package/dist/@types/csv.d.ts.map +1 -1
  24. package/dist/@types/index.d.ts +0 -1
  25. package/dist/@types/index.d.ts.map +1 -1
  26. package/dist/@types/internal/autoclose-policy.d.ts +1 -59
  27. package/dist/@types/internal/autoclose-policy.d.ts.map +1 -1
  28. package/dist/@types/internal/autoclose-reaction.d.ts +1 -2
  29. package/dist/@types/internal/autoclose-reaction.d.ts.map +1 -1
  30. package/dist/@types/internal/autoclose-window.d.ts +1 -1
  31. package/dist/@types/internal/autoclose-window.d.ts.map +1 -1
  32. package/dist/@types/internal/circuit-breaker.d.ts +1 -2
  33. package/dist/@types/internal/circuit-breaker.d.ts.map +1 -1
  34. package/dist/@types/{builders/build-classify.d.ts → internal/classify.d.ts} +2 -15
  35. package/dist/@types/internal/classify.d.ts.map +1 -0
  36. package/dist/@types/internal/close-cycle.d.ts.map +1 -1
  37. package/dist/@types/internal/config.d.ts +2 -42
  38. package/dist/@types/internal/config.d.ts.map +1 -1
  39. package/dist/@types/internal/correlate-cycle.d.ts +1 -1
  40. package/dist/@types/internal/correlate-cycle.d.ts.map +1 -1
  41. package/dist/@types/internal/{correlator.d.ts → correlation-id.d.ts} +1 -1
  42. package/dist/@types/internal/correlation-id.d.ts.map +1 -0
  43. package/dist/@types/internal/defer-config.d.ts.map +1 -1
  44. package/dist/@types/internal/drain-cycle.d.ts +1 -1
  45. package/dist/@types/internal/drain-cycle.d.ts.map +1 -1
  46. package/dist/@types/internal/{drain.d.ts → drain-ops.d.ts} +1 -1
  47. package/dist/@types/internal/drain-ops.d.ts.map +1 -0
  48. package/dist/@types/internal/event-sourcing.d.ts +1 -8
  49. package/dist/@types/internal/event-sourcing.d.ts.map +1 -1
  50. package/dist/@types/internal/{sensitive.d.ts → pii.d.ts} +4 -71
  51. package/dist/@types/internal/pii.d.ts.map +1 -0
  52. package/dist/@types/internal/projection-fold.d.ts +1 -2
  53. package/dist/@types/internal/projection-fold.d.ts.map +1 -1
  54. package/dist/@types/internal/{close-signal.d.ts → reaction-dispatch.d.ts} +47 -2
  55. package/dist/@types/internal/reaction-dispatch.d.ts.map +1 -0
  56. package/dist/@types/internal/report-once.d.ts +1 -1
  57. package/dist/@types/internal/settle.d.ts +21 -12
  58. package/dist/@types/internal/settle.d.ts.map +1 -1
  59. package/dist/@types/internal/tracing.d.ts +3 -3
  60. package/dist/@types/internal/tracing.d.ts.map +1 -1
  61. package/dist/@types/ports.d.ts +3 -43
  62. package/dist/@types/ports.d.ts.map +1 -1
  63. package/dist/@types/scoped.d.ts +1 -6
  64. package/dist/@types/scoped.d.ts.map +1 -1
  65. package/dist/@types/sensitive.d.ts +56 -0
  66. package/dist/@types/sensitive.d.ts.map +1 -0
  67. package/dist/@types/test/index.d.ts +1 -0
  68. package/dist/@types/test/index.d.ts.map +1 -1
  69. package/dist/@types/test/sandbox.d.ts +2 -26
  70. package/dist/@types/test/sandbox.d.ts.map +1 -1
  71. package/dist/@types/types/act.d.ts +214 -0
  72. package/dist/@types/types/act.d.ts.map +1 -0
  73. package/dist/@types/types/action.d.ts +69 -2
  74. package/dist/@types/types/action.d.ts.map +1 -1
  75. package/dist/@types/types/builders.d.ts +721 -0
  76. package/dist/@types/types/builders.d.ts.map +1 -0
  77. package/dist/@types/types/errors.d.ts +31 -1
  78. package/dist/@types/types/errors.d.ts.map +1 -1
  79. package/dist/@types/types/index.d.ts +38 -0
  80. package/dist/@types/types/index.d.ts.map +1 -1
  81. package/dist/@types/types/ports.d.ts +20 -18
  82. package/dist/@types/types/ports.d.ts.map +1 -1
  83. package/dist/@types/types/reaction.d.ts +11 -1
  84. package/dist/@types/types/reaction.d.ts.map +1 -1
  85. package/dist/@types/types/sandbox.d.ts +31 -0
  86. package/dist/@types/types/sandbox.d.ts.map +1 -0
  87. package/dist/@types/types/schemas.d.ts +12 -17
  88. package/dist/@types/types/schemas.d.ts.map +1 -1
  89. package/dist/chunk-NNWP65YM.cjs +264 -0
  90. package/dist/chunk-NNWP65YM.cjs.map +1 -0
  91. package/dist/{chunk-X3MMQIIP.js → chunk-NYH6FNTM.js} +174 -22
  92. package/dist/chunk-NYH6FNTM.js.map +1 -0
  93. package/dist/{chunk-HHKLVRR4.js → chunk-TJ4JRRUR.js} +38 -57
  94. package/dist/chunk-TJ4JRRUR.js.map +1 -0
  95. package/dist/chunk-YKL44PYX.cjs +1233 -0
  96. package/dist/chunk-YKL44PYX.cjs.map +1 -0
  97. package/dist/index.cjs +1954 -3440
  98. package/dist/index.cjs.map +1 -1
  99. package/dist/index.js +911 -1063
  100. package/dist/index.js.map +1 -1
  101. package/dist/test/index.cjs +16 -1113
  102. package/dist/test/index.cjs.map +1 -1
  103. package/dist/test/index.js +2 -2
  104. package/dist/test/index.js.map +1 -1
  105. package/dist/types/index.cjs +58 -276
  106. package/dist/types/index.cjs.map +1 -1
  107. package/dist/types/index.js +15 -1
  108. package/package.json +2 -2
  109. package/dist/@types/builders/build-classify.d.ts.map +0 -1
  110. package/dist/@types/builders/builder-base.d.ts +0 -70
  111. package/dist/@types/builders/builder-base.d.ts.map +0 -1
  112. package/dist/@types/builders/reaction-builder.d.ts +0 -55
  113. package/dist/@types/builders/reaction-builder.d.ts.map +0 -1
  114. package/dist/@types/internal/close-signal.d.ts.map +0 -1
  115. package/dist/@types/internal/correlator.d.ts.map +0 -1
  116. package/dist/@types/internal/defer-signal.d.ts +0 -32
  117. package/dist/@types/internal/defer-signal.d.ts.map +0 -1
  118. package/dist/@types/internal/drain.d.ts.map +0 -1
  119. package/dist/@types/internal/index.d.ts +0 -38
  120. package/dist/@types/internal/index.d.ts.map +0 -1
  121. package/dist/@types/internal/sensitive.d.ts.map +0 -1
  122. package/dist/chunk-HHKLVRR4.js.map +0 -1
  123. package/dist/chunk-X3MMQIIP.js.map +0 -1
@@ -0,0 +1,1233 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3;
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ var _chunkNNWP65YMcjs = require('./chunk-NNWP65YM.cjs');
10
+
11
+ // src/adapters/console-logger.ts
12
+ var LEVEL_VALUES = {
13
+ fatal: 60,
14
+ error: 50,
15
+ warn: 40,
16
+ info: 30,
17
+ debug: 20,
18
+ trace: 10
19
+ };
20
+ var LEVEL_COLORS = {
21
+ fatal: "\x1B[41m\x1B[37m",
22
+ // white on red bg
23
+ error: "\x1B[31m",
24
+ // red
25
+ warn: "\x1B[33m",
26
+ // yellow
27
+ info: "\x1B[32m",
28
+ // green
29
+ debug: "\x1B[36m",
30
+ // cyan
31
+ trace: "\x1B[90m"
32
+ // gray
33
+ };
34
+ var RESET = "\x1B[0m";
35
+ var noop = () => {
36
+ };
37
+ var ConsoleLogger = class _ConsoleLogger {
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+ constructor(options = {}) {
47
+ const {
48
+ level = "info",
49
+ pretty = process.env.NODE_ENV !== "production",
50
+ bindings
51
+ } = options;
52
+ this._pretty = pretty;
53
+ this.level = level;
54
+ const threshold = _nullishCoalesce(LEVEL_VALUES[level], () => ( 30));
55
+ const write = pretty ? this._pretty_write.bind(this, bindings) : this._json_write.bind(this, bindings);
56
+ this.fatal = write.bind(this, "fatal", 60);
57
+ this.error = threshold <= 50 ? write.bind(this, "error", 50) : noop;
58
+ this.warn = threshold <= 40 ? write.bind(this, "warn", 40) : noop;
59
+ this.info = threshold <= 30 ? write.bind(this, "info", 30) : noop;
60
+ this.debug = threshold <= 20 ? write.bind(this, "debug", 20) : noop;
61
+ this.trace = threshold <= 10 ? write.bind(this, "trace", 10) : noop;
62
+ }
63
+ /** No-op — `console.log` has no resources to release. */
64
+ async dispose() {
65
+ }
66
+ /** @inheritDoc */
67
+ child(bindings) {
68
+ return new _ConsoleLogger({
69
+ level: this.level,
70
+ pretty: this._pretty,
71
+ bindings
72
+ });
73
+ }
74
+ _json_write(bindings, level, _num, obj_or_msg, msg) {
75
+ let obj;
76
+ let message;
77
+ if (typeof obj_or_msg === "string") {
78
+ message = obj_or_msg;
79
+ obj = {};
80
+ } else if (obj_or_msg instanceof Error) {
81
+ message = _nullishCoalesce(msg, () => ( obj_or_msg.message));
82
+ obj = {
83
+ error: { message: obj_or_msg.message, name: obj_or_msg.name },
84
+ stack: obj_or_msg.stack
85
+ };
86
+ } else if (obj_or_msg !== null && typeof obj_or_msg === "object") {
87
+ message = msg;
88
+ obj = { ...obj_or_msg };
89
+ } else {
90
+ message = msg;
91
+ obj = { value: obj_or_msg };
92
+ }
93
+ const entry = Object.assign({ level, time: Date.now() }, bindings, obj);
94
+ if (message) entry.msg = message;
95
+ let line;
96
+ try {
97
+ line = JSON.stringify(entry);
98
+ } catch (e2) {
99
+ line = JSON.stringify({
100
+ level,
101
+ time: entry.time,
102
+ msg: _nullishCoalesce(message, () => ( "[unserializable]")),
103
+ unserializable: true
104
+ });
105
+ }
106
+ process.stdout.write(line + "\n");
107
+ }
108
+ _pretty_write(bindings, level, _num, obj_or_msg, msg) {
109
+ const color = LEVEL_COLORS[level];
110
+ const tag = `${color}${level.toUpperCase().padEnd(5)}${RESET}`;
111
+ const ts = (/* @__PURE__ */ new Date()).toISOString().slice(11, 23);
112
+ let message;
113
+ let data;
114
+ if (typeof obj_or_msg === "string") {
115
+ message = obj_or_msg;
116
+ } else if (obj_or_msg instanceof Error) {
117
+ message = _nullishCoalesce(msg, () => ( obj_or_msg.message));
118
+ data = obj_or_msg.stack;
119
+ } else {
120
+ message = _nullishCoalesce(msg, () => ( ""));
121
+ if (obj_or_msg !== void 0 && obj_or_msg !== null) {
122
+ try {
123
+ data = JSON.stringify(obj_or_msg);
124
+ } catch (e3) {
125
+ data = "[unserializable]";
126
+ }
127
+ }
128
+ }
129
+ const bind_str = bindings && Object.keys(bindings).length ? ` ${JSON.stringify(bindings)}` : "";
130
+ const parts = [ts, tag, message, data, bind_str].filter(Boolean);
131
+ process.stdout.write(parts.join(" ") + "\n");
132
+ }
133
+ };
134
+
135
+ // src/internal/lru-map.ts
136
+ var LruMap = (_class = class {
137
+ __init() {this._entries = /* @__PURE__ */ new Map()}
138
+
139
+ constructor(maxSize) {;_class.prototype.__init.call(this);
140
+ this._max_size = maxSize;
141
+ }
142
+ get(key) {
143
+ const v = this._entries.get(key);
144
+ if (v === void 0) return void 0;
145
+ this._entries.delete(key);
146
+ this._entries.set(key, v);
147
+ return v;
148
+ }
149
+ has(key) {
150
+ return this._entries.has(key);
151
+ }
152
+ set(key, value) {
153
+ this._entries.delete(key);
154
+ if (this._entries.size >= this._max_size) {
155
+ const oldest = this._entries.keys().next().value;
156
+ this._entries.delete(oldest);
157
+ }
158
+ this._entries.set(key, value);
159
+ }
160
+ delete(key) {
161
+ return this._entries.delete(key);
162
+ }
163
+ clear() {
164
+ this._entries.clear();
165
+ }
166
+ get size() {
167
+ return this._entries.size;
168
+ }
169
+ }, _class);
170
+
171
+ // src/adapters/in-memory-cache.ts
172
+ var InMemoryCache = class {
173
+ // CacheEntry<any> lets `get<TState>` and `set<TState>` flow without casts:
174
+ // any is bidirectionally compatible with the per-call TState binding, while
175
+ // the public Cache interface still presents a typed surface to callers.
176
+
177
+ constructor(options) {
178
+ this._entries = new LruMap(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _ => _.maxSize]), () => ( 1e3)));
179
+ }
180
+ /** @inheritDoc */
181
+ async get(stream) {
182
+ return this._entries.get(stream);
183
+ }
184
+ /** @inheritDoc */
185
+ async set(stream, entry) {
186
+ this._entries.set(stream, entry);
187
+ }
188
+ /** @inheritDoc */
189
+ async invalidate(stream) {
190
+ this._entries.delete(stream);
191
+ }
192
+ /** @inheritDoc */
193
+ async clear() {
194
+ this._entries.clear();
195
+ }
196
+ /** @inheritDoc */
197
+ async dispose() {
198
+ this._entries.clear();
199
+ }
200
+ /** Current number of entries held by the LRU. */
201
+ get size() {
202
+ return this._entries.size;
203
+ }
204
+ };
205
+
206
+ // src/config.ts
207
+ var _fs = require('fs'); var fs = _interopRequireWildcard(_fs);
208
+ var _zod = require('zod');
209
+
210
+ // src/internal/config.ts
211
+
212
+ var BackoffOptionsSchema = _zod.z.object({
213
+ strategy: _zod.z.enum(["fixed", "linear", "exponential"]),
214
+ baseMs: _zod.z.number().min(0),
215
+ maxMs: _zod.z.number().gt(0).optional(),
216
+ jitter: _zod.z.boolean().optional()
217
+ });
218
+ var DEFAULT_BACKOFF = {
219
+ strategy: "fixed",
220
+ baseMs: 1e4
221
+ };
222
+ var DEFAULT_MAX_RETRIES = 3;
223
+ var DEFAULT_BLOCK_ON_ERROR = true;
224
+ var ReactionOptionsSchema = _zod.z.object({
225
+ blockOnError: _zod.z.boolean(),
226
+ maxRetries: _zod.z.number().int().min(0),
227
+ backoff: BackoffOptionsSchema.optional()
228
+ });
229
+ function resolveReactionConfig(options) {
230
+ return ReactionOptionsSchema.parse(options);
231
+ }
232
+ var ActionOptionsSchema = _zod.z.object({
233
+ maxRetries: _zod.z.number().int().min(0).optional(),
234
+ backoff: BackoffOptionsSchema.optional()
235
+ });
236
+ function resolveActionConfig(options) {
237
+ return ActionOptionsSchema.parse(options);
238
+ }
239
+ var LaneConfigSchema = _zod.z.object({
240
+ name: _zod.z.string().min(1),
241
+ leaseMillis: _zod.z.number().min(0).optional(),
242
+ streamLimit: _zod.z.number().int().min(0).optional(),
243
+ cycleMs: _zod.z.number().min(0).optional()
244
+ });
245
+ function resolveLaneConfig(options) {
246
+ LaneConfigSchema.parse(options);
247
+ return options;
248
+ }
249
+ var DEFAULT_STREAM_LIMIT = 10;
250
+ var DEFAULT_EVENT_LIMIT = 10;
251
+ var DEFAULT_LEASE_MILLIS = 1e4;
252
+ var DrainOptionsSchema = _zod.z.object({
253
+ streamLimit: _zod.z.number().int().min(0).optional(),
254
+ eventLimit: _zod.z.number().int().min(0).optional(),
255
+ leaseMillis: _zod.z.number().min(0).optional()
256
+ });
257
+ function resolveDrainConfig(options) {
258
+ if (options === void 0) return void 0;
259
+ DrainOptionsSchema.parse(options);
260
+ return options;
261
+ }
262
+ var SettleOptionsSchema = DrainOptionsSchema.extend({
263
+ debounceMs: _zod.z.number().min(0).optional(),
264
+ // `maxPasses` defaults to Infinity (no cap) when omitted; a present value is
265
+ // a non-negative integer — `0` is legal and means "run no passes".
266
+ //
267
+ // `Infinity` is accepted explicitly. It is the documented default
268
+ // (`Act.settle`'s doc-comment and `SettleOptions.maxPasses` both name it),
269
+ // and `settle.ts` destructures `maxPasses = Infinity`, so the one value the
270
+ // docs advertise was the one value `z.number().int()` refused — Zod 4
271
+ // rejects `±Infinity`, and an integer check cannot pass it either. Wrapper
272
+ // code normalizing an optional cap (`maxPasses: opts.maxPasses ?? Infinity`)
273
+ // is the natural way to hit it. Accepting it also honors this module's own
274
+ // rule that a value which works today is never newly rejected.
275
+ maxPasses: _zod.z.union([_zod.z.number().int().min(0), _zod.z.literal(Number.POSITIVE_INFINITY)]).optional()
276
+ }).loose();
277
+ function resolveSettleConfig(options) {
278
+ if (options === void 0) return void 0;
279
+ SettleOptionsSchema.parse(options);
280
+ return options;
281
+ }
282
+ var MAX_SHUTDOWN_GRACE_MS = 3e4;
283
+ var ShutdownOptionsSchema = _zod.z.object({
284
+ // `0` is legal and is exactly today's behavior: stop scheduling and
285
+ // return without waiting.
286
+ graceMs: _zod.z.number().min(0).optional()
287
+ }).loose();
288
+ function resolveShutdownConfig(options) {
289
+ if (options === void 0) return void 0;
290
+ ShutdownOptionsSchema.parse(options);
291
+ return options;
292
+ }
293
+ var ActOptionsSchema = _zod.z.object({
294
+ maxSubscribedStreams: _zod.z.number().int().min(1).optional(),
295
+ settleDebounceMs: _zod.z.number().int().min(0).optional(),
296
+ autoSettle: _zod.z.boolean().optional()
297
+ }).loose();
298
+ function resolveActConfig(options) {
299
+ if (options === void 0) return void 0;
300
+ ActOptionsSchema.parse(options);
301
+ return options;
302
+ }
303
+ var DEFAULT_AUTOCLOSE_WINDOW_TZ = "UTC";
304
+ function is_valid_time_zone(tz) {
305
+ try {
306
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
307
+ return true;
308
+ } catch (e4) {
309
+ return false;
310
+ }
311
+ }
312
+ var AutocloseWindowSchema = _zod.z.object({
313
+ start: _zod.z.number().int().min(0).max(23, { message: "autocloseWindow.start must be an hour in [0, 23]" }),
314
+ end: _zod.z.number().int().min(0).max(23, { message: "autocloseWindow.end must be an hour in [0, 23]" }),
315
+ timeZone: _zod.z.string().refine(is_valid_time_zone, {
316
+ message: "autocloseWindow.timeZone must be a valid IANA time zone"
317
+ }).default(DEFAULT_AUTOCLOSE_WINDOW_TZ)
318
+ }).refine((w) => w.start !== w.end, {
319
+ message: "autocloseWindow.start and end must differ \u2014 an empty window disables autoclose"
320
+ });
321
+ var AutocloseOptionsSchema = _zod.z.object({
322
+ autocloseWindow: AutocloseWindowSchema.optional()
323
+ });
324
+ function resolveAutocloseConfig(options) {
325
+ return AutocloseOptionsSchema.parse({
326
+ autocloseWindow: _optionalChain([options, 'optionalAccess', _2 => _2.autocloseWindow])
327
+ });
328
+ }
329
+ var DEFAULT_CIRCUIT_FAILURE_THRESHOLD = 5;
330
+ var DEFAULT_CIRCUIT_COOLDOWN_MS = 3e4;
331
+ var CircuitBreakerOptionsSchema = _zod.z.object({
332
+ failureThreshold: _zod.z.number().int().min(1).default(DEFAULT_CIRCUIT_FAILURE_THRESHOLD),
333
+ cooldownMs: _zod.z.number().int().min(100).max(36e5).default(DEFAULT_CIRCUIT_COOLDOWN_MS)
334
+ });
335
+ var resolveCircuitBreakerConfig = (options) => CircuitBreakerOptionsSchema.parse(_nullishCoalesce(options, () => ( {})));
336
+ var DEFAULT_FOLD_FLUSH_EVERY = 1e3;
337
+ var DEFAULT_MAX_CACHED_STATES = 1e4;
338
+ var FoldOptionsSchema = _zod.z.object({
339
+ flushEvery: _zod.z.number().int().min(1).default(DEFAULT_FOLD_FLUSH_EVERY),
340
+ maxCachedStates: _zod.z.number().int().min(1).default(DEFAULT_MAX_CACHED_STATES)
341
+ });
342
+ function resolveFoldConfig(options) {
343
+ return FoldOptionsSchema.parse(options);
344
+ }
345
+
346
+ // src/utils.ts
347
+
348
+ var validate = (target, payload, schema) => {
349
+ try {
350
+ return schema ? schema.parse(payload) : payload;
351
+ } catch (error) {
352
+ if (error instanceof _zod.ZodError) {
353
+ throw new (0, _chunkNNWP65YMcjs.ValidationError)(target, payload, _zod.prettifyError.call(void 0, error));
354
+ }
355
+ throw new (0, _chunkNNWP65YMcjs.ValidationError)(target, payload, error);
356
+ }
357
+ };
358
+ var extend = (source, schema, target) => {
359
+ const value = validate("config", source, schema);
360
+ return { ...target, ...value };
361
+ };
362
+ async function sleep(ms) {
363
+ return new Promise((resolve) => setTimeout(resolve, _nullishCoalesce(ms, () => ( config().sleepMs))));
364
+ }
365
+ var SOURCE_METACHARACTERS = /[\^$.*+?()[\]{}|\\]/;
366
+ function is_literal_source(source) {
367
+ return !SOURCE_METACHARACTERS.test(source);
368
+ }
369
+ var ISO_8601 = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(\.\d+)?(Z|[+-][0-2][0-9]:[0-5][0-9])?$/;
370
+ var dateReviver = (_key, value) => typeof value === "string" && ISO_8601.test(value) ? new Date(value) : value;
371
+
372
+ // src/adapters/in-memory-store.ts
373
+ var InMemoryStream = (_class2 = class {
374
+
375
+
376
+ __init2() {this._at = -1}
377
+ __init3() {this._retry = -1}
378
+ __init4() {this._blocked = false}
379
+ __init5() {this._error = ""}
380
+ __init6() {this._leased_by = void 0}
381
+ __init7() {this._leased_until = void 0}
382
+ __init8() {this._priority = 0}
383
+ __init9() {this._lane = _chunkNNWP65YMcjs.DEFAULT_LANE}
384
+ // While in the future, the stream is held out of `claim`.
385
+ __init10() {this._deferred_at = void 0}
386
+ // Work mark; `undefined` = never correlated, so `claim` skips it.
387
+ __init11() {this._correlated_at = void 0}
388
+ constructor(stream, source, priority = 0, lane = _chunkNNWP65YMcjs.DEFAULT_LANE) {;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);_class2.prototype.__init6.call(this);_class2.prototype.__init7.call(this);_class2.prototype.__init8.call(this);_class2.prototype.__init9.call(this);_class2.prototype.__init10.call(this);_class2.prototype.__init11.call(this);
389
+ this.stream = stream;
390
+ this.source = source;
391
+ this._priority = priority;
392
+ this._lane = lane;
393
+ }
394
+ get priority() {
395
+ return this._priority;
396
+ }
397
+ get lane() {
398
+ return this._lane;
399
+ }
400
+ /** Replaced on every subscribe, so the current config wins on restart. */
401
+ set lane(value) {
402
+ this._lane = value;
403
+ }
404
+ bump_priority(priority) {
405
+ if (priority > this._priority) this._priority = priority;
406
+ }
407
+ get correlated_at() {
408
+ return this._correlated_at;
409
+ }
410
+ /** A mark never regresses, including at zero and negatives. */
411
+ mark(correlated_at) {
412
+ if (this._correlated_at === void 0 || correlated_at > this._correlated_at)
413
+ this._correlated_at = correlated_at;
414
+ }
415
+ /** Operator override; ignores the subscribe-time `max()`. */
416
+ set_priority(priority) {
417
+ this._priority = priority;
418
+ }
419
+ get is_available() {
420
+ return !this._blocked && (!this._leased_until || this._leased_until <= /* @__PURE__ */ new Date()) && (!this._deferred_at || this._deferred_at <= Date.now());
421
+ }
422
+ defer(deferred_at) {
423
+ this._deferred_at = deferred_at;
424
+ this._retry = -1;
425
+ }
426
+ get at() {
427
+ return this._at;
428
+ }
429
+ get retry() {
430
+ return this._retry;
431
+ }
432
+ get blocked() {
433
+ return this._blocked;
434
+ }
435
+ get error() {
436
+ return this._error;
437
+ }
438
+ get leased_by() {
439
+ return this._leased_by;
440
+ }
441
+ get leased_until() {
442
+ return this._leased_until;
443
+ }
444
+ get deferred_at() {
445
+ return this._deferred_at;
446
+ }
447
+ lease(lease, millis) {
448
+ this._leased_by = lease.by;
449
+ this._leased_until = new Date(Date.now() + millis);
450
+ this._retry = this._retry + 1;
451
+ return {
452
+ stream: this.stream,
453
+ source: this.source,
454
+ at: lease.at,
455
+ by: lease.by,
456
+ retry: this._retry,
457
+ lagging: lease.lagging,
458
+ lane: this._lane
459
+ };
460
+ }
461
+ /** Ack, or with `due`, also persist the schedule. See {@link Store.ack}. */
462
+ ack(lease) {
463
+ if (this._leased_by === lease.by) {
464
+ this._leased_by = void 0;
465
+ this._leased_until = void 0;
466
+ if (lease.due !== void 0) {
467
+ this._at = lease.at;
468
+ this._retry = lease.retry;
469
+ this._deferred_at = lease.due;
470
+ return void 0;
471
+ }
472
+ this._retry = -1;
473
+ this._at = lease.at;
474
+ this._deferred_at = void 0;
475
+ return {
476
+ stream: this.stream,
477
+ source: this.source,
478
+ at: this._at,
479
+ by: lease.by,
480
+ retry: this._retry,
481
+ lagging: lease.lagging,
482
+ lane: this._lane
483
+ };
484
+ }
485
+ }
486
+ block(lease, error) {
487
+ if (this._leased_by === lease.by && !this._blocked) {
488
+ this._blocked = true;
489
+ this._error = error;
490
+ this._deferred_at = void 0;
491
+ return {
492
+ stream: this.stream,
493
+ source: this.source,
494
+ at: this._at,
495
+ by: this._leased_by,
496
+ retry: this._retry,
497
+ error: this._error,
498
+ lagging: lease.lagging,
499
+ lane: this._lane
500
+ };
501
+ }
502
+ }
503
+ /** Retry resets to -1 (released); the next claim makes it 0. */
504
+ reset() {
505
+ this._at = -1;
506
+ this._retry = -1;
507
+ this._blocked = false;
508
+ this._error = "";
509
+ this._leased_by = void 0;
510
+ this._leased_until = void 0;
511
+ this._deferred_at = void 0;
512
+ }
513
+ /** True only when the stream was blocked. */
514
+ unblock() {
515
+ if (!this._blocked) return false;
516
+ this._blocked = false;
517
+ this._retry = -1;
518
+ this._error = "";
519
+ this._leased_by = void 0;
520
+ this._leased_until = void 0;
521
+ this._deferred_at = void 0;
522
+ return true;
523
+ }
524
+ }, _class2);
525
+ var InMemoryStore = (_class3 = class {constructor() { _class3.prototype.__init12.call(this);_class3.prototype.__init13.call(this);_class3.prototype.__init14.call(this);_class3.prototype.__init15.call(this);_class3.prototype.__init16.call(this);_class3.prototype.__init17.call(this);_class3.prototype.__init18.call(this); }
526
+ __init12() {this._events = []}
527
+ // Never reused. Deletions punch holes, so ids are not array indexes.
528
+ __init13() {this._next_id = 0}
529
+ __init14() {this._streams = /* @__PURE__ */ new Map()}
530
+ /** Correlate checkpoint: how far the log has been READ. */
531
+ __init15() {this._correlated_at = -1}
532
+ /** Per-correlator checkpoint and lease; keyless callers use `_correlated_at`. */
533
+ __init16() {this._correlators = /* @__PURE__ */ new Map()}
534
+ __init17() {this._stream_versions = /* @__PURE__ */ new Map()}
535
+ // stream → (event_id → cloned pii). Two levels so `forget_pii` drops one
536
+ // inner Map. Absence means no PII.
537
+ __init18() {this._pii = /* @__PURE__ */ new Map()}
538
+ _reset_indexes() {
539
+ this._events.length = 0;
540
+ this._next_id = 0;
541
+ this._correlated_at = -1;
542
+ this._stream_versions.clear();
543
+ this._pii.clear();
544
+ }
545
+ // Stores a cloned copy, so caller-side mutation can't reach it.
546
+ _put_pii(stream, id, pii) {
547
+ let per_stream = this._pii.get(stream);
548
+ if (!per_stream) {
549
+ per_stream = /* @__PURE__ */ new Map();
550
+ this._pii.set(stream, per_stream);
551
+ }
552
+ per_stream.set(id, structuredClone(pii));
553
+ }
554
+ // First index whose id is greater than `after` (ids are sorted, not dense).
555
+ _first_index_after(after) {
556
+ let lo = 0;
557
+ let hi = this._events.length;
558
+ while (lo < hi) {
559
+ const mid = lo + hi >>> 1;
560
+ if (this._events[mid].id > after) hi = mid;
561
+ else lo = mid + 1;
562
+ }
563
+ return lo;
564
+ }
565
+ // Allocation-free for events without PII, the common case.
566
+ _with_pii(e, wanted = true) {
567
+ if (!wanted) return e;
568
+ const pii = _optionalChain([this, 'access', _3 => _3._pii, 'access', _4 => _4.get, 'call', _5 => _5(e.stream), 'optionalAccess', _6 => _6.get, 'call', _7 => _7(e.id)]);
569
+ return pii ? { ...e, pii } : e;
570
+ }
571
+ async dispose() {
572
+ await sleep();
573
+ this._reset_indexes();
574
+ }
575
+ async seed() {
576
+ await sleep();
577
+ }
578
+ async drop() {
579
+ await sleep();
580
+ this._reset_indexes();
581
+ this._streams = /* @__PURE__ */ new Map();
582
+ }
583
+ in_query(query, e) {
584
+ if (query.stream && !this._stream_matches(query.stream, query, e.stream))
585
+ return false;
586
+ if (query.names && !query.names.includes(e.name)) return false;
587
+ if (query.correlation && _optionalChain([e, 'access', _8 => _8.meta, 'optionalAccess', _9 => _9.correlation]) !== query.correlation)
588
+ return false;
589
+ if (e.name === _chunkNNWP65YMcjs.SNAP_EVENT && !query.with_snaps) return false;
590
+ if (query.created_after && e.created <= query.created_after) return false;
591
+ if (query.created_before && e.created >= query.created_before) return false;
592
+ return true;
593
+ }
594
+ _stream_matches(pattern, query, stream) {
595
+ return query.stream_exact ? stream === pattern : RegExp(pattern).test(stream);
596
+ }
597
+ /** Index of the stream's latest snapshot, or -1; an explicit `after` wins. */
598
+ _snap_floor(query) {
599
+ if (!_optionalChain([query, 'optionalAccess', _10 => _10.with_snaps]) || !query.stream_exact || query.stream === void 0 || query.after !== void 0)
600
+ return -1;
601
+ for (let j = this._events.length - 1; j >= 0; j--) {
602
+ const e = this._events[j];
603
+ if (e.stream === query.stream && e.name === _chunkNNWP65YMcjs.SNAP_EVENT) return j;
604
+ }
605
+ return -1;
606
+ }
607
+ async query(callback, query) {
608
+ await sleep();
609
+ const floor = this._snap_floor(query);
610
+ const lo = floor >= 0 ? floor : this._first_index_after(_nullishCoalesce(_optionalChain([query, 'optionalAccess', _11 => _11.after]), () => ( -1)));
611
+ const hi = _optionalChain([query, 'optionalAccess', _12 => _12.before]) !== void 0 ? this._first_index_after(query.before - 1) : this._events.length;
612
+ const with_pii = _optionalChain([query, 'optionalAccess', _13 => _13.with_pii]) !== false;
613
+ let count = 0;
614
+ for (let k = 0; k < hi - lo; k++) {
615
+ const e = this._events[_optionalChain([query, 'optionalAccess', _14 => _14.backward]) ? hi - 1 - k : lo + k];
616
+ if (query && !this.in_query(query, e)) continue;
617
+ await Promise.resolve(
618
+ callback(this._with_pii(e, with_pii))
619
+ );
620
+ count++;
621
+ if (_optionalChain([query, 'optionalAccess', _15 => _15.limit]) && count >= query.limit) break;
622
+ }
623
+ return count;
624
+ }
625
+ async commit(stream, msgs, meta, expectedVersion) {
626
+ await sleep();
627
+ const current_version = _nullishCoalesce(this._stream_versions.get(stream), () => ( -1));
628
+ if (typeof expectedVersion === "number" && current_version !== expectedVersion) {
629
+ throw new (0, _chunkNNWP65YMcjs.ConcurrencyError)(
630
+ stream,
631
+ current_version,
632
+ msgs,
633
+ expectedVersion
634
+ );
635
+ }
636
+ let version = current_version + 1;
637
+ const committed = msgs.map(({ name, data, pii }) => {
638
+ const c = {
639
+ id: this._next_id++,
640
+ stream,
641
+ version,
642
+ created: /* @__PURE__ */ new Date(),
643
+ name,
644
+ data,
645
+ meta
646
+ };
647
+ this._events.push(c);
648
+ if (pii != null) this._put_pii(stream, c.id, pii);
649
+ version++;
650
+ return this._with_pii(c);
651
+ });
652
+ this._stream_versions.set(stream, version - 1);
653
+ return committed;
654
+ }
655
+ async claim(lagging, leading, by, millis, lane) {
656
+ await sleep();
657
+ const has_work = (s) => s.correlated_at !== void 0 && s.at < s.correlated_at;
658
+ const available = [...this._streams.values()].filter(
659
+ (s) => s.is_available && has_work(s) && (lane === void 0 || s.lane === lane)
660
+ );
661
+ const fair = lagging >= 2 ? Math.max(1, Math.floor(lagging / 4)) : 0;
662
+ const by_priority = [...available].sort(
663
+ (a, b) => b.priority - a.priority || a.at - b.at
664
+ );
665
+ const priority_slice = by_priority.slice(0, lagging - fair);
666
+ const picked = new Set(priority_slice.map((s) => s.stream));
667
+ const fair_slice = [...available].sort((a, b) => a.at - b.at).filter((s) => !picked.has(s.stream)).slice(0, fair);
668
+ const lag = [...priority_slice, ...fair_slice].map((s) => ({
669
+ stream: s.stream,
670
+ source: s.source,
671
+ at: s.at,
672
+ lagging: true
673
+ }));
674
+ const lead = available.sort((a, b) => b.at - a.at).slice(0, leading).map((s) => ({
675
+ stream: s.stream,
676
+ source: s.source,
677
+ at: s.at,
678
+ lagging: false
679
+ }));
680
+ const seen = /* @__PURE__ */ new Set();
681
+ const combined = [...lag, ...lead].filter((p) => {
682
+ if (seen.has(p.stream)) return false;
683
+ seen.add(p.stream);
684
+ return true;
685
+ });
686
+ return combined.map(
687
+ (p) => _optionalChain([this, 'access', _16 => _16._streams, 'access', _17 => _17.get, 'call', _18 => _18(p.stream), 'optionalAccess', _19 => _19.lease, 'call', _20 => _20({ ...p, by, retry: 0 }, millis)])
688
+ ).filter((l) => !!l);
689
+ }
690
+ async subscribe(streams, correlated_at, correlator) {
691
+ await sleep();
692
+ let correlating;
693
+ let keyed_at;
694
+ if (correlator) {
695
+ const now = Date.now();
696
+ const held = this._correlators.get(correlator.key);
697
+ const at = Math.max(_nullishCoalesce(_optionalChain([held, 'optionalAccess', _21 => _21.at]), () => ( this._correlated_at)), _nullishCoalesce(correlated_at, () => ( -1)));
698
+ keyed_at = at;
699
+ if (!held || held.until < now || held.by === correlator.by) {
700
+ correlating = true;
701
+ this._correlators.set(correlator.key, {
702
+ at,
703
+ by: correlator.by,
704
+ // Release outright, or a successor in the same ms is still refused.
705
+ until: correlator.millis > 0 ? now + correlator.millis : 0
706
+ });
707
+ } else {
708
+ correlating = false;
709
+ held.at = at;
710
+ }
711
+ if (correlated_at !== void 0 && correlated_at > this._correlated_at)
712
+ this._correlated_at = correlated_at;
713
+ } else if (correlated_at !== void 0 && correlated_at > this._correlated_at)
714
+ this._correlated_at = correlated_at;
715
+ let subscribed = 0;
716
+ for (const {
717
+ stream,
718
+ source,
719
+ priority = 0,
720
+ lane = _chunkNNWP65YMcjs.DEFAULT_LANE,
721
+ correlated_at: correlated_at2
722
+ } of streams) {
723
+ const existing = this._streams.get(stream);
724
+ if (existing) {
725
+ if (priority >= existing.priority) existing.lane = lane;
726
+ existing.bump_priority(priority);
727
+ if (correlated_at2 !== void 0) existing.mark(correlated_at2);
728
+ } else {
729
+ const created = new InMemoryStream(stream, source, priority, lane);
730
+ if (correlated_at2 !== void 0) created.mark(correlated_at2);
731
+ this._streams.set(stream, created);
732
+ subscribed++;
733
+ }
734
+ }
735
+ let watermark = -1;
736
+ for (const s of this._streams.values()) {
737
+ if (s.at > watermark) watermark = s.at;
738
+ }
739
+ return {
740
+ subscribed,
741
+ watermark,
742
+ correlated_at: _nullishCoalesce(keyed_at, () => ( this._correlated_at)),
743
+ ...correlating === void 0 ? {} : { correlating }
744
+ };
745
+ }
746
+ async ack(leases) {
747
+ await sleep();
748
+ return leases.map((l) => _optionalChain([this, 'access', _22 => _22._streams, 'access', _23 => _23.get, 'call', _24 => _24(l.stream), 'optionalAccess', _25 => _25.ack, 'call', _26 => _26(l)])).filter((l) => !!l);
749
+ }
750
+ async block(leases) {
751
+ await sleep();
752
+ return leases.map((l) => _optionalChain([this, 'access', _27 => _27._streams, 'access', _28 => _28.get, 'call', _29 => _29(l.stream), 'optionalAccess', _30 => _30.block, 'call', _31 => _31(l, l.error)])).filter((l) => !!l);
753
+ }
754
+ async defer(input, deferred_at) {
755
+ await sleep();
756
+ const selected = this._select(input);
757
+ for (const s of selected) s.defer(deferred_at);
758
+ return selected.length;
759
+ }
760
+ /** De-duplicated like the SQL `stream = ANY(...)`; unknown names skipped. */
761
+ _select(input) {
762
+ if (Array.isArray(input))
763
+ return [...new Set(input)].map((name) => this._streams.get(name)).filter((s) => s !== void 0);
764
+ return [...this._streams.values()].filter(this._filter_predicate(input));
765
+ }
766
+ _filter_predicate(filter) {
767
+ const stream_re = filter.stream !== void 0 && !filter.stream_exact ? new RegExp(filter.stream) : void 0;
768
+ const source_re = filter.source !== void 0 && !filter.source_exact ? new RegExp(filter.source) : void 0;
769
+ return (s) => {
770
+ if (filter.stream !== void 0) {
771
+ if (filter.stream_exact ? s.stream !== filter.stream : !stream_re.test(s.stream))
772
+ return false;
773
+ }
774
+ if (filter.source !== void 0) {
775
+ if (s.source === void 0) return false;
776
+ if (filter.source_exact ? s.source !== filter.source : !source_re.test(s.source))
777
+ return false;
778
+ }
779
+ if (filter.blocked !== void 0 && s.blocked !== filter.blocked)
780
+ return false;
781
+ if (filter.lane !== void 0 && s.lane !== filter.lane) return false;
782
+ return true;
783
+ };
784
+ }
785
+ async reset(input) {
786
+ await sleep();
787
+ const selected = this._select(input);
788
+ for (const s of selected) s.reset();
789
+ return selected.length;
790
+ }
791
+ async forget_pii(stream) {
792
+ await sleep();
793
+ const count = _nullishCoalesce(_optionalChain([this, 'access', _32 => _32._pii, 'access', _33 => _33.get, 'call', _34 => _34(stream), 'optionalAccess', _35 => _35.size]), () => ( 0));
794
+ this._pii.delete(stream);
795
+ return count;
796
+ }
797
+ async unblock(input) {
798
+ await sleep();
799
+ const selected = this._select(
800
+ Array.isArray(input) ? input : { ...input, blocked: true }
801
+ );
802
+ return selected.filter((s) => s.unblock()).length;
803
+ }
804
+ async prioritize(filter, priority) {
805
+ await sleep();
806
+ const changed = this._select(filter).filter((s) => s.priority !== priority);
807
+ for (const s of changed) s.set_priority(priority);
808
+ return changed.length;
809
+ }
810
+ async query_streams(callback, query) {
811
+ await sleep();
812
+ const limit = _nullishCoalesce(_optionalChain([query, 'optionalAccess', _36 => _36.limit]), () => ( 100));
813
+ const after = _optionalChain([query, 'optionalAccess', _37 => _37.after]);
814
+ const source_matches = _optionalChain([query, 'optionalAccess', _38 => _38.source_matches]);
815
+ const matches = this._filter_predicate(_nullishCoalesce(query, () => ( {})));
816
+ const reverse_cache = /* @__PURE__ */ new Map();
817
+ const reverse_match = (source) => {
818
+ let re = reverse_cache.get(source);
819
+ if (!re) {
820
+ re = new RegExp(source);
821
+ reverse_cache.set(source, re);
822
+ }
823
+ return source_matches.some((name) => re.test(name));
824
+ };
825
+ const sorted = [...this._streams.keys()].sort().map((stream) => this._streams.get(stream));
826
+ let count = 0;
827
+ for (const s of sorted) {
828
+ if (after !== void 0 && s.stream <= after) continue;
829
+ if (!matches(s)) continue;
830
+ if (source_matches !== void 0) {
831
+ if (s.source && !reverse_match(s.source)) continue;
832
+ }
833
+ if (count >= limit) break;
834
+ callback({
835
+ stream: s.stream,
836
+ source: s.source,
837
+ at: s.at,
838
+ retry: s.retry,
839
+ blocked: s.blocked,
840
+ error: s.error,
841
+ priority: s.priority,
842
+ leased_by: s.leased_by,
843
+ leased_until: s.leased_until,
844
+ lane: s.lane,
845
+ deferred_at: s.deferred_at,
846
+ correlated_at: s.correlated_at
847
+ });
848
+ count++;
849
+ }
850
+ return { maxEventId: _nullishCoalesce(_optionalChain([this, 'access', _39 => _39._events, 'access', _40 => _40.at, 'call', _41 => _41(-1), 'optionalAccess', _42 => _42.id]), () => ( -1)), count };
851
+ }
852
+ async query_stats(input, options) {
853
+ await sleep();
854
+ const exclude = new Set(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _43 => _43.exclude]), () => ( [])));
855
+ const want_tail = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _44 => _44.tail]), () => ( false));
856
+ const want_count = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _45 => _45.count]), () => ( false));
857
+ const want_names = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _46 => _46.names]), () => ( false));
858
+ const before = _optionalChain([options, 'optionalAccess', _47 => _47.before]);
859
+ const after = _optionalChain([options, 'optionalAccess', _48 => _48.after]);
860
+ const limit = _optionalChain([options, 'optionalAccess', _49 => _49.limit]);
861
+ const array_targets = Array.isArray(input) ? new Set(input) : null;
862
+ const filter = Array.isArray(input) ? null : input;
863
+ const stream_re = _optionalChain([filter, 'optionalAccess', _50 => _50.stream]) !== void 0 && !filter.stream_exact ? new RegExp(filter.stream) : void 0;
864
+ const scope_cache = /* @__PURE__ */ new Map();
865
+ const in_scope = (stream) => {
866
+ const cached = scope_cache.get(stream);
867
+ if (cached !== void 0) return cached;
868
+ let ok = true;
869
+ if (array_targets) {
870
+ ok = array_targets.has(stream);
871
+ } else if (_optionalChain([filter, 'optionalAccess', _51 => _51.stream]) !== void 0) {
872
+ ok = filter.stream_exact ? stream === filter.stream : (
873
+ // stream_re set when stream is regex
874
+ stream_re.test(stream)
875
+ );
876
+ }
877
+ scope_cache.set(stream, ok);
878
+ return ok;
879
+ };
880
+ const acc = /* @__PURE__ */ new Map();
881
+ for (const e of this._events) {
882
+ if (before !== void 0 && e.id >= before) continue;
883
+ if (!in_scope(e.stream)) continue;
884
+ if (exclude.has(e.name)) continue;
885
+ let a = acc.get(e.stream);
886
+ if (!a) {
887
+ a = { head: e, count: 0 };
888
+ if (want_tail) a.tail = e;
889
+ if (want_names) a.names = {};
890
+ acc.set(e.stream, a);
891
+ }
892
+ a.head = e;
893
+ a.count++;
894
+ if (want_names) {
895
+ const n = String(e.name);
896
+ a.names[n] = (_nullishCoalesce(a.names[n], () => ( 0))) + 1;
897
+ }
898
+ }
899
+ const ordered = [...acc.keys()].sort();
900
+ const out = /* @__PURE__ */ new Map();
901
+ for (const stream of ordered) {
902
+ if (limit !== void 0 && out.size >= limit) break;
903
+ if (after !== void 0 && stream <= after) continue;
904
+ const a = acc.get(stream);
905
+ const stats = { head: a.head };
906
+ if (want_tail) stats.tail = a.tail;
907
+ if (want_count) stats.count = a.count;
908
+ if (want_names) stats.names = a.names;
909
+ out.set(stream, stats);
910
+ }
911
+ return out;
912
+ }
913
+ async truncate(targets) {
914
+ await sleep();
915
+ const result = /* @__PURE__ */ new Map();
916
+ const windowed = targets.filter((t) => t.before !== void 0);
917
+ if (windowed.length) {
918
+ const drop = /* @__PURE__ */ new Set();
919
+ for (const { stream, before, max_id } of windowed) {
920
+ let boundary;
921
+ for (const e of this._events) {
922
+ if (e.stream === stream && e.name === _chunkNNWP65YMcjs.SNAP_EVENT && e.created < before && (max_id === void 0 || e.id <= max_id) && (!boundary || e.id > boundary.id))
923
+ boundary = e;
924
+ }
925
+ if (!boundary) continue;
926
+ let deleted = 0;
927
+ for (const e of this._events) {
928
+ if (e.stream === stream && e.id < boundary.id) {
929
+ drop.add(e.id);
930
+ _optionalChain([this, 'access', _52 => _52._pii, 'access', _53 => _53.get, 'call', _54 => _54(stream), 'optionalAccess', _55 => _55.delete, 'call', _56 => _56(e.id)]);
931
+ deleted++;
932
+ }
933
+ }
934
+ result.set(stream, { deleted, committed: boundary, before });
935
+ }
936
+ if (drop.size) this._events = this._events.filter((e) => !drop.has(e.id));
937
+ }
938
+ const full = targets.filter((t) => t.before === void 0);
939
+ for (const { stream, snapshot, meta } of full) {
940
+ let deleted = 0;
941
+ this._events = this._events.filter((e) => {
942
+ if (e.stream !== stream) return true;
943
+ deleted++;
944
+ return false;
945
+ });
946
+ this._stream_versions.delete(stream);
947
+ this._pii.delete(stream);
948
+ const event = {
949
+ id: this._next_id++,
950
+ stream,
951
+ version: 0,
952
+ created: /* @__PURE__ */ new Date(),
953
+ name: snapshot !== void 0 ? _chunkNNWP65YMcjs.SNAP_EVENT : _chunkNNWP65YMcjs.TOMBSTONE_EVENT,
954
+ data: _nullishCoalesce(snapshot, () => ( {})),
955
+ meta: _nullishCoalesce(meta, () => ( { correlation: "", causation: {} }))
956
+ };
957
+ this._events.push(event);
958
+ this._stream_versions.set(stream, 0);
959
+ result.set(stream, { deleted, committed: event });
960
+ }
961
+ return result;
962
+ }
963
+ /** A throw inside the driver restores the captured state. Ids restart at 0. */
964
+ async restore(driver) {
965
+ await sleep();
966
+ const prev_events = this._events;
967
+ const prev_next_id = this._next_id;
968
+ const prev_streams = this._streams;
969
+ const prev_stream_versions = this._stream_versions;
970
+ const prev_pii = this._pii;
971
+ const prev_correlated_at = this._correlated_at;
972
+ const prev_correlators = new Map(
973
+ [...this._correlators].map(([k, v]) => [k, { ...v }])
974
+ );
975
+ this._correlated_at = -1;
976
+ for (const c of this._correlators.values()) c.at = -1;
977
+ this._events = [];
978
+ this._next_id = 0;
979
+ this._streams = /* @__PURE__ */ new Map();
980
+ this._stream_versions = /* @__PURE__ */ new Map();
981
+ this._pii = /* @__PURE__ */ new Map();
982
+ try {
983
+ await driver(async (event) => {
984
+ const id = this._next_id++;
985
+ const { pii, ...rest } = event;
986
+ const committed = { ...rest, id };
987
+ this._events.push(committed);
988
+ if (pii != null) this._put_pii(event.stream, id, pii);
989
+ this._stream_versions.set(event.stream, event.version);
990
+ return id;
991
+ });
992
+ } catch (err) {
993
+ this._events = prev_events;
994
+ this._next_id = prev_next_id;
995
+ this._streams = prev_streams;
996
+ this._stream_versions = prev_stream_versions;
997
+ this._pii = prev_pii;
998
+ this._correlated_at = prev_correlated_at;
999
+ this._correlators = prev_correlators;
1000
+ throw err;
1001
+ }
1002
+ }
1003
+ }, _class3);
1004
+
1005
+ // src/disposers.ts
1006
+ var entries = [];
1007
+ var prune = () => {
1008
+ for (let i = entries.length - 1; i >= 0; i--) {
1009
+ const { ref } = entries[i];
1010
+ if (ref && !ref.deref()) entries.splice(i, 1);
1011
+ }
1012
+ };
1013
+ var register_disposer = (run) => {
1014
+ prune();
1015
+ entries.push({ run });
1016
+ };
1017
+ var register_weak_disposer = (ref, run) => {
1018
+ prune();
1019
+ entries.push({
1020
+ run,
1021
+ ref
1022
+ });
1023
+ };
1024
+ var run_disposers = async () => {
1025
+ for (const { run, ref } of [...entries].reverse()) {
1026
+ if (!ref) {
1027
+ await run();
1028
+ continue;
1029
+ }
1030
+ const target = ref.deref();
1031
+ if (target) await run(target);
1032
+ }
1033
+ };
1034
+
1035
+ // src/scoped.ts
1036
+ var _async_hooks = require('async_hooks');
1037
+ var scoped = new (0, _async_hooks.AsyncLocalStorage)();
1038
+ var reacting = new (0, _async_hooks.AsyncLocalStorage)();
1039
+ function make_run_scoped(bag) {
1040
+ return (fn) => scoped.run(bag, fn);
1041
+ }
1042
+ function current_autoclose_window() {
1043
+ return _optionalChain([scoped, 'access', _57 => _57.getStore, 'call', _58 => _58(), 'optionalAccess', _59 => _59.autoclose_window]);
1044
+ }
1045
+ function current_ports() {
1046
+ return scoped.getStore();
1047
+ }
1048
+ function run_reacting(event, fn) {
1049
+ const box = { event };
1050
+ return reacting.run(box, async () => {
1051
+ try {
1052
+ return await fn();
1053
+ } finally {
1054
+ box.event = void 0;
1055
+ }
1056
+ });
1057
+ }
1058
+ function current_reacting() {
1059
+ return _optionalChain([reacting, 'access', _60 => _60.getStore, 'call', _61 => _61(), 'optionalAccess', _62 => _62.event]);
1060
+ }
1061
+ function make_reaction_scope(app) {
1062
+ return { app, run: run_reacting };
1063
+ }
1064
+
1065
+ // src/ports.ts
1066
+ var adapters = /* @__PURE__ */ new Map();
1067
+ function port(injector) {
1068
+ return (adapter) => {
1069
+ if (!adapters.has(injector.name)) {
1070
+ const injected = injector(adapter);
1071
+ adapters.set(injector.name, injected);
1072
+ log().info(`[act] + ${injector.name}:${injected.constructor.name}`);
1073
+ }
1074
+ return adapters.get(injector.name);
1075
+ };
1076
+ }
1077
+ var log = port(function log2(adapter) {
1078
+ const cfg = config();
1079
+ return adapter || new ConsoleLogger({
1080
+ level: cfg.logLevel,
1081
+ pretty: cfg.env !== "production"
1082
+ });
1083
+ });
1084
+ var _store = port(function store(adapter) {
1085
+ return _nullishCoalesce(adapter, () => ( new InMemoryStore()));
1086
+ });
1087
+ var store2 = ((adapter) => {
1088
+ return _nullishCoalesce(_optionalChain([current_ports, 'call', _63 => _63(), 'optionalAccess', _64 => _64.store]), () => ( _store(adapter)));
1089
+ });
1090
+ var _cache = port(function cache(adapter) {
1091
+ return _nullishCoalesce(adapter, () => ( new InMemoryCache()));
1092
+ });
1093
+ var cache2 = ((adapter) => {
1094
+ return _nullishCoalesce(_optionalChain([current_ports, 'call', _65 => _65(), 'optionalAccess', _66 => _66.cache]), () => ( _cache(adapter)));
1095
+ });
1096
+ var default_scope = () => DEFAULT_SCOPE;
1097
+ var DEFAULT_SCOPE = {
1098
+ get store() {
1099
+ return _store();
1100
+ },
1101
+ get cache() {
1102
+ return _cache();
1103
+ }
1104
+ };
1105
+ async function disposeAndExit(code = "EXIT") {
1106
+ if (code === "ERROR" && config().env === "production") {
1107
+ log().warn(
1108
+ "disposeAndExit('ERROR') ignored in production \u2014 process kept alive"
1109
+ );
1110
+ return;
1111
+ }
1112
+ await run_disposers();
1113
+ for (const adapter of [...adapters.values()].reverse()) {
1114
+ await adapter.dispose();
1115
+ log().info(`[act] - ${adapter.constructor.name}`);
1116
+ }
1117
+ adapters.clear();
1118
+ config().env !== "test" && process.exit(code === "ERROR" ? 1 : 0);
1119
+ }
1120
+ function dispose(disposer) {
1121
+ disposer && register_disposer(disposer);
1122
+ return disposeAndExit;
1123
+ }
1124
+
1125
+ // src/config.ts
1126
+ var PackageSchema = _zod.z.object({
1127
+ name: _zod.z.string().min(1),
1128
+ version: _zod.z.string().min(1),
1129
+ description: _zod.z.string().min(1).optional(),
1130
+ author: _zod.z.object({ name: _zod.z.string().min(1), email: _zod.z.string().optional() }).optional().or(_zod.z.string().min(1)).optional(),
1131
+ license: _zod.z.string().min(1).optional(),
1132
+ dependencies: _zod.z.record(_zod.z.string(), _zod.z.string()).optional()
1133
+ });
1134
+ var FALLBACK_PACKAGE = {
1135
+ name: "act-fallback",
1136
+ version: "0.0.0-fallback",
1137
+ description: "Synthetic fallback \u2014 package.json could not be loaded"
1138
+ };
1139
+ var get_package = () => {
1140
+ try {
1141
+ const raw = JSON.parse(fs.readFileSync("package.json").toString());
1142
+ const pkg2 = {
1143
+ name: FALLBACK_PACKAGE.name,
1144
+ version: FALLBACK_PACKAGE.version
1145
+ };
1146
+ for (const [key, schema] of Object.entries(PackageSchema.shape)) {
1147
+ const field = schema.safeParse(_optionalChain([raw, 'optionalAccess', _67 => _67[key]]));
1148
+ if (field.success && field.data !== void 0) pkg2[key] = field.data;
1149
+ }
1150
+ return pkg2;
1151
+ } catch (err) {
1152
+ pkg_load_error = err;
1153
+ return FALLBACK_PACKAGE;
1154
+ }
1155
+ };
1156
+ var pkg_load_error;
1157
+ var BaseSchema = PackageSchema.extend({
1158
+ env: _zod.z.enum(_chunkNNWP65YMcjs.Environments),
1159
+ logLevel: _zod.z.enum(_chunkNNWP65YMcjs.LogLevels),
1160
+ logSingleLine: _zod.z.boolean(),
1161
+ sleepMs: _zod.z.number().int().min(0).max(5e3)
1162
+ });
1163
+ var { NODE_ENV, LOG_LEVEL, LOG_SINGLE_LINE, SLEEP_MS } = process.env;
1164
+ var env = NODE_ENV || "development";
1165
+ var logLevel = LOG_LEVEL || (NODE_ENV === "test" ? "fatal" : NODE_ENV === "production" ? "info" : "trace");
1166
+ var logSingleLine = (LOG_SINGLE_LINE || "true") === "true";
1167
+ var sleepMs = parseInt(NODE_ENV === "test" ? "0" : _nullishCoalesce(SLEEP_MS, () => ( "100")), 10);
1168
+ var pkg = get_package();
1169
+ var _validated;
1170
+ var config = () => {
1171
+ if (!_validated) {
1172
+ _validated = extend(
1173
+ { ...pkg, env, logLevel, logSingleLine, sleepMs },
1174
+ BaseSchema
1175
+ );
1176
+ if (pkg_load_error) {
1177
+ const msg = pkg_load_error instanceof Error ? pkg_load_error.message : typeof pkg_load_error === "string" ? pkg_load_error : "unknown error";
1178
+ log().warn(
1179
+ `[act] Could not read package.json (${msg}); using synthetic name="${FALLBACK_PACKAGE.name}" version="${FALLBACK_PACKAGE.version}".`
1180
+ );
1181
+ pkg_load_error = void 0;
1182
+ }
1183
+ }
1184
+ return _validated;
1185
+ };
1186
+ function resolveAutocloseConfig2(options) {
1187
+ return resolveAutocloseConfig(options);
1188
+ }
1189
+
1190
+
1191
+
1192
+
1193
+
1194
+
1195
+
1196
+
1197
+
1198
+
1199
+
1200
+
1201
+
1202
+
1203
+
1204
+
1205
+
1206
+
1207
+
1208
+
1209
+
1210
+
1211
+
1212
+
1213
+
1214
+
1215
+
1216
+
1217
+
1218
+
1219
+
1220
+
1221
+
1222
+
1223
+
1224
+
1225
+
1226
+
1227
+
1228
+
1229
+
1230
+
1231
+
1232
+ exports.ConsoleLogger = ConsoleLogger; exports.LruMap = LruMap; exports.InMemoryCache = InMemoryCache; exports.DEFAULT_BACKOFF = DEFAULT_BACKOFF; exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES; exports.DEFAULT_BLOCK_ON_ERROR = DEFAULT_BLOCK_ON_ERROR; exports.resolveReactionConfig = resolveReactionConfig; exports.resolveActionConfig = resolveActionConfig; exports.resolveLaneConfig = resolveLaneConfig; exports.DEFAULT_STREAM_LIMIT = DEFAULT_STREAM_LIMIT; exports.DEFAULT_EVENT_LIMIT = DEFAULT_EVENT_LIMIT; exports.DEFAULT_LEASE_MILLIS = DEFAULT_LEASE_MILLIS; exports.resolveDrainConfig = resolveDrainConfig; exports.resolveSettleConfig = resolveSettleConfig; exports.MAX_SHUTDOWN_GRACE_MS = MAX_SHUTDOWN_GRACE_MS; exports.resolveShutdownConfig = resolveShutdownConfig; exports.resolveActConfig = resolveActConfig; exports.resolveAutocloseConfig = resolveAutocloseConfig; exports.resolveCircuitBreakerConfig = resolveCircuitBreakerConfig; exports.resolveFoldConfig = resolveFoldConfig; exports.PackageSchema = PackageSchema; exports.config = config; exports.resolveAutocloseConfig2 = resolveAutocloseConfig2; exports.validate = validate; exports.extend = extend; exports.sleep = sleep; exports.is_literal_source = is_literal_source; exports.dateReviver = dateReviver; exports.InMemoryStore = InMemoryStore; exports.register_weak_disposer = register_weak_disposer; exports.make_run_scoped = make_run_scoped; exports.current_autoclose_window = current_autoclose_window; exports.current_reacting = current_reacting; exports.make_reaction_scope = make_reaction_scope; exports.port = port; exports.log = log; exports.store = store2; exports.cache = cache2; exports.default_scope = default_scope; exports.disposeAndExit = disposeAndExit; exports.dispose = dispose;
1233
+ //# sourceMappingURL=chunk-YKL44PYX.cjs.map