@fantastic.dev/better-stripe 0.94.0 → 0.95.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 (89) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts +6 -0
  4. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/operationJournal.js +10 -0
  6. package/dist/client/billing/renewalAttach/internal/operationJournal.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +5 -0
  8. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +40 -0
  10. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts +13 -0
  12. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js +43 -0
  14. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts +32 -0
  16. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +102 -0
  18. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.d.ts +3 -0
  20. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.js +59 -0
  22. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.d.ts +11 -0
  24. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js +132 -0
  26. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts +6 -0
  28. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js +16 -0
  30. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js.map +1 -0
  31. package/dist/client/billing/renewalObservation/evidence-invoice-lines.d.ts +27 -0
  32. package/dist/client/billing/renewalObservation/evidence-invoice-lines.d.ts.map +1 -0
  33. package/dist/client/billing/renewalObservation/evidence-invoice-lines.js +164 -0
  34. package/dist/client/billing/renewalObservation/evidence-invoice-lines.js.map +1 -0
  35. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts +4 -0
  36. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts.map +1 -0
  37. package/dist/client/billing/renewalObservation/evidence-invoice.js +190 -0
  38. package/dist/client/billing/renewalObservation/evidence-invoice.js.map +1 -0
  39. package/dist/client/billing/renewalObservation/evidence-material.d.ts +26 -0
  40. package/dist/client/billing/renewalObservation/evidence-material.d.ts.map +1 -0
  41. package/dist/client/billing/renewalObservation/evidence-material.js +253 -0
  42. package/dist/client/billing/renewalObservation/evidence-material.js.map +1 -0
  43. package/dist/client/billing/renewalObservation/evidence-v1-types.d.ts +156 -0
  44. package/dist/client/billing/renewalObservation/evidence-v1-types.d.ts.map +1 -0
  45. package/dist/client/billing/renewalObservation/evidence-v1-types.js +2 -0
  46. package/dist/client/billing/renewalObservation/evidence-v1-types.js.map +1 -0
  47. package/dist/client/billing/renewalObservation/evidence-v1.d.ts +4 -0
  48. package/dist/client/billing/renewalObservation/evidence-v1.d.ts.map +1 -0
  49. package/dist/client/billing/renewalObservation/evidence-v1.js +263 -0
  50. package/dist/client/billing/renewalObservation/evidence-v1.js.map +1 -0
  51. package/dist/client/billing/renewalObservation/terminal-evidence.d.ts +17 -0
  52. package/dist/client/billing/renewalObservation/terminal-evidence.d.ts.map +1 -0
  53. package/dist/client/billing/renewalObservation/terminal-evidence.js +289 -0
  54. package/dist/client/billing/renewalObservation/terminal-evidence.js.map +1 -0
  55. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  56. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  57. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  58. package/dist/component/balanceFunding/queries.d.ts +1 -1
  59. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  60. package/dist/component/earnings/triggers.d.ts +16 -16
  61. package/dist/component/payoutRelease/queries.d.ts +2 -2
  62. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  63. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  64. package/docs/renewal-context-reads.md +28 -0
  65. package/docs/renewal-material-observation.md +50 -0
  66. package/package.json +1 -1
  67. package/src/client/billing/renewalAttach/internal/operationJournal.ts +12 -0
  68. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +59 -0
  69. package/src/client/billing/renewalAttach/internal/producer/invocationProducer.ts +58 -0
  70. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +158 -0
  71. package/src/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.ts +54 -0
  72. package/src/client/billing/renewalAttach/internal/producer/ownerFactory.ts +136 -0
  73. package/src/client/billing/renewalAttach/internal/producer/producerClock.integration.test.ts +175 -0
  74. package/src/client/billing/renewalAttach/internal/producer/producerOwner.integration.test.ts +449 -0
  75. package/src/client/billing/renewalAttach/internal/producer/stockDelegateFactory.ts +23 -0
  76. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialDeclarations.ts +5 -0
  77. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +142 -0
  78. package/src/client/billing/renewalObservation/evidence-admission.test.ts +219 -0
  79. package/src/client/billing/renewalObservation/evidence-history.test.ts +187 -0
  80. package/src/client/billing/renewalObservation/evidence-invoice-controls.test.ts +293 -0
  81. package/src/client/billing/renewalObservation/evidence-invoice-lines.ts +238 -0
  82. package/src/client/billing/renewalObservation/evidence-invoice.test.ts +177 -0
  83. package/src/client/billing/renewalObservation/evidence-invoice.ts +271 -0
  84. package/src/client/billing/renewalObservation/evidence-material.test.ts +289 -0
  85. package/src/client/billing/renewalObservation/evidence-material.ts +313 -0
  86. package/src/client/billing/renewalObservation/evidence-v1-types.ts +186 -0
  87. package/src/client/billing/renewalObservation/evidence-v1.test.ts +371 -0
  88. package/src/client/billing/renewalObservation/evidence-v1.ts +286 -0
  89. package/src/client/billing/renewalObservation/terminal-evidence.ts +379 -0
@@ -0,0 +1,58 @@
1
+ import { mintInitialLineage, readInitialLineage } from "./lineageAuthority.js";
2
+ import { ownerForInitialLineage, type InitialOwner } from "./ownerFactory.js";
3
+ import { ownedAwaitForInitialLineage } from "./ownedAwaitFactory.js";
4
+ import { stockDelegateForInitialLineage } from "./stockDelegateFactory.js";
5
+ import type { createClassActionOperationJournal } from "../operationJournal.js";
6
+
7
+ export type InitialInvocationCore = Readonly<{
8
+ owner: InitialOwner;
9
+ basisJSON: string;
10
+ delegate: ReturnType<typeof stockDelegateForInitialLineage>;
11
+ owned<T>(work: () => T | PromiseLike<T>): Promise<T>;
12
+ operationalAuthority: false;
13
+ }>;
14
+
15
+ /** Node-only private construction. Does not admit an operational runtime profile. */
16
+ export async function captureInitialInvocationCore(
17
+ call: unknown,
18
+ journal: Awaited<ReturnType<typeof createClassActionOperationJournal>>,
19
+ ): Promise<InitialInvocationCore> {
20
+ const token = mintInitialLineage(call, journal, arguments.length);
21
+ const lineage = readInitialLineage(token);
22
+ const owner = ownerForInitialLineage(token);
23
+ try {
24
+ const owned = ownedAwaitForInitialLineage(token);
25
+ const reservation = lineage.reservation;
26
+ if (!("timingPolicyJSON" in reservation))
27
+ throw Error("INITIAL_LINEAGE_UNBOUND");
28
+ const bound = await owned(() =>
29
+ journal.bindInitialBasis({
30
+ attemptId: reservation.attemptId,
31
+ policyJSON: reservation.timingPolicyJSON,
32
+ basisJSON: lineage.basisJSON,
33
+ }),
34
+ );
35
+ if (
36
+ bound.status !== "bound" ||
37
+ bound.operationId !== reservation.operationId ||
38
+ bound.initialBasis.attemptId !== reservation.attemptId ||
39
+ bound.initialBasis.sourcePayloadId !== reservation.payloadId ||
40
+ bound.initialBasis.basisJSON !== lineage.basisJSON ||
41
+ bound.initialBasis.policyJSON !== reservation.timingPolicyJSON ||
42
+ bound.initialBasis.stage !== "attach" ||
43
+ bound.initialBasis.version !== 1
44
+ )
45
+ throw Error("INITIAL_LINEAGE_UNBOUND");
46
+ owner.check();
47
+ return Object.freeze({
48
+ owner,
49
+ basisJSON: lineage.basisJSON,
50
+ owned,
51
+ delegate: stockDelegateForInitialLineage(token),
52
+ operationalAuthority: false,
53
+ });
54
+ } catch (error) {
55
+ owner.retire();
56
+ throw error;
57
+ }
58
+ }
@@ -0,0 +1,158 @@
1
+ import Stripe from "stripe";
2
+ import { types } from "node:util";
3
+ import { consumeInitialClassReservation } from "../operationJournal.js";
4
+ import { captureInitialJournalSelection } from "./classOwnedActionRoot.js";
5
+ import { canonicalInitialBasis } from "../../../../../shared/renewalOperationJournal.js";
6
+
7
+ const method = Object.getOwnPropertyDescriptor(
8
+ Stripe.prototype,
9
+ "rawRequest",
10
+ )?.value;
11
+ const u64 = 18446744073709551615n;
12
+ function stop(): never {
13
+ throw Error("INITIAL_LINEAGE_UNBOUND");
14
+ }
15
+ const ms = (value: number) => Number.isSafeInteger(value) && value >= 0;
16
+
17
+ // Only this module mints identities. Retained journal DATA cannot construct one.
18
+ class InitialLineage {}
19
+ type Lineage = Readonly<{
20
+ reservation: ReturnType<typeof consumeInitialClassReservation>["reservation"];
21
+ selection: ReturnType<typeof captureInitialJournalSelection>;
22
+ client: Stripe;
23
+ method: Stripe["rawRequest"];
24
+ basis: Readonly<{
25
+ startWallMs: number;
26
+ startNs: bigint;
27
+ workEndWallMs: number;
28
+ workEndNs: bigint;
29
+ endWallMs: number;
30
+ endNs: bigint;
31
+ }>;
32
+ basisJSON: string;
33
+ initialHighNs: bigint;
34
+ policy: Readonly<{
35
+ firstDispatchedAt: number;
36
+ periodStart: number;
37
+ periodEnd: number;
38
+ }>;
39
+ wall: () => number;
40
+ monotonic: () => bigint;
41
+ }>;
42
+ const lineages = new WeakMap<object, Lineage>();
43
+
44
+ /** Consumes original CAS custody before any selector, runtime clock or Owner. */
45
+ export function mintInitialLineage(
46
+ call: unknown,
47
+ journal: unknown,
48
+ arity: number,
49
+ ): object {
50
+ const { reservation, binding } = consumeInitialClassReservation(
51
+ call,
52
+ journal,
53
+ );
54
+ if (arity !== 2) stop();
55
+ if (
56
+ !("recordVersion" in reservation) ||
57
+ reservation.recordVersion !== 2 ||
58
+ reservation.stage !== "attach" ||
59
+ !("timingPolicyJSON" in reservation)
60
+ )
61
+ stop();
62
+ const selection = captureInitialJournalSelection(
63
+ binding,
64
+ reservation.apiVersion,
65
+ );
66
+ const client = selection.select();
67
+ if (
68
+ !client ||
69
+ typeof client !== "object" ||
70
+ types.isProxy(client) ||
71
+ Object.getPrototypeOf(client) !== Stripe.prototype ||
72
+ Object.prototype.hasOwnProperty.call(client, "rawRequest") ||
73
+ typeof method !== "function" ||
74
+ Object.getOwnPropertyDescriptor(Stripe.prototype, "rawRequest")?.value !==
75
+ method
76
+ )
77
+ stop();
78
+ selection.check();
79
+ const policy = JSON.parse(reservation.timingPolicyJSON) as {
80
+ firstDispatchedAt: number;
81
+ periodStart: number;
82
+ periodEnd: number;
83
+ workEndWallMs: number;
84
+ endWallMs: number;
85
+ };
86
+ const wall = Date.now;
87
+ const monotonic = process.hrtime.bigint;
88
+ const lo = monotonic();
89
+ const startWallMs = wall();
90
+ const hi = monotonic();
91
+ if (
92
+ !ms(startWallMs) ||
93
+ lo < 0n ||
94
+ hi < lo ||
95
+ hi > u64 ||
96
+ startWallMs >= policy.workEndWallMs
97
+ )
98
+ stop();
99
+ const basis = Object.freeze({
100
+ startWallMs,
101
+ startNs: lo,
102
+ workEndWallMs: policy.workEndWallMs,
103
+ workEndNs:
104
+ lo + (BigInt(policy.workEndWallMs) - BigInt(startWallMs)) * 1000000n,
105
+ endWallMs: policy.endWallMs,
106
+ endNs: lo + (BigInt(policy.endWallMs) - BigInt(startWallMs)) * 1000000n,
107
+ });
108
+ if (basis.endNs > u64 || hi >= basis.workEndNs || hi >= basis.endNs) stop();
109
+ const rawBasisJSON = JSON.stringify({
110
+ startWallMs,
111
+ startNsDecimal: lo.toString(),
112
+ workEndWallMs: basis.workEndWallMs,
113
+ workEndNsDecimal: basis.workEndNs.toString(),
114
+ endWallMs: basis.endWallMs,
115
+ endNsDecimal: basis.endNs.toString(),
116
+ });
117
+ const { basisJSON } = canonicalInitialBasis(
118
+ reservation.timingPolicyJSON,
119
+ rawBasisJSON,
120
+ );
121
+ selection.check();
122
+ const token = Object.freeze(new InitialLineage());
123
+ lineages.set(
124
+ token,
125
+ Object.freeze({
126
+ reservation,
127
+ selection,
128
+ client: client as Stripe,
129
+ method: method as Stripe["rawRequest"],
130
+ basis,
131
+ basisJSON,
132
+ initialHighNs: hi,
133
+ policy: Object.freeze({
134
+ firstDispatchedAt: policy.firstDispatchedAt,
135
+ periodStart: policy.periodStart,
136
+ periodEnd: policy.periodEnd,
137
+ }),
138
+ wall,
139
+ monotonic,
140
+ }),
141
+ );
142
+ return token;
143
+ }
144
+
145
+ /** Opaque private identity required by every invocation kernel. */
146
+ export function readInitialLineage(token: object): Lineage {
147
+ const lineage = lineages.get(token);
148
+ if (!lineage) stop();
149
+ lineage.selection.check();
150
+ if (
151
+ Object.getOwnPropertyDescriptor(Stripe.prototype, "rawRequest")?.value !==
152
+ lineage.method ||
153
+ Object.prototype.hasOwnProperty.call(lineage.client, "rawRequest") ||
154
+ Object.getPrototypeOf(lineage.client) !== Stripe.prototype
155
+ )
156
+ stop();
157
+ return lineage;
158
+ }
@@ -0,0 +1,54 @@
1
+ import { ownerForInitialLineage } from "./ownerFactory.js";
2
+
3
+ /** Each continuation retains its own canonical Owner, with no ambient switch. */
4
+ export function ownedAwaitForInitialLineage(token: object) {
5
+ const owner = ownerForInitialLineage(token);
6
+ return function owned<T>(work: () => T | PromiseLike<T>): Promise<T> {
7
+ owner.check();
8
+ return new Promise((resolve, reject) => {
9
+ let settled = false;
10
+ let remove: (() => void) | null = null;
11
+ function finish(ok: boolean, value: unknown) {
12
+ if (settled) return;
13
+ settled = true;
14
+ remove?.();
15
+ if (ok) resolve(value as T);
16
+ else reject(value);
17
+ }
18
+ const retire = () => finish(false, Error("INITIAL_OWNER_STOP"));
19
+ remove = owner.subscribe(retire);
20
+ if (settled) {
21
+ remove();
22
+ return;
23
+ }
24
+ let pending: T | PromiseLike<T>;
25
+ try {
26
+ owner.check();
27
+ pending = work();
28
+ } catch (error) {
29
+ finish(false, error);
30
+ return;
31
+ }
32
+ void Promise.resolve(pending).then(
33
+ (value) => {
34
+ if (settled) return;
35
+ try {
36
+ owner.check();
37
+ finish(true, value);
38
+ } catch {
39
+ retire();
40
+ }
41
+ },
42
+ (error: unknown) => {
43
+ if (settled) return;
44
+ try {
45
+ owner.check();
46
+ finish(false, error);
47
+ } catch {
48
+ retire();
49
+ }
50
+ },
51
+ );
52
+ });
53
+ };
54
+ }
@@ -0,0 +1,136 @@
1
+ import { readInitialLineage } from "./lineageAuthority.js";
2
+ import { types } from "node:util";
3
+ import type { OriginalBasis, OriginalSample } from "../originalOwner.js";
4
+
5
+ export type InitialOwner = Readonly<{
6
+ basis: Readonly<OriginalBasis>;
7
+ check(): Readonly<OriginalSample>;
8
+ sample(): Readonly<OriginalSample>;
9
+ subscribe(fn: () => void): () => void;
10
+ retire(): void;
11
+ }>;
12
+
13
+ const owners = new WeakMap<object, InitialOwner>();
14
+ function stop(): never {
15
+ throw Error("INITIAL_OWNER_STOP");
16
+ }
17
+ /** One canonical, independently retired Owner per original private lineage. */
18
+ export function ownerForInitialLineage(token: object): InitialOwner {
19
+ const existing = owners.get(token);
20
+ if (existing) return existing;
21
+ const lineage = readInitialLineage(token);
22
+ const { basis, policy } = lineage;
23
+ let closed = false;
24
+ let checking = false;
25
+ let last: Readonly<OriginalSample> | null = null;
26
+ const listeners = new Set<{ fn: () => void; active: boolean }>();
27
+ let timer: ReturnType<typeof setTimeout> | undefined;
28
+ function retire() {
29
+ if (closed) return;
30
+ closed = true;
31
+ if (timer !== undefined) clearTimeout(timer);
32
+ const active = [...listeners];
33
+ listeners.clear();
34
+ for (const listener of active) {
35
+ if (!listener.active) continue;
36
+ listener.active = false;
37
+ try {
38
+ Reflect.apply(listener.fn, undefined, []);
39
+ } catch {
40
+ /* Retirement cannot be reversed by a waiter. */
41
+ }
42
+ }
43
+ }
44
+ function check(): Readonly<OriginalSample> {
45
+ if (closed || checking) {
46
+ retire();
47
+ stop();
48
+ }
49
+ checking = true;
50
+ try {
51
+ if (readInitialLineage(token) !== lineage) stop();
52
+ const wallMs = lineage.wall();
53
+ const ns = lineage.monotonic();
54
+ const nowSeconds = Math.floor(wallMs / 1000);
55
+ if (
56
+ !Number.isSafeInteger(wallMs) ||
57
+ wallMs < basis.startWallMs ||
58
+ wallMs >= basis.workEndWallMs ||
59
+ wallMs >= basis.endWallMs ||
60
+ ns < lineage.initialHighNs ||
61
+ ns >= basis.workEndNs ||
62
+ ns >= basis.endNs ||
63
+ (last && (wallMs < last.wallMs || ns < last.ns)) ||
64
+ nowSeconds < policy.firstDispatchedAt ||
65
+ nowSeconds - policy.firstDispatchedAt >= 86400 ||
66
+ nowSeconds < policy.periodStart ||
67
+ nowSeconds >= policy.periodEnd ||
68
+ closed
69
+ )
70
+ stop();
71
+ last = Object.freeze({ wallMs, ns, nowSeconds, retired: false });
72
+ return last;
73
+ } catch {
74
+ retire();
75
+ return stop();
76
+ } finally {
77
+ checking = false;
78
+ }
79
+ }
80
+ const owner: InitialOwner = Object.freeze({
81
+ get basis() {
82
+ if (closed) stop();
83
+ return basis;
84
+ },
85
+ check,
86
+ sample: check,
87
+ retire,
88
+ subscribe(listener: () => void) {
89
+ if (typeof listener !== "function" || types.isProxy(listener)) {
90
+ retire();
91
+ stop();
92
+ }
93
+ if (closed) {
94
+ try {
95
+ listener();
96
+ } catch {
97
+ /* Already retired. */
98
+ }
99
+ return () => {};
100
+ }
101
+ const record = { fn: listener, active: true };
102
+ listeners.add(record);
103
+ return () => {
104
+ record.active = false;
105
+ listeners.delete(record);
106
+ };
107
+ },
108
+ });
109
+ owners.set(token, owner);
110
+ function schedule() {
111
+ const sample = check();
112
+ const monotonicMs = Number(
113
+ (basis.workEndNs - sample.ns + 999999n) / 1000000n,
114
+ );
115
+ // Bound each timer chunk, retaining both original absolute cutoffs.
116
+ timer = setTimeout(
117
+ () => {
118
+ try {
119
+ schedule();
120
+ } catch {
121
+ retire();
122
+ }
123
+ },
124
+ Math.min(2147483647, basis.workEndWallMs - sample.wallMs, monotonicMs),
125
+ );
126
+ timer.unref?.();
127
+ }
128
+ try {
129
+ schedule();
130
+ check();
131
+ return owner;
132
+ } catch (error) {
133
+ retire();
134
+ throw error;
135
+ }
136
+ }
@@ -0,0 +1,175 @@
1
+ import assert from "node:assert/strict";
2
+ import { afterEach, beforeEach, expect, it, vi } from "vitest";
3
+ import { initialOperations } from "../test-fixtures/producerInitialOperation.js";
4
+ import {
5
+ INITIAL_NS,
6
+ INITIAL_WALL,
7
+ WORK_WALL,
8
+ } from "../test-fixtures/producerInitialDeclarations.js";
9
+ import { captureInitialInvocationCore } from "./invocationProducer.js";
10
+
11
+ const timerLimit = 2147483647;
12
+ let monotonic = INITIAL_NS;
13
+ beforeEach(() => {
14
+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
15
+ vi.setSystemTime(INITIAL_WALL);
16
+ monotonic = INITIAL_NS;
17
+ vi.spyOn(process.hrtime, "bigint").mockImplementation(() => monotonic);
18
+ });
19
+ afterEach(() => {
20
+ vi.useRealTimers();
21
+ vi.unstubAllGlobals();
22
+ vi.restoreAllMocks();
23
+ });
24
+
25
+ it("accepts a capture aperture above 1 ms inside the original cutoffs", async () => {
26
+ await initialOperations(async ({ fresh, journal }) => {
27
+ monotonic = INITIAL_NS + 2000000n;
28
+ vi.mocked(process.hrtime.bigint).mockReturnValueOnce(INITIAL_NS);
29
+ const core = await captureInitialInvocationCore(fresh.call, journal);
30
+ try {
31
+ expect(core.owner.basis.startNs).toBe(INITIAL_NS);
32
+ expect(core.owner.basis.workEndNs).toBe(INITIAL_NS + 3000000000n);
33
+ expect(core.owner.check().ns).toBe(monotonic);
34
+ } finally {
35
+ core.owner.retire();
36
+ }
37
+ });
38
+ });
39
+
40
+ it("refuses a capture reaching the projected work cutoff before binding", async () => {
41
+ await initialOperations(async ({ fresh, journal }) => {
42
+ monotonic = INITIAL_NS + 3000000000n;
43
+ vi.mocked(process.hrtime.bigint).mockReturnValueOnce(INITIAL_NS);
44
+ await expect(
45
+ captureInitialInvocationCore(fresh.call, journal),
46
+ ).rejects.toThrow();
47
+ const stored = await journal.loadAuthorizedOperation();
48
+ assert(stored && "initialBasis" in stored);
49
+ expect(stored.initialBasis).toBeNull();
50
+ monotonic = INITIAL_NS;
51
+ await expect(
52
+ captureInitialInvocationCore(fresh.call, journal),
53
+ ).rejects.toThrow();
54
+ });
55
+ });
56
+
57
+ it("accepts a short work timer with a final deadline beyond Node's timer range", async () => {
58
+ await initialOperations(
59
+ async ({ fresh, journal }) => {
60
+ const core = await captureInitialInvocationCore(fresh.call, journal);
61
+ expect(core.owner.basis.endWallMs).toBe(INITIAL_WALL + timerLimit + 1000);
62
+ vi.advanceTimersByTime(WORK_WALL - INITIAL_WALL);
63
+ expect(() => core.owner.check()).toThrow("INITIAL_OWNER_STOP");
64
+ },
65
+ 1,
66
+ { endWallMs: INITIAL_WALL + timerLimit + 1000 },
67
+ );
68
+ });
69
+
70
+ it("chunks long work timers and rechecks unchanged cutoffs on each callback", async () => {
71
+ const timers = vi.spyOn(globalThis, "setTimeout");
72
+ vi.spyOn(Date, "now").mockReturnValue(INITIAL_WALL);
73
+ await initialOperations(
74
+ async ({ fresh, journal }) => {
75
+ const core = await captureInitialInvocationCore(fresh.call, journal);
76
+ try {
77
+ const basis = core.owner.basis;
78
+ expect(timers.mock.calls[timers.mock.calls.length - 1]?.[1]).toBe(
79
+ timerLimit,
80
+ );
81
+ // Deliver a chunk while the two independent clocks still have work left.
82
+ vi.advanceTimersByTime(timerLimit);
83
+ expect(core.owner.basis).toBe(basis);
84
+ expect(timers.mock.calls[timers.mock.calls.length - 1]?.[1]).toBe(
85
+ timerLimit,
86
+ );
87
+ expect(core.owner.check().retired).toBe(false);
88
+ monotonic = basis.workEndNs;
89
+ vi.advanceTimersByTime(timerLimit);
90
+ expect(() => core.owner.check()).toThrow("INITIAL_OWNER_STOP");
91
+ expect(vi.getTimerCount()).toBe(0);
92
+ } finally {
93
+ core.owner.retire();
94
+ }
95
+ },
96
+ 1,
97
+ {
98
+ workEndWallMs: INITIAL_WALL + timerLimit + 1000,
99
+ endWallMs: INITIAL_WALL + timerLimit + 2000,
100
+ },
101
+ );
102
+ });
103
+
104
+ it("schedules the earlier monotonic cutoff after a wide capture", async () => {
105
+ const timers = vi.spyOn(globalThis, "setTimeout");
106
+ await initialOperations(async ({ fresh, journal }) => {
107
+ monotonic = INITIAL_NS + 2000000000n;
108
+ vi.mocked(process.hrtime.bigint).mockReturnValueOnce(INITIAL_NS);
109
+ const core = await captureInitialInvocationCore(fresh.call, journal);
110
+ expect(timers.mock.calls[timers.mock.calls.length - 1]?.[1]).toBe(1000);
111
+ monotonic = core.owner.basis.workEndNs;
112
+ vi.advanceTimersByTime(1000);
113
+ expect(() => core.owner.check()).toThrow("INITIAL_OWNER_STOP");
114
+ });
115
+ });
116
+
117
+ it("checks the original cutoff after an actual basis mutation is delayed", async () => {
118
+ let reached = () => {};
119
+ let release = () => {};
120
+ const binding = new Promise<void>((resolve) => {
121
+ reached = resolve;
122
+ });
123
+ const delayed = new Promise<void>((resolve) => {
124
+ release = resolve;
125
+ });
126
+ await initialOperations(
127
+ async ({ fresh, journal }) => {
128
+ const pending = captureInitialInvocationCore(fresh.call, journal);
129
+ const refused = expect(pending).rejects.toThrow("INITIAL_OWNER_STOP");
130
+ await binding;
131
+ const stored = await journal.loadAuthorizedOperation();
132
+ assert(stored && "initialBasis" in stored && stored.initialBasis);
133
+ const original = stored.initialBasis.basisJSON;
134
+ vi.setSystemTime(WORK_WALL);
135
+ monotonic = INITIAL_NS + 3000000000n;
136
+ release();
137
+ await refused;
138
+ const after = await journal.loadAuthorizedOperation();
139
+ assert(after && "initialBasis" in after);
140
+ expect(after.initialBasis?.basisJSON).toBe(original);
141
+ await expect(
142
+ captureInitialInvocationCore(fresh.call, journal),
143
+ ).rejects.toThrow();
144
+ },
145
+ 1,
146
+ {
147
+ afterBind: async () => {
148
+ reached();
149
+ await delayed;
150
+ },
151
+ },
152
+ );
153
+ });
154
+
155
+ it("constructs and binds using real Node wall and monotonic clocks", async () => {
156
+ vi.restoreAllMocks();
157
+ vi.useRealTimers();
158
+ const epochMs = Date.now();
159
+ await initialOperations(
160
+ async ({ fresh, journal }) => {
161
+ const core = await captureInitialInvocationCore(fresh.call, journal);
162
+ try {
163
+ expect(core.owner.basis.startWallMs).toBeGreaterThanOrEqual(epochMs);
164
+ expect(core.owner.check().retired).toBe(false);
165
+ const stored = await journal.loadAuthorizedOperation();
166
+ assert(stored && "initialBasis" in stored);
167
+ expect(stored.initialBasis?.basisJSON).toBe(core.basisJSON);
168
+ } finally {
169
+ core.owner.retire();
170
+ }
171
+ },
172
+ 1,
173
+ { epochMs },
174
+ );
175
+ });