@fantastic.dev/better-stripe 0.85.0 → 0.86.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 (62) hide show
  1. package/CHANGELOG.md +6 -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 +45 -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/index.d.ts +21 -0
  29. package/dist/client/billing/renewalV2/index.d.ts.map +1 -1
  30. package/dist/client/billing/renewalV2/index.js +80 -1
  31. package/dist/client/billing/renewalV2/index.js.map +1 -1
  32. package/dist/client/billing/renewalV2/receipt.d.ts +1 -0
  33. package/dist/client/billing/renewalV2/receipt.d.ts.map +1 -1
  34. package/dist/client/billing/renewalV2/receipt.js +3 -3
  35. package/dist/client/billing/renewalV2/receipt.js.map +1 -1
  36. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  37. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  38. package/dist/client/renewal.d.ts +2 -2
  39. package/dist/client/renewal.d.ts.map +1 -1
  40. package/dist/client/renewal.js +1 -1
  41. package/dist/client/renewal.js.map +1 -1
  42. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  43. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  44. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  45. package/dist/component/earnings/triggers.d.ts +16 -16
  46. package/dist/component/payoutRelease/queries.d.ts +2 -2
  47. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  48. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  49. package/docs/renewal-context-reads.md +6 -2
  50. package/docs/renewal-phase-assembly.md +73 -0
  51. package/package.json +1 -1
  52. package/src/client/billing/renewalAggregate/configure.ts +12 -79
  53. package/src/client/billing/renewalAggregate/configureMaterial.ts +122 -0
  54. package/src/client/billing/renewalAggregate/phases.ts +2 -2
  55. package/src/client/billing/renewalAggregate/preflight.ts +6 -161
  56. package/src/client/billing/renewalAggregate/readMaterial.ts +173 -0
  57. package/src/client/billing/renewalV2/binding.ts +7 -1
  58. package/src/client/billing/renewalV2/configure.test.ts +362 -0
  59. package/src/client/billing/renewalV2/configureInput.ts +84 -0
  60. package/src/client/billing/renewalV2/index.ts +124 -0
  61. package/src/client/billing/renewalV2/receipt.ts +3 -3
  62. package/src/client/renewal.ts +4 -0
@@ -0,0 +1,173 @@
1
+ import { z } from "zod";
2
+ import type { PreparedRenewalPriceReplacement } from "../renewalPriceReplacement.js";
3
+ import {
4
+ renewalSubscription,
5
+ renewalPrice,
6
+ renewalBillingCustomer,
7
+ } from "../renewalReplacementSchema.js";
8
+ import {
9
+ readInput,
10
+ referenceId,
11
+ equal,
12
+ conflict,
13
+ unsupported,
14
+ supportedVersion,
15
+ timestamp,
16
+ resourceId,
17
+ productId,
18
+ } from "./shared.js";
19
+ import { profileOf } from "./profile.js";
20
+ import { qualifySourceDiscounts } from "./sourceDiscounts.js";
21
+ import { qualifyOriginalSettings } from "./sourceSettings.js";
22
+ // Internal semantic material only. Public wrappers must rebuild their own preparation.
23
+ export type RenewalPreparationMaterial = Pick<
24
+ PreparedRenewalPriceReplacement,
25
+ "expected" | "quantity" | "providerSnapshot"
26
+ >;
27
+ const attachedReference = z.union([
28
+ resourceId("sub_sched"),
29
+ z
30
+ .object({
31
+ id: resourceId("sub_sched"),
32
+ object: z.literal("subscription_schedule"),
33
+ deleted: z.literal(false).optional(),
34
+ customer_account: resourceId("acct").optional(),
35
+ livemode: z.boolean().optional(),
36
+ })
37
+ .passthrough(),
38
+ ]);
39
+
40
+ export function validateReadMaterial(
41
+ args: Omit<z.infer<typeof readInput>, "prepared">,
42
+ prepared: RenewalPreparationMaterial,
43
+ scheduleId?: string,
44
+ ) {
45
+ supportedVersion(args.apiVersion);
46
+ const subscription = renewalSubscription
47
+ .extend({ schedule: scheduleId ? attachedReference : z.null() })
48
+ .safeParse(args.freshSubscription);
49
+ if (!subscription.success)
50
+ unsupported("unsupported_original_subscription_state");
51
+ const source = subscription.data;
52
+ if (scheduleId) {
53
+ if (
54
+ referenceId(source.schedule, "sub_sched", "subscription_schedule") !==
55
+ scheduleId
56
+ )
57
+ conflict("schedule_association_mismatch");
58
+ if (
59
+ typeof source.schedule === "object" &&
60
+ source.schedule !== null &&
61
+ ((source.schedule.customer_account !== undefined &&
62
+ source.schedule.customer_account !==
63
+ prepared.expected.customerAccountId) ||
64
+ (source.schedule.livemode !== undefined &&
65
+ source.schedule.livemode !== prepared.expected.livemode))
66
+ )
67
+ conflict("schedule_association_mismatch");
68
+ }
69
+ const { schedule: originalSchedule, ...original } =
70
+ prepared.providerSnapshot.subscription;
71
+ const { schedule: freshSchedule, ...fresh } = source;
72
+ if (scheduleId ? originalSchedule !== null : freshSchedule !== null)
73
+ conflict("schedule_association_mismatch");
74
+ if (!equal(original, fresh)) conflict("original_source_drift");
75
+ const target = renewalPrice.safeParse(args.targetPrice);
76
+ if (!target.success || !target.data.active)
77
+ unsupported("unsupported_target_price");
78
+ if (!equal(target.data, prepared.providerSnapshot.targetPrice))
79
+ conflict("target_price_drift");
80
+ if (
81
+ prepared.providerSnapshot.billingCustomer === undefined ||
82
+ args.billingCustomer === undefined
83
+ )
84
+ unsupported("missing_retained_billing_customer");
85
+ const customer = renewalBillingCustomer.safeParse(args.billingCustomer);
86
+ if (!customer.success) unsupported("unsupported_billing_customer");
87
+ if (!equal(customer.data, prepared.providerSnapshot.billingCustomer))
88
+ conflict("billing_customer_drift");
89
+ const referenceContext = {
90
+ customerAccountId: prepared.expected.customerAccountId,
91
+ livemode: prepared.expected.livemode,
92
+ };
93
+ if (
94
+ referenceId(source.customer, "cus", "customer", referenceContext) !==
95
+ customer.data.id ||
96
+ customer.data.customer_account !== prepared.expected.customerAccountId ||
97
+ customer.data.livemode !== prepared.expected.livemode
98
+ )
99
+ conflict("billing_customer_identity_mismatch");
100
+ const item = source.items.data[0];
101
+ if (
102
+ productId(item.price.product, referenceContext) !==
103
+ prepared.expected.currentProductId ||
104
+ productId(target.data.product, referenceContext) !==
105
+ prepared.expected.targetProductId
106
+ )
107
+ unsupported("product_identity_mismatch");
108
+ if (
109
+ args.observedAt < prepared.expected.periodStart ||
110
+ args.observedAt >= prepared.expected.periodEnd
111
+ )
112
+ unsupported("outside_original_paid_period");
113
+ for (const field of [
114
+ "billing_thresholds",
115
+ "managed_payments",
116
+ "next_pending_invoice_item_invoice",
117
+ "pending_invoice_item_interval",
118
+ "pending_setup_intent",
119
+ "canceled_at",
120
+ "ended_at",
121
+ "trial_settings",
122
+ ])
123
+ if (source[field] !== null) unsupported(`unsupported_original_${field}`);
124
+ if (item.billing_thresholds !== null)
125
+ unsupported("unsupported_item_billing_thresholds");
126
+ if (item.current_trial !== null)
127
+ unsupported("unsupported_or_missing_item_current_trial");
128
+ if (
129
+ !Array.isArray(source.billing_schedules) ||
130
+ source.billing_schedules.length
131
+ )
132
+ unsupported("unsupported_original_billing_schedules");
133
+ if (
134
+ source.trial_end !== null &&
135
+ (!timestamp.safeParse(source.trial_end).success ||
136
+ Number(source.trial_end) > prepared.expected.periodStart)
137
+ )
138
+ unsupported("unsupported_original_trial");
139
+ if (source.status_details != null || source.presentment_details != null)
140
+ unsupported("unsupported_special_billing_state");
141
+ const originalSettings = qualifyOriginalSettings(source, item, customer.data);
142
+ const profile = profileOf(source, item.price, target.data, args.apiVersion);
143
+ const anchor = timestamp.parse(source.billing_cycle_anchor);
144
+ if (anchor > prepared.expected.periodStart)
145
+ unsupported("unqualified_anchor_after_paid_period_start");
146
+ const discounts = qualifySourceDiscounts(
147
+ source.discounts,
148
+ "subscription",
149
+ prepared.expected,
150
+ customer.data.id,
151
+ args.observedAt,
152
+ );
153
+ const itemDiscounts = qualifySourceDiscounts(
154
+ item.discounts,
155
+ "item",
156
+ prepared.expected,
157
+ customer.data.id,
158
+ args.observedAt,
159
+ );
160
+ return {
161
+ prepared,
162
+ subscription: source,
163
+ item,
164
+ customer: customer.data,
165
+ targetPrice: target.data,
166
+ profile,
167
+ discounts,
168
+ itemDiscounts,
169
+ originalSettings,
170
+ };
171
+ }
172
+
173
+ export type RenewalReadMaterial = ReturnType<typeof validateReadMaterial>;
@@ -2,7 +2,13 @@ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
2
2
 
3
3
  /** Internal fixed-family encoding. This is consistency, not authorization. */
4
4
  export async function renewalBindingV2(
5
- family: "renewal" | "renewal-attach" | "renewal-attach-receipt",
5
+ family:
6
+ | "renewal"
7
+ | "renewal-attach"
8
+ | "renewal-attach-receipt"
9
+ | "renewal-baseline"
10
+ | "renewal-defaults"
11
+ | "renewal-configure",
6
12
  preimage: unknown,
7
13
  ): Promise<string> {
8
14
  // Finish all input capture and canonical bytes before the first await.
@@ -0,0 +1,362 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { createHash, webcrypto } from "node:crypto";
3
+ import * as sdk from "./index.js";
4
+ import { projectRenewalConfiguration as legacy } from "../renewalAggregate/configure.js";
5
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
6
+ import {
7
+ fixture,
8
+ type FixtureOptions,
9
+ } from "../../../../tests/renewalAggregate/fixtures.js";
10
+
11
+ const project = (raw: any): Promise<any> =>
12
+ sdk.projectRenewalConfigurationV2(raw);
13
+ function scenario(options: FixtureOptions = {}) {
14
+ const f = fixture(options);
15
+ const preparation = {
16
+ subscription: f.subscription,
17
+ targetPrice: f.targetPrice,
18
+ billingCustomer: f.billingCustomer,
19
+ expected: f.prepared.expected,
20
+ key: f.prepared.requestIdentity.key,
21
+ };
22
+ const { apiVersion, payload, key, firstDispatchedAt } = f.attachRequest;
23
+ const raw = {
24
+ preparation,
25
+ attachReceipt: {
26
+ attachRequest: {
27
+ preparation: structuredClone(preparation),
28
+ apiVersion,
29
+ attachKey: key,
30
+ firstDispatchedAt,
31
+ },
32
+ actualDispatch: {
33
+ scope: "platform" as const,
34
+ apiVersion,
35
+ method: "POST" as const,
36
+ path: "/v1/subscription_schedules" as const,
37
+ payload,
38
+ key,
39
+ firstDispatchedAt,
40
+ },
41
+ providerSnapshot: structuredClone(f.schedule),
42
+ },
43
+ freshSubscription: structuredClone(f.configureInput.freshSubscription),
44
+ targetPrice: structuredClone(f.targetPrice),
45
+ billingCustomer: structuredClone(f.billingCustomer),
46
+ schedule: structuredClone(f.schedule),
47
+ apiVersion,
48
+ observedAt: f.configureInput.observedAt,
49
+ firstDispatchedAt: f.configureInput.firstDispatchedAt,
50
+ configureKey: f.configureInput.configureKey,
51
+ };
52
+ return { raw, old: f.configureInput };
53
+ }
54
+ const digest = (family: string, value: unknown) =>
55
+ `${family}:v2:sha256:${createHash("sha256")
56
+ .update(
57
+ JSON.stringify(
58
+ renewalSnapshot(["betterstripe-renewal-binding", 2, family, value]),
59
+ ),
60
+ "utf8",
61
+ )
62
+ .digest("hex")}`;
63
+ afterEach(() => vi.unstubAllGlobals());
64
+ it.each([
65
+ {},
66
+ { targetInterval: "year" },
67
+ { start: 1769731200, end: 1772150400, observedAt: 1769817600 },
68
+ ])(
69
+ "projects complete V1-equivalent phases/profile with direct C4/C5/C6 bindings %j",
70
+ async (options) => {
71
+ expect(sdk.projectRenewalConfigurationV2).toBeTypeOf("function");
72
+ const { raw, old } = scenario(options),
73
+ before = structuredClone(raw);
74
+ const configurationOptions: sdk.ProjectRenewalConfigurationV2Options = raw;
75
+ const result =
76
+ await sdk.projectRenewalConfigurationV2(configurationOptions),
77
+ original = legacy(old);
78
+ expect(original.status).toBe("projected_configure_request");
79
+ if (original.status !== "projected_configure_request")
80
+ throw Error("fixture");
81
+ expect(result.status).toBe("projected_configure_request");
82
+ if (result.status !== "projected_configure_request")
83
+ throw Error("projection");
84
+ expect(result.payload).toEqual(original.payload);
85
+ expect(result.profile).toEqual(original.profile);
86
+ expect(result.version).toBe(2);
87
+ expect(result.providerQualification).toBe("required");
88
+ expect(result.baselineBinding).toBe(
89
+ digest("renewal-baseline", raw.attachReceipt.providerSnapshot),
90
+ );
91
+ expect(result.defaultSettingsBinding).toBe(
92
+ digest("renewal-defaults", raw.schedule.default_settings),
93
+ );
94
+ const {
95
+ status: _status,
96
+ profile: _profile,
97
+ providerQualification: _qualification,
98
+ requestIdentity,
99
+ ...unsigned
100
+ } = result;
101
+ expect(requestIdentity).toEqual({
102
+ key: raw.configureKey,
103
+ binding: digest("renewal-configure", unsigned),
104
+ });
105
+ expect(raw).toEqual(before);
106
+ expect(result.payload).not.toHaveProperty("default_settings");
107
+ expect(result.payload.phases[1]).not.toHaveProperty("end_date");
108
+ },
109
+ );
110
+ it.each([
111
+ [
112
+ "distinct key",
113
+ (x: any) => {
114
+ x.configureKey =
115
+ x.attachReceipt.actualDispatch?.key ?? x.attachReceipt.request.key;
116
+ },
117
+ ],
118
+ [
119
+ "dispatch ordering",
120
+ (x: any) => {
121
+ x.firstDispatchedAt = x.observedAt + 1;
122
+ },
123
+ ],
124
+ [
125
+ "source drift",
126
+ (x: any) => {
127
+ x.freshSubscription.currency = "eur";
128
+ },
129
+ ],
130
+ [
131
+ "association",
132
+ (x: any) => {
133
+ x.freshSubscription.schedule = null;
134
+ },
135
+ ],
136
+ [
137
+ "baseline",
138
+ (x: any) => {
139
+ x.schedule.opaque_future_field = true;
140
+ },
141
+ ],
142
+ ])("preserves exact existing Failure data for %s", async (_name, mutate) => {
143
+ const { raw, old } = scenario();
144
+ mutate(raw);
145
+ mutate(old);
146
+ expect(await project(raw)).toEqual(legacy(old));
147
+ });
148
+ it.each([
149
+ { item: { current_trial: { trial_end: 1770000000 } } },
150
+ { phase: { trial: true } },
151
+ { defaults: { collection_method: "unsupported" } },
152
+ ])(
153
+ "preserves unsupported owned-Schedule Failure reasons %j",
154
+ async (options) => {
155
+ const { raw, old } = scenario(options);
156
+ expect(await project(raw)).toEqual(legacy(old));
157
+ },
158
+ );
159
+ it("keeps invalid receipt aliases before the owned-Schedule failure boundary", async () => {
160
+ const { raw } = scenario();
161
+ raw.apiVersion = "different";
162
+ expect(await project(raw)).toEqual({
163
+ status: "conflict",
164
+ reason: "invalid_attach_receipt_binding",
165
+ });
166
+ });
167
+ it("rejects repeated raw preparation differences instead of accepting child claims", async () => {
168
+ const { raw } = scenario();
169
+ raw.attachReceipt.attachRequest.preparation.key = "other:logical";
170
+ expect((await project(raw)).status).not.toBe("projected_configure_request");
171
+ const invalid: any = scenario().raw;
172
+ invalid.prepared = fixture().prepared;
173
+ await expect(project(invalid)).rejects.toThrow();
174
+ });
175
+ it.each(["root", "preparation", "attachReceipt"])(
176
+ "rejects unknown %s names before inspecting values",
177
+ async (where) => {
178
+ const { raw } = scenario();
179
+ const value: any =
180
+ where === "root" ? raw : raw[where as "preparation" | "attachReceipt"];
181
+ const read = vi.fn();
182
+ Object.defineProperty(value, "unexpected", { enumerable: true, get: read });
183
+ await expect(project(raw)).rejects.toThrow();
184
+ expect(read).not.toHaveBeenCalled();
185
+ },
186
+ );
187
+ it("rechecks captured required fields before any digest after reflection mutation", async () => {
188
+ const { raw } = scenario();
189
+ const target: any = raw;
190
+ const proxy = new Proxy(target, {
191
+ getPrototypeOf(object) {
192
+ delete object.observedAt;
193
+ return Object.prototype;
194
+ },
195
+ });
196
+ const digest = vi.fn();
197
+ vi.stubGlobal("crypto", { subtle: { digest } });
198
+ await expect(project(proxy)).rejects.toThrow();
199
+ expect(digest).not.toHaveBeenCalled();
200
+ });
201
+ it("preserves absent-vs-present input fields and requires actual default settings", async () => {
202
+ const missing: any = scenario().raw;
203
+ delete missing.schedule.default_settings;
204
+ expect((await project(missing)).status).not.toBe(
205
+ "projected_configure_request",
206
+ );
207
+ const explicit: any = scenario().raw;
208
+ explicit.billingCustomer = undefined;
209
+ await expect(project(explicit)).rejects.toThrow();
210
+ });
211
+ it("owns all inputs before awaiting hashing", async () => {
212
+ const { raw } = scenario();
213
+ let release!: () => void;
214
+ const held = new Promise<void>((r) => {
215
+ release = r;
216
+ });
217
+ let calls = 0;
218
+ vi.stubGlobal("crypto", {
219
+ subtle: {
220
+ async digest(
221
+ algorithm: string,
222
+ bytes: Parameters<typeof webcrypto.subtle.digest>[1],
223
+ ) {
224
+ if (++calls === 1) await held;
225
+ return webcrypto.subtle.digest(algorithm, bytes);
226
+ },
227
+ },
228
+ });
229
+ const pending = project(raw);
230
+ raw.freshSubscription.schedule = null as any;
231
+ raw.configureKey = "changed";
232
+ release();
233
+ const result = await pending;
234
+ expect(result.status).toBe("projected_configure_request");
235
+ expect(result.key).not.toBe("changed");
236
+ });
237
+ it("projects substantial bounded raw bodies without building nested V1 claims", async () => {
238
+ const { raw } = scenario();
239
+ for (const body of [raw.schedule, raw.attachReceipt.providerSnapshot])
240
+ (body as any).opaque_retained = "x".repeat(90000);
241
+ expect(JSON.stringify(raw).length).toBeLessThan(500000);
242
+ const result = await project(raw);
243
+ expect(result.status).toBe("projected_configure_request");
244
+ expect(result.requestIdentity.binding.length).toBeLessThan(100);
245
+ });
246
+ it("returns the existing unsupported union when hashing fails", async () => {
247
+ vi.stubGlobal("crypto", {
248
+ subtle: { digest: () => Promise.reject(Error("failure")) },
249
+ });
250
+ expect(await project(scenario().raw)).toEqual({
251
+ status: "conflict",
252
+ reason: "invalid_prepared_binding",
253
+ });
254
+ });
255
+ it("preserves the owned-Schedule failure boundary when a later binding fails", async () => {
256
+ let calls = 0;
257
+ vi.stubGlobal("crypto", {
258
+ subtle: {
259
+ async digest(
260
+ algorithm: string,
261
+ bytes: Parameters<typeof webcrypto.subtle.digest>[1],
262
+ ) {
263
+ if (++calls === 6) throw Error("late digest failure");
264
+ return webcrypto.subtle.digest(algorithm, bytes);
265
+ },
266
+ },
267
+ });
268
+ expect(await project(scenario().raw)).toEqual({
269
+ status: "attached_unconfigured",
270
+ scheduleId: "sub_sched_owned",
271
+ reason: "incomplete_or_unsupported_schema",
272
+ });
273
+ });
274
+ it("retains the old missing-optional-Customer failure without inventing a read", async () => {
275
+ const f: any = scenario();
276
+ delete f.raw.billingCustomer;
277
+ delete f.old.billingCustomer;
278
+ expect(await project(f.raw)).toEqual(legacy(f.old));
279
+ });
280
+ it("does not accept a mismatched complete attachment dispatch through C6", async () => {
281
+ const f = scenario();
282
+ f.raw.attachReceipt.actualDispatch.payload.from_subscription = "sub_foreign";
283
+ expect(await project(f.raw)).toEqual({
284
+ status: "conflict",
285
+ reason: "invalid_attach_receipt_binding",
286
+ });
287
+ });
288
+ const ownSpecial = (body: object, value: unknown) =>
289
+ Object.defineProperty(body, "__proto__", { enumerable: true, value });
290
+ it("preserves identical full Schedule special own JSON keys in C4 and comparison", async () => {
291
+ const f = scenario();
292
+ ownSpecial(f.raw.schedule, { retained: true });
293
+ ownSpecial(f.raw.attachReceipt.providerSnapshot, { retained: true });
294
+ const before = structuredClone(f.raw),
295
+ result = await project(f.raw);
296
+ expect(result.status).toBe("projected_configure_request");
297
+ expect(result.baselineBinding).toBe(
298
+ digest("renewal-baseline", f.raw.attachReceipt.providerSnapshot),
299
+ );
300
+ expect(result.defaultSettingsBinding).toBe(
301
+ digest("renewal-defaults", f.raw.schedule.default_settings),
302
+ );
303
+ expect(f.raw).toEqual(before);
304
+ });
305
+ it("binds special own-key changes and rejects real full-baseline drift", async () => {
306
+ const a = scenario(),
307
+ b = scenario();
308
+ for (const body of [a.raw.schedule, a.raw.attachReceipt.providerSnapshot])
309
+ ownSpecial(body, { retained: 1 });
310
+ for (const body of [b.raw.schedule, b.raw.attachReceipt.providerSnapshot])
311
+ ownSpecial(body, { retained: 2 });
312
+ const x = await project(a.raw),
313
+ y = await project(b.raw);
314
+ expect(x.status).toBe("projected_configure_request");
315
+ expect(y.status).toBe("projected_configure_request");
316
+ expect(x.baselineBinding).not.toBe(y.baselineBinding);
317
+ expect(x.requestIdentity.binding).not.toBe(y.requestIdentity.binding);
318
+ const mismatched = scenario();
319
+ ownSpecial(mismatched.raw.schedule, { retained: true });
320
+ expect(await project(mismatched.raw)).toEqual({
321
+ status: "conflict",
322
+ reason: "acknowledged_baseline_or_defaults_drift",
323
+ });
324
+ });
325
+ it("does not drop unknown special own keys from strict default mappings to accept them", async () => {
326
+ const f = scenario();
327
+ for (const body of [
328
+ f.raw.schedule.default_settings,
329
+ f.raw.attachReceipt.providerSnapshot.default_settings,
330
+ ])
331
+ ownSpecial(body, { unsupported: true });
332
+ expect(await project(f.raw)).toEqual({
333
+ status: "attached_unconfigured",
334
+ scheduleId: "sub_sched_owned",
335
+ reason: "unsupported_schedule_defaults",
336
+ });
337
+ });
338
+ it("keeps V1 Schedule parsing after its original key validation boundary", () => {
339
+ const f = scenario();
340
+ f.old.configureKey = f.old.attachReceipt.request.key;
341
+ f.old.schedule = null as any;
342
+ expect(legacy(f.old)).toEqual({
343
+ status: "attached_unconfigured",
344
+ scheduleId: "sub_sched_owned",
345
+ reason: "configure_key_must_be_distinct",
346
+ });
347
+ f.old.configureKey = "another:configure-key";
348
+ expect(legacy(f.old)).toEqual({
349
+ status: "attached_unconfigured",
350
+ scheduleId: "sub_sched_owned",
351
+ reason: "incomplete_or_unsupported_schema",
352
+ });
353
+ });
354
+ it("exports the pure public API without exposing shared internal material helpers", async () => {
355
+ const root = await import("../../index.js");
356
+ expect(root).toHaveProperty(
357
+ "projectRenewalConfigurationV2",
358
+ sdk.projectRenewalConfigurationV2,
359
+ );
360
+ expect(root).not.toHaveProperty("validateReadMaterial");
361
+ expect(root).not.toHaveProperty("configureMaterial");
362
+ });
@@ -0,0 +1,84 @@
1
+ import { z } from "zod";
2
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
3
+ import { timestamp, type ObjectData } from "../renewalAggregate/shared.js";
4
+ import {
5
+ captureAttachmentReceipt,
6
+ validateAttachmentReceiptFields,
7
+ } from "./receipt.js";
8
+
9
+ function ownData(raw: unknown, required: string[], optional: string[] = []) {
10
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
11
+ throw Error("Invalid raw renewal configuration.");
12
+ const keys = Reflect.ownKeys(raw);
13
+ if (
14
+ keys.some(
15
+ (k) => typeof k !== "string" || ![...required, ...optional].includes(k),
16
+ ) ||
17
+ required.some((k) => !keys.includes(k))
18
+ )
19
+ throw Error("Invalid raw renewal configuration fields.");
20
+ const fields: ObjectData = {};
21
+ for (const key of keys) {
22
+ const d = Object.getOwnPropertyDescriptor(raw, key);
23
+ if (!d || !d.enumerable || !("value" in d))
24
+ throw Error("Renewal configuration requires own JSON data.");
25
+ fields[key as string] = d.value;
26
+ }
27
+ return fields;
28
+ }
29
+ function closed(raw: unknown) {
30
+ const root = ownData(
31
+ raw,
32
+ [
33
+ "preparation",
34
+ "attachReceipt",
35
+ "freshSubscription",
36
+ "targetPrice",
37
+ "schedule",
38
+ "apiVersion",
39
+ "observedAt",
40
+ "firstDispatchedAt",
41
+ "configureKey",
42
+ ],
43
+ ["billingCustomer"],
44
+ );
45
+ ownData(
46
+ root.preparation,
47
+ ["subscription", "targetPrice", "expected", "key"],
48
+ ["billingCustomer"],
49
+ );
50
+ validateAttachmentReceiptFields(root.attachReceipt);
51
+ }
52
+ const preparation = z
53
+ .object({
54
+ subscription: z.unknown(),
55
+ targetPrice: z.unknown(),
56
+ expected: z.unknown(),
57
+ key: z.string(),
58
+ billingCustomer: z.unknown().optional(),
59
+ })
60
+ .strict();
61
+ const input = z
62
+ .object({
63
+ preparation,
64
+ attachReceipt: z.unknown(),
65
+ freshSubscription: z.unknown(),
66
+ targetPrice: z.unknown(),
67
+ billingCustomer: z.unknown().optional(),
68
+ schedule: z.unknown(),
69
+ apiVersion: z.string(),
70
+ observedAt: timestamp,
71
+ firstDispatchedAt: timestamp,
72
+ configureKey: z.string(),
73
+ })
74
+ .strict();
75
+ export function captureConfiguration(raw: unknown) {
76
+ closed(raw);
77
+ const captured = renewalSnapshot(raw);
78
+ closed(captured);
79
+ const args = input.parse(captured);
80
+ return {
81
+ ...args,
82
+ attachReceipt: captureAttachmentReceipt(args.attachReceipt),
83
+ };
84
+ }