@fantastic.dev/better-stripe 0.95.0 → 0.96.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 (63) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -1
  4. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +2 -5
  5. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -1
  6. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.d.ts.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js +15 -4
  8. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js.map +1 -1
  9. package/dist/client/billing/renewalObservation/evidence-invoice-lines.d.ts +27 -0
  10. package/dist/client/billing/renewalObservation/evidence-invoice-lines.d.ts.map +1 -0
  11. package/dist/client/billing/renewalObservation/evidence-invoice-lines.js +164 -0
  12. package/dist/client/billing/renewalObservation/evidence-invoice-lines.js.map +1 -0
  13. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts +4 -0
  14. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts.map +1 -0
  15. package/dist/client/billing/renewalObservation/evidence-invoice.js +190 -0
  16. package/dist/client/billing/renewalObservation/evidence-invoice.js.map +1 -0
  17. package/dist/client/billing/renewalObservation/evidence-material.d.ts +26 -0
  18. package/dist/client/billing/renewalObservation/evidence-material.d.ts.map +1 -0
  19. package/dist/client/billing/renewalObservation/evidence-material.js +253 -0
  20. package/dist/client/billing/renewalObservation/evidence-material.js.map +1 -0
  21. package/dist/client/billing/renewalObservation/evidence-v1-types.d.ts +156 -0
  22. package/dist/client/billing/renewalObservation/evidence-v1-types.d.ts.map +1 -0
  23. package/dist/client/billing/renewalObservation/evidence-v1-types.js +2 -0
  24. package/dist/client/billing/renewalObservation/evidence-v1-types.js.map +1 -0
  25. package/dist/client/billing/renewalObservation/evidence-v1.d.ts +4 -0
  26. package/dist/client/billing/renewalObservation/evidence-v1.d.ts.map +1 -0
  27. package/dist/client/billing/renewalObservation/evidence-v1.js +263 -0
  28. package/dist/client/billing/renewalObservation/evidence-v1.js.map +1 -0
  29. package/dist/client/billing/renewalObservation/terminal-evidence.d.ts +17 -0
  30. package/dist/client/billing/renewalObservation/terminal-evidence.d.ts.map +1 -0
  31. package/dist/client/billing/renewalObservation/terminal-evidence.js +289 -0
  32. package/dist/client/billing/renewalObservation/terminal-evidence.js.map +1 -0
  33. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  34. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  35. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  36. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  37. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  38. package/dist/component/earnings/triggers.d.ts +16 -16
  39. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  40. package/dist/component/payoutRelease/queries.d.ts +2 -2
  41. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  42. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  43. package/dist/component/usageCredits/accounting.fixtures.d.ts +16 -16
  44. package/docs/renewal-context-reads.md +9 -5
  45. package/docs/renewal-material-observation.md +50 -0
  46. package/package.json +1 -1
  47. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +2 -5
  48. package/src/client/billing/renewalAttach/internal/producer/ownerFactory.ts +17 -5
  49. package/src/client/billing/renewalAttach/internal/producer/producerClock.integration.test.ts +175 -0
  50. package/src/client/billing/renewalAttach/internal/producer/producerOwner.integration.test.ts +15 -23
  51. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +62 -0
  52. package/src/client/billing/renewalObservation/evidence-admission.test.ts +219 -0
  53. package/src/client/billing/renewalObservation/evidence-history.test.ts +187 -0
  54. package/src/client/billing/renewalObservation/evidence-invoice-controls.test.ts +293 -0
  55. package/src/client/billing/renewalObservation/evidence-invoice-lines.ts +238 -0
  56. package/src/client/billing/renewalObservation/evidence-invoice.test.ts +177 -0
  57. package/src/client/billing/renewalObservation/evidence-invoice.ts +271 -0
  58. package/src/client/billing/renewalObservation/evidence-material.test.ts +289 -0
  59. package/src/client/billing/renewalObservation/evidence-material.ts +313 -0
  60. package/src/client/billing/renewalObservation/evidence-v1-types.ts +186 -0
  61. package/src/client/billing/renewalObservation/evidence-v1.test.ts +371 -0
  62. package/src/client/billing/renewalObservation/evidence-v1.ts +286 -0
  63. package/src/client/billing/renewalObservation/terminal-evidence.ts +379 -0
@@ -0,0 +1,286 @@
1
+ import type {
2
+ IdentityV1,
3
+ Reason,
4
+ RenewalEvidenceResultV1,
5
+ } from "./evidence-v1-types.js";
6
+ import { inspectTerminalEvidenceV1 } from "./terminal-evidence.js";
7
+ import { inspectInvoiceEvidenceV1 } from "./evidence-invoice.js";
8
+ import {
9
+ inspectCurrentMaterialEvidenceV1,
10
+ inspectHistoricalMaterialEvidenceV1,
11
+ inspectConfiguredEvidenceV1,
12
+ } from "./evidence-material.js";
13
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
14
+ import {
15
+ reconstructConfigurationV2,
16
+ type ProjectRenewalConfigurationV2Options,
17
+ type ConstructRenewalConfigurationReceiptV2Options,
18
+ } from "../renewalV2/index.js";
19
+ import { captureObservation } from "../renewalV2/observationInput.js";
20
+ import { object, array, get, productId } from "./common.js";
21
+
22
+ function invalid(): never {
23
+ throw Error("Invalid raw renewal evidence.");
24
+ }
25
+ function fields(raw: unknown, names: string[]) {
26
+ const value = object(raw);
27
+ const keys = Reflect.ownKeys(value);
28
+ if (keys.length !== names.length || names.some((k) => !keys.includes(k)))
29
+ invalid();
30
+ return value;
31
+ }
32
+ /** Copy the complete ordinary DATA model before any pure reconstruction. */
33
+ function capture(raw: unknown) {
34
+ let nodes = 0;
35
+ let characters = 0;
36
+ const seen = new Set<object>();
37
+ function copy(value: unknown, depth: number): unknown {
38
+ if (++nodes > 10000 || depth > 40) invalid();
39
+ if (typeof value === "string") {
40
+ characters += value.length;
41
+ if (characters > 500000) invalid();
42
+ return value;
43
+ }
44
+ if (value === null || typeof value === "boolean") return value;
45
+ if (typeof value === "number" && Number.isFinite(value)) return value;
46
+ if (!value || typeof value !== "object" || seen.has(value)) invalid();
47
+ const isArray = Array.isArray(value);
48
+ if (
49
+ !isArray &&
50
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value))
51
+ )
52
+ invalid();
53
+ seen.add(value);
54
+ const keys = Reflect.ownKeys(value);
55
+ const entries: [string, unknown][] = [];
56
+ const length = isArray
57
+ ? Object.getOwnPropertyDescriptor(value, "length")
58
+ : null;
59
+ if (
60
+ isArray &&
61
+ (!length ||
62
+ !("value" in length) ||
63
+ !Number.isSafeInteger(length.value) ||
64
+ length.value < 0 ||
65
+ length.value > 10000)
66
+ )
67
+ invalid();
68
+ for (const key of keys) {
69
+ if (isArray && key === "length") continue;
70
+ if (typeof key !== "string") invalid();
71
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
72
+ if (!descriptor || !descriptor.enumerable || !("value" in descriptor))
73
+ invalid();
74
+ characters += key.length;
75
+ if (characters > 500000) invalid();
76
+ if (
77
+ isArray &&
78
+ (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= length!.value)
79
+ )
80
+ invalid();
81
+ entries.push([key, copy(descriptor.value, depth + 1)]);
82
+ }
83
+ seen.delete(value);
84
+ if (!isArray) return Object.fromEntries(entries);
85
+ if (entries.length !== length!.value) invalid();
86
+ const selected = new Map(entries);
87
+ return Array.from({ length: length!.value }, (_, i) => {
88
+ if (!selected.has(String(i))) invalid();
89
+ return selected.get(String(i));
90
+ });
91
+ }
92
+ try {
93
+ const copied = renewalSnapshot(copy(raw, 0));
94
+ if (new TextEncoder().encode(JSON.stringify(copied)).byteLength > 500000)
95
+ invalid();
96
+ return fields(copied, [
97
+ "version",
98
+ "apiVersion",
99
+ "configuration",
100
+ "configureReceipt",
101
+ "reads",
102
+ "invoiceContext",
103
+ "historicalSnapshot",
104
+ ]);
105
+ } catch {
106
+ invalid();
107
+ }
108
+ }
109
+ function unknown(reason: Reason): RenewalEvidenceResultV1 {
110
+ return {
111
+ version: 1,
112
+ kind: "renewal_evidence_data",
113
+ apiVersion: "2026-09-30.endive",
114
+ identity: null,
115
+ lifecycle: {
116
+ predicate: "unknown",
117
+ providerStatus: null,
118
+ facts: null,
119
+ completion: null,
120
+ reason,
121
+ },
122
+ currentMaterial: {
123
+ predicate: "unknown",
124
+ observedItemId: null,
125
+ nativePeriod: null,
126
+ reason,
127
+ },
128
+ historicalMaterial: {
129
+ predicate: "unknown",
130
+ observedItemId: null,
131
+ nativePeriod: null,
132
+ reason,
133
+ },
134
+ invoiceEvidence: {
135
+ predicate: "unknown",
136
+ original: null,
137
+ current: null,
138
+ reason,
139
+ },
140
+ acknowledgementEstablished: false,
141
+ authenticationEstablished: false,
142
+ operationalAuthority: false,
143
+ providerQualificationRequired: true,
144
+ };
145
+ }
146
+ /** Unsigned terminal evidence DATA; no transport or operational admission. */
147
+ export async function inspectRenewalEvidenceV1(
148
+ input: unknown,
149
+ ): Promise<RenewalEvidenceResultV1> {
150
+ const raw = capture(input);
151
+ if (raw.apiVersion !== "2026-09-30.endive")
152
+ return unknown("unsupported_api_version");
153
+ if (raw.version !== 1) return unknown("unsupported_profile");
154
+ let result = unknown("incomplete_material");
155
+ try {
156
+ const captured = captureObservation({
157
+ configuration: raw.configuration,
158
+ reads: raw.reads,
159
+ ...(raw.configureReceipt === null
160
+ ? {}
161
+ : { configureReceipt: raw.configureReceipt }),
162
+ });
163
+ const reconstructed = await reconstructConfigurationV2(
164
+ captured.configuration as ProjectRenewalConfigurationV2Options,
165
+ );
166
+ if (!reconstructed.material) return result;
167
+ const { material, result: desired } = reconstructed;
168
+ const prepared = material.prepared;
169
+ const expected = object(prepared.expected);
170
+ const originalSub = get(object(prepared.providerSnapshot), "subscription");
171
+ const originalItem = object(array(get(originalSub, "items").data)[0]);
172
+ const context = {
173
+ customerAccountId: String(expected.customerAccountId),
174
+ livemode: expected.livemode as boolean,
175
+ };
176
+ const identity: IdentityV1 = {
177
+ scope: "platform",
178
+ ...context,
179
+ customerId: String(object(material.args.billingCustomer).id),
180
+ scheduleId: material.receipt.scheduleId,
181
+ subscriptionId: String(expected.subscriptionId),
182
+ originalItemId: String(originalItem.id),
183
+ targetPriceId: String(expected.targetPriceId),
184
+ targetProductId: productId(
185
+ object(material.args.targetPrice).product,
186
+ context,
187
+ ),
188
+ originalNativePeriod: {
189
+ start: Number(expected.periodStart),
190
+ end: Number(expected.periodEnd),
191
+ },
192
+ targetBoundary: Number(expected.periodEnd),
193
+ };
194
+ result = { ...result, identity };
195
+ const configured = await inspectConfiguredEvidenceV1({
196
+ configuration:
197
+ captured.configuration as ProjectRenewalConfigurationV2Options,
198
+ configureReceipt: captured.configureReceipt
199
+ ? (captured.configureReceipt as ConstructRenewalConfigurationReceiptV2Options)
200
+ : null,
201
+ owned: { ...material, request: desired },
202
+ });
203
+ const lifecycle = inspectTerminalEvidenceV1({
204
+ identity,
205
+ reads: captured.reads,
206
+ originalSchedule: material.receipt.providerSnapshot,
207
+ originalSub,
208
+ originalCustomer: material.args.billingCustomer,
209
+ target: material.args.targetPrice,
210
+ desired,
211
+ configured,
212
+ });
213
+ result = {
214
+ ...result,
215
+ lifecycle,
216
+ currentMaterial: {
217
+ predicate:
218
+ lifecycle.reason === "owned_identity_mismatch"
219
+ ? "conflict"
220
+ : "unknown",
221
+ observedItemId: null,
222
+ nativePeriod: null,
223
+ reason:
224
+ lifecycle.reason === "owned_identity_mismatch"
225
+ ? "owned_identity_mismatch"
226
+ : "terminal_completion_unproven",
227
+ },
228
+ historicalMaterial: {
229
+ predicate: "unknown",
230
+ observedItemId: null,
231
+ nativePeriod: null,
232
+ reason:
233
+ raw.historicalSnapshot === null
234
+ ? "not_supplied"
235
+ : "unsupported_profile",
236
+ },
237
+ invoiceEvidence: {
238
+ predicate: "unknown",
239
+ original: null,
240
+ current: null,
241
+ reason:
242
+ raw.invoiceContext === null ? "not_supplied" : "unsupported_profile",
243
+ },
244
+ };
245
+ if (
246
+ lifecycle.predicate === "status_only" &&
247
+ lifecycle.providerStatus === "active"
248
+ )
249
+ result = {
250
+ ...result,
251
+ currentMaterial: await inspectCurrentMaterialEvidenceV1(
252
+ {
253
+ configuration:
254
+ captured.configuration as ProjectRenewalConfigurationV2Options,
255
+ reads: {
256
+ schedule: captured.reads.schedule,
257
+ subscription: captured.reads.subscription,
258
+ targetPrice: captured.reads.targetPrice,
259
+ billingCustomer: captured.reads.billingCustomer,
260
+ coupons: captured.reads.coupons,
261
+ },
262
+ ...(captured.configureReceipt
263
+ ? {
264
+ configureReceipt:
265
+ captured.configureReceipt as ConstructRenewalConfigurationReceiptV2Options,
266
+ }
267
+ : {}),
268
+ },
269
+ raw.invoiceContext,
270
+ ),
271
+ };
272
+ if (raw.invoiceContext !== null)
273
+ result = {
274
+ ...result,
275
+ invoiceEvidence: await inspectInvoiceEvidenceV1(raw),
276
+ };
277
+ if (raw.historicalSnapshot !== null)
278
+ result = {
279
+ ...result,
280
+ historicalMaterial: await inspectHistoricalMaterialEvidenceV1(raw),
281
+ };
282
+ return result;
283
+ } catch {
284
+ return result;
285
+ }
286
+ }
@@ -0,0 +1,379 @@
1
+ import type { ConfiguredEvidenceV1 } from "./evidence-material.js";
2
+ import type {
3
+ IdentityV1,
4
+ LifecycleV1,
5
+ Presence,
6
+ TerminalFactsV1,
7
+ } from "./evidence-v1-types.js";
8
+ import {
9
+ object,
10
+ array,
11
+ get,
12
+ equal,
13
+ clone,
14
+ referenceId,
15
+ planMatchesPrice,
16
+ type O,
17
+ } from "./common.js";
18
+ import { weeklyPending } from "./weeklyPending.js";
19
+
20
+ type Input = {
21
+ identity: IdentityV1;
22
+ reads: O;
23
+ originalSchedule: unknown;
24
+ originalSub: O;
25
+ originalCustomer: unknown;
26
+ target: unknown;
27
+ desired: unknown;
28
+ configured: ConfiguredEvidenceV1;
29
+ };
30
+ const owns = (value: O, key: string) =>
31
+ Object.prototype.hasOwnProperty.call(value, key);
32
+ function timestamp(value: unknown): value is number {
33
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
34
+ }
35
+ function presence<T>(
36
+ value: O,
37
+ key: string,
38
+ parse: (raw: unknown) => T,
39
+ ): Presence<T> {
40
+ return owns(value, key)
41
+ ? { presence: "present", value: parse(value[key]) }
42
+ : { presence: "absent" };
43
+ }
44
+ function nullableTime(raw: unknown) {
45
+ if (raw === null || timestamp(raw)) return raw;
46
+ throw Error("invalid_terminal_field");
47
+ }
48
+ /** Full comparison view changes only named lifecycle fields, never raw reads. */
49
+ function historyView(
50
+ schedule: O,
51
+ originalPrice: O,
52
+ target: O,
53
+ context: {
54
+ customerAccountId: string;
55
+ livemode: boolean;
56
+ },
57
+ ) {
58
+ const view = clone(schedule);
59
+ for (const key of [
60
+ "status",
61
+ "subscription",
62
+ "current_phase",
63
+ "canceled_at",
64
+ "completed_at",
65
+ "released_at",
66
+ "released_subscription",
67
+ ])
68
+ delete view[key];
69
+ view.customer = referenceId(view.customer, "cus", "customer", context);
70
+ view.phases = array(view.phases).map((raw) => {
71
+ const phase = clone(object(raw));
72
+ const items = array(phase.items);
73
+ if (items.length !== 1) throw Error("terminal_completion_unproven");
74
+ phase.items = items.map((rawItem) => {
75
+ const item = clone(object(rawItem));
76
+ const id = referenceId(item.price, "price", "price", context);
77
+ const known =
78
+ id === originalPrice.id
79
+ ? originalPrice
80
+ : id === target.id
81
+ ? target
82
+ : null;
83
+ if (!known) throw Error("material_mismatch");
84
+ if (typeof item.price !== "string") {
85
+ const expanded = object(item.price);
86
+ const minimal = Object.keys(expanded).every((key) =>
87
+ ["id", "object", "deleted", "livemode", "customer_account"].includes(
88
+ key,
89
+ ),
90
+ );
91
+ if (!minimal && !equal(expanded, known))
92
+ throw Error("material_mismatch");
93
+ }
94
+ item.price = id;
95
+ if (owns(item, "plan")) {
96
+ if (typeof item.plan === "string") {
97
+ if (item.plan !== id) throw Error("material_mismatch");
98
+ } else if (!planMatchesPrice(item.plan, known, context))
99
+ throw Error("terminal_completion_unproven");
100
+ item.plan = id;
101
+ }
102
+ return item;
103
+ });
104
+ return phase;
105
+ });
106
+ return view;
107
+ }
108
+ /** Unsigned facts and a narrow complete owned history comparison only. */
109
+ export function inspectTerminalEvidenceV1(input: Input): LifecycleV1 {
110
+ let providerStatus: string | null = null;
111
+ let facts: TerminalFactsV1 | null = null;
112
+ const fail = (
113
+ reason:
114
+ | "invalid_terminal_field"
115
+ | "owned_identity_mismatch"
116
+ | "material_mismatch"
117
+ | "terminal_completion_unproven"
118
+ | "incomplete_material"
119
+ | "unsupported_profile",
120
+ conflict = false,
121
+ ): LifecycleV1 => ({
122
+ predicate: conflict ? "conflict" : "unknown",
123
+ providerStatus,
124
+ facts,
125
+ completion: null,
126
+ reason,
127
+ });
128
+ try {
129
+ const { identity } = input;
130
+ const schedule = get(input.reads, "schedule");
131
+ const sub = get(input.reads, "subscription");
132
+ const customer = get(input.reads, "billingCustomer");
133
+ const context = {
134
+ customerAccountId: identity.customerAccountId,
135
+ livemode: identity.livemode,
136
+ };
137
+ providerStatus =
138
+ typeof schedule.status === "string" ? schedule.status : null;
139
+ const relation = (raw: unknown) => {
140
+ if (raw === null) return null;
141
+ const id = referenceId(raw, "sub", "subscription", context);
142
+ if (typeof raw !== "string") {
143
+ const expanded = object(raw);
144
+ if (
145
+ !Object.keys(expanded).every((key) =>
146
+ [
147
+ "id",
148
+ "object",
149
+ "deleted",
150
+ "livemode",
151
+ "customer_account",
152
+ ].includes(key),
153
+ ) &&
154
+ !equal(expanded, sub)
155
+ )
156
+ throw Error("owned_identity_mismatch");
157
+ }
158
+ return id;
159
+ };
160
+ facts = {
161
+ canceledAt: presence(schedule, "canceled_at", nullableTime),
162
+ completedAt: presence(schedule, "completed_at", nullableTime),
163
+ releasedAt: presence(schedule, "released_at", nullableTime),
164
+ subscriptionId: presence(schedule, "subscription", relation),
165
+ releasedSubscriptionId: presence(
166
+ schedule,
167
+ "released_subscription",
168
+ relation,
169
+ ),
170
+ };
171
+ const customerId = (raw: unknown) =>
172
+ referenceId(raw, "cus", "customer", context);
173
+ if (
174
+ schedule.id !== identity.scheduleId ||
175
+ schedule.object !== "subscription_schedule" ||
176
+ schedule.customer_account !== identity.customerAccountId ||
177
+ schedule.livemode !== identity.livemode ||
178
+ customerId(schedule.customer) !== identity.customerId ||
179
+ sub.id !== identity.subscriptionId ||
180
+ sub.object !== "subscription" ||
181
+ sub.customer_account !== identity.customerAccountId ||
182
+ sub.livemode !== identity.livemode ||
183
+ customerId(sub.customer) !== identity.customerId ||
184
+ customer.id !== identity.customerId ||
185
+ customer.object !== "customer" ||
186
+ customer.customer_account !== identity.customerAccountId ||
187
+ customer.livemode !== identity.livemode
188
+ )
189
+ return fail("owned_identity_mismatch", true);
190
+ for (const field of [facts.subscriptionId, facts.releasedSubscriptionId])
191
+ if (
192
+ field.presence === "present" &&
193
+ field.value !== null &&
194
+ field.value !== identity.subscriptionId
195
+ )
196
+ return fail("owned_identity_mismatch", true);
197
+ if (
198
+ input.configured.predicate === "unknown" ||
199
+ input.configured.predicate === "conflict"
200
+ )
201
+ return fail(
202
+ input.configured.reason === "material_mismatch"
203
+ ? "material_mismatch"
204
+ : input.configured.reason === "incomplete_material"
205
+ ? "incomplete_material"
206
+ : "terminal_completion_unproven",
207
+ input.configured.predicate === "conflict",
208
+ );
209
+ if (providerStatus === "active" || providerStatus === "not_started")
210
+ return {
211
+ predicate: "status_only",
212
+ providerStatus,
213
+ facts: null,
214
+ completion: null,
215
+ reason: null,
216
+ };
217
+ if (providerStatus === "canceled" || providerStatus === "released")
218
+ return {
219
+ predicate: "status_only",
220
+ providerStatus,
221
+ facts,
222
+ completion: null,
223
+ reason: null,
224
+ };
225
+ if (providerStatus !== "completed") return fail("unsupported_profile");
226
+ if (
227
+ facts.completedAt.presence !== "present" ||
228
+ facts.completedAt.value === null ||
229
+ !owns(schedule, "current_phase") ||
230
+ schedule.current_phase !== null
231
+ )
232
+ return fail("terminal_completion_unproven");
233
+ // Unknown nullable presence is not silently rewritten to null for comparison.
234
+ if (Object.values(facts).some((field) => field.presence !== "present"))
235
+ return fail("terminal_completion_unproven");
236
+ const original = object(input.originalSchedule);
237
+ const originalPhase = object(array(original.phases)[0]);
238
+ const phases = array(schedule.phases);
239
+ if (phases.length !== 2) return fail("terminal_completion_unproven");
240
+ const targetPhase = object(phases[1]);
241
+ if (
242
+ schedule.end_behavior !== "release" ||
243
+ !timestamp(targetPhase.end_date) ||
244
+ targetPhase.start_date !== identity.targetBoundary ||
245
+ targetPhase.end_date <= identity.targetBoundary ||
246
+ facts.completedAt.value < targetPhase.end_date
247
+ )
248
+ return fail("terminal_completion_unproven");
249
+ if (!equal(customer, input.originalCustomer))
250
+ return fail("material_mismatch", true);
251
+ for (const raw of [schedule.customer, sub.customer]) {
252
+ if (typeof raw !== "string") {
253
+ const expanded = object(raw);
254
+ if (
255
+ !Object.keys(expanded).every((key) =>
256
+ [
257
+ "id",
258
+ "object",
259
+ "deleted",
260
+ "livemode",
261
+ "customer_account",
262
+ ].includes(key),
263
+ ) &&
264
+ !equal(expanded, customer)
265
+ )
266
+ return fail("material_mismatch", true);
267
+ }
268
+ }
269
+ const originalItem = object(array(get(input.originalSub, "items").data)[0]);
270
+ const retainedCoupons = new Map<string, unknown>();
271
+ for (const raw of [
272
+ ...array(input.originalSub.discounts),
273
+ ...array(originalItem.discounts),
274
+ ]) {
275
+ const coupon = get(get(object(raw), "source"), "coupon");
276
+ if (
277
+ typeof coupon.id !== "string" ||
278
+ (retainedCoupons.has(coupon.id) &&
279
+ !equal(retainedCoupons.get(coupon.id), coupon))
280
+ )
281
+ return fail("terminal_completion_unproven");
282
+ retainedCoupons.set(coupon.id, coupon);
283
+ }
284
+ const coupons = array(input.reads.coupons);
285
+ const seenCoupons = new Set<string>();
286
+ for (const raw of coupons) {
287
+ const coupon = object(raw);
288
+ if (
289
+ typeof coupon.id !== "string" ||
290
+ seenCoupons.has(coupon.id) ||
291
+ !retainedCoupons.has(coupon.id)
292
+ )
293
+ return fail("terminal_completion_unproven");
294
+ if (!equal(coupon, retainedCoupons.get(coupon.id)))
295
+ return fail("material_mismatch", true);
296
+ seenCoupons.add(coupon.id);
297
+ }
298
+ if (seenCoupons.size !== retainedCoupons.size)
299
+ return fail("terminal_completion_unproven");
300
+ const target = object(input.target);
301
+ if (!equal(target, input.reads.targetPrice))
302
+ return fail("material_mismatch", true);
303
+ const desired = object(input.desired);
304
+ const expected = { periodEnd: identity.targetBoundary };
305
+ if (
306
+ !weeklyPending({
307
+ desired,
308
+ originalSub: input.originalSub,
309
+ sub,
310
+ expected,
311
+ target,
312
+ targetPhase,
313
+ schedule,
314
+ phases,
315
+ })
316
+ )
317
+ return fail("terminal_completion_unproven");
318
+ const targetTemplate = clone(originalPhase);
319
+ targetTemplate.start_date = identity.targetBoundary;
320
+ targetTemplate.end_date = targetPhase.end_date;
321
+ targetTemplate.proration_behavior = "none";
322
+ targetTemplate.billing_cycle_anchor = object(
323
+ array(get(desired, "payload").phases)[1],
324
+ ).billing_cycle_anchor;
325
+ const item = clone(object(array(targetTemplate.items)[0]));
326
+ item.price = identity.targetPriceId;
327
+ if (owns(item, "plan")) item.plan = identity.targetPriceId;
328
+ targetTemplate.items = [item];
329
+ const template = clone(original);
330
+ template.phases = [clone(originalPhase), targetTemplate];
331
+ const originalPrice = get(
332
+ object(array(get(input.originalSub, "items").data)[0]),
333
+ "price",
334
+ );
335
+ const actual = historyView(schedule, originalPrice, target, context);
336
+ if (!equal(actual, historyView(template, originalPrice, target, context)))
337
+ return fail("material_mismatch", true);
338
+ if (
339
+ input.configured.predicate === "qualified" &&
340
+ (targetPhase.end_date !== input.configured.targetEnd ||
341
+ !equal(
342
+ actual,
343
+ historyView(
344
+ input.configured.snapshot,
345
+ originalPrice,
346
+ target,
347
+ context,
348
+ ),
349
+ ))
350
+ )
351
+ return fail("material_mismatch", true);
352
+ return {
353
+ predicate: "completed_correlated",
354
+ providerStatus: "completed",
355
+ facts,
356
+ completion: {
357
+ scheduleId: identity.scheduleId,
358
+ subscriptionId: identity.subscriptionId,
359
+ completedAt: facts.completedAt.value,
360
+ targetPeriod: {
361
+ start: identity.targetBoundary,
362
+ end: targetPhase.end_date,
363
+ },
364
+ finalPhaseEnd: targetPhase.end_date,
365
+ endBehavior: "release",
366
+ comparison: "full_normalized_phase_history_match",
367
+ },
368
+ reason: null,
369
+ };
370
+ } catch (error) {
371
+ if (error instanceof Error && error.message === "owned_identity_mismatch")
372
+ return fail("owned_identity_mismatch", true);
373
+ if (error instanceof Error && error.message === "material_mismatch")
374
+ return fail("material_mismatch", true);
375
+ if (error instanceof Error && error.message === "invalid_terminal_field")
376
+ return fail("invalid_terminal_field");
377
+ return fail("terminal_completion_unproven");
378
+ }
379
+ }