@fantastic.dev/better-stripe 0.80.0 → 0.82.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 (103) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAggregate/configure.d.ts +35 -0
  4. package/dist/client/billing/renewalAggregate/configure.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAggregate/configure.js +96 -0
  6. package/dist/client/billing/renewalAggregate/configure.js.map +1 -0
  7. package/dist/client/billing/renewalAggregate/index.d.ts +3 -0
  8. package/dist/client/billing/renewalAggregate/index.d.ts.map +1 -0
  9. package/dist/client/billing/renewalAggregate/index.js +3 -0
  10. package/dist/client/billing/renewalAggregate/index.js.map +1 -0
  11. package/dist/client/billing/renewalAggregate/phaseContext.d.ts +176 -0
  12. package/dist/client/billing/renewalAggregate/phaseContext.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAggregate/phaseContext.js +112 -0
  14. package/dist/client/billing/renewalAggregate/phaseContext.js.map +1 -0
  15. package/dist/client/billing/renewalAggregate/phases.d.ts +7 -0
  16. package/dist/client/billing/renewalAggregate/phases.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAggregate/phases.js +192 -0
  18. package/dist/client/billing/renewalAggregate/phases.js.map +1 -0
  19. package/dist/client/billing/renewalAggregate/preflight.d.ts +594 -0
  20. package/dist/client/billing/renewalAggregate/preflight.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAggregate/preflight.js +164 -0
  22. package/dist/client/billing/renewalAggregate/preflight.js.map +1 -0
  23. package/dist/client/billing/renewalAggregate/profile.d.ts +8 -0
  24. package/dist/client/billing/renewalAggregate/profile.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAggregate/profile.js +60 -0
  26. package/dist/client/billing/renewalAggregate/profile.js.map +1 -0
  27. package/dist/client/billing/renewalAggregate/receipt.d.ts +40 -0
  28. package/dist/client/billing/renewalAggregate/receipt.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAggregate/receipt.js +62 -0
  30. package/dist/client/billing/renewalAggregate/receipt.js.map +1 -0
  31. package/dist/client/billing/renewalAggregate/shared.d.ts +51 -0
  32. package/dist/client/billing/renewalAggregate/shared.d.ts.map +1 -0
  33. package/dist/client/billing/renewalAggregate/shared.js +87 -0
  34. package/dist/client/billing/renewalAggregate/shared.js.map +1 -0
  35. package/dist/client/billing/renewalAggregate/sourceDiscounts.d.ts +42 -0
  36. package/dist/client/billing/renewalAggregate/sourceDiscounts.d.ts.map +1 -0
  37. package/dist/client/billing/renewalAggregate/sourceDiscounts.js +90 -0
  38. package/dist/client/billing/renewalAggregate/sourceDiscounts.js.map +1 -0
  39. package/dist/client/billing/renewalAggregate/sourceSettings.d.ts +136 -0
  40. package/dist/client/billing/renewalAggregate/sourceSettings.d.ts.map +1 -0
  41. package/dist/client/billing/renewalAggregate/sourceSettings.js +82 -0
  42. package/dist/client/billing/renewalAggregate/sourceSettings.js.map +1 -0
  43. package/dist/client/billing/renewalAggregate/taxRetention.d.ts +8 -0
  44. package/dist/client/billing/renewalAggregate/taxRetention.d.ts.map +1 -0
  45. package/dist/client/billing/renewalAggregate/taxRetention.js +23 -0
  46. package/dist/client/billing/renewalAggregate/taxRetention.js.map +1 -0
  47. package/dist/client/billing/renewalPriceReplacement.d.ts +2 -0
  48. package/dist/client/billing/renewalPriceReplacement.d.ts.map +1 -1
  49. package/dist/client/billing/renewalProjection/discounts.d.ts +20 -0
  50. package/dist/client/billing/renewalProjection/discounts.d.ts.map +1 -0
  51. package/dist/client/billing/renewalProjection/discounts.js +121 -0
  52. package/dist/client/billing/renewalProjection/discounts.js.map +1 -0
  53. package/dist/client/billing/renewalProjection/itemSettings.d.ts +14 -0
  54. package/dist/client/billing/renewalProjection/itemSettings.d.ts.map +1 -0
  55. package/dist/client/billing/renewalProjection/itemSettings.js +41 -0
  56. package/dist/client/billing/renewalProjection/itemSettings.js.map +1 -0
  57. package/dist/client/billing/renewalProjection/settings.d.ts +18 -0
  58. package/dist/client/billing/renewalProjection/settings.d.ts.map +1 -0
  59. package/dist/client/billing/renewalProjection/settings.js +132 -0
  60. package/dist/client/billing/renewalProjection/settings.js.map +1 -0
  61. package/dist/client/billing/renewalProjection/settingsSchema.d.ts +200 -0
  62. package/dist/client/billing/renewalProjection/settingsSchema.d.ts.map +1 -0
  63. package/dist/client/billing/renewalProjection/settingsSchema.js +150 -0
  64. package/dist/client/billing/renewalProjection/settingsSchema.js.map +1 -0
  65. package/dist/client/billing/renewalReplacementSchema.d.ts +2 -0
  66. package/dist/client/billing/renewalReplacementSchema.d.ts.map +1 -1
  67. package/dist/client/billing/renewalReplacementSchema.js +10 -4
  68. package/dist/client/billing/renewalReplacementSchema.js.map +1 -1
  69. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  70. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  71. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  72. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  73. package/dist/component/payoutRelease/queries.d.ts +2 -2
  74. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  75. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  76. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  77. package/docs/renewal-phase-assembly.md +180 -0
  78. package/docs/renewal-preservation-mappings.md +94 -0
  79. package/docs/renewal-price-replacements.md +7 -0
  80. package/package.json +1 -1
  81. package/src/client/billing/renewal-discount-projection.test.ts +207 -0
  82. package/src/client/billing/renewal-item-settings-projection.test.ts +79 -0
  83. package/src/client/billing/renewal-price-replacement.test.ts +46 -0
  84. package/src/client/billing/renewal-settings-projection.test.ts +300 -0
  85. package/src/client/billing/renewalAggregate/configure.test.ts +372 -0
  86. package/src/client/billing/renewalAggregate/configure.ts +164 -0
  87. package/src/client/billing/renewalAggregate/index.ts +2 -0
  88. package/src/client/billing/renewalAggregate/phaseContext.ts +144 -0
  89. package/src/client/billing/renewalAggregate/phases.ts +247 -0
  90. package/src/client/billing/renewalAggregate/preflight.test.ts +233 -0
  91. package/src/client/billing/renewalAggregate/preflight.ts +211 -0
  92. package/src/client/billing/renewalAggregate/profile.ts +76 -0
  93. package/src/client/billing/renewalAggregate/receipt.ts +76 -0
  94. package/src/client/billing/renewalAggregate/shared.ts +106 -0
  95. package/src/client/billing/renewalAggregate/sourceAndTaxRetention.test.ts +247 -0
  96. package/src/client/billing/renewalAggregate/sourceDiscounts.ts +112 -0
  97. package/src/client/billing/renewalAggregate/sourceSettings.ts +88 -0
  98. package/src/client/billing/renewalAggregate/taxRetention.ts +28 -0
  99. package/src/client/billing/renewalProjection/discounts.ts +152 -0
  100. package/src/client/billing/renewalProjection/itemSettings.ts +55 -0
  101. package/src/client/billing/renewalProjection/settings.ts +163 -0
  102. package/src/client/billing/renewalProjection/settingsSchema.ts +154 -0
  103. package/src/client/billing/renewalReplacementSchema.ts +10 -4
@@ -0,0 +1,233 @@
1
+ import { expect, it } from "vitest";
2
+ import { preflightRenewalReplacement } from "./index.js";
3
+ import {
4
+ alter,
5
+ fixture,
6
+ stamp,
7
+ } from "../../../../tests/renewalAggregate/fixtures.js";
8
+
9
+ it("preflights exact cross-product paid terms without claiming provider qualification", () => {
10
+ const f = fixture();
11
+ const before = structuredClone(f.preflightInput);
12
+ const result = preflightRenewalReplacement(f.preflightInput);
13
+ expect(result).toMatchObject({
14
+ status: "preflighted_for_projection",
15
+ scope: "platform",
16
+ expected: f.prepared.expected,
17
+ quantity: 3,
18
+ providerQualification: "required",
19
+ profile: {
20
+ apiVersion: "2026-09-30.endive",
21
+ billingMode: "classic",
22
+ cadence: "same",
23
+ anchor: "ordinary",
24
+ },
25
+ });
26
+ expect(f.preflightInput).toEqual(before);
27
+ expect(result.status).not.toBe("pending");
28
+ expect(result.status).not.toBe("effective");
29
+ });
30
+
31
+ it("rejects an empty discount hierarchy before attach despite observed ancestor absence", () => {
32
+ const f = fixture({
33
+ subscription: { discounts: [] },
34
+ item: { discounts: [] },
35
+ });
36
+ expect(f.billingCustomer.discount).toBeNull();
37
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
38
+ status: "unsupported",
39
+ reason: expect.stringMatching(/discount|inherit/i),
40
+ });
41
+ });
42
+
43
+ it.each([
44
+ {
45
+ billing_thresholds: { amount_gte: 100, reset_billing_cycle_anchor: false },
46
+ },
47
+ { managed_payments: { enabled: true } },
48
+ { trial_end: stamp("2026-02-01T00:00:00Z") },
49
+ { next_pending_invoice_item_invoice: stamp("2026-01-25T00:00:00Z") },
50
+ { billing_mode: { type: "future_mode", flexible: null } },
51
+ ])(
52
+ "rejects known unproven original settings before attach %j",
53
+ (subscription) => {
54
+ expect(
55
+ preflightRenewalReplacement(fixture({ subscription }).preflightInput),
56
+ ).toMatchObject({ status: "unsupported", reason: expect.any(String) });
57
+ },
58
+ );
59
+
60
+ it.each([
61
+ ["customer_account", "acct_foreign"],
62
+ ["customer", "cus_foreign"],
63
+ ["currency", "eur"],
64
+ ["schedule", "sub_sched_foreign"],
65
+ ["cancel_at_period_end", true],
66
+ ] as const)("rejects fresh original drift at %s", (field, value) => {
67
+ const input = alter(
68
+ fixture().preflightInput,
69
+ ["freshSubscription", field],
70
+ value,
71
+ );
72
+ const result = preflightRenewalReplacement(input);
73
+ expect(["unsupported", "conflict"]).toContain(result.status);
74
+ expect(result).toHaveProperty("reason", expect.any(String));
75
+ });
76
+
77
+ it("rejects a forged logical binding rather than trusting its string", () => {
78
+ const result = preflightRenewalReplacement(
79
+ alter(
80
+ fixture().preflightInput,
81
+ ["prepared", "requestIdentity", "binding"],
82
+ "renewal:v1:forged",
83
+ ),
84
+ );
85
+ expect(result).toMatchObject({
86
+ status: "conflict",
87
+ reason: expect.stringMatching(/binding|prepared|identity/i),
88
+ });
89
+ });
90
+
91
+ it.each([
92
+ [["freshSubscription", "id"], "sub_other"],
93
+ [["freshSubscription", "items", "data", 0, "id"], "si_other"],
94
+ [["freshSubscription", "items", "data", 0, "quantity"], 4],
95
+ [["freshSubscription", "items", "data", 0, "current_period_end"], 999],
96
+ [["freshSubscription", "items", "data", 0, "price", "id"], "price_other"],
97
+ [
98
+ ["freshSubscription", "items", "data", 0, "price", "product"],
99
+ "other-product",
100
+ ],
101
+ [["freshSubscription", "items", "has_more"], true],
102
+ [["targetPrice", "id"], "price_other"],
103
+ [["targetPrice", "product"], "other-product"],
104
+ [["targetPrice", "active"], false],
105
+ [["targetPrice", "currency"], "eur"],
106
+ [["targetPrice", "livemode"], true],
107
+ [["billingCustomer", "customer_account"], "acct_other"],
108
+ [["billingCustomer", "deleted"], true],
109
+ ] as const)(
110
+ "rejects exact selector or incomplete read drift at %j",
111
+ (path, value) => {
112
+ const result = preflightRenewalReplacement(
113
+ alter(fixture().preflightInput, [...path], value),
114
+ );
115
+ expect(["unsupported", "conflict"]).toContain(result.status);
116
+ expect(result).toHaveProperty("reason", expect.any(String));
117
+ },
118
+ );
119
+
120
+ it("classifies flexible billing explicitly without silently migrating it", () => {
121
+ const f = fixture({
122
+ subscription: {
123
+ billing_mode: {
124
+ type: "flexible",
125
+ flexible: { proration_discounts: "included" },
126
+ updated_at: stamp("2025-12-01T00:00:00Z"),
127
+ },
128
+ },
129
+ });
130
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
131
+ status: "preflighted_for_projection",
132
+ providerQualification: "required",
133
+ profile: { billingMode: "flexible", cadence: "same" },
134
+ });
135
+ });
136
+
137
+ it("treats a different recurring count as changed cadence", () => {
138
+ expect(
139
+ preflightRenewalReplacement(fixture({ targetCount: 3 }).preflightInput),
140
+ ).toMatchObject({
141
+ status: "preflighted_for_projection",
142
+ profile: { cadence: "changed" },
143
+ providerQualification: "required",
144
+ });
145
+ });
146
+
147
+ it.each([
148
+ [
149
+ "2026-01-31T00:00:00Z",
150
+ "2026-02-28T00:00:00Z",
151
+ "2026-02-01T00:00:00Z",
152
+ "month",
153
+ ],
154
+ [
155
+ "2024-01-31T00:00:00Z",
156
+ "2024-02-29T00:00:00Z",
157
+ "2024-02-01T00:00:00Z",
158
+ "month",
159
+ ],
160
+ [
161
+ "2024-02-29T00:00:00Z",
162
+ "2025-02-28T00:00:00Z",
163
+ "2024-06-01T00:00:00Z",
164
+ "year",
165
+ ],
166
+ ] as const)(
167
+ "retains calendar-edge qualification for %s",
168
+ (start, end, observed, interval) => {
169
+ const f = fixture({
170
+ start: stamp(start),
171
+ end: stamp(end),
172
+ observedAt: stamp(observed),
173
+ currentInterval: interval,
174
+ targetInterval: interval,
175
+ });
176
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
177
+ status: "preflighted_for_projection",
178
+ providerQualification: "required",
179
+ profile: { anchor: "calendar_edge", cadence: "same" },
180
+ });
181
+ },
182
+ );
183
+
184
+ it("keeps changed-cadence anchor configuration explicitly unsupported", () => {
185
+ const f = fixture({
186
+ targetInterval: "year",
187
+ subscription: {
188
+ billing_cycle_anchor_config: {
189
+ day_of_month: 15,
190
+ month: null,
191
+ hour: 0,
192
+ minute: 0,
193
+ second: 0,
194
+ },
195
+ },
196
+ });
197
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
198
+ status: "unsupported",
199
+ reason: expect.stringMatching(/anchor|cadence/i),
200
+ });
201
+ });
202
+
203
+ it("does not normalize an explicit preview version to endive", () => {
204
+ const result = preflightRenewalReplacement({
205
+ ...fixture().preflightInput,
206
+ apiVersion: "2026-09-30.preview",
207
+ });
208
+ expect(result).toMatchObject({
209
+ status: "unsupported",
210
+ reason: expect.stringMatching(/version|preview/i),
211
+ });
212
+ });
213
+
214
+ it.each([
215
+ { id: "custom-target", object: "customer", livemode: false },
216
+ { id: "custom-target", object: "product", livemode: true },
217
+ ])("rejects contradictory expanded target product facts %j", (product) => {
218
+ if (product.object !== "product") {
219
+ const malformedFreshRead = alter(
220
+ fixture().preflightInput,
221
+ ["targetPrice", "product"],
222
+ product,
223
+ );
224
+ expect(preflightRenewalReplacement(malformedFreshRead).status).toBe(
225
+ "unsupported",
226
+ );
227
+ return;
228
+ }
229
+ const f = fixture({ target: { product } });
230
+ expect(preflightRenewalReplacement(f.preflightInput).status).toBe(
231
+ "unsupported",
232
+ );
233
+ });
@@ -0,0 +1,211 @@
1
+ import { z } from "zod";
2
+ import { prepareRenewalPriceReplacement } from "../renewalPriceReplacement.js";
3
+ import {
4
+ renewalSubscription,
5
+ renewalPrice,
6
+ renewalBillingCustomer,
7
+ } from "../renewalReplacementSchema.js";
8
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
9
+ import {
10
+ object,
11
+ readInput,
12
+ referenceId,
13
+ equal,
14
+ conflict,
15
+ unsupported,
16
+ failure,
17
+ supportedVersion,
18
+ timestamp,
19
+ resourceId,
20
+ productId,
21
+ } from "./shared.js";
22
+ import { profileOf } from "./profile.js";
23
+ import { qualifySourceDiscounts } from "./sourceDiscounts.js";
24
+ import { qualifyOriginalSettings } from "./sourceSettings.js";
25
+
26
+ export function retainedPreparation(value: unknown) {
27
+ try {
28
+ const candidate = object(value);
29
+ const snapshot = object(candidate.providerSnapshot);
30
+ const identity = object(candidate.requestIdentity);
31
+ const prepared = prepareRenewalPriceReplacement({
32
+ subscription: snapshot.subscription,
33
+ targetPrice: snapshot.targetPrice,
34
+ ...(snapshot.billingCustomer === undefined
35
+ ? {}
36
+ : { billingCustomer: snapshot.billingCustomer }),
37
+ expected: candidate.expected as Parameters<
38
+ typeof prepareRenewalPriceReplacement
39
+ >[0]["expected"],
40
+ key: z.string().parse(identity.key),
41
+ });
42
+ if (!equal(prepared, candidate)) conflict("invalid_prepared_binding");
43
+ return prepared;
44
+ } catch {
45
+ return conflict("invalid_prepared_binding");
46
+ }
47
+ }
48
+
49
+ const attachedReference = z.union([
50
+ resourceId("sub_sched"),
51
+ z
52
+ .object({
53
+ id: resourceId("sub_sched"),
54
+ object: z.literal("subscription_schedule"),
55
+ deleted: z.literal(false).optional(),
56
+ customer_account: resourceId("acct").optional(),
57
+ livemode: z.boolean().optional(),
58
+ })
59
+ .passthrough(),
60
+ ]);
61
+
62
+ export function validateReads(
63
+ args: z.infer<typeof readInput>,
64
+ scheduleId?: string,
65
+ ) {
66
+ const prepared = retainedPreparation(args.prepared);
67
+ supportedVersion(args.apiVersion);
68
+ const subscription = renewalSubscription
69
+ .extend({ schedule: scheduleId ? attachedReference : z.null() })
70
+ .safeParse(args.freshSubscription);
71
+ if (!subscription.success)
72
+ unsupported("unsupported_original_subscription_state");
73
+ const source = subscription.data;
74
+ if (scheduleId) {
75
+ if (
76
+ referenceId(source.schedule, "sub_sched", "subscription_schedule") !==
77
+ scheduleId
78
+ )
79
+ conflict("schedule_association_mismatch");
80
+ if (
81
+ typeof source.schedule === "object" &&
82
+ source.schedule !== null &&
83
+ ((source.schedule.customer_account !== undefined &&
84
+ source.schedule.customer_account !==
85
+ prepared.expected.customerAccountId) ||
86
+ (source.schedule.livemode !== undefined &&
87
+ source.schedule.livemode !== prepared.expected.livemode))
88
+ )
89
+ conflict("schedule_association_mismatch");
90
+ }
91
+ const { schedule: originalSchedule, ...original } =
92
+ prepared.providerSnapshot.subscription;
93
+ const { schedule: freshSchedule, ...fresh } = source;
94
+ if (scheduleId ? originalSchedule !== null : freshSchedule !== null)
95
+ conflict("schedule_association_mismatch");
96
+ if (!equal(original, fresh)) conflict("original_source_drift");
97
+ const target = renewalPrice.safeParse(args.targetPrice);
98
+ if (!target.success || !target.data.active)
99
+ unsupported("unsupported_target_price");
100
+ if (!equal(target.data, prepared.providerSnapshot.targetPrice))
101
+ conflict("target_price_drift");
102
+ if (
103
+ prepared.providerSnapshot.billingCustomer === undefined ||
104
+ args.billingCustomer === undefined
105
+ )
106
+ unsupported("missing_retained_billing_customer");
107
+ const customer = renewalBillingCustomer.safeParse(args.billingCustomer);
108
+ if (!customer.success) unsupported("unsupported_billing_customer");
109
+ if (!equal(customer.data, prepared.providerSnapshot.billingCustomer))
110
+ conflict("billing_customer_drift");
111
+ const referenceContext = {
112
+ customerAccountId: prepared.expected.customerAccountId,
113
+ livemode: prepared.expected.livemode,
114
+ };
115
+ if (
116
+ referenceId(source.customer, "cus", "customer", referenceContext) !==
117
+ customer.data.id ||
118
+ customer.data.customer_account !== prepared.expected.customerAccountId ||
119
+ customer.data.livemode !== prepared.expected.livemode
120
+ )
121
+ conflict("billing_customer_identity_mismatch");
122
+ const item = source.items.data[0];
123
+ if (
124
+ productId(item.price.product, referenceContext) !==
125
+ prepared.expected.currentProductId ||
126
+ productId(target.data.product, referenceContext) !==
127
+ prepared.expected.targetProductId
128
+ )
129
+ unsupported("product_identity_mismatch");
130
+ if (
131
+ args.observedAt < prepared.expected.periodStart ||
132
+ args.observedAt >= prepared.expected.periodEnd
133
+ )
134
+ unsupported("outside_original_paid_period");
135
+ for (const field of [
136
+ "billing_thresholds",
137
+ "managed_payments",
138
+ "next_pending_invoice_item_invoice",
139
+ "pending_invoice_item_interval",
140
+ "pending_setup_intent",
141
+ "canceled_at",
142
+ "ended_at",
143
+ "trial_settings",
144
+ ])
145
+ if (source[field] !== null) unsupported(`unsupported_original_${field}`);
146
+ if (item.billing_thresholds !== null)
147
+ unsupported("unsupported_item_billing_thresholds");
148
+ if (item.current_trial !== null)
149
+ unsupported("unsupported_or_missing_item_current_trial");
150
+ if (
151
+ !Array.isArray(source.billing_schedules) ||
152
+ source.billing_schedules.length
153
+ )
154
+ unsupported("unsupported_original_billing_schedules");
155
+ if (
156
+ source.trial_end !== null &&
157
+ (!timestamp.safeParse(source.trial_end).success ||
158
+ Number(source.trial_end) > prepared.expected.periodStart)
159
+ )
160
+ unsupported("unsupported_original_trial");
161
+ if (source.status_details != null || source.presentment_details != null)
162
+ unsupported("unsupported_special_billing_state");
163
+ const originalSettings = qualifyOriginalSettings(source, item, customer.data);
164
+ const profile = profileOf(source, item.price, target.data, args.apiVersion);
165
+ const anchor = timestamp.parse(source.billing_cycle_anchor);
166
+ if (anchor > prepared.expected.periodStart)
167
+ unsupported("unqualified_anchor_after_paid_period_start");
168
+ const discounts = qualifySourceDiscounts(
169
+ source.discounts,
170
+ "subscription",
171
+ prepared.expected,
172
+ customer.data.id,
173
+ args.observedAt,
174
+ );
175
+ const itemDiscounts = qualifySourceDiscounts(
176
+ item.discounts,
177
+ "item",
178
+ prepared.expected,
179
+ customer.data.id,
180
+ args.observedAt,
181
+ );
182
+ return {
183
+ prepared,
184
+ subscription: source,
185
+ item,
186
+ customer: customer.data,
187
+ targetPrice: target.data,
188
+ profile,
189
+ discounts,
190
+ itemDiscounts,
191
+ originalSettings,
192
+ };
193
+ }
194
+
195
+ export function preflightRenewalReplacement(input: unknown) {
196
+ try {
197
+ const args = readInput.parse(renewalSnapshot(input));
198
+ const reads = validateReads(args);
199
+ return {
200
+ version: 1 as const,
201
+ status: "preflighted_for_projection" as const,
202
+ scope: "platform" as const,
203
+ expected: reads.prepared.expected,
204
+ quantity: reads.prepared.quantity,
205
+ profile: reads.profile,
206
+ providerQualification: "required" as const,
207
+ };
208
+ } catch (error) {
209
+ return failure(error);
210
+ }
211
+ }
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ import { object, timestamp, unsupported } from "./shared.js";
3
+
4
+ const mode = z
5
+ .object({
6
+ type: z.enum(["classic", "flexible"]),
7
+ flexible: z
8
+ .object({
9
+ proration_discounts: z.enum(["included", "itemized"]).optional(),
10
+ })
11
+ .strict()
12
+ .nullable(),
13
+ updated_at: timestamp.optional(),
14
+ })
15
+ .strict()
16
+ .refine((value) => value.type !== "classic" || value.flexible === null);
17
+ const anchorConfig = z
18
+ .object({
19
+ day_of_month: z.number().int().min(1).max(31),
20
+ month: z.number().int().min(1).max(12).nullable(),
21
+ hour: z.number().int().min(0).max(23).nullable(),
22
+ minute: z.number().int().min(0).max(59).nullable(),
23
+ second: z.number().int().min(0).max(59).nullable(),
24
+ })
25
+ .strict()
26
+ .nullable();
27
+ export type RenewalProfile = {
28
+ apiVersion: string;
29
+ billingMode: "classic" | "flexible";
30
+ cadence: "same" | "changed";
31
+ anchor: "ordinary" | "calendar_edge";
32
+ };
33
+
34
+ export function profileOf(
35
+ subscription: Record<string, unknown>,
36
+ currentPrice: unknown,
37
+ targetPrice: unknown,
38
+ apiVersion: string,
39
+ ): RenewalProfile {
40
+ const parsedMode = mode.safeParse(subscription.billing_mode);
41
+ if (!parsedMode.success) unsupported("unsupported_billing_mode");
42
+ const parsedConfig = anchorConfig.safeParse(
43
+ subscription.billing_cycle_anchor_config,
44
+ );
45
+ if (!parsedConfig.success) unsupported("unsupported_anchor_config");
46
+ const anchor = timestamp.safeParse(subscription.billing_cycle_anchor);
47
+ if (
48
+ !anchor.success ||
49
+ !Number.isFinite(new Date(anchor.data * 1000).getTime())
50
+ )
51
+ unsupported("unsupported_numeric_anchor");
52
+ const current = object(object(currentPrice).recurring);
53
+ const target = object(object(targetPrice).recurring);
54
+ const cadence =
55
+ current.interval === target.interval &&
56
+ current.interval_count === target.interval_count
57
+ ? "same"
58
+ : "changed";
59
+ if (parsedConfig.data !== null) {
60
+ if (current.interval !== "month" && current.interval !== "year")
61
+ unsupported("unsupported_anchor_config_cadence");
62
+ if (cadence === "changed")
63
+ unsupported("unsupported_changed_cadence_anchor_config");
64
+ }
65
+ const calendar = current.interval === "month" || current.interval === "year";
66
+ const edge =
67
+ calendar &&
68
+ (new Date(anchor.data * 1000).getUTCDate() >= 29 ||
69
+ (parsedConfig.data?.day_of_month ?? 0) >= 29);
70
+ return {
71
+ apiVersion,
72
+ billingMode: parsedMode.data.type,
73
+ cadence,
74
+ anchor: edge ? "calendar_edge" : "ordinary",
75
+ };
76
+ }
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ import { idempotencyOptions } from "../../core/idempotency.js";
3
+ import { binding, conflict, resourceId, timestamp } from "./shared.js";
4
+
5
+ const requestSchema = z
6
+ .object({
7
+ version: z.literal(1),
8
+ stage: z.literal("attach"),
9
+ scope: z.literal("platform"),
10
+ apiVersion: z.string(),
11
+ logicalBinding: z.string(),
12
+ method: z.literal("POST"),
13
+ path: z.literal("/v1/subscription_schedules"),
14
+ payload: z.object({ from_subscription: resourceId("sub") }).strict(),
15
+ key: z.string(),
16
+ firstDispatchedAt: timestamp,
17
+ requestIdentity: z
18
+ .object({ key: z.string(), binding: z.string() })
19
+ .strict(),
20
+ })
21
+ .strict();
22
+ const receiptSchema = z
23
+ .object({
24
+ version: z.literal(1),
25
+ stage: z.literal("attached_unconfigured"),
26
+ scope: z.literal("platform"),
27
+ logicalBinding: z.string(),
28
+ request: requestSchema,
29
+ scheduleId: resourceId("sub_sched"),
30
+ subscriptionId: resourceId("sub"),
31
+ customerAccountId: resourceId("acct"),
32
+ livemode: z.boolean(),
33
+ providerSnapshot: z.unknown(),
34
+ binding: z.string(),
35
+ })
36
+ .strict();
37
+
38
+ export function validateAttachReceipt(
39
+ value: unknown,
40
+ prepared: {
41
+ requestIdentity: { binding: string };
42
+ expected: {
43
+ subscriptionId: string;
44
+ customerAccountId: string;
45
+ livemode: boolean;
46
+ };
47
+ },
48
+ apiVersion: string,
49
+ observedAt: number,
50
+ ) {
51
+ try {
52
+ const receipt = receiptSchema.parse(value);
53
+ const { requestIdentity, ...unsignedRequest } = receipt.request;
54
+ const { binding: receivedBinding, ...unsignedReceipt } = receipt;
55
+ const key = idempotencyOptions(receipt.request.key)?.idempotencyKey;
56
+ if (
57
+ !key ||
58
+ requestIdentity.key !== key ||
59
+ requestIdentity.binding !== binding("renewal-attach", unsignedRequest) ||
60
+ receivedBinding !== binding("renewal-attach-receipt", unsignedReceipt) ||
61
+ receipt.logicalBinding !== prepared.requestIdentity.binding ||
62
+ receipt.request.logicalBinding !== prepared.requestIdentity.binding ||
63
+ receipt.request.apiVersion !== apiVersion ||
64
+ receipt.request.payload.from_subscription !==
65
+ prepared.expected.subscriptionId ||
66
+ receipt.subscriptionId !== prepared.expected.subscriptionId ||
67
+ receipt.customerAccountId !== prepared.expected.customerAccountId ||
68
+ receipt.livemode !== prepared.expected.livemode ||
69
+ receipt.request.firstDispatchedAt > observedAt
70
+ )
71
+ conflict("invalid_attach_receipt_binding");
72
+ return receipt;
73
+ } catch {
74
+ return conflict("invalid_attach_receipt_binding");
75
+ }
76
+ }
@@ -0,0 +1,106 @@
1
+ import { z } from "zod";
2
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
3
+
4
+ export const timestamp = z
5
+ .number()
6
+ .int()
7
+ .nonnegative()
8
+ .max(Number.MAX_SAFE_INTEGER);
9
+ export const resourceId = (prefix: string) =>
10
+ z
11
+ .string()
12
+ .max(255)
13
+ .regex(new RegExp(`^${prefix}_[A-Za-z0-9_]+$`));
14
+ export type ObjectData = Record<string, unknown>;
15
+ export class ProjectionError extends Error {
16
+ constructor(
17
+ readonly kind: "unsupported" | "conflict",
18
+ reason: string,
19
+ ) {
20
+ super(reason);
21
+ }
22
+ }
23
+ export function unsupported(reason: string): never {
24
+ throw new ProjectionError("unsupported", reason);
25
+ }
26
+ export function conflict(reason: string): never {
27
+ throw new ProjectionError("conflict", reason);
28
+ }
29
+ export const object = (value: unknown): ObjectData =>
30
+ z.record(z.string(), z.unknown()).parse(value);
31
+ export const canonical = (value: unknown) =>
32
+ JSON.stringify(renewalSnapshot(value));
33
+ export const binding = (namespace: string, value: unknown) =>
34
+ `${namespace}:v1:${canonical(value)}`;
35
+ export const equal = (left: unknown, right: unknown) =>
36
+ canonical(left) === canonical(right);
37
+
38
+ export type ReferenceContext = { livemode: boolean; customerAccountId: string };
39
+ function referenceFacts(reference: ObjectData, context?: ReferenceContext) {
40
+ if (
41
+ context &&
42
+ ((reference.livemode !== undefined &&
43
+ reference.livemode !== context.livemode) ||
44
+ (reference.customer_account !== undefined &&
45
+ reference.customer_account !== context.customerAccountId))
46
+ )
47
+ unsupported("expanded_reference_scope_mismatch");
48
+ }
49
+ export function referenceId(
50
+ value: unknown,
51
+ prefix: string,
52
+ kind: string,
53
+ context?: ReferenceContext,
54
+ ): string {
55
+ if (typeof value === "string") return resourceId(prefix).parse(value);
56
+ const reference = object(value);
57
+ if (reference.object !== kind || reference.deleted === true)
58
+ unsupported(`invalid_${kind}_reference`);
59
+ referenceFacts(reference, context);
60
+ return resourceId(prefix).parse(reference.id);
61
+ }
62
+ export function productId(value: unknown, context: ReferenceContext): string {
63
+ const id = z.string().min(1).max(255).regex(/\S/);
64
+ if (typeof value === "string") return id.parse(value);
65
+ const reference = object(value);
66
+ if (reference.object !== "product" || reference.deleted === true)
67
+ unsupported("invalid_product_reference");
68
+ referenceFacts(reference, context);
69
+ return id.parse(reference.id);
70
+ }
71
+ export type Failure =
72
+ | { status: "unsupported" | "conflict"; reason: string }
73
+ | { status: "attached_unconfigured"; scheduleId: string; reason: string };
74
+ export function failure(error: unknown, scheduleId?: string): Failure {
75
+ const known = error instanceof ProjectionError;
76
+ const kind = known ? error.kind : "unsupported";
77
+ const reason = known ? error.message : "incomplete_or_unsupported_schema";
78
+ if (kind === "unsupported" && scheduleId)
79
+ return { status: "attached_unconfigured", scheduleId, reason };
80
+ return { status: kind, reason };
81
+ }
82
+
83
+ export const readInput = z
84
+ .object({
85
+ prepared: z.unknown(),
86
+ freshSubscription: z.unknown(),
87
+ targetPrice: z.unknown(),
88
+ billingCustomer: z.unknown().optional(),
89
+ apiVersion: z.string(),
90
+ observedAt: timestamp,
91
+ })
92
+ .strict();
93
+ export const configureInput = readInput
94
+ .extend({
95
+ attachReceipt: z.unknown(),
96
+ schedule: z.unknown(),
97
+ configureKey: z.string(),
98
+ firstDispatchedAt: timestamp,
99
+ })
100
+ .strict();
101
+
102
+ export function supportedVersion(version: string) {
103
+ if (version !== "2026-09-30.endive")
104
+ unsupported("unqualified_api_version_profile");
105
+ return version;
106
+ }