pending-task-kit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,705 @@
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 __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ DEFAULT_MAX_FAILURE_COUNT: () => DEFAULT_MAX_FAILURE_COUNT,
24
+ DEFAULT_POLL_INTERVAL_MS: () => DEFAULT_POLL_INTERVAL_MS,
25
+ DEFAULT_POLL_LEASE_TTL_MULTIPLIER: () => DEFAULT_POLL_LEASE_TTL_MULTIPLIER,
26
+ DEFAULT_POLL_TICK_MS: () => DEFAULT_POLL_TICK_MS,
27
+ DEFAULT_RESULT_EVENT: () => DEFAULT_RESULT_EVENT,
28
+ DEFAULT_STORAGE_KEY: () => DEFAULT_STORAGE_KEY,
29
+ DEFAULT_TTL_MS: () => DEFAULT_TTL_MS,
30
+ PendingTaskPoller: () => PendingTaskPoller,
31
+ clearResultRelay: () => clearResultRelay,
32
+ createPendingTaskRegistryBinding: () => createPendingTaskRegistryBinding,
33
+ createPendingTaskStore: () => createPendingTaskStore,
34
+ createPollLeaseClaimer: () => createPollLeaseClaimer,
35
+ createTtlDedupeCache: () => createTtlDedupeCache,
36
+ generatePollOwnerId: () => generatePollOwnerId,
37
+ isPendingTaskShape: () => isPendingTaskShape,
38
+ parseResultRelay: () => parseResultRelay,
39
+ parseTasksFromStorageValue: () => parseTasksFromStorageValue,
40
+ withTabLock: () => withTabLock,
41
+ writeResultRelay: () => writeResultRelay
42
+ });
43
+ module.exports = __toCommonJS(src_exports);
44
+
45
+ // src/store.ts
46
+ var import_zustand = require("zustand");
47
+ var import_middleware = require("zustand/middleware");
48
+ var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
49
+ var DEFAULT_STORAGE_KEY = "pending-tasks";
50
+ function isPendingTaskShape(value) {
51
+ if (!value || typeof value !== "object") return false;
52
+ const t = value;
53
+ return typeof t.id === "string" && typeof t.type === "string" && typeof t.startedAt === "number" && (typeof t.taskId === "number" || typeof t.taskId === "string");
54
+ }
55
+ function parseTasksFromStorageValue(value) {
56
+ if (!value) return [];
57
+ try {
58
+ const parsed = JSON.parse(value);
59
+ const tasks = parsed?.state?.tasks;
60
+ if (!Array.isArray(tasks)) return [];
61
+ return tasks.filter(isPendingTaskShape);
62
+ } catch {
63
+ return [];
64
+ }
65
+ }
66
+ function readPersistedTasks(storageKey) {
67
+ if (typeof localStorage === "undefined") return [];
68
+ return parseTasksFromStorageValue(localStorage.getItem(storageKey));
69
+ }
70
+ function createPendingTaskStore(options = {}) {
71
+ const storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;
72
+ const readPersisted = () => readPersistedTasks(storageKey);
73
+ const writeTasks = (tasks) => {
74
+ try {
75
+ useStore.setState({ tasks });
76
+ useStore.hasUnpersistedWrites = false;
77
+ } catch {
78
+ useStore.hasUnpersistedWrites = true;
79
+ }
80
+ };
81
+ const useStore = (0, import_zustand.create)()(
82
+ (0, import_middleware.persist)(
83
+ (_set, get) => {
84
+ const base = () => useStore.hasUnpersistedWrites ? get().tasks : readPersisted();
85
+ return {
86
+ tasks: [],
87
+ addTask: (task) => {
88
+ const next = base().filter((t) => t.id !== task.id);
89
+ next.push(task);
90
+ writeTasks(next);
91
+ },
92
+ removeTask: (id) => {
93
+ writeTasks(base().filter((t) => t.id !== id));
94
+ },
95
+ updateTask: (id, patch) => {
96
+ writeTasks(base().map((t) => t.id === id ? { ...t, ...patch } : t));
97
+ },
98
+ pruneTasksBy: (predicate) => {
99
+ writeTasks(base().filter(predicate));
100
+ },
101
+ clearAllTasks: () => writeTasks([])
102
+ };
103
+ },
104
+ {
105
+ name: storageKey,
106
+ storage: (0, import_middleware.createJSONStorage)(() => localStorage),
107
+ partialize: (state) => ({ tasks: state.tasks })
108
+ }
109
+ )
110
+ );
111
+ useStore.storageKey = storageKey;
112
+ useStore.hasUnpersistedWrites = false;
113
+ useStore.writeTasks = writeTasks;
114
+ return useStore;
115
+ }
116
+
117
+ // src/registry.ts
118
+ function createPendingTaskRegistryBinding(store, registry) {
119
+ function addTask(task) {
120
+ const handler = registry[task.type];
121
+ const ttlMs = handler?.ttlMs;
122
+ const withTtl = ttlMs === void 0 ? task : { ...task, ttlMs };
123
+ store.getState().addTask(withTtl);
124
+ }
125
+ function addTaskIfMissing(task) {
126
+ const existsInMemory = store.getState().tasks.some((t) => t.id === task.id);
127
+ const existsPersisted = !store.hasUnpersistedWrites && readPersistedTasks(store.storageKey).some((t) => t.id === task.id);
128
+ if (!existsInMemory && !existsPersisted) {
129
+ addTask(task);
130
+ }
131
+ }
132
+ return { addTask, addTaskIfMissing };
133
+ }
134
+
135
+ // src/safe-storage.ts
136
+ function safeGetItem(key) {
137
+ try {
138
+ if (typeof localStorage === "undefined") return null;
139
+ return localStorage.getItem(key);
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+ function safeSetItem(key, value) {
145
+ try {
146
+ if (typeof localStorage === "undefined") return false;
147
+ localStorage.setItem(key, value);
148
+ return true;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ function safeRemoveItem(key) {
154
+ try {
155
+ if (typeof localStorage === "undefined") return;
156
+ localStorage.removeItem(key);
157
+ } catch {
158
+ }
159
+ }
160
+
161
+ // src/poll-lease.ts
162
+ function readLease(storageKey) {
163
+ const raw = safeGetItem(storageKey);
164
+ if (!raw) return null;
165
+ try {
166
+ const parsed = JSON.parse(raw);
167
+ if (typeof parsed.ownerId !== "string" || typeof parsed.expiresAt !== "number" || typeof parsed.fence !== "number") {
168
+ return null;
169
+ }
170
+ return parsed;
171
+ } catch {
172
+ return null;
173
+ }
174
+ }
175
+ function writeLease(storageKey, lease) {
176
+ safeSetItem(storageKey, JSON.stringify(lease));
177
+ }
178
+ function createPollLeaseClaimer(storageKey, ttlMs) {
179
+ if (ttlMs <= 0 && typeof console !== "undefined") {
180
+ console.warn(`pending-task-kit: pollLeaseTtlMs must be positive, got ${ttlMs}`);
181
+ }
182
+ return {
183
+ claim(ownerId) {
184
+ const current = readLease(storageKey);
185
+ const now = Date.now();
186
+ if (current && current.ownerId !== ownerId && current.expiresAt > now) {
187
+ return { leader: false };
188
+ }
189
+ const isRenewal = current !== null && current.ownerId === ownerId && current.expiresAt > now;
190
+ const fence = isRenewal ? current.fence : (current?.fence ?? 0) + 1;
191
+ writeLease(storageKey, { ownerId, fence, expiresAt: now + ttlMs });
192
+ return { leader: true, fence };
193
+ },
194
+ release(ownerId) {
195
+ const current = readLease(storageKey);
196
+ if (current?.ownerId === ownerId) {
197
+ writeLease(storageKey, { ownerId, fence: current.fence, expiresAt: 0 });
198
+ }
199
+ }
200
+ };
201
+ }
202
+ function generatePollOwnerId() {
203
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
204
+ return crypto.randomUUID();
205
+ }
206
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
207
+ }
208
+
209
+ // src/result-relay.ts
210
+ var RESULT_STATUSES = [
211
+ "success",
212
+ "failure",
213
+ "error",
214
+ "expired"
215
+ ];
216
+ function isResultStatus(value) {
217
+ return typeof value === "string" && RESULT_STATUSES.includes(value);
218
+ }
219
+ function writeResultRelay(storageKey, detail) {
220
+ try {
221
+ const serialized = JSON.stringify(detail);
222
+ safeSetItem(storageKey, serialized);
223
+ } catch {
224
+ }
225
+ }
226
+ function parseResultRelay(value) {
227
+ if (!value) return null;
228
+ try {
229
+ const parsed = JSON.parse(value);
230
+ if (!isPendingTaskShape(parsed.task) || !isResultStatus(parsed.status)) {
231
+ return null;
232
+ }
233
+ return parsed;
234
+ } catch {
235
+ return null;
236
+ }
237
+ }
238
+ function clearResultRelay(storageKey) {
239
+ safeRemoveItem(storageKey);
240
+ }
241
+
242
+ // src/tab-lock.ts
243
+ async function withTabLock(name, operation) {
244
+ const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
245
+ if (!locks) {
246
+ return operation();
247
+ }
248
+ return locks.request(name, async () => operation());
249
+ }
250
+
251
+ // src/engine.ts
252
+ var DEFAULT_POLL_TICK_MS = 2e3;
253
+ var DEFAULT_POLL_INTERVAL_MS = 1e4;
254
+ var DEFAULT_MAX_FAILURE_COUNT = 5;
255
+ var DEFAULT_RESULT_EVENT = "pending-task-result";
256
+ var DEFAULT_POLL_LEASE_TTL_MULTIPLIER = 4;
257
+ function describeError(error) {
258
+ if (error instanceof Error) return error.message;
259
+ return typeof error === "string" ? error : "Unknown error";
260
+ }
261
+ var PendingTaskPoller = class {
262
+ constructor(options) {
263
+ this.isChecking = false;
264
+ this.pendingForce = false;
265
+ this.stopped = false;
266
+ /** Task ids that already got their one `finalCheckOnExpiry` attempt, so a repeatedly-failing
267
+ * final check doesn't get retried every tick. Reset on process restart — worst case that
268
+ * costs one extra check, never an infinite retry loop.
269
+ *
270
+ * Every id added here (only when a task is expired, right before its final `check()`) is
271
+ * removed again before the *same* tick's iteration moves past that task — either by
272
+ * `finalize()`'s first line, or by one of the leadership-loss/`onCheckError`-intercept
273
+ * branches that bail out without ever reaching `finalize()`. Nothing here is meant to
274
+ * survive past the tick that added it. */
275
+ this.finalCheckAttempted = /* @__PURE__ */ new Set();
276
+ const storageKey = options.storageKey ?? options.store.storageKey ?? DEFAULT_STORAGE_KEY;
277
+ const pollTickMs = options.pollTickMs ?? DEFAULT_POLL_TICK_MS;
278
+ this.options = {
279
+ store: options.store,
280
+ registry: options.registry,
281
+ pollTickMs,
282
+ defaultPollIntervalMs: options.defaultPollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,
283
+ defaultTtlMs: options.defaultTtlMs ?? DEFAULT_TTL_MS,
284
+ maxFailureCount: options.maxFailureCount ?? DEFAULT_MAX_FAILURE_COUNT,
285
+ dispatchDomEvent: options.dispatchDomEvent ?? typeof window !== "undefined",
286
+ eventName: options.eventName ?? DEFAULT_RESULT_EVENT,
287
+ storageKey,
288
+ crossTabPollLeaderElection: options.crossTabPollLeaderElection ?? true,
289
+ pollLeaseKey: options.pollLeaseKey ?? `${storageKey}-poll-leader`,
290
+ pollLeaseTtlMs: options.pollLeaseTtlMs ?? pollTickMs * DEFAULT_POLL_LEASE_TTL_MULTIPLIER,
291
+ resultRelayKey: options.resultRelayKey ?? `${storageKey}-result-relay`,
292
+ onResult: options.onResult,
293
+ onCheckError: options.onCheckError,
294
+ claimResultOnce: options.claimResultOnce,
295
+ acceptRelayedResult: options.acceptRelayedResult
296
+ };
297
+ this.ownerId = generatePollOwnerId();
298
+ this.pollLease = createPollLeaseClaimer(this.options.pollLeaseKey, this.options.pollLeaseTtlMs);
299
+ }
300
+ start() {
301
+ this.stopped = false;
302
+ if (this.intervalId !== void 0) return;
303
+ this.intervalId = setInterval(() => {
304
+ this.runTickSafely(false);
305
+ }, this.options.pollTickMs);
306
+ if (typeof window !== "undefined") {
307
+ this.storageListener = (event) => {
308
+ if (event.key === null) {
309
+ this.options.store.writeTasks([]);
310
+ return;
311
+ }
312
+ if (event.key === this.options.storageKey) {
313
+ this.options.store.writeTasks(parseTasksFromStorageValue(event.newValue));
314
+ return;
315
+ }
316
+ if (this.options.crossTabPollLeaderElection && event.key === this.options.resultRelayKey) {
317
+ const detail = parseResultRelay(event.newValue);
318
+ if (!detail) return;
319
+ let accepted;
320
+ try {
321
+ accepted = this.options.acceptRelayedResult?.(detail) ?? true;
322
+ } catch (error) {
323
+ queueMicrotask(() => {
324
+ throw error;
325
+ });
326
+ return;
327
+ }
328
+ if (accepted) void this.dispatchRelayedResult(detail);
329
+ }
330
+ };
331
+ window.addEventListener("storage", this.storageListener);
332
+ }
333
+ this.runTickSafely(false);
334
+ }
335
+ stop() {
336
+ this.stopped = true;
337
+ this.pendingForce = false;
338
+ if (this.intervalId !== void 0) {
339
+ clearInterval(this.intervalId);
340
+ this.intervalId = void 0;
341
+ }
342
+ if (this.storageListener && typeof window !== "undefined") {
343
+ window.removeEventListener("storage", this.storageListener);
344
+ this.storageListener = void 0;
345
+ }
346
+ if (this.options.crossTabPollLeaderElection) {
347
+ void this.releaseLeadership().catch(() => void 0);
348
+ }
349
+ }
350
+ /** Re-check every tracked task right now, bypassing each task's poll interval (e.g. on tab focus). */
351
+ forceCheckAll() {
352
+ this.runTickSafely(true);
353
+ }
354
+ claimLeadership() {
355
+ return withTabLock(this.options.pollLeaseKey, () => this.pollLease.claim(this.ownerId));
356
+ }
357
+ /**
358
+ * Re-confirms that poll leadership is still this tab's — and still the *same continuous
359
+ * tenure* as when `fence` was captured, not just "is nobody else currently holding it" (a
360
+ * no-op returning `fence` unchanged when `crossTabPollLeaderElection` is off). Clears `task`'s
361
+ * `finalCheckAttempted` bookkeeping and returns `false` if not — the caller should stop
362
+ * treating this tick's remaining due tasks as network-eligible (though it may still process
363
+ * ones that need no leadership) rather than act on a possibly-stale outcome.
364
+ *
365
+ * A fence mismatch (rather than just an owner-id mismatch) is needed to catch leadership
366
+ * having churned through another tab and back to this one while a slow `handler.check()` was
367
+ * in flight: this tab's lease can expire mid-check, another tab claims it and fully resolves
368
+ * the same task, and that tab's own lease can *also* expire before this tab's stale response
369
+ * comes back — at which point this tab's next claim legitimately succeeds under its own
370
+ * stable owner id (nothing currently holds the lease), even though leadership genuinely
371
+ * changed hands in between. See `PollLeaseClaimResult`.
372
+ */
373
+ async reconfirmLeadership(task, expired, fence) {
374
+ if (!this.options.crossTabPollLeaderElection) return fence;
375
+ if (this.stopped) {
376
+ if (expired) this.finalCheckAttempted.delete(task.id);
377
+ return false;
378
+ }
379
+ let result;
380
+ try {
381
+ result = await this.claimLeadership();
382
+ } catch (error) {
383
+ if (expired) this.finalCheckAttempted.delete(task.id);
384
+ throw error;
385
+ }
386
+ if (result.leader && result.fence === fence) return result.fence;
387
+ if (expired) this.finalCheckAttempted.delete(task.id);
388
+ return false;
389
+ }
390
+ releaseLeadership() {
391
+ return withTabLock(this.options.pollLeaseKey, () => {
392
+ this.pollLease.release(this.ownerId);
393
+ });
394
+ }
395
+ /** Fires `runTick`, but instead of leaving its promise `void`-called (which would turn an
396
+ * exception thrown by a consumer callback — `onResult`, `onCheckError`, or a `dispatchEvent`
397
+ * listener — into a silent unhandled rejection), re-throws it as an uncaught exception on a
398
+ * fresh microtask. `runTick`'s own `finally` has already flushed the batch and reset
399
+ * `isChecking` by the time this ever runs, so a broken consumer callback can't take the
400
+ * poller down — it just becomes visible the way any other uncaught error in the host
401
+ * environment would be, instead of vanishing. */
402
+ runTickSafely(force) {
403
+ this.runTick(force).catch((error) => {
404
+ queueMicrotask(() => {
405
+ throw error;
406
+ });
407
+ });
408
+ }
409
+ /** Reads the freshest snapshot of `task` from the store, in case another tab wrote to it
410
+ * while this tab's `handler.check()` was in flight — narrows, but doesn't eliminate, the
411
+ * window where a concurrent cross-tab write to the same task could be clobbered.
412
+ *
413
+ * Indexes `store.getState().tasks` into a Map keyed by id rather than doing a linear find
414
+ * each call — this is called once per pending/failing task per tick, so a plain find would
415
+ * make a tick O(n²). The cache keys off the `tasks` array reference, which zustand only
416
+ * replaces on an actual write, so it's rebuilt only when the store has genuinely changed. */
417
+ getLatestTask(task) {
418
+ const tasks = this.options.store.getState().tasks;
419
+ if (this.latestTasksCache?.tasks !== tasks) {
420
+ this.latestTasksCache = { tasks, byId: new Map(tasks.map((t) => [t.id, t])) };
421
+ }
422
+ return this.latestTasksCache.byId.get(task.id) ?? task;
423
+ }
424
+ /** Applies a whole tick's worth of per-task updates/removals (`patch: null` means "remove")
425
+ * in a single read-modify-write, instead of one persisted-storage round trip per task.
426
+ * Reads the freshest persisted list right before writing (same "never resurrect a task
427
+ * another tab already removed" guarantee `PendingTaskStore`'s own mutators give) — unless
428
+ * the store's `hasUnpersistedWrites` is set (a write on *any* path for this store, including
429
+ * this store's own direct mutators, failed and hasn't yet been followed by a success), in
430
+ * which case persisted storage is stale relative to this tab's memory, so this flush builds
431
+ * on `store.getState().tasks` instead. Writes through `writeTasks`, which swallows a
432
+ * throwing write and updates that same shared flag — see the comment in `store.ts`. */
433
+ flushBatch(batch) {
434
+ if (batch.size === 0) return;
435
+ const base = this.options.store.hasUnpersistedWrites ? this.options.store.getState().tasks : readPersistedTasks(this.options.storageKey);
436
+ const next = [];
437
+ for (const t of base) {
438
+ if (!batch.has(t.id)) {
439
+ next.push(t);
440
+ continue;
441
+ }
442
+ const patch = batch.get(t.id);
443
+ if (patch !== null) next.push({ ...t, ...patch });
444
+ }
445
+ this.options.store.writeTasks(next);
446
+ }
447
+ async finalize(task, detail, handler, batch) {
448
+ this.finalCheckAttempted.delete(task.id);
449
+ batch.set(task.id, null);
450
+ if (detail.status === "expired") return;
451
+ const silent = detail.status === "success" ? handler?.silentOnSuccess : handler?.silentOnFailure;
452
+ if (silent) return;
453
+ let claimed;
454
+ try {
455
+ claimed = this.options.claimResultOnce ? await this.options.claimResultOnce(task) : true;
456
+ } catch {
457
+ return;
458
+ }
459
+ if (!claimed) return;
460
+ const fullDetail = { task, ...detail };
461
+ if (this.options.crossTabPollLeaderElection) {
462
+ writeResultRelay(this.options.resultRelayKey, fullDetail);
463
+ }
464
+ this.options.onResult?.(fullDetail);
465
+ if (this.options.dispatchDomEvent && typeof window !== "undefined") {
466
+ window.dispatchEvent(new CustomEvent(this.options.eventName, { detail: fullDetail }));
467
+ }
468
+ }
469
+ /**
470
+ * Handles a result relayed from another tab's leader — mirrors finalize()'s own
471
+ * `claimResultOnce` gate and dispatch, so a `claimResultOnce` composed for "one notification
472
+ * system-wide" (see its doc comment's "keep both if you want both properties") applies
473
+ * uniformly whether this tab detected the result itself or only learned about it via the
474
+ * relay, not just to the narrower direct-detection race `claimResultOnce` guarded before this
475
+ * relay existed.
476
+ *
477
+ * Fired-and-forgotten (`void`-called) from the "storage" listener rather than awaited, so it
478
+ * has no `this.stopped` check of its own: `stop()` removes the listener (no *new* relayed
479
+ * result starts one of these after that), but one already in flight when `stop()` is called
480
+ * (e.g. awaiting a slow `claimResultOnce`) still runs to completion — the same tolerance
481
+ * `runTick`'s own doc comment describes for an in-flight tick.
482
+ */
483
+ async dispatchRelayedResult(detail) {
484
+ let claimed;
485
+ try {
486
+ claimed = this.options.claimResultOnce ? await this.options.claimResultOnce(detail.task) : true;
487
+ } catch {
488
+ return;
489
+ }
490
+ if (!claimed) return;
491
+ try {
492
+ this.options.onResult?.(detail);
493
+ if (this.options.dispatchDomEvent && typeof window !== "undefined") {
494
+ window.dispatchEvent(new CustomEvent(this.options.eventName, { detail }));
495
+ }
496
+ } catch (error) {
497
+ queueMicrotask(() => {
498
+ throw error;
499
+ });
500
+ }
501
+ }
502
+ async runTick(force) {
503
+ if (this.stopped) return;
504
+ if (this.isChecking) {
505
+ this.pendingForce = this.pendingForce || force;
506
+ return;
507
+ }
508
+ const tasks = this.options.store.getState().tasks;
509
+ if (tasks.length === 0) return;
510
+ this.isChecking = true;
511
+ const batch = /* @__PURE__ */ new Map();
512
+ try {
513
+ const now = Date.now();
514
+ let fence;
515
+ let leadershipLost = false;
516
+ for (const task of tasks) {
517
+ const handler = this.options.registry[task.type];
518
+ const ttlMs = task.ttlMs ?? this.options.defaultTtlMs;
519
+ const expired = now - task.startedAt >= ttlMs;
520
+ if (!handler) {
521
+ if (expired) {
522
+ await this.finalize(task, { status: "expired" }, handler, batch);
523
+ }
524
+ continue;
525
+ }
526
+ const interval = handler.pollIntervalMs ?? this.options.defaultPollIntervalMs;
527
+ const lastChecked = task.lastCheckedAt ?? task.startedAt;
528
+ const due = force || now - lastChecked >= interval;
529
+ const finalAttemptDone = this.finalCheckAttempted.has(task.id);
530
+ if (expired && (!handler.finalCheckOnExpiry || finalAttemptDone)) {
531
+ await this.finalize(task, { status: "expired" }, handler, batch);
532
+ continue;
533
+ }
534
+ if (!due && !expired) continue;
535
+ if (expired) {
536
+ this.finalCheckAttempted.add(task.id);
537
+ }
538
+ if (this.options.crossTabPollLeaderElection) {
539
+ if (leadershipLost || this.stopped) {
540
+ leadershipLost = true;
541
+ if (expired) this.finalCheckAttempted.delete(task.id);
542
+ continue;
543
+ }
544
+ if (fence === void 0) {
545
+ let claimed;
546
+ try {
547
+ claimed = await this.claimLeadership();
548
+ } catch (error) {
549
+ if (expired) this.finalCheckAttempted.delete(task.id);
550
+ throw error;
551
+ }
552
+ if (!claimed.leader) {
553
+ leadershipLost = true;
554
+ if (expired) this.finalCheckAttempted.delete(task.id);
555
+ continue;
556
+ }
557
+ fence = claimed.fence;
558
+ }
559
+ }
560
+ let result;
561
+ try {
562
+ result = await handler.check(task);
563
+ } catch (error) {
564
+ const reconfirmedOnError = await this.reconfirmLeadership(task, expired, fence);
565
+ if (reconfirmedOnError === false) {
566
+ leadershipLost = true;
567
+ fence = void 0;
568
+ continue;
569
+ }
570
+ fence = reconfirmedOnError;
571
+ let intercepted;
572
+ try {
573
+ intercepted = this.options.onCheckError?.(error, task);
574
+ } catch (onCheckErrorError) {
575
+ queueMicrotask(() => {
576
+ throw onCheckErrorError;
577
+ });
578
+ intercepted = false;
579
+ }
580
+ if (intercepted) {
581
+ batch.set(task.id, { lastCheckedAt: now });
582
+ this.finalCheckAttempted.delete(task.id);
583
+ break;
584
+ }
585
+ if (expired) {
586
+ await this.finalize(task, { status: "expired" }, handler, batch);
587
+ continue;
588
+ }
589
+ const latest = this.getLatestTask(task);
590
+ const failureCount = (latest.failureCount ?? 0) + 1;
591
+ if (failureCount >= this.options.maxFailureCount) {
592
+ await this.finalize(task, { status: "error", data: describeError(error) }, handler, batch);
593
+ } else {
594
+ batch.set(task.id, { lastCheckedAt: now, failureCount });
595
+ }
596
+ continue;
597
+ }
598
+ const reconfirmedOnSuccess = await this.reconfirmLeadership(task, expired, fence);
599
+ if (reconfirmedOnSuccess === false) {
600
+ leadershipLost = true;
601
+ fence = void 0;
602
+ continue;
603
+ }
604
+ fence = reconfirmedOnSuccess;
605
+ if (result.status === "pending") {
606
+ const latest = this.getLatestTask(task);
607
+ batch.set(task.id, {
608
+ lastCheckedAt: now,
609
+ failureCount: 0,
610
+ metadata: { ...latest.metadata, ...result.progress }
611
+ });
612
+ if (expired) {
613
+ await this.finalize(task, { status: "expired" }, handler, batch);
614
+ }
615
+ continue;
616
+ }
617
+ await this.finalize(task, { status: result.status, data: result.data }, handler, batch);
618
+ }
619
+ } finally {
620
+ this.flushBatch(batch);
621
+ this.isChecking = false;
622
+ if (this.pendingForce && !this.stopped) {
623
+ this.pendingForce = false;
624
+ this.runTickSafely(true);
625
+ }
626
+ }
627
+ }
628
+ };
629
+
630
+ // src/ttl-dedupe-cache.ts
631
+ function createTtlDedupeCache(storageKey, ttlMs) {
632
+ const read = () => {
633
+ const raw = safeGetItem(storageKey);
634
+ if (!raw) return {};
635
+ try {
636
+ const parsed = JSON.parse(raw);
637
+ return parsed && typeof parsed === "object" ? parsed : {};
638
+ } catch {
639
+ return {};
640
+ }
641
+ };
642
+ const write = (state) => {
643
+ safeSetItem(storageKey, JSON.stringify(Object.fromEntries(state)));
644
+ };
645
+ const prune = (state, now) => {
646
+ const next = /* @__PURE__ */ new Map();
647
+ for (const [id, entry] of Object.entries(state)) {
648
+ if (now - entry.claimedAt < ttlMs) {
649
+ next.set(id, entry);
650
+ }
651
+ }
652
+ return next;
653
+ };
654
+ return {
655
+ /** Returns true the first time `id` is claimed within the TTL window, false on any repeat. */
656
+ claim(id) {
657
+ const now = Date.now();
658
+ const state = prune(read(), now);
659
+ if (state.has(id)) {
660
+ write(state);
661
+ return false;
662
+ }
663
+ state.set(id, { claimedAt: now });
664
+ write(state);
665
+ return true;
666
+ },
667
+ /** Wipes every claim this cache holds — e.g. on explicit user logout, if `id`s (or
668
+ * whatever metadata a caller's own claim wrapper attaches alongside them) can carry PII.
669
+ * Unlike `claim`, this doesn't need TTL pruning first: it removes the whole entry
670
+ * regardless of age.
671
+ *
672
+ * Best-effort, not atomic with a concurrent `claim()` in another tab: like every other
673
+ * primitive in this package, this is a plain, unlocked read-modify-write (`claim` reads,
674
+ * then this removes), so a `claim()` in another tab that read its state just before this
675
+ * call's removal lands can write that stale state back afterwards, resurrecting the very
676
+ * claim this call meant to wipe. Compose your own `withTabLock` around both calls if a
677
+ * logout-time clear must be atomic with respect to a claim that could race it. */
678
+ clear() {
679
+ safeRemoveItem(storageKey);
680
+ }
681
+ };
682
+ }
683
+ // Annotate the CommonJS export names for ESM import in node:
684
+ 0 && (module.exports = {
685
+ DEFAULT_MAX_FAILURE_COUNT,
686
+ DEFAULT_POLL_INTERVAL_MS,
687
+ DEFAULT_POLL_LEASE_TTL_MULTIPLIER,
688
+ DEFAULT_POLL_TICK_MS,
689
+ DEFAULT_RESULT_EVENT,
690
+ DEFAULT_STORAGE_KEY,
691
+ DEFAULT_TTL_MS,
692
+ PendingTaskPoller,
693
+ clearResultRelay,
694
+ createPendingTaskRegistryBinding,
695
+ createPendingTaskStore,
696
+ createPollLeaseClaimer,
697
+ createTtlDedupeCache,
698
+ generatePollOwnerId,
699
+ isPendingTaskShape,
700
+ parseResultRelay,
701
+ parseTasksFromStorageValue,
702
+ withTabLock,
703
+ writeResultRelay
704
+ });
705
+ //# sourceMappingURL=index.cjs.map