@fantastic.dev/better-stripe 0.111.0 → 0.112.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts +564 -0
  4. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js +103 -21
  6. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts +18 -1
  8. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js +54 -1
  10. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts +4 -0
  12. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts.map +1 -1
  13. package/dist/client/billing/renewalAttach/internal/observation/invocation.js +1 -0
  14. package/dist/client/billing/renewalAttach/internal/observation/invocation.js.map +1 -1
  15. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts +4 -0
  16. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts.map +1 -1
  17. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js +6 -1
  18. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js.map +1 -1
  19. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.d.ts +38 -0
  20. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.js +172 -0
  22. package/dist/client/billing/renewalAttach/internal/observation/witnessAuthorization.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/observation/witnessData.d.ts +135 -0
  24. package/dist/client/billing/renewalAttach/internal/observation/witnessData.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/observation/witnessData.js +143 -0
  26. package/dist/client/billing/renewalAttach/internal/observation/witnessData.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.d.ts +85 -0
  28. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.js +121 -0
  30. package/dist/client/billing/renewalAttach/internal/observation/witnessOperation.js.map +1 -0
  31. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.d.ts +44 -0
  32. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.d.ts.map +1 -0
  33. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.js +4 -0
  34. package/dist/client/billing/renewalAttach/internal/operations/witnessProfiles.js.map +1 -0
  35. package/dist/client/billing/renewalAttach/internal/producer/configureJournalWork.d.ts +1 -1
  36. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.d.ts +21 -21
  37. package/dist/client/billing/renewalAttach/internal/producer/journalWorkFactory.d.ts +3 -3
  38. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.d.ts +1 -1
  39. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  40. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  41. package/dist/component/_generated/api.d.ts +24 -0
  42. package/dist/component/_generated/api.d.ts.map +1 -1
  43. package/dist/component/_generated/api.js.map +1 -1
  44. package/dist/component/_generated/component.d.ts +94 -10
  45. package/dist/component/_generated/component.d.ts.map +1 -1
  46. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  47. package/dist/component/balanceFunding/queries.d.ts +1 -1
  48. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  49. package/dist/component/renewalWitnesses/mutations.d.ts +45 -0
  50. package/dist/component/renewalWitnesses/mutations.d.ts.map +1 -0
  51. package/dist/component/renewalWitnesses/mutations.js +14 -0
  52. package/dist/component/renewalWitnesses/mutations.js.map +1 -0
  53. package/dist/component/renewalWitnesses/queries.d.ts +39 -0
  54. package/dist/component/renewalWitnesses/queries.d.ts.map +1 -0
  55. package/dist/component/renewalWitnesses/queries.js +11 -0
  56. package/dist/component/renewalWitnesses/queries.js.map +1 -0
  57. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  58. package/docs/renewal-witness-protocol.md +61 -10
  59. package/package.json +1 -1
  60. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +142 -19
  61. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +90 -1
  62. package/src/client/billing/renewalAttach/internal/observation/invocation.ts +2 -0
  63. package/src/client/billing/renewalAttach/internal/observation/readerAuthorization.ts +6 -1
  64. package/src/client/billing/renewalAttach/internal/observation/witnessAcquisition.integration.test.ts +348 -0
  65. package/src/client/billing/renewalAttach/internal/observation/witnessActor.integration.test.ts +204 -0
  66. package/src/client/billing/renewalAttach/internal/observation/witnessAuthorization.ts +239 -0
  67. package/src/client/billing/renewalAttach/internal/observation/witnessCapabilities.integration.test.ts +231 -0
  68. package/src/client/billing/renewalAttach/internal/observation/witnessData.ts +189 -0
  69. package/src/client/billing/renewalAttach/internal/observation/witnessHistorical.integration.test.ts +98 -0
  70. package/src/client/billing/renewalAttach/internal/observation/witnessImmutable.integration.test.ts +78 -0
  71. package/src/client/billing/renewalAttach/internal/observation/witnessInvoice.integration.test.ts +85 -0
  72. package/src/client/billing/renewalAttach/internal/observation/witnessLifecycle.integration.test.ts +264 -0
  73. package/src/client/billing/renewalAttach/internal/observation/witnessOperation.ts +205 -0
  74. package/src/client/billing/renewalAttach/internal/observation/witnessProfile.integration.test.ts +93 -0
  75. package/src/client/billing/renewalAttach/internal/observation/witnessRPCControls.integration.test.ts +256 -0
  76. package/src/client/billing/renewalAttach/internal/operations/witnessProfiles.ts +58 -0
  77. package/src/client/billing/renewalAttach/internal/test-fixtures/invoiceObservation.ts +3 -1
  78. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +8 -0
  79. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +18 -7
  80. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessHistory.ts +70 -0
  81. package/src/client/billing/renewalAttach/internal/test-fixtures/witnessObservation.ts +353 -0
  82. package/src/component/_generated/api.ts +24 -0
  83. package/src/component/_generated/component.ts +98 -10
  84. package/src/component/renewalWitnesses/mutations.ts +17 -0
  85. package/src/component/renewalWitnesses/queries.ts +11 -0
  86. package/src/component/renewalWitnesses/routes.test.ts +154 -0
@@ -0,0 +1,256 @@
1
+ import {
2
+ prepareWitnessObservation,
3
+ invokeWitnessCapture,
4
+ invokeWitnessRead,
5
+ readStoredWitness,
6
+ witnessFixtureOptions,
7
+ } from "../test-fixtures/witnessObservation.js";
8
+ import { configureAdmissionCase } from "../test-fixtures/producerConfigureAdmission.js";
9
+ import { captureFreshWitnessRenewalObservation } from "./freshActor.js";
10
+ import {
11
+ getFunctionAddress,
12
+ type GenericActionCtx,
13
+ type GenericDataModel,
14
+ } from "convex/server";
15
+ import { expect } from "vitest";
16
+ import assert from "node:assert/strict";
17
+
18
+ const isRetain = (ref: Parameters<typeof getFunctionAddress>[0]) =>
19
+ getFunctionAddress(ref).reference?.endsWith("/retainAuthorizedWitness");
20
+ const isRead = (ref: Parameters<typeof getFunctionAddress>[0]) =>
21
+ getFunctionAddress(ref).reference?.endsWith("/readAuthorizedWitness");
22
+ function data(raw: unknown) {
23
+ assert(raw !== null && typeof raw === "object");
24
+ return raw;
25
+ }
26
+
27
+ configureAdmissionCase(
28
+ "retention and later read settle original native RPC Promises despite poisoned public then",
29
+ prepareWitnessObservation,
30
+ async (h, state) => {
31
+ let poisons = 0,
32
+ selected = 0;
33
+ const before = (ctx: GenericActionCtx<GenericDataModel>) => {
34
+ const mutate = ctx.runMutation,
35
+ query = ctx.runQuery;
36
+ Object.defineProperty(ctx, "runMutation", {
37
+ value: (...args: Parameters<typeof mutate>) => {
38
+ const pending = mutate.apply(ctx, args);
39
+ if (isRetain(args[0])) {
40
+ selected++;
41
+ void Object.defineProperty(pending, "then", {
42
+ value() {
43
+ poisons++;
44
+ throw Error("PUBLIC_RETENTION_THEN_POISON");
45
+ },
46
+ });
47
+ }
48
+ return pending;
49
+ },
50
+ });
51
+ Object.defineProperty(ctx, "runQuery", {
52
+ value: (...args: Parameters<typeof query>) => {
53
+ const pending = query.apply(ctx, args);
54
+ if (isRead(args[0])) {
55
+ selected++;
56
+ void Object.defineProperty(pending, "then", {
57
+ value() {
58
+ poisons++;
59
+ throw Error("PUBLIC_READBACK_THEN_POISON");
60
+ },
61
+ });
62
+ }
63
+ return pending;
64
+ },
65
+ });
66
+ };
67
+ const retained = await invokeWitnessCapture(h, state, { before });
68
+ assert("witnessRetention" in retained);
69
+ expect(retained.witnessRetention?.status).toBe("retained");
70
+ const later = await invokeWitnessRead(h, state, { before });
71
+ expect(later.evidence?.historicalMaterial.predicate).toBe(
72
+ "snapshot_target_material_match",
73
+ );
74
+ expect(selected).toBe(3);
75
+ expect(poisons).toBe(0);
76
+ },
77
+ witnessFixtureOptions,
78
+ );
79
+
80
+ for (const shape of ["copied-reply", "thenable"] as const)
81
+ configureAdmissionCase(
82
+ "a " + shape + " cannot substitute for the actual mutation Promise",
83
+ prepareWitnessObservation,
84
+ async (h, state) => {
85
+ const first = await invokeWitnessCapture(h, state);
86
+ assert(
87
+ "witnessRetention" in first &&
88
+ first.witnessRetention?.status === "retained",
89
+ );
90
+ const stored = await readStoredWitness(h, state);
91
+ let intercepted = 0,
92
+ thenCalls = 0;
93
+ await expect(
94
+ invokeWitnessCapture(h, state, {
95
+ before(ctx) {
96
+ const mutate = ctx.runMutation;
97
+ Object.defineProperty(ctx, "runMutation", {
98
+ value: (...args: Parameters<typeof mutate>) => {
99
+ if (!isRetain(args[0])) return mutate.apply(ctx, args);
100
+ intercepted++;
101
+ const copy = structuredClone(first.witnessRetention);
102
+ return shape === "copied-reply"
103
+ ? copy
104
+ : {
105
+ then(resolve: (value: unknown) => void) {
106
+ thenCalls++;
107
+ resolve(copy);
108
+ },
109
+ };
110
+ },
111
+ });
112
+ },
113
+ }),
114
+ ).rejects.toThrow("RENEWAL_WITNESS_INVALID");
115
+ expect(intercepted).toBe(1);
116
+ expect(thenCalls).toBe(0);
117
+ expect(await readStoredWitness(h, state)).toEqual(stored);
118
+ },
119
+ witnessFixtureOptions,
120
+ );
121
+
122
+ configureAdmissionCase(
123
+ "a copied thenable readback cannot grant later historical DATA",
124
+ prepareWitnessObservation,
125
+ async (h, state) => {
126
+ await invokeWitnessCapture(h, state);
127
+ const stored = await readStoredWitness(h, state);
128
+ let thenCalls = 0;
129
+ const before = h.calls.length;
130
+ await expect(
131
+ invokeWitnessRead(h, state, {
132
+ before(ctx) {
133
+ const query = ctx.runQuery;
134
+ Object.defineProperty(ctx, "runQuery", {
135
+ value: (...args: Parameters<typeof query>) => {
136
+ if (!isRead(args[0])) return query.apply(ctx, args);
137
+ return {
138
+ then(resolve: (value: unknown) => void) {
139
+ thenCalls++;
140
+ resolve(structuredClone(stored));
141
+ },
142
+ };
143
+ },
144
+ });
145
+ },
146
+ }),
147
+ ).rejects.toThrow("RENEWAL_WITNESS_INVALID");
148
+ expect(thenCalls).toBe(0);
149
+ expect(h.calls).toHaveLength(before);
150
+ expect(await readStoredWitness(h, state)).toEqual(stored);
151
+ },
152
+ witnessFixtureOptions,
153
+ );
154
+
155
+ for (const phase of ["retention-readback", "historical-read"] as const)
156
+ for (const change of ["row-id", "payload", "rehashed-payload"] as const)
157
+ configureAdmissionCase(
158
+ phase + " refuses a changed " + change,
159
+ prepareWitnessObservation,
160
+ async (h, state) => {
161
+ if (phase === "historical-read") await invokeWitnessCapture(h, state);
162
+ let changed = 0;
163
+ const invoke =
164
+ phase === "historical-read"
165
+ ? invokeWitnessRead
166
+ : invokeWitnessCapture;
167
+ await expect(
168
+ invoke(h, state, {
169
+ before(ctx) {
170
+ const query = ctx.runQuery;
171
+ Object.defineProperty(ctx, "runQuery", {
172
+ value: async (...args: Parameters<typeof query>) => {
173
+ const actual = await query.apply(ctx, args);
174
+ if (!isRead(args[0])) return actual;
175
+ const reply = data(structuredClone(actual)),
176
+ descriptor = data(Reflect.get(reply, "descriptor"));
177
+ changed++;
178
+ if (change === "row-id")
179
+ Reflect.set(
180
+ descriptor,
181
+ "witnessRowId",
182
+ "controlled-foreign-row",
183
+ );
184
+ else {
185
+ const raw = Reflect.get(reply, "payloadJSON");
186
+ assert(typeof raw === "string");
187
+ const payload = JSON.parse(raw);
188
+ payload.capturedSubject =
189
+ "https://host.test|changed-captured-subject";
190
+ const json = JSON.stringify(payload);
191
+ Reflect.set(reply, "payloadJSON", json);
192
+ if (change === "rehashed-payload") {
193
+ const hash = await crypto.subtle.digest(
194
+ "SHA-256",
195
+ new TextEncoder().encode(
196
+ "renewal-witness:v1\u0000" + json,
197
+ ),
198
+ );
199
+ const hex = [...new Uint8Array(hash)]
200
+ .map((n) => n.toString(16).padStart(2, "0"))
201
+ .join("");
202
+ Reflect.set(
203
+ descriptor,
204
+ "payloadBinding",
205
+ "renewal-witness:v1:sha256:" + hex,
206
+ );
207
+ Reflect.set(
208
+ descriptor,
209
+ "capturedSubject",
210
+ payload.capturedSubject,
211
+ );
212
+ }
213
+ }
214
+ return reply;
215
+ },
216
+ });
217
+ },
218
+ }),
219
+ ).rejects.toThrow();
220
+ expect(changed).toBe(1);
221
+ const stored = await readStoredWitness(h, state);
222
+ assert(stored);
223
+ expect(JSON.parse(stored.payloadJSON).capturedSubject).toBe(
224
+ witnessFixtureOptions.identity.tokenIdentifier,
225
+ );
226
+ },
227
+ witnessFixtureOptions,
228
+ );
229
+
230
+ configureAdmissionCase(
231
+ "returned retention DATA cannot register another capture invocation",
232
+ prepareWitnessObservation,
233
+ async (h, state) => {
234
+ const output = await invokeWitnessCapture(h, state);
235
+ assert("witnessRetention" in output);
236
+ const before = h.calls.length,
237
+ stored = await readStoredWitness(h, state);
238
+ await h.inAnotherAction(async (ctx) => {
239
+ await expect(
240
+ captureFreshWitnessRenewalObservation(
241
+ h.sdk,
242
+ structuredClone(output.witnessRetention),
243
+ ),
244
+ ).rejects.toThrow();
245
+ await expect(
246
+ captureFreshWitnessRenewalObservation(h.sdk, {
247
+ ...output.witnessRetention,
248
+ actualActionCtx: ctx,
249
+ }),
250
+ ).rejects.toThrow();
251
+ });
252
+ expect(h.calls).toHaveLength(before);
253
+ expect(await readStoredWitness(h, state)).toEqual(stored);
254
+ },
255
+ witnessFixtureOptions,
256
+ );
@@ -0,0 +1,58 @@
1
+ import type { FunctionReference } from "convex/server";
2
+ import type { WitnessIdentity } from "../../../../../shared/renewalWitness.js";
3
+ import type {
4
+ FreshObservationProfile,
5
+ InvoiceObservationProfile,
6
+ } from "./sourceOperations.js";
7
+
8
+ export type WitnessScope = Readonly<{
9
+ identity: WitnessIdentity;
10
+ providerScope: Readonly<{
11
+ mode: "platform";
12
+ stripeAccount: null;
13
+ livemode: boolean;
14
+ customerAccountId: string;
15
+ customerId: string;
16
+ subscriptionId: string;
17
+ scheduleId: string;
18
+ }>;
19
+ configureRequestBinding: string;
20
+ observedItemId: string;
21
+ nativePeriod: Readonly<{ start: number; end: number }>;
22
+ }>;
23
+ export type WitnessRetentionArgs = {
24
+ capability: "renewal_witness_retain_v1";
25
+ scope: WitnessScope;
26
+ };
27
+ export type WitnessReadArgs = {
28
+ capability: "renewal_witness_read_v1";
29
+ identity: WitnessIdentity;
30
+ };
31
+ type BaseProfile = Readonly<{
32
+ freshProfile: FreshObservationProfile;
33
+ invoiceProfile: InvoiceObservationProfile | null;
34
+ }>;
35
+ export type WitnessCaptureProfile = BaseProfile &
36
+ Readonly<{
37
+ authorizationQuery: FunctionReference<
38
+ "query",
39
+ "public" | "internal",
40
+ WitnessRetentionArgs,
41
+ unknown
42
+ >;
43
+ }>;
44
+ export type WitnessReadProfile = BaseProfile &
45
+ Readonly<{
46
+ authorizationQuery: FunctionReference<
47
+ "query",
48
+ "public" | "internal",
49
+ WitnessReadArgs,
50
+ unknown
51
+ >;
52
+ }>;
53
+
54
+ /** Fixed Source associations only. Returned DATA cannot populate these profiles. */
55
+ export const COMPILED_WITNESS_CAPTURE_ENTRIES: readonly WitnessCaptureProfile[] =
56
+ Object.freeze([]);
57
+ export const COMPILED_WITNESS_READ_ENTRIES: readonly WitnessReadProfile[] =
58
+ Object.freeze([]);
@@ -147,7 +147,9 @@ export async function prepareInvoiceObservation(
147
147
  const profile = Object.freeze({
148
148
  freshProfile: state.profile,
149
149
  readProfile: "endive-pinned-invoices-fence-7-v1",
150
- authorizationQuery: makeFunctionReference("initialOwner:authorizeInvoices"),
150
+ authorizationQuery: makeFunctionReference<"query">(
151
+ "initialOwner:authorizeInvoices",
152
+ ),
151
153
  });
152
154
  admissionControls.invoices.splice(
153
155
  0,
@@ -413,6 +413,12 @@ export async function configureAdmissionFixture(
413
413
  hostInvoiceQuery?: NonNullable<
414
414
  Parameters<typeof initialOperations>[2]
415
415
  >["hostQuery"];
416
+ hostWitnessRetainQuery?: NonNullable<
417
+ Parameters<typeof initialOperations>[2]
418
+ >["hostQuery"];
419
+ hostWitnessReadQuery?: NonNullable<
420
+ Parameters<typeof initialOperations>[2]
421
+ >["hostQuery"];
416
422
  count?: number;
417
423
  keys?: readonly string[];
418
424
  afterBind?: (reply: unknown) => Promise<void>;
@@ -444,6 +450,8 @@ export async function configureAdmissionFixture(
444
450
  identity: options.identity,
445
451
  hostQuery: options.hostQuery,
446
452
  hostInvoiceQuery: options.hostInvoiceQuery,
453
+ hostWitnessRetainQuery: options.hostWitnessRetainQuery,
454
+ hostWitnessReadQuery: options.hostWitnessReadQuery,
447
455
  source: captureRetainedInput(baseline.original),
448
456
  afterBind: options.afterBind,
449
457
  afterQuery: options.afterQuery,
@@ -35,6 +35,7 @@ export async function initialOperations(
35
35
  ctx: GenericActionCtx<GenericDataModel>;
36
36
  inAnotherAction(
37
37
  work: (ctx: GenericActionCtx<GenericDataModel>) => Promise<void>,
38
+ identity?: { subject: string; issuer: string; tokenIdentifier: string },
38
39
  ): Promise<void>;
39
40
  }) => Promise<void>,
40
41
  count = 1,
@@ -42,6 +43,8 @@ export async function initialOperations(
42
43
  identity?: { subject: string; issuer: string; tokenIdentifier: string };
43
44
  hostQuery?: ReturnType<typeof queryGeneric>;
44
45
  hostInvoiceQuery?: ReturnType<typeof queryGeneric>;
46
+ hostWitnessRetainQuery?: ReturnType<typeof queryGeneric>;
47
+ hostWitnessReadQuery?: ReturnType<typeof queryGeneric>;
45
48
  epochMs?: number;
46
49
  workEndWallMs?: number;
47
50
  endWallMs?: number;
@@ -184,6 +187,12 @@ export async function initialOperations(
184
187
  ...(options.hostInvoiceQuery
185
188
  ? { authorizeInvoices: options.hostInvoiceQuery }
186
189
  : {}),
190
+ ...(options.hostWitnessRetainQuery
191
+ ? { authorizeWitnessRetention: options.hostWitnessRetainQuery }
192
+ : {}),
193
+ ...(options.hostWitnessReadQuery
194
+ ? { authorizeWitnessRead: options.hostWitnessReadQuery }
195
+ : {}),
187
196
  secondary: actionGeneric({
188
197
  args: { id: v.string() },
189
198
  handler: async (ctx, args): Promise<null> => {
@@ -284,16 +293,18 @@ export async function initialOperations(
284
293
  sdk: selectedSDK,
285
294
  index,
286
295
  ctx,
287
- async inAnotherAction(work) {
296
+ async inAnotherAction(work, identity) {
288
297
  const id = String(++secondaryId);
289
298
  secondaryWork.set(id, work);
290
299
  try {
291
- await ctx.runAction(
292
- makeFunctionReference<"action", { id: string }, null>(
293
- "initialOwner:secondary",
294
- ),
295
- { id },
296
- );
300
+ const ref = makeFunctionReference<
301
+ "action",
302
+ { id: string },
303
+ null
304
+ >("initialOwner:secondary");
305
+ if (identity)
306
+ await t.withIdentity(identity).action(ref, { id });
307
+ else await ctx.runAction(ref, { id });
297
308
  } finally {
298
309
  secondaryWork.delete(id);
299
310
  }
@@ -0,0 +1,70 @@
1
+ import assert from "node:assert/strict";
2
+ import { components } from "../../../../../../example/convex/_generated/api.js";
3
+ import { constructRenewalConfigurationReceiptV2 } from "../../../renewalV2/index.js";
4
+ import { canonicalJournalEvent } from "../../../../../shared/renewalOperationJournal.js";
5
+ import { canonicalConfigure } from "../../../../../component/renewalOperations/configureJournal.fixtures.js";
6
+ import type { prepareWitnessObservation } from "./witnessObservation.js";
7
+
8
+ /** Real later component retention, not a runtime/public provider ACK. */
9
+ export async function retainLaterWitnessC9(
10
+ h: Parameters<typeof prepareWitnessObservation>[0],
11
+ state: Awaited<ReturnType<typeof prepareWitnessObservation>>,
12
+ targetEndOffset = 0,
13
+ ) {
14
+ const refs = components.betterStripe.renewalOperations;
15
+ const stage = state.full.configure;
16
+ assert(stage.attempt && "initialBasis" in state.full.parent.operation);
17
+ const basis = state.full.parent.operation.initialBasis;
18
+ assert(basis);
19
+ const record = JSON.parse(stage.operation.recordJSON);
20
+ const reservation = stage.attempt.reservation;
21
+ await h.ctx.runMutation(refs.mutations.bindInitialBasis, {
22
+ operationId: state.operationId,
23
+ attemptId: reservation.attemptId,
24
+ policyJSON: canonicalConfigure(record.timingPolicy),
25
+ basisJSON: basis.basisJSON,
26
+ });
27
+ const body = structuredClone(state.reads.schedule);
28
+ body.current_phase = structuredClone(
29
+ record.configureRecord.configuration.schedule.current_phase,
30
+ );
31
+ const phases = body.phases as Record<string, unknown>[];
32
+ phases[1].end_date = Number(phases[1].end_date) + targetEndOffset;
33
+ const transport = {
34
+ status: 200,
35
+ requestId: "req_controlled_later_witness_C9",
36
+ };
37
+ const rawReceipt = {
38
+ configuration: record.configureRecord.configuration,
39
+ actualDispatch: record.dispatch,
40
+ providerSnapshot: body,
41
+ transport,
42
+ };
43
+ const receipt = await constructRenewalConfigurationReceiptV2(rawReceipt);
44
+ const request = record.configureRecord.request;
45
+ const events = [
46
+ { event: "dispatch", stage: "configure", request },
47
+ { event: "response", stage: "configure", request, body, transport },
48
+ { event: "receipt", stage: "configure", request, receipt },
49
+ ];
50
+ for (const [index, event] of events.entries()) {
51
+ if (index === 2)
52
+ await h.ctx.runMutation(refs.mutations.retainProviderAcknowledgement, {
53
+ operationId: state.operationId,
54
+ attemptId: reservation.attemptId,
55
+ expectedSequence: 2,
56
+ receiptJSON: canonicalConfigure(receipt),
57
+ });
58
+ const sequence = index === 0 ? 1 : index === 1 ? 2 : 3;
59
+ const data = await canonicalJournalEvent(
60
+ sequence,
61
+ canonicalConfigure(event),
62
+ );
63
+ await h.ctx.runMutation(refs.mutations.appendStageEvent, {
64
+ reservation,
65
+ expectedSequence: index,
66
+ event: { sequence, binding: data.binding, dataJSON: data.json },
67
+ });
68
+ }
69
+ return { rawReceipt, receipt };
70
+ }