@fantastic.dev/better-stripe 0.82.0 → 0.83.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.
- package/CHANGELOG.md +6 -0
- package/README.md +1 -1
- package/dist/client/billing/renewalAttach/couponJoins.d.ts +23 -0
- package/dist/client/billing/renewalAttach/couponJoins.d.ts.map +1 -0
- package/dist/client/billing/renewalAttach/couponJoins.js +76 -0
- package/dist/client/billing/renewalAttach/couponJoins.js.map +1 -0
- package/dist/client/billing/renewalAttach/index.d.ts +3 -0
- package/dist/client/billing/renewalAttach/index.d.ts.map +1 -0
- package/dist/client/billing/renewalAttach/index.js +3 -0
- package/dist/client/billing/renewalAttach/index.js.map +1 -0
- package/dist/client/billing/renewalAttach/reader.d.ts +141 -0
- package/dist/client/billing/renewalAttach/reader.d.ts.map +1 -0
- package/dist/client/billing/renewalAttach/reader.js +80 -0
- package/dist/client/billing/renewalAttach/reader.js.map +1 -0
- package/dist/client/billing/renewalAttach/request.d.ts +30 -0
- package/dist/client/billing/renewalAttach/request.d.ts.map +1 -0
- package/dist/client/billing/renewalAttach/request.js +39 -0
- package/dist/client/billing/renewalAttach/request.js.map +1 -0
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
- package/dist/client/index.d.ts +3 -5
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -3
- package/dist/client/index.js.map +1 -1
- package/dist/client/renewal.d.ts +8 -0
- package/dist/client/renewal.d.ts.map +1 -0
- package/dist/client/renewal.js +4 -0
- package/dist/client/renewal.js.map +1 -0
- package/dist/client/renewalContextClient.d.ts +130 -0
- package/dist/client/renewalContextClient.d.ts.map +1 -0
- package/dist/client/renewalContextClient.js +10 -0
- package/dist/client/renewalContextClient.js.map +1 -0
- package/dist/client/usage/observationClient.d.ts +2 -2
- package/dist/client/usage/observationClient.d.ts.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/earnings/triggers.d.ts +16 -16
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
- package/dist/component/usage/allowance.fixtures.d.ts +16 -16
- package/docs/renewal-context-reads.md +113 -0
- package/docs/renewal-price-replacements.md +55 -16
- package/package.json +1 -1
- package/src/client/billing/renewalAttach/couponEvidence.test.ts +104 -0
- package/src/client/billing/renewalAttach/couponJoins.ts +95 -0
- package/src/client/billing/renewalAttach/index.ts +9 -0
- package/src/client/billing/renewalAttach/reader.test.ts +409 -0
- package/src/client/billing/renewalAttach/reader.ts +131 -0
- package/src/client/billing/renewalAttach/request.ts +49 -0
- package/src/client/index.ts +3 -8
- package/src/client/renewal.ts +13 -0
- package/src/client/renewalContextClient.ts +23 -0
|
@@ -2351,14 +2351,6 @@ export declare function setupAllowance(): Promise<{
|
|
|
2351
2351
|
preparationId: import("convex/values").GenericId<"balanceFundingPreparations">;
|
|
2352
2352
|
requestKey: string;
|
|
2353
2353
|
result?: {
|
|
2354
|
-
reason: "identity_changed" | "revision_changed" | "scope_busy";
|
|
2355
|
-
retryable: false;
|
|
2356
|
-
status: "conflict";
|
|
2357
|
-
} | {
|
|
2358
|
-
reason: "policy_invalid";
|
|
2359
|
-
retryable: false;
|
|
2360
|
-
status: "rejected";
|
|
2361
|
-
} | {
|
|
2362
2354
|
operation: {
|
|
2363
2355
|
accountId: string;
|
|
2364
2356
|
operationId: import("convex/values").GenericId<"balanceFundingOperations">;
|
|
@@ -2369,6 +2361,14 @@ export declare function setupAllowance(): Promise<{
|
|
|
2369
2361
|
} | {
|
|
2370
2362
|
enabled: boolean;
|
|
2371
2363
|
status: "unchanged";
|
|
2364
|
+
} | {
|
|
2365
|
+
reason: "identity_changed" | "revision_changed" | "scope_busy";
|
|
2366
|
+
retryable: false;
|
|
2367
|
+
status: "conflict";
|
|
2368
|
+
} | {
|
|
2369
|
+
reason: "policy_invalid";
|
|
2370
|
+
retryable: false;
|
|
2371
|
+
status: "rejected";
|
|
2372
2372
|
} | {
|
|
2373
2373
|
reason: "provider_pending";
|
|
2374
2374
|
retryable: true;
|
|
@@ -2379,14 +2379,6 @@ export declare function setupAllowance(): Promise<{
|
|
|
2379
2379
|
payload: import("convex/values").VString<string, "required">;
|
|
2380
2380
|
preparationId: import("convex/values").VId<import("convex/values").GenericId<"balanceFundingPreparations">, "required">;
|
|
2381
2381
|
result: import("convex/values").VUnion<{
|
|
2382
|
-
reason: "identity_changed" | "revision_changed" | "scope_busy";
|
|
2383
|
-
retryable: false;
|
|
2384
|
-
status: "conflict";
|
|
2385
|
-
} | {
|
|
2386
|
-
reason: "policy_invalid";
|
|
2387
|
-
retryable: false;
|
|
2388
|
-
status: "rejected";
|
|
2389
|
-
} | {
|
|
2390
2382
|
operation: {
|
|
2391
2383
|
accountId: string;
|
|
2392
2384
|
operationId: import("convex/values").GenericId<"balanceFundingOperations">;
|
|
@@ -2397,6 +2389,14 @@ export declare function setupAllowance(): Promise<{
|
|
|
2397
2389
|
} | {
|
|
2398
2390
|
enabled: boolean;
|
|
2399
2391
|
status: "unchanged";
|
|
2392
|
+
} | {
|
|
2393
|
+
reason: "identity_changed" | "revision_changed" | "scope_busy";
|
|
2394
|
+
retryable: false;
|
|
2395
|
+
status: "conflict";
|
|
2396
|
+
} | {
|
|
2397
|
+
reason: "policy_invalid";
|
|
2398
|
+
retryable: false;
|
|
2399
|
+
status: "rejected";
|
|
2400
2400
|
} | {
|
|
2401
2401
|
reason: "provider_pending";
|
|
2402
2402
|
retryable: true;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Renewal context reads and attachment request preparation
|
|
2
|
+
|
|
3
|
+
`BetterStripe.readRenewalPriceReplacementContext` reads the original provider
|
|
4
|
+
subscription, authorized target price and correlated billing Customer. Hosts
|
|
5
|
+
must authorize the caller and exact original selectors before invoking it on
|
|
6
|
+
the server. This method does not create or update provider resources, persist
|
|
7
|
+
operation ownership or establish financial preservation.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
const context = await betterStripe.readRenewalPriceReplacementContext(ctx, {
|
|
11
|
+
expected,
|
|
12
|
+
});
|
|
13
|
+
const prepared = prepareRenewalPriceReplacement({
|
|
14
|
+
subscription: context.subscription,
|
|
15
|
+
targetPrice: context.targetPrice,
|
|
16
|
+
billingCustomer: context.billingCustomer,
|
|
17
|
+
expected,
|
|
18
|
+
key: logicalKey,
|
|
19
|
+
});
|
|
20
|
+
const attachRequest = prepareRenewalScheduleAttachment({
|
|
21
|
+
prepared,
|
|
22
|
+
apiVersion: context.apiVersion,
|
|
23
|
+
attachKey,
|
|
24
|
+
firstDispatchedAt,
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The two preparation functions are pure exports. The host supplies and durably
|
|
29
|
+
retains the logical key, explicit attachment key, original first-dispatch time
|
|
30
|
+
and complete records under immutable authorization. An explicitly chosen attach
|
|
31
|
+
key may equal the logical key; no key is silently reused, derived or generated.
|
|
32
|
+
A future configure key must differ from the attachment key.
|
|
33
|
+
|
|
34
|
+
## Fixed acquisition profile
|
|
35
|
+
|
|
36
|
+
The initial profile supports platform requests using the configured
|
|
37
|
+
`2026-09-30.endive` API and Stripe 23 read shapes. Other versions reject before
|
|
38
|
+
reading. The public class selects the maintained single-attempt client,
|
|
39
|
+
including protection against the SDK's closed-connection special retry; every
|
|
40
|
+
read also requests zero automatic retries. Failures remain visible. There is no
|
|
41
|
+
fallback expansion, alternate endpoint or stale cache after a failed read.
|
|
42
|
+
|
|
43
|
+
The method performs these planned GETs in order:
|
|
44
|
+
|
|
45
|
+
1. Retrieve the exact subscription with `discounts`, `items.data.discounts`
|
|
46
|
+
and `items.data.price` expanded.
|
|
47
|
+
2. Retrieve the exact target price.
|
|
48
|
+
3. Retrieve the actual subscription's Customer, correlated to the authorized
|
|
49
|
+
customer-configured account and mode.
|
|
50
|
+
4. Retrieve each distinct coupon referenced by the expanded subscription/item
|
|
51
|
+
discounts, in first-occurrence order. Each level is capped at 20 discounts,
|
|
52
|
+
so at most 40 coupon GETs follow the three original reads.
|
|
53
|
+
|
|
54
|
+
Discounts must be expanded and have an actual coupon source. There is no
|
|
55
|
+
Discount retrieval endpoint used here. The item path
|
|
56
|
+
`items.data.discounts.source.coupon` exceeds the provider's four-property
|
|
57
|
+
expansion limit. Explicit coupon GET joins are part of the initial read plan,
|
|
58
|
+
including when a coupon was already expanded. Same-ID undeleted coupon results
|
|
59
|
+
expand string references in the canonical context. If a coupon was already
|
|
60
|
+
expanded, its complete canonical JSON must equal the separate GET result.
|
|
61
|
+
Duration, applicability, unknown fields and ordered arrays must agree; object
|
|
62
|
+
key order does not matter. Minimal expanded references and original-only or
|
|
63
|
+
GET-only fields are conservatively rejected as unsupported read-shape drift.
|
|
64
|
+
The join never merges or overwrites existing full source facts. Repeated
|
|
65
|
+
references are each compared, even when their coupon GET is deduplicated.
|
|
66
|
+
Contradictory available mode facts reject before a coupon GET.
|
|
67
|
+
|
|
68
|
+
All other full JSON fields, array ordering and unknown provider data are
|
|
69
|
+
retained within the existing bounded snapshot policy. No missing values become
|
|
70
|
+
null or empty lists. The result records `readProfile: "renewal-context-v1"`, a
|
|
71
|
+
server observation time and `providerQualification: "required"`. It does not
|
|
72
|
+
promise that multiple reads were atomic or that a context remains fresh later.
|
|
73
|
+
A preparation supplied from a different expansion/read shape must not be
|
|
74
|
+
silently rebound to this profile during a future writer invocation.
|
|
75
|
+
|
|
76
|
+
A nonnull observed `subscription.schedule` is returned as an observation. It is
|
|
77
|
+
not adopted as an acknowledgement of attachment. The existing initial pure
|
|
78
|
+
preparation still requires an unattached original. A later explicit replay of
|
|
79
|
+
an unknown attachment result needs a distinct material-state guard permitting
|
|
80
|
+
the actual nonnull association while preserving the original retained snapshot.
|
|
81
|
+
This reader does not fabricate a null association to bypass that guard.
|
|
82
|
+
|
|
83
|
+
## Bound request and remaining writer contract
|
|
84
|
+
|
|
85
|
+
The pure builder validates the retained logical preparation and explicit key.
|
|
86
|
+
It binds version, attach stage, platform scope, actual API version, logical
|
|
87
|
+
binding, method/path, complete payload `{ from_subscription: subscriptionId }`,
|
|
88
|
+
key and original first-dispatch time. It generates no phase, metadata, arbitrary
|
|
89
|
+
create option, receipt or provider acknowledgement.
|
|
90
|
+
|
|
91
|
+
No attachment writer is exposed by these helpers. There are currently no
|
|
92
|
+
accepted provider execution profiles. A positive structural preflight remains
|
|
93
|
+
insufficient to authorize a POST; callers cannot unlock one with a qualification
|
|
94
|
+
flag. Direct existing forever discount IDs are representable by the projection
|
|
95
|
+
helpers, while actual mirroring and preservation require separate provider
|
|
96
|
+
qualification. Empty discount reads do not prove suppression versus inheritance
|
|
97
|
+
and remain unsupported at projection preflight, even when the Customer has no
|
|
98
|
+
observed discount. Reading such facts does not qualify their transition.
|
|
99
|
+
|
|
100
|
+
A future writer must reacquire this full scoped context before its one POST.
|
|
101
|
+
Initial dispatch requires no attached schedule. Explicit lost-response replay
|
|
102
|
+
must use the same retained full request/key/time, permit a newly observed
|
|
103
|
+
nonnull association without adopting it by shape, and keep provider conflicts
|
|
104
|
+
visible. A local replay age limit below 24 hours cannot guarantee replay after
|
|
105
|
+
provider pruning. No retries, configure chaining or cancel/release rollback are
|
|
106
|
+
implemented here. A successful future attachment acknowledgement must remain
|
|
107
|
+
`attached_unconfigured`; target pending/effective states require separately
|
|
108
|
+
qualified configuration and observation.
|
|
109
|
+
|
|
110
|
+
See the [replacement contract](renewal-price-replacements.md) and
|
|
111
|
+
[phase assembly](renewal-phase-assembly.md) for baseline, replay and observation
|
|
112
|
+
boundaries. Read comparison is best effort and cannot exclude concurrent
|
|
113
|
+
Dashboard or other provider writers.
|
|
@@ -169,25 +169,64 @@ field is not proof of a lossless provider transition. The configure mapper must
|
|
|
169
169
|
resolve every applicable row before the first mutation; no response-object spread
|
|
170
170
|
or extra `subscriptions.update` workaround is permitted.
|
|
171
171
|
|
|
172
|
-
| Original setting | Required mapping or explicit unsupported boundary
|
|
173
|
-
| ----------------------------------- |
|
|
174
|
-
| Item and period | Verify complete single-item identity, expanded original price/product, quantity and item period. Keep current start/end and paid item unchanged; bind the target to that exact end. Metered/tiered or missing quantities need a separate supported contract.
|
|
175
|
-
| Null and inheritance | Preserve the distinction between schedule defaults, phase overrides and customer fallback. Extract expanded IDs. Send empty-string clears only for fields declared `Emptyable`; never universally turn null into omission, zero or an empty string.
|
|
176
|
-
| Discounts | Preserve existing discount IDs, order, duration and item/subscription precedence. Omission
|
|
177
|
-
| Tax | Project only writable enabled/liability values and tax-rate IDs at their original level. Do not copy read-only disabled reasons. Preserve manual versus automatic mode and liability scope; unresolved combinations reject.
|
|
178
|
-
| Trial | Retain historical dates. Active/future trials need an exact phase timeline plus proof of retained `trial_settings`. Never force `trial_end: now`, add a free phase or blindly resend past timestamps.
|
|
179
|
-
| Cancellation | `cancel_at` and `cancel_at_period_end` have no direct phase equivalents. Reject cancellation intent until an exact supported mapping exists. `end_behavior` is not a substitute, and must not clear the original intent.
|
|
180
|
-
| Payment method | Normalize an expanded method to its ID at the same defaults/phase level. Null may mean fallback and is not a writable clear in every location. Do not freeze a customer default into a new explicit override.
|
|
181
|
-
| Legacy sources and payment settings | No direct phase/default write for `default_source` or `payment_settings`. Absence of a write field does not prove Stripe loses the subscription value. Explicit nondefault cases need retained-field proof or fail before attachment; never translate a legacy source to a payment-method ID.
|
|
182
|
-
| Application fee | Phase/default fee writes have a connected-account prerequisite. Nonnull fee, including zero, is outside this platform contract until ownership and retention are qualified. Do not add a connected header or silently drop the fee.
|
|
183
|
-
| Routing | `transfer_data` and `on_behalf_of` are separate from fee ownership. Preserve destination/account IDs and exact percentage/omission semantics where supported. Do not infer zero/full transfer or compute financial splits.
|
|
184
|
-
| Invoice/collection | Preserve collection mode, due-day semantics, issuer/tax IDs and supported custom invoice fields at their original level. Auto-charge null days are not a writable null. Unknown issuer values and unsupported clear/inheritance cases reject.
|
|
185
|
-
| Anchor, billing mode and thresholds | A numeric subscription anchor cannot be copied into a phase enum. Prove unchanged current boundary and target-cadence behavior. Preserve migrated billing mode; map thresholds only when their effect on renewal is supported. No automatic anchor reset.
|
|
186
|
-
| Metadata and extra invoice items | Retain reserved and host metadata without turning subscription metadata into repeated phase-entry changes. Additional invoice items can charge again in a new phase; reject nonempty additions until no-duplicate semantics are supported.
|
|
187
|
-
| Other provider states | Pending updates/setup, pauses, managed billing and special schedules need explicit supported classification. Similar field names are not equivalent. A field missing from the phase schema is a verification gap, not proof it is discarded.
|
|
172
|
+
| Original setting | Required mapping or explicit unsupported boundary |
|
|
173
|
+
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
174
|
+
| Item and period | Verify complete single-item identity, expanded original price/product, quantity and item period. Keep current start/end and paid item unchanged; bind the target to that exact end. Metered/tiered or missing quantities need a separate supported contract. |
|
|
175
|
+
| Null and inheritance | Preserve the distinction between schedule defaults, phase overrides and customer fallback. Extract expanded IDs. Send empty-string clears only for fields declared `Emptyable`; never universally turn null into omission, zero or an empty string. |
|
|
176
|
+
| Discounts | Preserve existing discount IDs, order, duration and item/subscription precedence. Omission and provider empty-string clearing have different write semantics. Current empty discount reads do not prove historical suppression or inheritance; those contexts remain unsupported. Re-redeeming a coupon can restart duration. Establish target-product eligibility and provenance before supporting a discounted transition. |
|
|
177
|
+
| Tax | Project only writable enabled/liability values and tax-rate IDs at their original level. Do not copy read-only disabled reasons. Preserve manual versus automatic mode and liability scope; unresolved combinations reject. |
|
|
178
|
+
| Trial | Retain historical dates. Active/future trials need an exact phase timeline plus proof of retained `trial_settings`. Never force `trial_end: now`, add a free phase or blindly resend past timestamps. |
|
|
179
|
+
| Cancellation | `cancel_at` and `cancel_at_period_end` have no direct phase equivalents. Reject cancellation intent until an exact supported mapping exists. `end_behavior` is not a substitute, and must not clear the original intent. |
|
|
180
|
+
| Payment method | Normalize an expanded method to its ID at the same defaults/phase level. Null may mean fallback and is not a writable clear in every location. Do not freeze a customer default into a new explicit override. |
|
|
181
|
+
| Legacy sources and payment settings | No direct phase/default write for `default_source` or `payment_settings`. Absence of a write field does not prove Stripe loses the subscription value. Explicit nondefault cases need retained-field proof or fail before attachment; never translate a legacy source to a payment-method ID. |
|
|
182
|
+
| Application fee | Phase/default fee writes have a connected-account prerequisite. Nonnull fee, including zero, is outside this platform contract until ownership and retention are qualified. Do not add a connected header or silently drop the fee. |
|
|
183
|
+
| Routing | `transfer_data` and `on_behalf_of` are separate from fee ownership. Preserve destination/account IDs and exact percentage/omission semantics where supported. Do not infer zero/full transfer or compute financial splits. |
|
|
184
|
+
| Invoice/collection | Preserve collection mode, due-day semantics, issuer/tax IDs and supported custom invoice fields at their original level. Auto-charge null days are not a writable null. Unknown issuer values and unsupported clear/inheritance cases reject. |
|
|
185
|
+
| Anchor, billing mode and thresholds | A numeric subscription anchor cannot be copied into a phase enum. Prove unchanged current boundary and target-cadence behavior. Preserve migrated billing mode; map thresholds only when their effect on renewal is supported. No automatic anchor reset. |
|
|
186
|
+
| Metadata and extra invoice items | Retain reserved and host metadata without turning subscription metadata into repeated phase-entry changes. Additional invoice items can charge again in a new phase; reject nonempty additions until no-duplicate semantics are supported. |
|
|
187
|
+
| Other provider states | Pending updates/setup, pauses, managed billing and special schedules need explicit supported classification. Similar field names are not equivalent. A field missing from the phase schema is a verification gap, not proof it is discarded. |
|
|
188
188
|
|
|
189
189
|
The completed mapper specification and recovery contract must independently fit
|
|
190
190
|
the configure/reconciliation ticket's estimate before write implementation starts.
|
|
191
191
|
Split further when needed, preserving the complete cross-product renewal outcome.
|
|
192
192
|
Unsupported boundaries must remain visible to the host and in acceptance criteria.
|
|
193
193
|
Controlled unit tests alone cannot qualify live preservation or consumer policy.
|
|
194
|
+
|
|
195
|
+
## Provider context reads and retained attachment requests
|
|
196
|
+
|
|
197
|
+
The [renewal context reader](renewal-context-reads.md) acquires a fixed provider
|
|
198
|
+
read profile and prepares an immutable attachment request. It does not attach a
|
|
199
|
+
schedule. Provider qualification and the remaining attachment, configuration and
|
|
200
|
+
observation stages are still required before this becomes a usable replacement
|
|
201
|
+
workflow.
|
|
202
|
+
|
|
203
|
+
## Unknown configuration outcomes and observation
|
|
204
|
+
|
|
205
|
+
A future explicit replay of an unknown configure result must retain the same
|
|
206
|
+
complete request, key and original first-dispatch time. It may dispatch only
|
|
207
|
+
while the freshly read owned schedule still equals the complete retained
|
|
208
|
+
preconfigure baseline, preserved defaults and original subscription material,
|
|
209
|
+
and elapsed time is less than 24 hours. This local limit is not permanent
|
|
210
|
+
provider replay assurance. A changed or already applied schedule is handed to
|
|
211
|
+
observation; it must not be reprojected into another initial request.
|
|
212
|
+
|
|
213
|
+
A provider GET is not a POST acknowledgement. Sufficient exact provider evidence
|
|
214
|
+
may eventually recover pending or effective state without an acknowledgement;
|
|
215
|
+
otherwise the outcome remains unknown. If a configure acknowledgement exists,
|
|
216
|
+
retain its complete canonical baseline and correlate subsequent observations
|
|
217
|
+
with it. Pending requires the exact future phase, original boundary, current
|
|
218
|
+
paid terms/defaults and linked buyer/subscription.
|
|
219
|
+
Effective state while the target phase is current requires a unique authorized
|
|
220
|
+
target item, matching quantity, currency, applicable period/settings and owned
|
|
221
|
+
phase/subscription relation. Do not require the old item ID to survive a price
|
|
222
|
+
transition. Before implementing this observer, define and independently review
|
|
223
|
+
fixed normalization covering the full retained desired request and
|
|
224
|
+
provider-computed phase-end/duration evidence. Context reading does not provide
|
|
225
|
+
that observer normalization.
|
|
226
|
+
|
|
227
|
+
Canceled, released or completed facts alone do not prove effectiveness. Manual
|
|
228
|
+
release, missing historical correlation, matching price or wall time leave
|
|
229
|
+
causal effectiveness unknown. Preserve acknowledged receipts through read
|
|
230
|
+
failure. No automatic replay, key rotation, stage chaining, cancel/release or
|
|
231
|
+
rollback follows an unknown result. Snapshot equality is not atomic provider
|
|
232
|
+
compare-and-swap or proof that other writers were excluded.
|
package/package.json
CHANGED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
import { joinRenewalCoupons } from "./couponJoins.js";
|
|
4
|
+
const apiVersion = "2026-09-30.endive";
|
|
5
|
+
const baseline = {
|
|
6
|
+
id: "custom-offer",
|
|
7
|
+
object: "coupon",
|
|
8
|
+
livemode: false,
|
|
9
|
+
duration: "forever",
|
|
10
|
+
applies_to: { products: ["current", "target"] },
|
|
11
|
+
};
|
|
12
|
+
const expanded = (coupon: unknown, id = "di_original") => ({
|
|
13
|
+
discounts: [{ id, object: "discount", source: { type: "coupon", coupon } }],
|
|
14
|
+
});
|
|
15
|
+
function controlled(value: unknown) {
|
|
16
|
+
const calls: string[] = [];
|
|
17
|
+
const stripe = new Stripe("sk_test_SYNTHETIC", {
|
|
18
|
+
apiVersion,
|
|
19
|
+
maxNetworkRetries: 0,
|
|
20
|
+
httpClient: {
|
|
21
|
+
getClientName: () => "controlled-coupon-evidence",
|
|
22
|
+
async makeRequest(_host, _port, path, method) {
|
|
23
|
+
calls.push(`${method} ${path}`);
|
|
24
|
+
return {
|
|
25
|
+
getStatusCode: () => 200,
|
|
26
|
+
getHeaders: () => ({
|
|
27
|
+
"request-id": "req_synthetic",
|
|
28
|
+
"stripe-version": apiVersion,
|
|
29
|
+
}),
|
|
30
|
+
toJSON: async () => structuredClone(value),
|
|
31
|
+
getRawResponse: () => ({}),
|
|
32
|
+
toStream: () => null,
|
|
33
|
+
} as unknown as Stripe.HttpClientResponse;
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
calls,
|
|
39
|
+
join: (source: unknown, item: unknown = { discounts: [] }) =>
|
|
40
|
+
joinRenewalCoupons(
|
|
41
|
+
stripe,
|
|
42
|
+
source as Record<string, unknown>,
|
|
43
|
+
item as Record<string, unknown>,
|
|
44
|
+
false,
|
|
45
|
+
{ apiVersion, maxNetworkRetries: 0 },
|
|
46
|
+
),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
describe("expanded coupon full evidence equality", () => {
|
|
50
|
+
it.each([
|
|
51
|
+
["duration", { ...baseline, duration: "once" }, baseline],
|
|
52
|
+
[
|
|
53
|
+
"applicability",
|
|
54
|
+
{ ...baseline, applies_to: { products: ["current"] } },
|
|
55
|
+
baseline,
|
|
56
|
+
],
|
|
57
|
+
[
|
|
58
|
+
"original-only unknown fact",
|
|
59
|
+
{ ...baseline, unknown_provider_fact: { retained: "original" } },
|
|
60
|
+
baseline,
|
|
61
|
+
],
|
|
62
|
+
[
|
|
63
|
+
"minimal expanded reference",
|
|
64
|
+
{ id: baseline.id, object: "coupon" },
|
|
65
|
+
baseline,
|
|
66
|
+
],
|
|
67
|
+
[
|
|
68
|
+
"fresh-only unknown fact",
|
|
69
|
+
baseline,
|
|
70
|
+
{ ...baseline, unknown_provider_fact: "fresh" },
|
|
71
|
+
],
|
|
72
|
+
[
|
|
73
|
+
"ordered applicability",
|
|
74
|
+
{ ...baseline, applies_to: { products: ["target", "current"] } },
|
|
75
|
+
baseline,
|
|
76
|
+
],
|
|
77
|
+
])(
|
|
78
|
+
"rejects %s drift instead of replacing original facts",
|
|
79
|
+
async (_label, original, fetched) => {
|
|
80
|
+
const h = controlled(fetched);
|
|
81
|
+
await expect(h.join(expanded(original))).rejects.toThrow();
|
|
82
|
+
expect(h.calls).toEqual(["GET /v1/coupons/custom-offer"]);
|
|
83
|
+
},
|
|
84
|
+
);
|
|
85
|
+
it("retains full equal unknown facts and tolerates object-key order", async () => {
|
|
86
|
+
const extra = { nested: ["retained", 0] };
|
|
87
|
+
const original = { ...baseline, unknown_provider_fact: extra };
|
|
88
|
+
const fetched = { unknown_provider_fact: extra, ...baseline };
|
|
89
|
+
const h = controlled(fetched);
|
|
90
|
+
const result = await h.join(expanded(original));
|
|
91
|
+
expect(result.subscriptionDiscounts[0].source.coupon).toEqual(original);
|
|
92
|
+
expect(h.calls).toHaveLength(1);
|
|
93
|
+
});
|
|
94
|
+
it("checks every expanded reference even when the coupon GET is deduplicated", async () => {
|
|
95
|
+
const h = controlled(baseline);
|
|
96
|
+
await expect(
|
|
97
|
+
h.join(
|
|
98
|
+
expanded(baseline),
|
|
99
|
+
expanded({ ...baseline, duration: "once" }, "di_item"),
|
|
100
|
+
),
|
|
101
|
+
).rejects.toThrow();
|
|
102
|
+
expect(h.calls).toHaveLength(1);
|
|
103
|
+
});
|
|
104
|
+
});
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type Stripe from "stripe";
|
|
3
|
+
import { equal, object, unsupported } from "../renewalAggregate/shared.js";
|
|
4
|
+
import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
|
|
5
|
+
|
|
6
|
+
const id = z.string().min(1).max(255).regex(/\S/);
|
|
7
|
+
const discount = z
|
|
8
|
+
.object({
|
|
9
|
+
id: z.string().regex(/^di_[A-Za-z0-9_]+$/),
|
|
10
|
+
object: z.literal("discount"),
|
|
11
|
+
deleted: z.literal(false).optional(),
|
|
12
|
+
source: z
|
|
13
|
+
.object({
|
|
14
|
+
type: z.literal("coupon"),
|
|
15
|
+
coupon: z.union([
|
|
16
|
+
id,
|
|
17
|
+
z
|
|
18
|
+
.object({
|
|
19
|
+
id,
|
|
20
|
+
object: z.literal("coupon"),
|
|
21
|
+
deleted: z.literal(false).optional(),
|
|
22
|
+
})
|
|
23
|
+
.passthrough(),
|
|
24
|
+
]),
|
|
25
|
+
})
|
|
26
|
+
.passthrough(),
|
|
27
|
+
})
|
|
28
|
+
.passthrough();
|
|
29
|
+
/** Explicit bounded joins, never a fallback for failed or over-depth expansion. */
|
|
30
|
+
export async function joinRenewalCoupons(
|
|
31
|
+
stripe: Stripe,
|
|
32
|
+
subscription: Record<string, unknown>,
|
|
33
|
+
item: Record<string, unknown>,
|
|
34
|
+
livemode: boolean,
|
|
35
|
+
options: Stripe.RequestOptions,
|
|
36
|
+
) {
|
|
37
|
+
const lists = [subscription.discounts, item.discounts].map((value) => {
|
|
38
|
+
const parsed = z.array(discount).max(20).safeParse(value);
|
|
39
|
+
if (!parsed.success)
|
|
40
|
+
unsupported("incomplete_or_unsupported_discount_evidence");
|
|
41
|
+
return parsed.data;
|
|
42
|
+
});
|
|
43
|
+
for (const list of lists)
|
|
44
|
+
for (const redemption of list) {
|
|
45
|
+
const ref = redemption.source.coupon;
|
|
46
|
+
if (
|
|
47
|
+
typeof ref !== "string" &&
|
|
48
|
+
ref.livemode !== undefined &&
|
|
49
|
+
ref.livemode !== livemode
|
|
50
|
+
)
|
|
51
|
+
unsupported("expanded_coupon_mode_mismatch");
|
|
52
|
+
}
|
|
53
|
+
const coupons = new Map<string, Record<string, unknown>>();
|
|
54
|
+
for (const list of lists)
|
|
55
|
+
for (const redemption of list) {
|
|
56
|
+
const couponId =
|
|
57
|
+
typeof redemption.source.coupon === "string"
|
|
58
|
+
? redemption.source.coupon
|
|
59
|
+
: redemption.source.coupon.id;
|
|
60
|
+
let coupon = coupons.get(couponId);
|
|
61
|
+
if (!coupon) {
|
|
62
|
+
coupon = object(
|
|
63
|
+
renewalSnapshot(await stripe.coupons.retrieve(couponId, {}, options)),
|
|
64
|
+
);
|
|
65
|
+
if (
|
|
66
|
+
coupon.id !== couponId ||
|
|
67
|
+
coupon.object !== "coupon" ||
|
|
68
|
+
coupon.deleted === true ||
|
|
69
|
+
(coupon.livemode !== undefined && coupon.livemode !== livemode)
|
|
70
|
+
)
|
|
71
|
+
unsupported("coupon_join_identity_mismatch");
|
|
72
|
+
coupons.set(couponId, coupon);
|
|
73
|
+
}
|
|
74
|
+
// A join may expand a string reference, but must never replace facts
|
|
75
|
+
// already present in a full read. Shape drift is conservatively rejected.
|
|
76
|
+
if (
|
|
77
|
+
typeof redemption.source.coupon !== "string" &&
|
|
78
|
+
!equal(redemption.source.coupon, coupon)
|
|
79
|
+
)
|
|
80
|
+
unsupported("expanded_coupon_read_drift");
|
|
81
|
+
}
|
|
82
|
+
const joined = lists.map((list) =>
|
|
83
|
+
list.map((redemption) => {
|
|
84
|
+
const couponId =
|
|
85
|
+
typeof redemption.source.coupon === "string"
|
|
86
|
+
? redemption.source.coupon
|
|
87
|
+
: redemption.source.coupon.id;
|
|
88
|
+
return {
|
|
89
|
+
...redemption,
|
|
90
|
+
source: { ...redemption.source, coupon: coupons.get(couponId)! },
|
|
91
|
+
};
|
|
92
|
+
}),
|
|
93
|
+
);
|
|
94
|
+
return { subscriptionDiscounts: joined[0], itemDiscounts: joined[1] };
|
|
95
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export {
|
|
2
|
+
readRenewalPriceReplacementContext,
|
|
3
|
+
type ReadRenewalPriceReplacementContextOptions,
|
|
4
|
+
} from "./reader.js";
|
|
5
|
+
export {
|
|
6
|
+
prepareRenewalScheduleAttachment,
|
|
7
|
+
type PrepareRenewalScheduleAttachmentOptions,
|
|
8
|
+
type PreparedRenewalScheduleAttachment,
|
|
9
|
+
} from "./request.js";
|