@fantastic.dev/better-stripe 0.100.0 → 0.102.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 (119) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +2 -0
  4. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +16 -0
  6. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.d.ts +7 -0
  8. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.d.ts.map +1 -0
  9. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.js +117 -0
  10. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.js.map +1 -0
  11. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.d.ts +53 -0
  12. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.js +198 -0
  14. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.d.ts +959 -0
  16. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.js +115 -0
  18. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts +2 -0
  20. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts.map +1 -1
  21. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js +4 -0
  22. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js.map +1 -1
  23. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts +1 -0
  24. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -1
  25. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +1 -0
  26. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -1
  27. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +18 -18
  28. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +9 -9
  29. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +50 -50
  30. package/dist/client/connect/payoutSyncTestHelpers.d.ts +25 -25
  31. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  32. package/dist/component/balanceFunding/queries.d.ts +1 -1
  33. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  34. package/dist/component/earnings/triggers.d.ts +22 -22
  35. package/dist/component/payoutRelease/queries.d.ts +2 -2
  36. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  37. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  38. package/dist/component/renewalOperations/attachValidation.d.ts +19 -0
  39. package/dist/component/renewalOperations/attachValidation.d.ts.map +1 -0
  40. package/dist/component/renewalOperations/attachValidation.js +167 -0
  41. package/dist/component/renewalOperations/attachValidation.js.map +1 -0
  42. package/dist/component/renewalOperations/configureAcknowledgement.d.ts +13 -0
  43. package/dist/component/renewalOperations/configureAcknowledgement.d.ts.map +1 -0
  44. package/dist/component/renewalOperations/configureAcknowledgement.js +108 -0
  45. package/dist/component/renewalOperations/configureAcknowledgement.js.map +1 -0
  46. package/dist/component/renewalOperations/configureParent.d.ts +10 -0
  47. package/dist/component/renewalOperations/configureParent.d.ts.map +1 -0
  48. package/dist/component/renewalOperations/configureParent.js +62 -0
  49. package/dist/component/renewalOperations/configureParent.js.map +1 -0
  50. package/dist/component/renewalOperations/configureValidation.d.ts +12 -0
  51. package/dist/component/renewalOperations/configureValidation.d.ts.map +1 -0
  52. package/dist/component/renewalOperations/configureValidation.js +64 -0
  53. package/dist/component/renewalOperations/configureValidation.js.map +1 -0
  54. package/dist/component/renewalOperations/helpers.d.ts +16 -21
  55. package/dist/component/renewalOperations/helpers.d.ts.map +1 -1
  56. package/dist/component/renewalOperations/helpers.js +13 -169
  57. package/dist/component/renewalOperations/helpers.js.map +1 -1
  58. package/dist/component/renewalOperations/mutations.d.ts +6 -6
  59. package/dist/component/renewalOperations/mutations.d.ts.map +1 -1
  60. package/dist/component/renewalOperations/mutations.js +14 -7
  61. package/dist/component/renewalOperations/mutations.js.map +1 -1
  62. package/dist/component/renewalOperations/operationContext.d.ts +12 -0
  63. package/dist/component/renewalOperations/operationContext.d.ts.map +1 -0
  64. package/dist/component/renewalOperations/operationContext.js +14 -0
  65. package/dist/component/renewalOperations/operationContext.js.map +1 -0
  66. package/dist/component/renewalOperations/queries.d.ts +4 -4
  67. package/dist/component/renewalOperations/queries.js +2 -1
  68. package/dist/component/renewalOperations/queries.js.map +1 -1
  69. package/dist/component/renewalOperations/schema.d.ts +59 -59
  70. package/dist/component/renewalOperations/schema.js +3 -3
  71. package/dist/component/renewalOperations/schema.js.map +1 -1
  72. package/dist/component/renewalOperations/stageAcknowledgement.d.ts +15 -0
  73. package/dist/component/renewalOperations/stageAcknowledgement.d.ts.map +1 -0
  74. package/dist/component/renewalOperations/stageAcknowledgement.js +20 -0
  75. package/dist/component/renewalOperations/stageAcknowledgement.js.map +1 -0
  76. package/dist/component/renewalOperations/validationTypes.d.ts +9 -0
  77. package/dist/component/renewalOperations/validationTypes.d.ts.map +1 -0
  78. package/dist/component/renewalOperations/validationTypes.js +2 -0
  79. package/dist/component/renewalOperations/validationTypes.js.map +1 -0
  80. package/dist/component/schema.d.ts +9 -9
  81. package/dist/component/usage/allowance.fixtures.d.ts +25 -25
  82. package/dist/component/usageCredits/accounting.fixtures.d.ts +9 -9
  83. package/dist/shared/renewalOperationJournal.d.ts +1 -1
  84. package/dist/shared/renewalOperationJournal.d.ts.map +1 -1
  85. package/dist/shared/renewalOperationJournal.js +41 -9
  86. package/dist/shared/renewalOperationJournal.js.map +1 -1
  87. package/docs/renewal-context-reads.md +81 -11
  88. package/package.json +1 -1
  89. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +21 -0
  90. package/src/client/billing/renewalAttach/internal/producer/configureAdmission.ts +179 -0
  91. package/src/client/billing/renewalAttach/internal/producer/configureJournalData.ts +248 -0
  92. package/src/client/billing/renewalAttach/internal/producer/configureLineage.ts +166 -0
  93. package/src/client/billing/renewalAttach/internal/producer/invocationProducer.ts +13 -0
  94. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +2 -0
  95. package/src/client/billing/renewalAttach/internal/producer/producerConfigureAdmission.integration.test.ts +203 -0
  96. package/src/client/billing/renewalAttach/internal/producer/producerConfigureControls.integration.test.ts +566 -0
  97. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +316 -0
  98. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +61 -3
  99. package/src/component/renewalOperations/attachValidation.ts +203 -0
  100. package/src/component/renewalOperations/configureAcknowledgement.test.ts +30 -0
  101. package/src/component/renewalOperations/configureAcknowledgement.ts +182 -0
  102. package/src/component/renewalOperations/configureAcknowledgementControls.test.ts +96 -0
  103. package/src/component/renewalOperations/configureBasis.test.ts +77 -0
  104. package/src/component/renewalOperations/configureCreation.test.ts +75 -0
  105. package/src/component/renewalOperations/configureJournal.fixtures.ts +385 -0
  106. package/src/component/renewalOperations/configureParent.ts +71 -0
  107. package/src/component/renewalOperations/configurePolicy.test.ts +105 -0
  108. package/src/component/renewalOperations/configurePublication.test.ts +85 -0
  109. package/src/component/renewalOperations/configureReceiptBounds.test.ts +39 -0
  110. package/src/component/renewalOperations/configureSourceControls.test.ts +65 -0
  111. package/src/component/renewalOperations/configureValidation.ts +70 -0
  112. package/src/component/renewalOperations/helpers.ts +21 -204
  113. package/src/component/renewalOperations/mutations.ts +16 -7
  114. package/src/component/renewalOperations/operationContext.ts +21 -0
  115. package/src/component/renewalOperations/queries.ts +1 -1
  116. package/src/component/renewalOperations/schema.ts +3 -3
  117. package/src/component/renewalOperations/stageAcknowledgement.ts +45 -0
  118. package/src/component/renewalOperations/validationTypes.ts +9 -0
  119. package/src/shared/renewalOperationJournal.ts +49 -8
@@ -0,0 +1,316 @@
1
+ import assert from "node:assert/strict";
2
+ import { afterEach, beforeEach, vi } from "vitest";
3
+ import { initialOperations } from "./producerInitialOperation.js";
4
+ import { makeConfigureReadNativeBaseline } from "./configureReadNativeBaseline.js";
5
+ import { captureRetainedInput } from "../material/capture.js";
6
+ import { captureInitialInvocationCore } from "../producer/invocationProducer.js";
7
+ import { createClassActionOperationJournal } from "../operationJournal.js";
8
+ import { components } from "../../../../../../example/convex/_generated/api.js";
9
+ import { BetterStripe } from "../../../../index.js";
10
+ import { renewalSnapshot } from "../../../renewalReplacementSnapshot.js";
11
+ import {
12
+ prepareRenewalPriceReplacementV2,
13
+ prepareRenewalScheduleAttachmentV2,
14
+ projectRenewalConfigurationV2,
15
+ } from "../../../renewalV2/index.js";
16
+ import { INITIAL_NS } from "./producerInitialDeclarations.js";
17
+
18
+ const controls = vi.hoisted(() => ({
19
+ entries: [{ coversRetained: () => true, coversFresh: () => true }],
20
+ recovery: [] as { originalEntry: unknown; coversReplay(): boolean }[],
21
+ legacy: 0,
22
+ selectors: 0,
23
+ }));
24
+ vi.mock("../operations/sourceOperations.js", () => {
25
+ const poison = () => {
26
+ controls.legacy++;
27
+ throw Error("LEGACY_SOURCE_POISON");
28
+ };
29
+ return {
30
+ COMPILED_INITIAL_ENTRIES: controls.entries,
31
+ COMPILED_RECOVERY_ENTRIES: controls.recovery,
32
+ ORIGINAL_ORIGIN_ASSOCIATION: null,
33
+ loadFixedInitialOperation: poison,
34
+ loadFixedExplicitRecoveryOperation: poison,
35
+ loadOwnedTransportSource: poison,
36
+ loadInitialOwnedTransportSource: poison,
37
+ loadRecoveryOwnedTransportSource: poison,
38
+ };
39
+ });
40
+ vi.mock("../originalOwner.js", () => {
41
+ const poison = () => {
42
+ controls.legacy++;
43
+ throw Error("LEGACY_OWNER_POISON");
44
+ };
45
+ return {
46
+ OWNER: Object.freeze({
47
+ get basis() {
48
+ return poison();
49
+ },
50
+ check: poison,
51
+ sample: poison,
52
+ subscribe: poison,
53
+ retire: poison,
54
+ }),
55
+ };
56
+ });
57
+ vi.mock("../../../../helpers.js", async (original) => {
58
+ const actual = await original<typeof import("../../../../helpers.js")>();
59
+ return {
60
+ ...actual,
61
+ getStripeClient(...args: Parameters<typeof actual.getStripeClient>) {
62
+ controls.selectors++;
63
+ return actual.getStripeClient(...args);
64
+ },
65
+ };
66
+ });
67
+ export const admissionControls = controls;
68
+ const canonical = (value: unknown) => JSON.stringify(renewalSnapshot(value));
69
+ beforeEach(() => {
70
+ controls.legacy = 0;
71
+ controls.selectors = 0;
72
+ controls.entries.splice(0, controls.entries.length, {
73
+ coversRetained: () => true,
74
+ coversFresh: () => true,
75
+ });
76
+ controls.recovery.splice(0, controls.recovery.length, {
77
+ originalEntry: controls.entries[0],
78
+ coversReplay: () => true,
79
+ });
80
+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
81
+ vi.setSystemTime(
82
+ (makeConfigureReadNativeBaseline().clockPlan.attachSeconds + 1) * 1000,
83
+ );
84
+ vi.spyOn(process.hrtime, "bigint").mockReturnValue(INITIAL_NS);
85
+ });
86
+ afterEach(() => {
87
+ vi.useRealTimers();
88
+ vi.unstubAllGlobals();
89
+ vi.restoreAllMocks();
90
+ });
91
+
92
+ async function setup(
93
+ input: Parameters<Parameters<typeof initialOperations>[0]>[0],
94
+ completion: { mode: string; posts: number },
95
+ ) {
96
+ const { journal, fresh, sdk, ctx, index } = input;
97
+ assert(fresh.result.disposition === "acquired" && fresh.call);
98
+ const parentReservation = fresh.result.reservation;
99
+ const baseline = makeConfigureReadNativeBaseline();
100
+ const source = captureRetainedInput(baseline.original);
101
+ const calls: { method: string; path: string }[] = [];
102
+ const routes = new Map<string, unknown>([
103
+ ["/v1/subscriptions/sub_original", source.originalBundle.wireSubscription],
104
+ ["/v1/prices/price_target", source.originalBundle.wireTargetPrice],
105
+ ["/v1/customers/cus_buyer", source.originalBundle.wireBillingCustomer],
106
+ ...source.originalBundle.couponReads.map((row): [string, unknown] => [
107
+ "/v1/coupons/" + encodeURIComponent(String(row.couponId)),
108
+ row.wireCoupon,
109
+ ]),
110
+ ]);
111
+ vi.stubGlobal("fetch", async (url: RequestInfo | URL, init?: RequestInit) => {
112
+ const path = new URL(String(url)).pathname;
113
+ const method = init?.method ?? "";
114
+ calls.push({ method, path });
115
+ if (method === "POST") {
116
+ completion.posts++;
117
+ if (completion.mode === "replay" && completion.posts === 1)
118
+ throw Error("CONTROLLED_LOST_RESPONSE");
119
+ }
120
+ const body = method === "POST" ? baseline.schedule : routes.get(path);
121
+ assert(body);
122
+ assert(
123
+ method === "GET" ||
124
+ (method === "POST" && path === "/v1/subscription_schedules"),
125
+ );
126
+ return new Response(JSON.stringify(body), {
127
+ status: 200,
128
+ headers: {
129
+ "content-type": "application/json",
130
+ "request-id": "req_synthetic_admission",
131
+ },
132
+ });
133
+ });
134
+ const core = await captureInitialInvocationCore(fresh.call, journal);
135
+ let childOrdinal = 0;
136
+ async function child(
137
+ options: {
138
+ sdk?: BetterStripe;
139
+ stage?: "attach" | "configure";
140
+ ctx?: typeof ctx;
141
+ change?: (record: Record<string, unknown>) => void;
142
+ } = {},
143
+ ) {
144
+ const ordinal = ++childOrdinal;
145
+ const loaded = await journal.loadAuthorizedOperation();
146
+ assert(loaded);
147
+ const parent = JSON.parse(loaded.recordJSON);
148
+ const prepared = await prepareRenewalPriceReplacementV2(
149
+ source.attachRequest.preparation,
150
+ );
151
+ const attach = await prepareRenewalScheduleAttachmentV2({
152
+ prepared,
153
+ apiVersion: source.attachRequest.apiVersion,
154
+ attachKey: source.attachRequest.attachKey,
155
+ firstDispatchedAt: source.attachRequest.firstDispatchedAt,
156
+ });
157
+ const configuration = {
158
+ preparation: source.attachRequest.preparation,
159
+ attachReceipt: {
160
+ attachRequest: source.attachRequest,
161
+ actualDispatch: {
162
+ scope: attach.scope,
163
+ apiVersion: attach.apiVersion,
164
+ method: attach.method,
165
+ path: attach.path,
166
+ payload: attach.payload,
167
+ key: attach.key,
168
+ firstDispatchedAt: attach.firstDispatchedAt,
169
+ },
170
+ providerSnapshot: baseline.schedule,
171
+ },
172
+ freshSubscription: {
173
+ ...source.attachRequest.preparation.subscription,
174
+ schedule: baseline.schedule.id,
175
+ },
176
+ targetPrice: source.attachRequest.preparation.targetPrice,
177
+ billingCustomer: source.attachRequest.preparation.billingCustomer,
178
+ schedule: baseline.schedule,
179
+ apiVersion: source.attachRequest.apiVersion,
180
+ observedAt: baseline.configurationTime,
181
+ firstDispatchedAt: baseline.configurationTime,
182
+ configureKey: "configure:admission:root" + index + ":" + ordinal,
183
+ };
184
+ const request = await projectRenewalConfigurationV2(configuration);
185
+ assert("requestIdentity" in request);
186
+ const { scope, apiVersion, method, path, payload, key, firstDispatchedAt } =
187
+ request;
188
+ const known = await journal.readProviderAcknowledgement();
189
+ assert(known);
190
+ const record = {
191
+ schemaVersion: 2,
192
+ authorization: {
193
+ scope: "configure-child-host",
194
+ id: "configure-consent-root" + index + "-" + ordinal,
195
+ revision: 1,
196
+ },
197
+ logicalOperationId: "configure-child-root" + index + "-" + ordinal,
198
+ stage: "configure",
199
+ account: parent.account,
200
+ apiVersion,
201
+ requestBinding: request.requestIdentity.binding,
202
+ dispatch: {
203
+ scope,
204
+ apiVersion,
205
+ method,
206
+ path,
207
+ payload,
208
+ key,
209
+ firstDispatchedAt,
210
+ },
211
+ parentAttachment: {
212
+ operationId: parentReservation.operationId,
213
+ attemptId: parentReservation.attemptId,
214
+ sourcePayloadId: parentReservation.payloadId,
215
+ receiptBinding: known.retention.receiptBinding,
216
+ },
217
+ configureRecord: {
218
+ configuration,
219
+ request,
220
+ attachReceipt: JSON.parse(known.receiptJSON),
221
+ originalBundle: source.originalBundle,
222
+ },
223
+ timingPolicy: { ...parent.timingPolicy, firstDispatchedAt },
224
+ };
225
+ options.change?.(record);
226
+ const recordJSON = canonical(record);
227
+ const selectedCtx = options.ctx ?? ctx;
228
+ const refs = components.betterStripe.renewalOperations;
229
+ const created = await selectedCtx.runMutation(
230
+ refs.mutations.createAuthorizedOperation,
231
+ {
232
+ authorizationScope: record.authorization.scope,
233
+ authorizationRevision: 1,
234
+ logicalOperationId: record.logicalOperationId,
235
+ recordJSON,
236
+ },
237
+ );
238
+ assert(created.status === "created");
239
+ const childJournal = await createClassActionOperationJournal(
240
+ options.sdk ?? sdk,
241
+ { actualActionCtx: selectedCtx, operationId: created.operationId },
242
+ );
243
+ const reserveArgs = {
244
+ expectedRevision: 0,
245
+ stage: options.stage ?? "configure",
246
+ expectedRequestBinding: record.requestBinding,
247
+ recordJSON,
248
+ };
249
+ const childFresh = await childJournal.reserveFreshAttempt(reserveArgs);
250
+ assert(childFresh.result.disposition === "acquired" && childFresh.call);
251
+ return {
252
+ journal: childJournal,
253
+ fresh: childFresh,
254
+ record,
255
+ reserveArgs,
256
+ created,
257
+ };
258
+ }
259
+ async function complete(mode: "initial" | "replay" | "resume" = "initial") {
260
+ completion.mode = mode;
261
+ if (mode === "initial") return core.initialAttach().invoke();
262
+ try {
263
+ await core.initialAttach().invoke();
264
+ } catch (error) {
265
+ if (mode !== "replay") throw error;
266
+ }
267
+ return core.recoverAttach().invoke();
268
+ }
269
+ return { ...input, core, child, calls, baseline, source, complete };
270
+ }
271
+ export async function configureAdmissionFixture(
272
+ work: (h: Awaited<ReturnType<typeof setup>>) => Promise<void>,
273
+ options: {
274
+ count?: number;
275
+ keys?: readonly string[];
276
+ afterBind?: (reply: unknown) => Promise<void>;
277
+ afterQuery?: (
278
+ reply: unknown,
279
+ reference: string,
280
+ args: unknown,
281
+ ) => Promise<void>;
282
+ afterAppend?: () => Promise<void>;
283
+ } = {},
284
+ ) {
285
+ const baseline = makeConfigureReadNativeBaseline();
286
+ const completion = { mode: "initial", posts: 0, appends: 0 };
287
+ await initialOperations(
288
+ async (input) => {
289
+ const h = await setup(input, completion);
290
+ try {
291
+ await work(h);
292
+ } finally {
293
+ h.core.owner.retire();
294
+ }
295
+ },
296
+ options.count ?? 1,
297
+ {
298
+ keys: options.keys,
299
+ source: captureRetainedInput(baseline.original),
300
+ afterBind: options.afterBind,
301
+ afterQuery: options.afterQuery,
302
+ afterAppend: async () => {
303
+ completion.appends++;
304
+ if (completion.mode === "resume" && completion.appends === 2)
305
+ throw Error("CONTROLLED_APPEND_REPLY_REJECTION");
306
+ await options.afterAppend?.();
307
+ },
308
+ workEndWallMs:
309
+ (baseline.clockPlan.attachSeconds + baseline.clockPlan.workSeconds) *
310
+ 1000,
311
+ endWallMs:
312
+ (baseline.clockPlan.attachSeconds + baseline.clockPlan.endSeconds) *
313
+ 1000,
314
+ },
315
+ );
316
+ }
@@ -1,10 +1,13 @@
1
1
  import assert from "node:assert/strict";
2
+ import { v } from "convex/values";
2
3
  import { convexTest } from "convex-test";
3
4
  import {
4
5
  actionGeneric,
5
6
  defineSchema,
6
7
  makeFunctionReference,
7
8
  getFunctionAddress,
9
+ type GenericActionCtx,
10
+ type GenericDataModel,
8
11
  } from "convex/server";
9
12
  import { BetterStripe } from "../../../../index.js";
10
13
  import { components } from "../../../../../../example/convex/_generated/api.js";
@@ -28,13 +31,22 @@ export async function initialOperations(
28
31
  fresh: Fresh;
29
32
  sdk: BetterStripe;
30
33
  index: number;
34
+ ctx: GenericActionCtx<GenericDataModel>;
35
+ inAnotherAction(
36
+ work: (ctx: GenericActionCtx<GenericDataModel>) => Promise<void>,
37
+ ): Promise<void>;
31
38
  }) => Promise<void>,
32
39
  count = 1,
33
40
  options: {
34
41
  epochMs?: number;
35
42
  workEndWallMs?: number;
36
43
  endWallMs?: number;
37
- afterBind?: () => Promise<void>;
44
+ afterBind?: (reply: unknown) => Promise<void>;
45
+ afterQuery?: (
46
+ reply: unknown,
47
+ reference: string,
48
+ args: unknown,
49
+ ) => Promise<void>;
38
50
  afterAppend?: () => Promise<void>;
39
51
  beforeAppend?: () => Promise<void>;
40
52
  afterRetain?: () => Promise<void>;
@@ -158,11 +170,37 @@ export async function initialOperations(
158
170
  new BetterStripe(components.betterStripe, { STRIPE_SECRET_KEY: key }),
159
171
  );
160
172
  const refs = components.betterStripe.renewalOperations;
173
+ const secondaryWork = new Map<
174
+ string,
175
+ (ctx: GenericActionCtx<GenericDataModel>) => Promise<void>
176
+ >();
177
+ let secondaryId = 0;
161
178
  const host = {
179
+ secondary: actionGeneric({
180
+ args: { id: v.string() },
181
+ handler: async (ctx, args): Promise<null> => {
182
+ const work = secondaryWork.get(args.id);
183
+ assert(work);
184
+ secondaryWork.delete(args.id);
185
+ await work(ctx);
186
+ return null;
187
+ },
188
+ }),
162
189
  run: actionGeneric({
163
190
  args: {},
164
191
  handler: async (ctx): Promise<null> => {
165
192
  const runMutation = ctx.runMutation;
193
+ const runQuery = ctx.runQuery;
194
+ if (options.afterQuery)
195
+ ctx.runQuery = async (ref, ...args) => {
196
+ const reply = await runQuery(ref, ...args);
197
+ await options.afterQuery?.(
198
+ reply,
199
+ getFunctionAddress(ref).reference ?? "",
200
+ args[0],
201
+ );
202
+ return reply;
203
+ };
166
204
  if (
167
205
  options.afterBind ||
168
206
  options.afterAppend ||
@@ -184,7 +222,7 @@ export async function initialOperations(
184
222
  ) &&
185
223
  options.afterBind
186
224
  )
187
- await options.afterBind();
225
+ await options.afterBind(result);
188
226
  if (
189
227
  getFunctionAddress(ref).reference?.endsWith(
190
228
  "/appendStageEvent",
@@ -232,7 +270,27 @@ export async function initialOperations(
232
270
  recordJSON,
233
271
  });
234
272
  assert(fresh.result.disposition === "acquired" && fresh.call);
235
- await work({ journal, fresh, sdk: selectedSDK, index });
273
+ await work({
274
+ journal,
275
+ fresh,
276
+ sdk: selectedSDK,
277
+ index,
278
+ ctx,
279
+ async inAnotherAction(work) {
280
+ const id = String(++secondaryId);
281
+ secondaryWork.set(id, work);
282
+ try {
283
+ await ctx.runAction(
284
+ makeFunctionReference<"action", { id: string }, null>(
285
+ "initialOwner:secondary",
286
+ ),
287
+ { id },
288
+ );
289
+ } finally {
290
+ secondaryWork.delete(id);
291
+ }
292
+ },
293
+ });
236
294
  }),
237
295
  );
238
296
  return null;
@@ -0,0 +1,203 @@
1
+ import { renewalSnapshot } from "../../client/billing/renewalReplacementSnapshot.js";
2
+ import { constructRenewalScheduleAttachmentReceiptV2 } from "../../client/billing/renewalV2/index.js";
3
+ import { captureAttachmentReceipt } from "../../client/billing/renewalV2/receipt.js";
4
+ import {
5
+ captureAttachSource,
6
+ captureAttachDispatch,
7
+ captureAttachResponse,
8
+ captureAttachReceipt,
9
+ } from "../../client/billing/renewalAttach/internal/c10/eventCapture.js";
10
+ import { requiredJSONSnapshot } from "../../client/billing/renewalAttach/internal/material/requiredJson.js";
11
+ import type { canonicalJournalRecord } from "../../shared/renewalOperationJournal.js";
12
+ import type { Reservation, CheckedEvents } from "./validationTypes.js";
13
+
14
+ export function acknowledgementConflict(): never {
15
+ throw Error("RENEWAL_JOURNAL_CONFLICT");
16
+ }
17
+ function isJSONObject(value: unknown): value is Record<string, unknown> {
18
+ return value !== null && typeof value === "object" && !Array.isArray(value);
19
+ }
20
+ export function jsonObject(value: unknown) {
21
+ if (!isJSONObject(value)) acknowledgementConflict();
22
+ return value;
23
+ }
24
+ export function sameJSON(left: unknown, right: unknown) {
25
+ return (
26
+ JSON.stringify(renewalSnapshot(left)) ===
27
+ JSON.stringify(renewalSnapshot(right))
28
+ );
29
+ }
30
+ type AttachReceipt = Awaited<
31
+ ReturnType<typeof constructRenewalScheduleAttachmentReceiptV2>
32
+ >;
33
+
34
+ /** Parsed JSON DATA admission only; no caller-object or provider provenance. */
35
+ export function admitAttachReceiptOutputDATA(
36
+ receiptJSON: string,
37
+ rebuilt: AttachReceipt,
38
+ ) {
39
+ if (
40
+ typeof receiptJSON !== "string" ||
41
+ receiptJSON.length > 500000 ||
42
+ new TextEncoder().encode(receiptJSON).length > 500000
43
+ )
44
+ acknowledgementConflict();
45
+ const parsed: unknown = JSON.parse(receiptJSON);
46
+ if (!sameJSON(parsed, rebuilt)) acknowledgementConflict();
47
+ const output = renewalSnapshot({
48
+ status: "attach_acknowledged",
49
+ operationalAuthority: false,
50
+ receipt: parsed,
51
+ });
52
+ const slots = new Map<string, { expected: string; family: string }>([
53
+ [
54
+ JSON.stringify(["receipt", "logicalBinding"]),
55
+ { expected: rebuilt.logicalBinding, family: "renewal" },
56
+ ],
57
+ [
58
+ JSON.stringify(["receipt", "request", "logicalBinding"]),
59
+ { expected: rebuilt.request.logicalBinding, family: "renewal" },
60
+ ],
61
+ [
62
+ JSON.stringify(["receipt", "request", "requestIdentity", "binding"]),
63
+ {
64
+ expected: rebuilt.request.requestIdentity.binding,
65
+ family: "renewal-attach",
66
+ },
67
+ ],
68
+ [
69
+ JSON.stringify(["receipt", "binding"]),
70
+ { expected: rebuilt.binding, family: "renewal-attach-receipt" },
71
+ ],
72
+ ]);
73
+ const found = new Set<string>();
74
+ function walk(value: unknown, path: string[]) {
75
+ const key = JSON.stringify(path);
76
+ const slot = slots.get(key);
77
+ if (slot) {
78
+ if (
79
+ value !== slot.expected ||
80
+ typeof value !== "string" ||
81
+ !new RegExp("^" + slot.family + ":v2:sha256:[0-9a-f]{64}$").test(value)
82
+ )
83
+ acknowledgementConflict();
84
+ found.add(key);
85
+ return;
86
+ }
87
+ if (value === null || typeof value !== "object") {
88
+ requiredJSONSnapshot(value);
89
+ return;
90
+ }
91
+ for (const [name, child] of Object.entries(value)) {
92
+ requiredJSONSnapshot(name);
93
+ requiredJSONSnapshot({ [name]: child === null ? null : true });
94
+ walk(child, [...path, name]);
95
+ }
96
+ }
97
+ walk(output, []);
98
+ if (
99
+ found.size !== 4 ||
100
+ new TextEncoder().encode(JSON.stringify(output)).length > 500000
101
+ )
102
+ acknowledgementConflict();
103
+ return JSON.stringify(output.receipt);
104
+ }
105
+
106
+ /** Full stored-source/event/C3 consistency; these are unsigned DATA checks. */
107
+ export async function validateAttachAcknowledgement(
108
+ full: ReturnType<typeof canonicalJournalRecord>,
109
+ reservation: Reservation,
110
+ events: CheckedEvents,
111
+ receiptJSON: string,
112
+ ) {
113
+ if (
114
+ reservation.stage !== "attach" ||
115
+ (events.length !== 2 && events.length !== 3) ||
116
+ events[0].sequence !== 1 ||
117
+ events[1].sequence !== 2
118
+ )
119
+ acknowledgementConflict();
120
+ const parsedOriginal: unknown = JSON.parse(full.json);
121
+ const original = jsonObject(parsedOriginal);
122
+ const account = jsonObject(original.account);
123
+ const source = captureAttachSource(original.attachRequest);
124
+ if (!sameJSON(original.attachRequest, source)) acknowledgementConflict();
125
+ const parsedDispatch: unknown = JSON.parse(events[0].dataJSON);
126
+ const parsedResponse: unknown = JSON.parse(events[1].dataJSON);
127
+ captureAttachDispatch(parsedDispatch);
128
+ captureAttachResponse(parsedResponse);
129
+ const dispatch = jsonObject(parsedDispatch);
130
+ const response = jsonObject(parsedResponse);
131
+ const raw = captureAttachmentReceipt({
132
+ attachRequest: source,
133
+ actualDispatch: original.dispatch,
134
+ providerSnapshot: response.body,
135
+ });
136
+ // C3 internally rebuilds C1/C2 and compares the entire closed seven-wire input.
137
+ const rebuilt = await constructRenewalScheduleAttachmentReceiptV2({
138
+ attachRequest: source,
139
+ actualDispatch: raw.actualDispatch,
140
+ providerSnapshot: raw.providerSnapshot,
141
+ });
142
+ const request = rebuilt.request;
143
+ const seven = {
144
+ scope: request.scope,
145
+ apiVersion: request.apiVersion,
146
+ method: request.method,
147
+ path: request.path,
148
+ payload: request.payload,
149
+ key: request.key,
150
+ firstDispatchedAt: request.firstDispatchedAt,
151
+ };
152
+ if (
153
+ !sameJSON(original.dispatch, seven) ||
154
+ !sameJSON(dispatch.request, request) ||
155
+ !sameJSON(response.request, request) ||
156
+ original.stage !== "attach" ||
157
+ original.apiVersion !== request.apiVersion ||
158
+ full.requestBinding !== request.requestIdentity.binding ||
159
+ reservation.key !== request.key ||
160
+ reservation.apiVersion !== request.apiVersion ||
161
+ reservation.firstDispatchedAt !== request.firstDispatchedAt ||
162
+ account.mode !== "platform" ||
163
+ account.stripeAccount !== null ||
164
+ account.livemode !== rebuilt.livemode ||
165
+ !sameJSON(JSON.parse(reservation.accountJSON), account)
166
+ )
167
+ acknowledgementConflict();
168
+ if ("recordVersion" in reservation) {
169
+ if (
170
+ !sameJSON(JSON.parse(reservation.timingPolicyJSON), original.timingPolicy)
171
+ )
172
+ acknowledgementConflict();
173
+ } else if (!sameJSON(JSON.parse(reservation.basisJSON), original.basis))
174
+ acknowledgementConflict();
175
+ const admittedJSON = admitAttachReceiptOutputDATA(receiptJSON, rebuilt);
176
+ // Only ACTUAL published event3 is checked. A head2 retention does not model
177
+ // or require a prospective receipt-event envelope to pass another cap.
178
+ if (events.length === 3)
179
+ validateAttachReceiptEventDATA(events[2].dataJSON, rebuilt);
180
+ return {
181
+ receiptJSON: admittedJSON,
182
+ receiptBinding: rebuilt.binding,
183
+ receipt: rebuilt,
184
+ };
185
+ }
186
+
187
+ /** Whole typed C10 DATA and full request/receipt equality, never ACK authority. */
188
+ export function validateAttachReceiptEventDATA(
189
+ raw: string,
190
+ receipt: AttachReceipt,
191
+ ) {
192
+ const parsed: unknown = JSON.parse(raw);
193
+ captureAttachReceipt(parsed);
194
+ if (
195
+ !sameJSON(parsed, {
196
+ event: "receipt",
197
+ stage: "attach",
198
+ request: receipt.request,
199
+ receipt,
200
+ })
201
+ )
202
+ acknowledgementConflict();
203
+ }
@@ -0,0 +1,30 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { configureAcknowledgementFixture } from "./configureJournal.fixtures.js";
3
+
4
+ afterEach(() => vi.unstubAllGlobals());
5
+ it.each(["absent", "null", "object"] as const)(
6
+ "retains complete C9 DATA at head2 with %s defaults without claiming receipt3",
7
+ async (defaults) => {
8
+ const h = await configureAcknowledgementFixture(defaults);
9
+ const retained = await h.t.mutation(h.retain, h.retainArgs);
10
+ expect(retained.status).toBe("retained");
11
+ expect(retained.stage).toBe("configure");
12
+ expect(retained.receiptBinding).toBe(h.receipt.binding);
13
+ const read = await h.t.query(h.readAcknowledgement, {
14
+ operationId: h.created.operationId,
15
+ });
16
+ expect(read.retention).toEqual(retained);
17
+ expect(read.receiptJSON).toBe(h.retainArgs.receiptJSON);
18
+ expect(JSON.parse(read.receiptJSON).providerSnapshot).toEqual(h.response);
19
+ expect(
20
+ (
21
+ await h.t.query(h.readAttempt, {
22
+ operationId: h.created.operationId,
23
+ attemptId: h.acquired.reservation.attemptId,
24
+ })
25
+ ).events,
26
+ ).toHaveLength(2);
27
+ expect(await h.t.mutation(h.retain, h.retainArgs)).toEqual(retained);
28
+ expect(h.fetches()).toBe(0);
29
+ },
30
+ );