@fantastic.dev/better-stripe 0.85.0 → 0.87.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 (65) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAggregate/configure.d.ts.map +1 -1
  4. package/dist/client/billing/renewalAggregate/configure.js +4 -56
  5. package/dist/client/billing/renewalAggregate/configure.js.map +1 -1
  6. package/dist/client/billing/renewalAggregate/configureMaterial.d.ts +29 -0
  7. package/dist/client/billing/renewalAggregate/configureMaterial.d.ts.map +1 -0
  8. package/dist/client/billing/renewalAggregate/configureMaterial.js +63 -0
  9. package/dist/client/billing/renewalAggregate/configureMaterial.js.map +1 -0
  10. package/dist/client/billing/renewalAggregate/phases.d.ts +2 -2
  11. package/dist/client/billing/renewalAggregate/phases.d.ts.map +1 -1
  12. package/dist/client/billing/renewalAggregate/phases.js.map +1 -1
  13. package/dist/client/billing/renewalAggregate/preflight.d.ts +1 -118
  14. package/dist/client/billing/renewalAggregate/preflight.d.ts.map +1 -1
  15. package/dist/client/billing/renewalAggregate/preflight.js +3 -118
  16. package/dist/client/billing/renewalAggregate/preflight.js.map +1 -1
  17. package/dist/client/billing/renewalAggregate/readMaterial.d.ts +335 -0
  18. package/dist/client/billing/renewalAggregate/readMaterial.d.ts.map +1 -0
  19. package/dist/client/billing/renewalAggregate/readMaterial.js +121 -0
  20. package/dist/client/billing/renewalAggregate/readMaterial.js.map +1 -0
  21. package/dist/client/billing/renewalV2/binding.d.ts +1 -1
  22. package/dist/client/billing/renewalV2/binding.d.ts.map +1 -1
  23. package/dist/client/billing/renewalV2/binding.js.map +1 -1
  24. package/dist/client/billing/renewalV2/configureInput.d.ts +46 -0
  25. package/dist/client/billing/renewalV2/configureInput.d.ts.map +1 -0
  26. package/dist/client/billing/renewalV2/configureInput.js +69 -0
  27. package/dist/client/billing/renewalV2/configureInput.js.map +1 -0
  28. package/dist/client/billing/renewalV2/configureReceipt.d.ts +19 -0
  29. package/dist/client/billing/renewalV2/configureReceipt.d.ts.map +1 -0
  30. package/dist/client/billing/renewalV2/configureReceipt.js +91 -0
  31. package/dist/client/billing/renewalV2/configureReceipt.js.map +1 -0
  32. package/dist/client/billing/renewalV2/index.d.ts +55 -0
  33. package/dist/client/billing/renewalV2/index.d.ts.map +1 -1
  34. package/dist/client/billing/renewalV2/index.js +145 -1
  35. package/dist/client/billing/renewalV2/index.js.map +1 -1
  36. package/dist/client/billing/renewalV2/receipt.d.ts +1 -0
  37. package/dist/client/billing/renewalV2/receipt.d.ts.map +1 -1
  38. package/dist/client/billing/renewalV2/receipt.js +3 -3
  39. package/dist/client/billing/renewalV2/receipt.js.map +1 -1
  40. package/dist/client/renewal.d.ts +2 -2
  41. package/dist/client/renewal.d.ts.map +1 -1
  42. package/dist/client/renewal.js +1 -1
  43. package/dist/client/renewal.js.map +1 -1
  44. package/dist/client/usage/observationClient.d.ts +2 -2
  45. package/dist/client/usage/observationClient.d.ts.map +1 -1
  46. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  47. package/dist/component/payoutRelease/queries.d.ts +2 -2
  48. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  49. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  50. package/docs/renewal-context-reads.md +10 -2
  51. package/docs/renewal-phase-assembly.md +141 -0
  52. package/package.json +1 -1
  53. package/src/client/billing/renewalAggregate/configure.ts +12 -79
  54. package/src/client/billing/renewalAggregate/configureMaterial.ts +122 -0
  55. package/src/client/billing/renewalAggregate/phases.ts +2 -2
  56. package/src/client/billing/renewalAggregate/preflight.ts +6 -161
  57. package/src/client/billing/renewalAggregate/readMaterial.ts +173 -0
  58. package/src/client/billing/renewalV2/binding.ts +10 -1
  59. package/src/client/billing/renewalV2/configure.test.ts +362 -0
  60. package/src/client/billing/renewalV2/configureInput.ts +84 -0
  61. package/src/client/billing/renewalV2/configureReceipt.test.ts +558 -0
  62. package/src/client/billing/renewalV2/configureReceipt.ts +96 -0
  63. package/src/client/billing/renewalV2/index.ts +241 -0
  64. package/src/client/billing/renewalV2/receipt.ts +3 -3
  65. package/src/client/renewal.ts +7 -0
@@ -11,6 +11,147 @@ This aggregate consumes V1 records. The public
11
11
  produces separate unsigned consistency data; it does not migrate records or
12
12
  enable this projector to accept V2 receipts.
13
13
 
14
+ ## Raw V2 configuration projection
15
+
16
+ `projectRenewalConfigurationV2` is a public async constructor. It shares the
17
+ complete material checks and phase assembly below with the V1 aggregate, while
18
+ constructing compact V2 bindings directly:
19
+
20
+ ```ts
21
+ import { projectRenewalConfigurationV2 } from "@fantastic.dev/better-stripe";
22
+
23
+ const candidate = await projectRenewalConfigurationV2({
24
+ preparation: originalPreparationInputs,
25
+ attachReceipt: {
26
+ attachRequest: {
27
+ preparation: originalPreparationInputs,
28
+ apiVersion,
29
+ attachKey,
30
+ firstDispatchedAt: attachFirstDispatchedAt,
31
+ },
32
+ actualDispatch: retainedAttachDispatch,
33
+ providerSnapshot: retainedAttachScheduleBody,
34
+ },
35
+ freshSubscription,
36
+ targetPrice,
37
+ billingCustomer,
38
+ schedule: freshSchedule,
39
+ apiVersion,
40
+ observedAt,
41
+ firstDispatchedAt: configureFirstDispatchedAt,
42
+ configureKey,
43
+ });
44
+ ```
45
+
46
+ `preparation` contains the original raw Subscription, target Price, billing
47
+ Customer, expected selectors and logical key. `attachReceipt` contains the raw
48
+ inputs to the [C3 constructor](renewal-context-reads.md#v2-attachment-receipt-consistency),
49
+ including all seven actual attachment dispatch fields. It is not a previously
50
+ computed receipt. Both complete preparation inputs must agree. The function
51
+ rebuilds C1 and C3 internally instead of accepting a derived handle, verification
52
+ flag or converted V1 record.
53
+
54
+ All inputs are captured before the first await. Closed constructor inputs
55
+ require own data properties, reject unexpected names and are checked again on
56
+ the detached copy. Provider records retain the existing bounded JSON policy;
57
+ optional fields are not replaced with null or invented defaults. The same
58
+ original-source, profile, Discount, payment, tax, settings, identity, period,
59
+ full-baseline and default-preservation checks apply. Actual subscription
60
+ association is required; the constructor does not replace it with null to pass
61
+ the original preparation checks.
62
+
63
+ Success is `projected_configure_request`, with version `2`, the complete
64
+ normalized two-phase payload and `providerQualification: "required"`. C4
65
+ (`renewal-baseline`) binds the entire original Schedule body. C5
66
+ (`renewal-defaults`) binds the exact validated default settings. C6
67
+ (`renewal-configure`) binds the complete unsigned request, including the rebuilt
68
+ C1/C3 identities, key, API version, POST path, payload and original configure
69
+ first-dispatch time. Each uses the same fixed V2 domain encoding and 500,000-byte
70
+ UTF-8 preimage limit. No nested V1 claim is constructed or rewritten to obtain
71
+ these bindings.
72
+
73
+ Semantic failures retain the existing `unsupported`, `conflict` and
74
+ `attached_unconfigured` data shapes and reasons. Once the rebuilt attachment's
75
+ identity and time joins are accepted, an unsupported projection includes its
76
+ Schedule ID. This is a consistency classification, not authenticated ownership.
77
+ Malformed constructor inputs or JSON capture errors reject the promise; handle
78
+ those separately from returned projection failures.
79
+
80
+ The function performs no provider call or storage operation. It does not produce
81
+ a configured-response receipt, execute the configure request, establish provider
82
+ qualification, prove acknowledgement provenance or certify renewal
83
+ effectiveness. Protect original records and enforce host authorization and all
84
+ provider qualification gates before dispatch. Existing V1 APIs and record
85
+ formats are unchanged.
86
+
87
+ ## Raw V2 configuration receipts
88
+
89
+ `constructRenewalConfigurationReceiptV2` records unsigned operation consistency
90
+ from raw configuration inputs and a retained response:
91
+
92
+ ```ts
93
+ import { constructRenewalConfigurationReceiptV2 } from "@fantastic.dev/better-stripe";
94
+
95
+ const receipt = await constructRenewalConfigurationReceiptV2({
96
+ configuration: originalRawConfigurationInputs,
97
+ actualDispatch: {
98
+ scope: "platform",
99
+ apiVersion,
100
+ method: "POST",
101
+ path: projectedRequest.path,
102
+ payload: projectedRequest.payload,
103
+ key: projectedRequest.key,
104
+ firstDispatchedAt: projectedRequest.firstDispatchedAt,
105
+ },
106
+ providerSnapshot: retainedConfiguredScheduleBody,
107
+ transport: {
108
+ status: retainedStatus,
109
+ ...(retainedRequestId === undefined
110
+ ? {}
111
+ : { requestId: retainedRequestId }),
112
+ },
113
+ });
114
+ ```
115
+
116
+ `configuration` is the complete raw input to `projectRenewalConfigurationV2`,
117
+ including its repeated original preparation and raw attachment receipt inputs.
118
+ Do not supply a projected request, stored receipt or verification handle in its
119
+ place. The constructor captures the entire input before its first await and
120
+ rebuilds C6 internally. Any returned C6 Failure rejects C9 with a fixed error;
121
+ C6's own Failure union remains unchanged. All seven actual dispatch fields,
122
+ including the complete payload, key and first-dispatch time, must equal C6.
123
+
124
+ Transport is closed `{ status, requestId? }`. Status must be an integer from
125
+ 200 through 299. A present request ID must contain 1–255 characters; omit it
126
+ when absent. Null, empty or explicitly undefined IDs reject. Supply the complete
127
+ plain JSON Schedule body rather than an SDK wrapper: any own `lastResponse`
128
+ property, including hidden metadata, rejects. The public bounded JSON limits and
129
+ own-data constructor checks remain; captured required fields are checked again
130
+ before hashing.
131
+
132
+ Available response identity relations must agree with C6's Schedule,
133
+ Subscription, Customer, account and mode. The complete response body, including
134
+ unknown safe JSON keys, remains in C7 (`renewal-configured-baseline`). C8
135
+ (`renewal-configured-defaults`) is present only when the response owns
136
+ `default_settings`: absent stays absent, own null is hashed as null, and a present
137
+ object is hashed in full. C9 (`renewal-configure-receipt`) binds the complete
138
+ unsigned receipt, including the full C6 request, response, exact transport and
139
+ C7/optional C8. Each exact UTF-8 preimage retains the 500,000-byte limit; the
140
+ whole input and result retain the existing JSON traversal and size limits.
141
+
142
+ The result uses version `2`, stage `configure_acknowledged` and verification
143
+ `owned_response_only`. These are unsigned data-format literals. They do not
144
+ authenticate acknowledgement or ownership. A caller can manufacture coherent
145
+ data that passes. This operation-only constructor does not require response
146
+ phases or defaults to match the requested configuration and cannot certify that
147
+ they were applied. Full phase/material comparison, response acquisition and
148
+ same-call provenance, authorization, custody, provider qualification and renewal
149
+ effectiveness remain separate requirements.
150
+
151
+ No provider call, retry, key rotation, storage write, V1 conversion or native
152
+ qualification occurs. Keep the original operation records protected, and do not
153
+ treat the receipt or a matching digest as permission to write or grant service.
154
+
14
155
  A candidate always has `providerQualification: "required"`. This describes a
15
156
  remaining requirement, not authorization to dispatch. Host-supplied flags cannot
16
157
  prove provider behavior, ownership, original configuration or historical intent.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.85.0",
3
+ "version": "0.87.0",
4
4
  "description": "Convex component for Stripe Accounts v2, subscriptions, metered billing and Connect marketplaces, with React workflows.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -1,20 +1,17 @@
1
- import { z } from "zod";
2
1
  import type Stripe from "stripe";
3
- import { idempotencyOptions } from "../../core/idempotency.js";
4
2
  import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
5
3
  import { retainedPreparation, validateReads } from "./preflight.js";
6
4
  import { validateAttachReceipt } from "./receipt.js";
7
- import { assemblePhases } from "./phases.js";
5
+ import {
6
+ configureMaterial,
7
+ validateConfigureStart,
8
+ } from "./configureMaterial.js";
8
9
  import type { RenewalProfile } from "./profile.js";
9
10
  import {
10
11
  binding,
11
- object,
12
12
  configureInput,
13
- equal,
14
- conflict,
15
- unsupported,
16
13
  failure,
17
- referenceId,
14
+ object,
18
15
  type Failure,
19
16
  } from "./shared.js";
20
17
 
@@ -60,78 +57,14 @@ export function projectRenewalConfiguration(
60
57
  args.observedAt,
61
58
  );
62
59
  ownedScheduleId = receipt.scheduleId;
63
- const key = idempotencyOptions(args.configureKey)?.idempotencyKey;
64
- if (!key || key === receipt.request.requestIdentity.key)
65
- unsupported("configure_key_must_be_distinct");
66
- if (
67
- args.firstDispatchedAt > args.observedAt ||
68
- args.firstDispatchedAt < receipt.request.firstDispatchedAt
69
- )
70
- unsupported("invalid_retained_dispatch_time");
71
- const rawSubscription = object(args.freshSubscription);
72
- if (
73
- rawSubscription.schedule == null ||
74
- referenceId(
75
- rawSubscription.schedule,
76
- "sub_sched",
77
- "subscription_schedule",
78
- ) !== receipt.scheduleId
79
- )
80
- conflict("schedule_association_mismatch");
60
+ const key = validateConfigureStart(args, receipt);
81
61
  const reads = validateReads(args, receipt.scheduleId);
82
- const schedule = object(args.schedule);
83
- if (!equal(schedule, receipt.providerSnapshot))
84
- conflict("acknowledged_baseline_or_defaults_drift");
85
- const expected = prepared.expected;
86
- const referenceContext = {
87
- livemode: expected.livemode,
88
- customerAccountId: expected.customerAccountId,
89
- };
90
- if (
91
- schedule.id !== receipt.scheduleId ||
92
- schedule.object !== "subscription_schedule" ||
93
- schedule.customer_account !== expected.customerAccountId ||
94
- schedule.livemode !== expected.livemode ||
95
- referenceId(schedule.customer, "cus", "customer", referenceContext) !==
96
- reads.customer.id ||
97
- referenceId(
98
- schedule.subscription,
99
- "sub",
100
- "subscription",
101
- referenceContext,
102
- ) !== expected.subscriptionId
103
- )
104
- conflict("acknowledged_schedule_identity_mismatch");
105
- if (
106
- schedule.status !== "active" ||
107
- schedule.end_behavior !== "release" ||
108
- schedule.application !== null ||
109
- schedule.canceled_at !== null ||
110
- schedule.completed_at !== null ||
111
- schedule.released_at !== null ||
112
- schedule.released_subscription !== null ||
113
- (schedule.pause_schedules !== undefined &&
114
- (!Array.isArray(schedule.pause_schedules) ||
115
- schedule.pause_schedules.length))
116
- )
117
- unsupported("unsupported_acknowledged_schedule_state");
118
- if (!equal(schedule.billing_mode, reads.subscription.billing_mode))
119
- unsupported("schedule_billing_mode_mismatch");
120
- const current = z
121
- .object({ start_date: z.number(), end_date: z.number() })
122
- .strict()
123
- .parse(schedule.current_phase);
124
- if (
125
- current.start_date !== expected.periodStart ||
126
- current.end_date !== expected.periodEnd
127
- )
128
- conflict("current_phase_period_drift");
129
- const phases = assemblePhases(reads, schedule);
130
- const payload = {
131
- end_behavior: "release" as const,
132
- proration_behavior: "none" as const,
133
- phases,
134
- };
62
+ const { schedule, payload } = configureMaterial(
63
+ object(args.schedule),
64
+ prepared,
65
+ receipt,
66
+ reads,
67
+ );
135
68
  const request = {
136
69
  version: 1 as const,
137
70
  stage: "configure" as const,
@@ -0,0 +1,122 @@
1
+ import { z } from "zod";
2
+ import type Stripe from "stripe";
3
+ import { idempotencyOptions } from "../../core/idempotency.js";
4
+ import { assemblePhases } from "./phases.js";
5
+ import type {
6
+ RenewalPreparationMaterial,
7
+ RenewalReadMaterial,
8
+ } from "./readMaterial.js";
9
+ import {
10
+ object,
11
+ configureInput,
12
+ equal,
13
+ conflict,
14
+ unsupported,
15
+ referenceId,
16
+ type ObjectData,
17
+ } from "./shared.js";
18
+ type Args = Pick<
19
+ z.infer<typeof configureInput>,
20
+ | "configureKey"
21
+ | "firstDispatchedAt"
22
+ | "observedAt"
23
+ | "freshSubscription"
24
+ | "schedule"
25
+ >;
26
+ type Receipt = {
27
+ scheduleId: string;
28
+ providerSnapshot: unknown;
29
+ request: { firstDispatchedAt: number; requestIdentity: { key: string } };
30
+ };
31
+ // Internal only: all callers validate their own receipt before entering these predicates.
32
+ export function validateConfigureStart(args: Args, receipt: Receipt) {
33
+ const key = idempotencyOptions(args.configureKey)?.idempotencyKey;
34
+ if (!key || key === receipt.request.requestIdentity.key)
35
+ unsupported("configure_key_must_be_distinct");
36
+ if (
37
+ args.firstDispatchedAt > args.observedAt ||
38
+ args.firstDispatchedAt < receipt.request.firstDispatchedAt
39
+ )
40
+ unsupported("invalid_retained_dispatch_time");
41
+ const rawSubscription = object(args.freshSubscription);
42
+ if (
43
+ rawSubscription.schedule == null ||
44
+ referenceId(
45
+ rawSubscription.schedule,
46
+ "sub_sched",
47
+ "subscription_schedule",
48
+ ) !== receipt.scheduleId
49
+ )
50
+ conflict("schedule_association_mismatch");
51
+ return key;
52
+ }
53
+ export function configureMaterial(
54
+ schedule: ObjectData,
55
+ prepared: RenewalPreparationMaterial,
56
+ receipt: Receipt,
57
+ reads: RenewalReadMaterial,
58
+ ): {
59
+ schedule: ObjectData;
60
+ payload: {
61
+ end_behavior: "release";
62
+ proration_behavior: "none";
63
+ phases: [
64
+ Stripe.SubscriptionScheduleUpdateParams.Phase,
65
+ Stripe.SubscriptionScheduleUpdateParams.Phase,
66
+ ];
67
+ };
68
+ } {
69
+ if (!equal(schedule, receipt.providerSnapshot))
70
+ conflict("acknowledged_baseline_or_defaults_drift");
71
+ const expected = prepared.expected;
72
+ const referenceContext = {
73
+ livemode: expected.livemode,
74
+ customerAccountId: expected.customerAccountId,
75
+ };
76
+ if (
77
+ schedule.id !== receipt.scheduleId ||
78
+ schedule.object !== "subscription_schedule" ||
79
+ schedule.customer_account !== expected.customerAccountId ||
80
+ schedule.livemode !== expected.livemode ||
81
+ referenceId(schedule.customer, "cus", "customer", referenceContext) !==
82
+ reads.customer.id ||
83
+ referenceId(
84
+ schedule.subscription,
85
+ "sub",
86
+ "subscription",
87
+ referenceContext,
88
+ ) !== expected.subscriptionId
89
+ )
90
+ conflict("acknowledged_schedule_identity_mismatch");
91
+ if (
92
+ schedule.status !== "active" ||
93
+ schedule.end_behavior !== "release" ||
94
+ schedule.application !== null ||
95
+ schedule.canceled_at !== null ||
96
+ schedule.completed_at !== null ||
97
+ schedule.released_at !== null ||
98
+ schedule.released_subscription !== null ||
99
+ (schedule.pause_schedules !== undefined &&
100
+ (!Array.isArray(schedule.pause_schedules) ||
101
+ schedule.pause_schedules.length))
102
+ )
103
+ unsupported("unsupported_acknowledged_schedule_state");
104
+ if (!equal(schedule.billing_mode, reads.subscription.billing_mode))
105
+ unsupported("schedule_billing_mode_mismatch");
106
+ const current = z
107
+ .object({ start_date: z.number(), end_date: z.number() })
108
+ .strict()
109
+ .parse(schedule.current_phase);
110
+ if (
111
+ current.start_date !== expected.periodStart ||
112
+ current.end_date !== expected.periodEnd
113
+ )
114
+ conflict("current_phase_period_drift");
115
+ const phases = assemblePhases(reads, schedule);
116
+ const payload = {
117
+ end_behavior: "release" as const,
118
+ proration_behavior: "none" as const,
119
+ phases,
120
+ };
121
+ return { schedule, payload };
122
+ }
@@ -13,7 +13,7 @@ import {
13
13
  equal,
14
14
  unsupported,
15
15
  } from "./shared.js";
16
- import type { validateReads } from "./preflight.js";
16
+ import type { RenewalReadMaterial } from "./readMaterial.js";
17
17
  import type { OriginalRedemptions } from "./sourceDiscounts.js";
18
18
  import { preserveTaxLevels } from "./taxRetention.js";
19
19
 
@@ -85,7 +85,7 @@ function metadataMatches(
85
85
  }
86
86
 
87
87
  export function assemblePhases(
88
- reads: ReturnType<typeof validateReads>,
88
+ reads: RenewalReadMaterial,
89
89
  schedule: Record<string, unknown>,
90
90
  ): [
91
91
  Stripe.SubscriptionScheduleUpdateParams.Phase,
@@ -1,28 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { prepareRenewalPriceReplacement } from "../renewalPriceReplacement.js";
3
- import {
4
- renewalSubscription,
5
- renewalPrice,
6
- renewalBillingCustomer,
7
- } from "../renewalReplacementSchema.js";
8
3
  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
-
4
+ import { object, readInput, equal, conflict, failure } from "./shared.js";
5
+ import { validateReadMaterial } from "./readMaterial.js";
26
6
  export function retainedPreparation(value: unknown) {
27
7
  try {
28
8
  const candidate = object(value);
@@ -46,150 +26,15 @@ export function retainedPreparation(value: unknown) {
46
26
  }
47
27
  }
48
28
 
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
29
  export function validateReads(
63
30
  args: z.infer<typeof readInput>,
64
31
  scheduleId?: string,
65
32
  ) {
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,
33
+ return validateReadMaterial(
34
+ args,
35
+ retainedPreparation(args.prepared),
36
+ scheduleId,
181
37
  );
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
38
  }
194
39
 
195
40
  export function preflightRenewalReplacement(input: unknown) {