@fantastic.dev/better-stripe 0.87.0 → 0.88.1

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 (126) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAggregate/readMaterial.d.ts.map +1 -1
  4. package/dist/client/billing/renewalAggregate/readMaterial.js +4 -3
  5. package/dist/client/billing/renewalAggregate/readMaterial.js.map +1 -1
  6. package/dist/client/billing/renewalObservation/active-scheduled.d.ts +6 -0
  7. package/dist/client/billing/renewalObservation/active-scheduled.d.ts.map +1 -0
  8. package/dist/client/billing/renewalObservation/active-scheduled.js +37 -0
  9. package/dist/client/billing/renewalObservation/active-scheduled.js.map +1 -0
  10. package/dist/client/billing/renewalObservation/common.d.ts +47 -0
  11. package/dist/client/billing/renewalObservation/common.d.ts.map +1 -0
  12. package/dist/client/billing/renewalObservation/common.js +39 -0
  13. package/dist/client/billing/renewalObservation/common.js.map +1 -0
  14. package/dist/client/billing/renewalObservation/configured-baseline.d.ts +76 -0
  15. package/dist/client/billing/renewalObservation/configured-baseline.d.ts.map +1 -0
  16. package/dist/client/billing/renewalObservation/configured-baseline.js +26 -0
  17. package/dist/client/billing/renewalObservation/configured-baseline.js.map +1 -0
  18. package/dist/client/billing/renewalObservation/coupon-discount-joins.d.ts +53 -0
  19. package/dist/client/billing/renewalObservation/coupon-discount-joins.d.ts.map +1 -0
  20. package/dist/client/billing/renewalObservation/coupon-discount-joins.js +103 -0
  21. package/dist/client/billing/renewalObservation/coupon-discount-joins.js.map +1 -0
  22. package/dist/client/billing/renewalObservation/invoice-tax-identity.d.ts +52 -0
  23. package/dist/client/billing/renewalObservation/invoice-tax-identity.d.ts.map +1 -0
  24. package/dist/client/billing/renewalObservation/invoice-tax-identity.js +49 -0
  25. package/dist/client/billing/renewalObservation/invoice-tax-identity.js.map +1 -0
  26. package/dist/client/billing/renewalObservation/pending-and-stage.d.ts +76 -0
  27. package/dist/client/billing/renewalObservation/pending-and-stage.d.ts.map +1 -0
  28. package/dist/client/billing/renewalObservation/pending-and-stage.js +36 -0
  29. package/dist/client/billing/renewalObservation/pending-and-stage.js.map +1 -0
  30. package/dist/client/billing/renewalObservation/phase-price-normalization.d.ts +57 -0
  31. package/dist/client/billing/renewalObservation/phase-price-normalization.d.ts.map +1 -0
  32. package/dist/client/billing/renewalObservation/phase-price-normalization.js +70 -0
  33. package/dist/client/billing/renewalObservation/phase-price-normalization.js.map +1 -0
  34. package/dist/client/billing/renewalObservation/planProjection.d.ts +8 -0
  35. package/dist/client/billing/renewalObservation/planProjection.d.ts.map +1 -0
  36. package/dist/client/billing/renewalObservation/planProjection.js +150 -0
  37. package/dist/client/billing/renewalObservation/planProjection.js.map +1 -0
  38. package/dist/client/billing/renewalObservation/reference-catalog.d.ts +37 -0
  39. package/dist/client/billing/renewalObservation/reference-catalog.d.ts.map +1 -0
  40. package/dist/client/billing/renewalObservation/reference-catalog.js +109 -0
  41. package/dist/client/billing/renewalObservation/reference-catalog.js.map +1 -0
  42. package/dist/client/billing/renewalObservation/schedule-templates.d.ts +74 -0
  43. package/dist/client/billing/renewalObservation/schedule-templates.d.ts.map +1 -0
  44. package/dist/client/billing/renewalObservation/schedule-templates.js +72 -0
  45. package/dist/client/billing/renewalObservation/schedule-templates.js.map +1 -0
  46. package/dist/client/billing/renewalObservation/scheduled-context.d.ts +44 -0
  47. package/dist/client/billing/renewalObservation/scheduled-context.d.ts.map +1 -0
  48. package/dist/client/billing/renewalObservation/scheduled-context.js +64 -0
  49. package/dist/client/billing/renewalObservation/scheduled-context.js.map +1 -0
  50. package/dist/client/billing/renewalObservation/scheduled-identity.d.ts +53 -0
  51. package/dist/client/billing/renewalObservation/scheduled-identity.d.ts.map +1 -0
  52. package/dist/client/billing/renewalObservation/scheduled-identity.js +95 -0
  53. package/dist/client/billing/renewalObservation/scheduled-identity.js.map +1 -0
  54. package/dist/client/billing/renewalObservation/scheduled-normalization.d.ts +59 -0
  55. package/dist/client/billing/renewalObservation/scheduled-normalization.d.ts.map +1 -0
  56. package/dist/client/billing/renewalObservation/scheduled-normalization.js +29 -0
  57. package/dist/client/billing/renewalObservation/scheduled-normalization.js.map +1 -0
  58. package/dist/client/billing/renewalObservation/settings-normalization.d.ts +54 -0
  59. package/dist/client/billing/renewalObservation/settings-normalization.d.ts.map +1 -0
  60. package/dist/client/billing/renewalObservation/settings-normalization.js +53 -0
  61. package/dist/client/billing/renewalObservation/settings-normalization.js.map +1 -0
  62. package/dist/client/billing/renewalObservation/stage-runner.d.ts +4 -0
  63. package/dist/client/billing/renewalObservation/stage-runner.d.ts.map +1 -0
  64. package/dist/client/billing/renewalObservation/stage-runner.js +34 -0
  65. package/dist/client/billing/renewalObservation/stage-runner.js.map +1 -0
  66. package/dist/client/billing/renewalObservation/weeklyPending.d.ts +13 -0
  67. package/dist/client/billing/renewalObservation/weeklyPending.d.ts.map +1 -0
  68. package/dist/client/billing/renewalObservation/weeklyPending.js +55 -0
  69. package/dist/client/billing/renewalObservation/weeklyPending.js.map +1 -0
  70. package/dist/client/billing/renewalPriceReplacement.d.ts.map +1 -1
  71. package/dist/client/billing/renewalPriceReplacement.js +7 -3
  72. package/dist/client/billing/renewalPriceReplacement.js.map +1 -1
  73. package/dist/client/billing/renewalV2/index.d.ts +383 -0
  74. package/dist/client/billing/renewalV2/index.d.ts.map +1 -1
  75. package/dist/client/billing/renewalV2/index.js +8 -3
  76. package/dist/client/billing/renewalV2/index.js.map +1 -1
  77. package/dist/client/billing/renewalV2/observation.d.ts +19 -0
  78. package/dist/client/billing/renewalV2/observation.d.ts.map +1 -0
  79. package/dist/client/billing/renewalV2/observation.js +95 -0
  80. package/dist/client/billing/renewalV2/observation.js.map +1 -0
  81. package/dist/client/billing/renewalV2/observationInput.d.ts +77 -0
  82. package/dist/client/billing/renewalV2/observationInput.d.ts.map +1 -0
  83. package/dist/client/billing/renewalV2/observationInput.js +140 -0
  84. package/dist/client/billing/renewalV2/observationInput.js.map +1 -0
  85. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  86. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  87. package/dist/client/renewal.d.ts +2 -0
  88. package/dist/client/renewal.d.ts.map +1 -1
  89. package/dist/client/renewal.js +1 -0
  90. package/dist/client/renewal.js.map +1 -1
  91. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  92. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  93. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  94. package/dist/component/earnings/triggers.d.ts +16 -16
  95. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  96. package/docs/client-api.md +26 -0
  97. package/docs/renewal-context-reads.md +10 -0
  98. package/docs/renewal-material-observation.md +124 -0
  99. package/docs/renewal-phase-assembly.md +7 -0
  100. package/docs/renewal-price-replacements.md +3 -0
  101. package/package.json +1 -1
  102. package/src/client/billing/renewalAggregate/readMaterial.ts +5 -3
  103. package/src/client/billing/renewalObservation/active-scheduled.ts +67 -0
  104. package/src/client/billing/renewalObservation/common.ts +83 -0
  105. package/src/client/billing/renewalObservation/configured-baseline.ts +55 -0
  106. package/src/client/billing/renewalObservation/coupon-discount-joins.ts +163 -0
  107. package/src/client/billing/renewalObservation/invoice-tax-identity.ts +65 -0
  108. package/src/client/billing/renewalObservation/pending-and-stage.ts +89 -0
  109. package/src/client/billing/renewalObservation/phase-price-normalization.ts +106 -0
  110. package/src/client/billing/renewalObservation/planProjection.ts +177 -0
  111. package/src/client/billing/renewalObservation/reference-catalog.ts +150 -0
  112. package/src/client/billing/renewalObservation/schedule-templates.ts +118 -0
  113. package/src/client/billing/renewalObservation/scheduled-context.ts +98 -0
  114. package/src/client/billing/renewalObservation/scheduled-identity.ts +175 -0
  115. package/src/client/billing/renewalObservation/scheduled-normalization.ts +49 -0
  116. package/src/client/billing/renewalObservation/settings-normalization.ts +60 -0
  117. package/src/client/billing/renewalObservation/stage-runner.ts +30 -0
  118. package/src/client/billing/renewalObservation/weeklyPending.ts +81 -0
  119. package/src/client/billing/renewalPriceReplacement.ts +7 -3
  120. package/src/client/billing/renewalV2/index.ts +14 -6
  121. package/src/client/billing/renewalV2/observation.boundary-review.test.ts +49 -0
  122. package/src/client/billing/renewalV2/observation.test.ts +334 -0
  123. package/src/client/billing/renewalV2/observation.ts +149 -0
  124. package/src/client/billing/renewalV2/observationInput.ts +167 -0
  125. package/src/client/billing/renewalV2/rawRetention.test.ts +293 -0
  126. package/src/client/renewal.ts +7 -0
@@ -0,0 +1,81 @@
1
+ import { object, get, array, need, type O } from "./common.js";
2
+ function noReset(sub: O) {
3
+ return (
4
+ sub.billing_cycle_anchor_config === null &&
5
+ sub.trial_start === null &&
6
+ sub.trial_end === null &&
7
+ sub.billing_thresholds === null &&
8
+ sub.cancel_at === null &&
9
+ sub.canceled_at === null &&
10
+ sub.cancel_at_period_end === false &&
11
+ sub.pending_update === null &&
12
+ sub.pause_collection === null &&
13
+ array(get(sub, "items").data).every((x) => {
14
+ const i = object(x);
15
+ return (
16
+ i.billing_thresholds === null &&
17
+ (i.current_trial === null ||
18
+ !Object.prototype.hasOwnProperty.call(i, "current_trial"))
19
+ );
20
+ })
21
+ );
22
+ }
23
+ /** Narrow UTC-week inference. Never takes an expected end or caller evidence. */
24
+ export function weeklyPending(state: {
25
+ desired: O;
26
+ originalSub: O;
27
+ sub: O;
28
+ expected: O;
29
+ target: O;
30
+ targetPhase: O;
31
+ schedule: O;
32
+ phases: unknown[];
33
+ }) {
34
+ const profile = get(state.desired, "profile"),
35
+ target = get(state.target, "recurring");
36
+ if (
37
+ profile.billingMode !== "classic" ||
38
+ profile.cadence !== "changed" ||
39
+ profile.anchor !== "ordinary" ||
40
+ target.interval !== "week" ||
41
+ target.interval_count !== 1 ||
42
+ target.usage_type !== "licensed" ||
43
+ state.schedule.end_behavior !== "release" ||
44
+ !noReset(state.originalSub) ||
45
+ !noReset(state.sub)
46
+ )
47
+ return false;
48
+ const phases = array(get(state.desired, "payload").phases),
49
+ desired = object(phases[1]),
50
+ duration = get(desired, "duration");
51
+ if (
52
+ duration.interval !== "week" ||
53
+ duration.interval_count !== 1 ||
54
+ desired.billing_cycle_anchor !== "phase_start" ||
55
+ state.targetPhase.billing_cycle_anchor !== "phase_start" ||
56
+ !state.phases.every((p) => {
57
+ const phase = object(p);
58
+ return (
59
+ phase.trial === false &&
60
+ phase.trial_end === null &&
61
+ phase.billing_thresholds === null
62
+ );
63
+ })
64
+ )
65
+ return false;
66
+ const start = state.expected.periodEnd;
67
+ if (
68
+ !Number.isSafeInteger(start) ||
69
+ typeof start !== "number" ||
70
+ start < 0 ||
71
+ !Number.isSafeInteger(start + 604800)
72
+ )
73
+ return false;
74
+ const expectedEnd = start + 604800;
75
+ need(
76
+ state.targetPhase.start_date === start &&
77
+ state.targetPhase.end_date === expectedEnd,
78
+ "target_phase_duration_mismatch",
79
+ );
80
+ return true;
81
+ }
@@ -100,9 +100,13 @@ export function prepareRenewalPriceReplacement(
100
100
  if (subscription[field] != null)
101
101
  throw new Error(`Renewal replacement does not support ${field}.`);
102
102
  const providerSnapshot = renewalSnapshot({
103
- subscription,
104
- targetPrice,
105
- ...(billingCustomer === undefined ? {} : { billingCustomer }),
103
+ // Validation supplies semantic types; retain the complete detached bodies.
104
+ // Passthrough parsers can omit safe own JSON keys such as __proto__.
105
+ subscription: source.subscription as typeof subscription,
106
+ targetPrice: source.targetPrice as typeof targetPrice,
107
+ ...(billingCustomer === undefined
108
+ ? {}
109
+ : { billingCustomer: args.billingCustomer as typeof billingCustomer }),
106
110
  });
107
111
  const bound = {
108
112
  version: 1 as const,
@@ -244,11 +244,9 @@ export type ProjectedRenewalConfigurationV2 = Omit<
244
244
  export type RenewalConfigurationProjectionFailure = Failure;
245
245
 
246
246
  /** Pure raw-only configuration candidate; provider qualification remains required. */
247
- export async function projectRenewalConfigurationV2(
247
+ export async function reconstructConfigurationV2(
248
248
  options: ProjectRenewalConfigurationV2Options,
249
- ): Promise<
250
- ProjectedRenewalConfigurationV2 | RenewalConfigurationProjectionFailure
251
- > {
249
+ ) {
252
250
  const args = captureConfiguration(options);
253
251
  let ownedScheduleId: string | undefined;
254
252
  try {
@@ -323,7 +321,7 @@ export async function projectRenewalConfigurationV2(
323
321
  schedule.default_settings,
324
322
  ),
325
323
  };
326
- return renewalSnapshot({
324
+ const result: ProjectedRenewalConfigurationV2 = renewalSnapshot({
327
325
  ...request,
328
326
  status: "projected_configure_request" as const,
329
327
  providerQualification: "required" as const,
@@ -333,11 +331,21 @@ export async function projectRenewalConfigurationV2(
333
331
  binding: await renewalBindingV2("renewal-configure", request),
334
332
  },
335
333
  });
334
+ return { result, material: { args, prepared, receipt, reads } };
336
335
  } catch (error) {
337
- return failure(error, ownedScheduleId);
336
+ return { result: failure(error, ownedScheduleId), material: undefined };
338
337
  }
339
338
  }
340
339
 
340
+ /** Pure V2 projection; the reconstruction context stays internal to fixed callers. */
341
+ export async function projectRenewalConfigurationV2(
342
+ options: ProjectRenewalConfigurationV2Options,
343
+ ): Promise<
344
+ ProjectedRenewalConfigurationV2 | RenewalConfigurationProjectionFailure
345
+ > {
346
+ return (await reconstructConfigurationV2(options)).result;
347
+ }
348
+
341
349
  export type ConstructRenewalConfigurationReceiptV2Options = {
342
350
  configuration: ProjectRenewalConfigurationV2Options;
343
351
  actualDispatch: Pick<
@@ -0,0 +1,49 @@
1
+ import { expect, it } from "vitest";
2
+ import { inspectRenewalScheduleMaterialV2 } from "../../index.js";
3
+ import { observationInput } from "../../../../tests/renewalObservation/fixtures.js";
4
+
5
+ it("retains a supplied terminal string as unsigned facts only", async () => {
6
+ const raw = observationInput();
7
+ raw.reads.schedule.status = "canceled";
8
+ expect(await inspectRenewalScheduleMaterialV2(raw)).toMatchObject({
9
+ predicate: "terminal_facts_only",
10
+ providerStatus: "canceled",
11
+ effectiveness: "unknown",
12
+ acknowledgementEstablished: false,
13
+ authenticationEstablished: false,
14
+ });
15
+ });
16
+
17
+ it("does not coerce an array-shaped status into a known terminal fact", async () => {
18
+ const raw = observationInput();
19
+ (raw.reads.schedule as Record<string, unknown>).status = ["canceled"];
20
+ let result;
21
+ try {
22
+ result = await inspectRenewalScheduleMaterialV2(raw);
23
+ } catch (error) {
24
+ expect(error).toBeInstanceOf(Error);
25
+ expect((error as Error).message).toBe("Invalid raw renewal observation.");
26
+ return;
27
+ }
28
+ expect(["unknown", "conflict"]).toContain(result.predicate);
29
+ });
30
+
31
+ it.each([["canceled"], {}, null, 7, false])(
32
+ "keeps malformed bare status %j outside terminal facts",
33
+ async (status) => {
34
+ const raw = observationInput();
35
+ (raw.reads.schedule as Record<string, unknown>).status = status;
36
+ expect(await inspectRenewalScheduleMaterialV2(raw)).toMatchObject({
37
+ predicate: "unknown",
38
+ reason: "invalid_schedule_status",
39
+ });
40
+ },
41
+ );
42
+ it("retains unknown string status disposition", async () => {
43
+ const raw = observationInput();
44
+ raw.reads.schedule.status = "future_provider_status";
45
+ expect(await inspectRenewalScheduleMaterialV2(raw)).toMatchObject({
46
+ predicate: "unknown",
47
+ reason: "unsupported_schedule_status",
48
+ });
49
+ });
@@ -0,0 +1,334 @@
1
+ import { projectRenewalConfigurationV2 } from "./index.js";
2
+ import { it, expect } from "vitest";
3
+ import * as sdk from "./observation.js";
4
+ import { observationInput } from "../../../../tests/renewalObservation/fixtures.js";
5
+ const inspect = (raw: unknown) => {
6
+ expect((sdk as any).inspectRenewalScheduleMaterialV2).toBeTypeOf("function");
7
+ return (sdk as any).inspectRenewalScheduleMaterialV2(raw);
8
+ };
9
+ it("matches full classic changed-cadence weekly pending material without a configure ACK", async () => {
10
+ const raw = observationInput();
11
+ const before = structuredClone(raw);
12
+ const r = await inspect(raw);
13
+ expect(r).toMatchObject({
14
+ predicate: "pending_material_match",
15
+ acknowledgementEstablished: false,
16
+ authenticationEstablished: false,
17
+ providerQualificationRequired: true,
18
+ });
19
+ expect(raw).toEqual(before);
20
+ expect(raw.configuration.preparation.subscription).toHaveProperty(
21
+ "latest_invoice",
22
+ "in_original",
23
+ );
24
+ });
25
+ it("matches a unique full native active item only when the retained invoice pointer is coherent", async () => {
26
+ const raw = observationInput(true);
27
+ expect(raw.reads.subscription.latest_invoice).toBe("in_original");
28
+ expect(raw.reads.subscription.items.data[0].plan.object).toBe("plan");
29
+ expect(await inspect(raw)).toMatchObject({
30
+ predicate: "current_target_material_match",
31
+ observedItemId: "si_successor",
32
+ });
33
+ });
34
+ it("keeps I0 to I1 native invoice-pointer changes conflicting instead of dropping required material", async () => {
35
+ const raw = observationInput(true);
36
+ raw.reads.subscription.latest_invoice = "in_successor";
37
+ expect(raw.configuration.preparation.subscription.latest_invoice).toBe(
38
+ "in_original",
39
+ );
40
+ expect(await inspect(raw)).toMatchObject({
41
+ predicate: "conflict",
42
+ reason: "effective_full_material_drift",
43
+ });
44
+ });
45
+
46
+ it("keeps an unproved monthly pending duration unknown without treating reads as an ACK", async () => {
47
+ expect(await inspect(observationInput(false, false))).toMatchObject({
48
+ predicate: "unknown",
49
+ reason: "future_duration_not_bound",
50
+ acknowledgementEstablished: false,
51
+ });
52
+ });
53
+ it.each([-1, 1, 604800])(
54
+ "rejects a full weekly future phase whose end differs by %i seconds",
55
+ async (delta) => {
56
+ const raw = observationInput();
57
+ raw.reads.schedule.phases[1].end_date += delta;
58
+ expect(await inspect(raw)).toMatchObject({
59
+ predicate: "conflict",
60
+ reason: "target_phase_duration_mismatch",
61
+ });
62
+ },
63
+ );
64
+ it("does not use the weekly rule for flexible material", async () => {
65
+ const raw = observationInput();
66
+ const mode = {
67
+ type: "flexible",
68
+ flexible: { proration_discounts: "included" },
69
+ };
70
+ for (const sub of [
71
+ raw.configuration.preparation.subscription,
72
+ raw.configuration.attachReceipt.attachRequest.preparation.subscription,
73
+ raw.configuration.freshSubscription,
74
+ raw.reads.subscription,
75
+ ])
76
+ Object.assign(sub, { billing_mode: mode });
77
+ for (const schedule of [
78
+ raw.configuration.schedule,
79
+ raw.configuration.attachReceipt.providerSnapshot,
80
+ raw.reads.schedule,
81
+ ])
82
+ Object.assign(schedule, { billing_mode: mode });
83
+ expect(await inspect(raw)).toMatchObject({
84
+ predicate: "unknown",
85
+ reason: "future_duration_not_bound",
86
+ });
87
+ });
88
+ it("does not omit latest_invoice to manufacture a full native positive", async () => {
89
+ const raw = observationInput(true);
90
+ delete (raw.reads.subscription as Record<string, unknown>).latest_invoice;
91
+ expect(await inspect(raw)).toMatchObject({
92
+ predicate: "unknown",
93
+ reason: "missing_latest_invoice",
94
+ });
95
+ });
96
+ it("retains canceled terminal facts without assigning effectiveness", async () => {
97
+ const raw = observationInput();
98
+ raw.reads.schedule.status = "canceled";
99
+ expect(await inspect(raw)).toMatchObject({
100
+ predicate: "terminal_facts_only",
101
+ effectiveness: "unknown",
102
+ });
103
+ });
104
+ it.each(["prototype", "getter", "symbol", "hidden"])(
105
+ "rejects non-JSON %s roots before invoking a getter",
106
+ async (kind) => {
107
+ const raw: any = observationInput();
108
+ let calls = 0;
109
+ if (kind === "prototype") Object.setPrototypeOf(raw, { custom: true });
110
+ if (kind === "getter")
111
+ Object.defineProperty(raw, "reads", {
112
+ enumerable: true,
113
+ get() {
114
+ calls++;
115
+ throw Error("private");
116
+ },
117
+ });
118
+ if (kind === "symbol") raw[Symbol("private")] = true;
119
+ if (kind === "hidden")
120
+ Object.defineProperty(raw, "hidden", { value: "private" });
121
+ await expect(inspect(raw)).rejects.toThrow(
122
+ "Invalid raw renewal observation",
123
+ );
124
+ expect(calls).toBe(0);
125
+ },
126
+ );
127
+ it("rejects nested hidden SDK response metadata instead of stripping it", async () => {
128
+ const raw = observationInput();
129
+ let calls = 0;
130
+ Object.defineProperty(raw.reads.schedule, "lastResponse", {
131
+ get() {
132
+ calls++;
133
+ throw Error("private");
134
+ },
135
+ });
136
+ await expect(inspect(raw)).rejects.toThrow("Invalid raw renewal observation");
137
+ expect(calls).toBe(0);
138
+ });
139
+ it("captures reads before asynchronous digest work", async () => {
140
+ const raw = observationInput(true);
141
+ const pending = inspect(raw);
142
+ raw.reads.subscription.latest_invoice = "in_mutated";
143
+ raw.reads.schedule.phases[1].end_date++;
144
+ expect(await pending).toMatchObject({
145
+ predicate: "current_target_material_match",
146
+ });
147
+ });
148
+ it("retains unknown own special fields in the full subscription comparison", async () => {
149
+ const raw = observationInput(true);
150
+ Object.defineProperty(raw.reads.subscription, "__proto__", {
151
+ value: { retained: true },
152
+ enumerable: true,
153
+ });
154
+ expect(await inspect(raw)).toMatchObject({
155
+ predicate: "conflict",
156
+ reason: "effective_full_material_drift",
157
+ });
158
+ });
159
+ it("rejects the new API's whole input byte/node bounds", async () => {
160
+ const raw: any = observationInput();
161
+ raw.reads.subscription.extra = "🧪".repeat(130000);
162
+ await expect(inspect(raw)).rejects.toThrow();
163
+ const nodes: any = observationInput();
164
+ nodes.reads.subscription.extra = Array.from({ length: 10001 }, () => null);
165
+ await expect(inspect(nodes)).rejects.toThrow();
166
+ });
167
+
168
+ async function withReceipt(active = false, weekly = false) {
169
+ const raw: any = observationInput(active, weekly),
170
+ baseline = observationInput(false, weekly);
171
+ const request = await projectRenewalConfigurationV2(raw.configuration);
172
+ if (request.status !== "projected_configure_request") throw Error("fixture");
173
+ const { scope, apiVersion, method, path, payload, key, firstDispatchedAt } =
174
+ request;
175
+ raw.configureReceipt = {
176
+ configuration: structuredClone(raw.configuration),
177
+ actualDispatch: {
178
+ scope,
179
+ apiVersion,
180
+ method,
181
+ path,
182
+ payload,
183
+ key,
184
+ firstDispatchedAt,
185
+ },
186
+ providerSnapshot: baseline.reads.schedule,
187
+ transport: { status: 200, requestId: "req_material" },
188
+ };
189
+ return raw;
190
+ }
191
+ it("uses complete raw C9 historical material for monthly pending without authenticating it", async () => {
192
+ expect(await inspect(await withReceipt())).toMatchObject({
193
+ predicate: "pending_material_match",
194
+ acknowledgementEstablished: false,
195
+ authenticationEstablished: false,
196
+ });
197
+ });
198
+ it("does not let a C9 receipt authorize a new native invoice pointer", async () => {
199
+ const raw = await withReceipt(true);
200
+ raw.reads.subscription.latest_invoice = "in_successor";
201
+ expect(await inspect(raw)).toMatchObject({
202
+ predicate: "conflict",
203
+ reason: "effective_full_material_drift",
204
+ });
205
+ });
206
+ it("rejects differing repeated raw C9 configuration", async () => {
207
+ const raw = await withReceipt();
208
+ raw.configureReceipt.configuration.configureKey = "different";
209
+ expect(await inspect(raw)).toMatchObject({
210
+ predicate: "conflict",
211
+ reason: "invalid_repeated_configuration",
212
+ });
213
+ });
214
+ it.each([
215
+ "scope",
216
+ "apiVersion",
217
+ "method",
218
+ "path",
219
+ "payload",
220
+ "key",
221
+ "firstDispatchedAt",
222
+ ])("never trusts a tampered raw C9 dispatch %s", async (field) => {
223
+ const raw = await withReceipt();
224
+ raw.configureReceipt.actualDispatch[field] =
225
+ field === "payload" ? {} : field === "firstDispatchedAt" ? 1 : "foreign";
226
+ if (field === "scope" || field === "method")
227
+ await expect(inspect(raw)).rejects.toThrow(
228
+ "Invalid raw renewal observation.",
229
+ );
230
+ else
231
+ expect(await inspect(raw)).toMatchObject({
232
+ predicate: "unknown",
233
+ reason: "incomplete_or_unsupported_schema",
234
+ });
235
+ });
236
+ it("captures repeated C9 input before any asynchronous digest", async () => {
237
+ const raw = await withReceipt();
238
+ const pending = inspect(raw);
239
+ raw.configureReceipt.configuration.configureKey = "changed_after_capture";
240
+ expect(await pending).toMatchObject({ predicate: "pending_material_match" });
241
+ });
242
+ it("does not create a native positive by omitting both original and current invoice pointers", async () => {
243
+ const raw: any = observationInput(true);
244
+ for (const sub of [
245
+ raw.configuration.preparation.subscription,
246
+ raw.configuration.attachReceipt.attachRequest.preparation.subscription,
247
+ raw.configuration.freshSubscription,
248
+ raw.reads.subscription,
249
+ ])
250
+ delete sub.latest_invoice;
251
+ expect(await inspect(raw)).toMatchObject({
252
+ predicate: "unknown",
253
+ reason: "missing_latest_invoice",
254
+ });
255
+ });
256
+ it("rejects metadata introduced by descriptor reflection after the own-key snapshot", async () => {
257
+ const raw: any = observationInput(true),
258
+ target = raw.reads.subscription;
259
+ let introduced = false;
260
+ raw.reads.subscription = new Proxy(target, {
261
+ getOwnPropertyDescriptor(t, key) {
262
+ const d = Reflect.getOwnPropertyDescriptor(t, key);
263
+ if (key === "items" && !introduced) {
264
+ introduced = true;
265
+ Object.defineProperty(t, "lastResponse", {
266
+ value: { statusCode: 200 },
267
+ configurable: true,
268
+ });
269
+ }
270
+ return d;
271
+ },
272
+ });
273
+ await expect(inspect(raw)).rejects.toThrow(
274
+ "Invalid raw renewal observation.",
275
+ );
276
+ expect(introduced).toBe(true);
277
+ });
278
+
279
+ it("keeps multi-week pending duration unsupported without C9 baseline evidence", async () => {
280
+ expect(await inspect(observationInput(false, true, 2))).toMatchObject({
281
+ predicate: "unknown",
282
+ reason: "future_duration_not_bound",
283
+ });
284
+ });
285
+ it("retains paid settings and full Customer/Coupon unknown material despite a correct weekly end", async () => {
286
+ for (const change of [
287
+ (x: any) => {
288
+ x.reads.billingCustomer.new_unknown = "drift";
289
+ },
290
+ (x: any) => {
291
+ x.reads.coupons[0].times_redeemed++;
292
+ },
293
+ (x: any) => {
294
+ x.reads.subscription.items.data[0].plan.nickname = "drift";
295
+ },
296
+ (x: any) => {
297
+ x.reads.subscription.metadata.keep = "drift";
298
+ },
299
+ ]) {
300
+ const raw = observationInput();
301
+ change(raw);
302
+ expect((await inspect(raw)).predicate).not.toBe("pending_material_match");
303
+ }
304
+ });
305
+ it("accepts plain null-prototype and benign Proxy roots without evaluating caller code", async () => {
306
+ const raw = observationInput(true);
307
+ const nullRoot = Object.assign(Object.create(null), raw);
308
+ expect(await inspect(nullRoot)).toMatchObject({
309
+ predicate: "current_target_material_match",
310
+ });
311
+ let prototypes = 0;
312
+ const proxy = new Proxy(raw, {
313
+ getPrototypeOf(t) {
314
+ prototypes++;
315
+ return Reflect.getPrototypeOf(t);
316
+ },
317
+ });
318
+ expect(await inspect(proxy)).toMatchObject({
319
+ predicate: "current_target_material_match",
320
+ });
321
+ expect(prototypes).toBe(1);
322
+ });
323
+ it("rejects a nested toJSON function without calling it", async () => {
324
+ const raw: any = observationInput();
325
+ let calls = 0;
326
+ raw.reads.subscription.toJSON = () => {
327
+ calls++;
328
+ throw Error("private");
329
+ };
330
+ await expect(inspect(raw)).rejects.toThrow(
331
+ "Invalid raw renewal observation.",
332
+ );
333
+ expect(calls).toBe(0);
334
+ });
@@ -0,0 +1,149 @@
1
+ import {
2
+ captureObservation,
3
+ type InspectRenewalScheduleMaterialV2Options,
4
+ } from "./observationInput.js";
5
+ import {
6
+ reconstructConfigurationV2,
7
+ constructRenewalConfigurationReceiptV2,
8
+ type ProjectRenewalConfigurationV2Options,
9
+ type ConstructRenewalConfigurationReceiptV2Options,
10
+ } from "./index.js";
11
+ import { createContext } from "../renewalObservation/scheduled-context.js";
12
+ import { runStages } from "../renewalObservation/stage-runner.js";
13
+ import {
14
+ Stop,
15
+ object,
16
+ array,
17
+ get,
18
+ equal,
19
+ type ObserverCandidateResult,
20
+ type Evidence,
21
+ } from "../renewalObservation/common.js";
22
+ export type {
23
+ InspectRenewalScheduleMaterialV2Options,
24
+ RenewalScheduleMaterialReads,
25
+ } from "./observationInput.js";
26
+ export type RenewalScheduleMaterialObservationV2 = {
27
+ predicate:
28
+ | "attached_unconfigured_match"
29
+ | "pending_material_match"
30
+ | "current_target_material_match"
31
+ | "terminal_facts_only"
32
+ | "unknown"
33
+ | "conflict";
34
+ reason?: string;
35
+ observedItemId?: string;
36
+ nativePeriod?: { start: number; end: number };
37
+ providerStatus?: unknown;
38
+ effectiveness?: "unknown";
39
+ acknowledgementEstablished: false;
40
+ authenticationEstablished: false;
41
+ providerQualificationRequired: true;
42
+ };
43
+ const base = {
44
+ acknowledgementEstablished: false,
45
+ authenticationEstablished: false,
46
+ providerQualificationRequired: true,
47
+ } as const;
48
+ function result(
49
+ r: ObserverCandidateResult,
50
+ ): RenewalScheduleMaterialObservationV2 {
51
+ const predicate =
52
+ r.predicate === "confirmed_pending"
53
+ ? "pending_material_match"
54
+ : r.predicate === "active_effective_match"
55
+ ? "current_target_material_match"
56
+ : r.predicate === "configured_baseline_material_match"
57
+ ? "unknown"
58
+ : r.predicate;
59
+ return {
60
+ ...base,
61
+ predicate,
62
+ ...(r.reason ? { reason: r.reason } : {}),
63
+ ...(r.observedItemId ? { observedItemId: r.observedItemId } : {}),
64
+ ...(r.nativePeriod ? { nativePeriod: r.nativePeriod } : {}),
65
+ ...(r.providerStatus !== undefined
66
+ ? { providerStatus: r.providerStatus }
67
+ : {}),
68
+ ...(r.effectiveness ? { effectiveness: r.effectiveness } : {}),
69
+ };
70
+ }
71
+ /** Unsigned full-material comparison only. No HTTP, trusted-store or entitlement authority. */
72
+ export async function inspectRenewalScheduleMaterialV2(
73
+ options: InspectRenewalScheduleMaterialV2Options,
74
+ ): Promise<RenewalScheduleMaterialObservationV2> {
75
+ const captured = captureObservation(options);
76
+ try {
77
+ const reconstruction = await reconstructConfigurationV2(
78
+ captured.configuration as ProjectRenewalConfigurationV2Options,
79
+ );
80
+ if (!reconstruction.material)
81
+ return {
82
+ ...base,
83
+ predicate:
84
+ reconstruction.result.status === "conflict" ? "conflict" : "unknown",
85
+ reason: reconstruction.result.reason,
86
+ };
87
+ const { material, result: request } = reconstruction;
88
+ const owned = { ...material, request };
89
+ let evidence: Evidence | undefined;
90
+ if (captured.configureReceipt) {
91
+ if (
92
+ !equal(captured.configureReceipt.configuration, captured.configuration)
93
+ )
94
+ return {
95
+ ...base,
96
+ predicate: "conflict",
97
+ reason: "invalid_repeated_configuration",
98
+ };
99
+ const receipt = await constructRenewalConfigurationReceiptV2(
100
+ captured.configureReceipt as ConstructRenewalConfigurationReceiptV2Options,
101
+ );
102
+ const sub = get(material.prepared.providerSnapshot, "subscription"),
103
+ item = object(array(get(sub, "items").data)[0]);
104
+ const coupons = new Map<string, Record<string, unknown>>();
105
+ for (const raw of [...array(sub.discounts), ...array(item.discounts)]) {
106
+ const coupon = get(get(object(raw), "source"), "coupon"),
107
+ id = String(coupon.id);
108
+ if (coupons.has(id) && !equal(coupons.get(id), coupon))
109
+ throw new Stop("historical_coupon_conflict");
110
+ coupons.set(id, coupon);
111
+ }
112
+ const historical = {
113
+ schedule: receipt.providerSnapshot,
114
+ subscription: material.args.freshSubscription,
115
+ targetPrice: material.args.targetPrice,
116
+ billingCustomer: material.args.billingCustomer,
117
+ coupons: [...coupons.values()],
118
+ };
119
+ const proof = runStages(createContext(owned, historical, "baseline"));
120
+ if (
121
+ proof.predicate !== "configured_baseline_material_match" ||
122
+ typeof proof.proofTargetEnd !== "number" ||
123
+ !proof.proofStage
124
+ )
125
+ return {
126
+ ...base,
127
+ predicate: proof.predicate === "conflict" ? "conflict" : "unknown",
128
+ reason: proof.reason ?? "configured_baseline_material_unproven",
129
+ };
130
+ evidence = {
131
+ targetEnd: proof.proofTargetEnd,
132
+ comparable: proof.comparableSchedule,
133
+ stage: proof.proofStage,
134
+ };
135
+ }
136
+ return result(
137
+ runStages(createContext(owned, captured.reads, "live", evidence)),
138
+ );
139
+ } catch (error) {
140
+ return {
141
+ ...base,
142
+ predicate: error instanceof Stop ? error.kind : "unknown",
143
+ reason:
144
+ error instanceof Stop
145
+ ? error.reason
146
+ : "incomplete_or_unsupported_schema",
147
+ };
148
+ }
149
+ }