@fantastic.dev/better-stripe 0.54.0 → 0.55.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 (122) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +112 -34
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +40 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +112 -34
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +40 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +5 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/usage/client.d.ts +2 -2
  14. package/dist/client/usage/client.d.ts.map +1 -1
  15. package/dist/client/usage/client.js +2 -2
  16. package/dist/client/usage/client.js.map +1 -1
  17. package/dist/client/usage/index.d.ts +5 -0
  18. package/dist/client/usage/index.d.ts.map +1 -1
  19. package/dist/client/usage/invoiceObservation.d.ts +38 -0
  20. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  21. package/dist/client/usage/invoiceObservation.js +157 -0
  22. package/dist/client/usage/invoiceObservation.js.map +1 -0
  23. package/dist/client/usage/observationClient.d.ts +83 -0
  24. package/dist/client/usage/observationClient.d.ts.map +1 -0
  25. package/dist/client/usage/observationClient.js +157 -0
  26. package/dist/client/usage/observationClient.js.map +1 -0
  27. package/dist/client/usage/observationTypes.d.ts +63 -0
  28. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  29. package/dist/client/usage/observationTypes.js +59 -0
  30. package/dist/client/usage/observationTypes.js.map +1 -0
  31. package/dist/client/usage/providerObservation.d.ts +4 -0
  32. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  33. package/dist/client/usage/providerObservation.js +96 -0
  34. package/dist/client/usage/providerObservation.js.map +1 -0
  35. package/dist/client/usage/reconciliation.d.ts +12 -0
  36. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  37. package/dist/client/usage/reconciliation.js +48 -0
  38. package/dist/client/usage/reconciliation.js.map +1 -0
  39. package/dist/client/usage/summary.d.ts +50 -0
  40. package/dist/client/usage/summary.d.ts.map +1 -0
  41. package/dist/client/usage/summary.js +110 -0
  42. package/dist/client/usage/summary.js.map +1 -0
  43. package/dist/component/_generated/api.d.ts +8 -0
  44. package/dist/component/_generated/api.d.ts.map +1 -1
  45. package/dist/component/_generated/api.js.map +1 -1
  46. package/dist/component/_generated/component.d.ts +95 -0
  47. package/dist/component/_generated/component.d.ts.map +1 -1
  48. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  49. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  50. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  51. package/dist/component/earnings/triggers.d.ts +104 -18
  52. package/dist/component/earnings/triggers.d.ts.map +1 -1
  53. package/dist/component/refundHistory/queries.d.ts +1 -1
  54. package/dist/component/schema.d.ts +40 -1
  55. package/dist/component/schema.js +3 -0
  56. package/dist/component/schema.js.map +1 -1
  57. package/dist/component/usage/schema.d.ts +7 -2
  58. package/dist/component/usage/schema.d.ts.map +1 -1
  59. package/dist/component/usageDelivery/fields.d.ts +1 -0
  60. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  61. package/dist/component/usageDelivery/fields.js +1 -0
  62. package/dist/component/usageDelivery/fields.js.map +1 -1
  63. package/dist/component/usageDelivery/helpers.d.ts +1 -0
  64. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  65. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  66. package/dist/component/usageDelivery/mutations.js +8 -1
  67. package/dist/component/usageDelivery/mutations.js.map +1 -1
  68. package/dist/component/usageDelivery/queries.d.ts +2 -0
  69. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  70. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  71. package/dist/component/usageDelivery/steps.js +8 -1
  72. package/dist/component/usageDelivery/steps.js.map +1 -1
  73. package/dist/component/usageObservations/helpers.d.ts +38 -0
  74. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  75. package/dist/component/usageObservations/helpers.js +80 -0
  76. package/dist/component/usageObservations/helpers.js.map +1 -0
  77. package/dist/component/usageObservations/history.d.ts +6 -0
  78. package/dist/component/usageObservations/history.d.ts.map +1 -0
  79. package/dist/component/usageObservations/history.js +29 -0
  80. package/dist/component/usageObservations/history.js.map +1 -0
  81. package/dist/component/usageObservations/mutations.d.ts +6 -0
  82. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  83. package/dist/component/usageObservations/mutations.js +39 -0
  84. package/dist/component/usageObservations/mutations.js.map +1 -0
  85. package/dist/component/usageObservations/queries.d.ts +78 -0
  86. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  87. package/dist/component/usageObservations/queries.js +131 -0
  88. package/dist/component/usageObservations/queries.js.map +1 -0
  89. package/dist/component/usageObservations/schema.d.ts +72 -0
  90. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  91. package/dist/component/usageObservations/schema.js +29 -0
  92. package/dist/component/usageObservations/schema.js.map +1 -0
  93. package/docs/README.md +2 -0
  94. package/docs/metering-setup.md +2 -0
  95. package/docs/usage-observations.md +152 -0
  96. package/package.json +3 -2
  97. package/src/client/index.ts +18 -0
  98. package/src/client/usage/client.ts +2 -2
  99. package/src/client/usage/index.ts +18 -0
  100. package/src/client/usage/invoiceObservation.test.ts +195 -0
  101. package/src/client/usage/invoiceObservation.ts +203 -0
  102. package/src/client/usage/observationClient.ts +233 -0
  103. package/src/client/usage/observationTypes.ts +101 -0
  104. package/src/client/usage/providerObservation.test.ts +207 -0
  105. package/src/client/usage/providerObservation.ts +124 -0
  106. package/src/client/usage/reconciliation.test.ts +117 -0
  107. package/src/client/usage/reconciliation.ts +86 -0
  108. package/src/client/usage/summary.test.ts +222 -0
  109. package/src/client/usage/summary.ts +188 -0
  110. package/src/component/_generated/api.ts +8 -0
  111. package/src/component/_generated/component.ts +135 -0
  112. package/src/component/schema.ts +6 -0
  113. package/src/component/usageDelivery/fields.ts +1 -0
  114. package/src/component/usageDelivery/mutations.ts +26 -1
  115. package/src/component/usageDelivery/steps.ts +39 -1
  116. package/src/component/usageObservations/helpers.ts +95 -0
  117. package/src/component/usageObservations/history.test.ts +87 -0
  118. package/src/component/usageObservations/history.ts +39 -0
  119. package/src/component/usageObservations/mutations.ts +39 -0
  120. package/src/component/usageObservations/queries.test.ts +162 -0
  121. package/src/component/usageObservations/queries.ts +145 -0
  122. package/src/component/usageObservations/schema.ts +40 -0
@@ -0,0 +1,203 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import {
4
+ observationOptions,
5
+ verifyObservationSource,
6
+ type UsageObservationOptions,
7
+ } from "./observationTypes.js";
8
+ import type { UsageAvailability } from "./boundaries.js";
9
+ import { UsageCatalogError } from "./catalogTypes.js";
10
+ import { decimalFromScaled } from "./summary.js";
11
+ export type UsageInvoiceLine = {
12
+ lineId: string;
13
+ stripePriceId: string;
14
+ subscriptionItemId: string;
15
+ amount: string;
16
+ currency: string;
17
+ quantity: string | null;
18
+ providerQuantityDecimal: string | null;
19
+ unitAmountDecimal: string | null;
20
+ creditAppliedAmount: string;
21
+ nativePeriod: { start: number; end: number };
22
+ proration: boolean;
23
+ };
24
+ export type UsageInvoiceObservation = {
25
+ kind: "preview" | "invoice";
26
+ invoiceId: string;
27
+ status: "draft" | "open" | "paid" | "void" | "uncollectible";
28
+ finalized: boolean;
29
+ amountDue: string;
30
+ amountPaid: string;
31
+ total: string;
32
+ currency: string;
33
+ linesComplete: boolean;
34
+ lines: UsageInvoiceLine[];
35
+ meterAmount: UsageAvailability<{ amount: string; currency: string }>;
36
+ paymentEvidence: "not_resolved";
37
+ };
38
+ const idOf = (value: string | { id: string } | null | undefined) =>
39
+ typeof value === "string" ? value : value?.id;
40
+ function amount(value: number): string {
41
+ if (!Number.isSafeInteger(value)) throw new Error("Unsafe native amount");
42
+ return String(value);
43
+ }
44
+ function decimal(value: Stripe.Decimal | null | undefined): string | null {
45
+ if (value == null) return null;
46
+ const text = value.toString();
47
+ if (!/^\d+(\.\d{1,12})?$/.test(text) || text.length > 64)
48
+ throw new Error("Unsupported native decimal");
49
+ return text;
50
+ }
51
+ export async function observeUsageInvoice(
52
+ stripe: Stripe,
53
+ input: UsageObservationOptions,
54
+ invoiceId?: string,
55
+ ): Promise<UsageAvailability<UsageInvoiceObservation>> {
56
+ const opts = observationOptions(input),
57
+ observedAt = Math.floor(Date.now() / 1000);
58
+ if (invoiceId !== undefined)
59
+ z.string()
60
+ .regex(/^in_[a-zA-Z0-9]+$/)
61
+ .max(100)
62
+ .parse(invoiceId);
63
+ try {
64
+ if (!(await verifyObservationSource(stripe, opts)))
65
+ return {
66
+ status: "unsupported",
67
+ reason: "provider_binding_mismatch",
68
+ retryable: false,
69
+ };
70
+ const invoice = invoiceId
71
+ ? await stripe.invoices.retrieve(invoiceId)
72
+ : await stripe.invoices.createPreview({
73
+ subscription: opts.subscription.subscriptionId,
74
+ customer_account: opts.scope.customerAccount,
75
+ });
76
+ const status = z
77
+ .enum(["draft", "open", "paid", "void", "uncollectible"])
78
+ .safeParse(invoice.status);
79
+ if (
80
+ !status.success ||
81
+ !invoice.id ||
82
+ invoice.id.length > 100 ||
83
+ (invoiceId && invoice.id !== invoiceId) ||
84
+ invoice.livemode !== opts.scope.livemode ||
85
+ invoice.customer_account !== opts.scope.customerAccount ||
86
+ idOf(invoice.customer) !== opts.binding.stripeCustomerId ||
87
+ idOf(invoice.parent?.subscription_details?.subscription) !==
88
+ opts.subscription.subscriptionId ||
89
+ invoice.currency !== opts.binding.plan.rate.currency
90
+ )
91
+ return {
92
+ status: "unsupported",
93
+ reason: "invoice_binding_mismatch",
94
+ retryable: false,
95
+ };
96
+ const lines: UsageInvoiceLine[] = [];
97
+ let ambiguous = false;
98
+ const linesComplete =
99
+ !invoice.lines.has_more && invoice.lines.data.length <= 100;
100
+ for (const line of invoice.lines.data.slice(0, 100)) {
101
+ if (line.pricing?.price_details?.price !== opts.binding.stripePriceId)
102
+ continue;
103
+ const parent = line.parent?.subscription_item_details;
104
+ if (
105
+ parent?.subscription !== opts.subscription.subscriptionId ||
106
+ parent.subscription_item !== opts.subscription.subscriptionItemId ||
107
+ line.currency !== invoice.currency
108
+ ) {
109
+ ambiguous = true;
110
+ continue;
111
+ }
112
+ const providerQuantity = decimal(line.quantity_decimal);
113
+ let quantity: string | null = null;
114
+ if (providerQuantity !== null) {
115
+ const [whole, fraction = ""] = providerQuantity.split(".");
116
+ quantity = decimalFromScaled(
117
+ BigInt(whole + fraction),
118
+ fraction.length + opts.binding.plan.unit.precision,
119
+ );
120
+ }
121
+ const creditApplied = (line.pretax_credit_amounts ?? [])
122
+ .filter((value) => value.type === "credit_balance_transaction")
123
+ .reduce((sum, value) => sum + BigInt(amount(value.amount)), 0n);
124
+ lines.push({
125
+ lineId: line.id,
126
+ stripePriceId: opts.binding.stripePriceId,
127
+ subscriptionItemId: parent.subscription_item,
128
+ amount: amount(line.amount),
129
+ currency: line.currency,
130
+ quantity,
131
+ providerQuantityDecimal: providerQuantity,
132
+ unitAmountDecimal: decimal(line.pricing.unit_amount_decimal),
133
+ creditAppliedAmount: creditApplied.toString(),
134
+ nativePeriod: { start: line.period.start, end: line.period.end },
135
+ proration: parent.proration,
136
+ });
137
+ }
138
+ const meterAmount: UsageInvoiceObservation["meterAmount"] = !linesComplete
139
+ ? {
140
+ status: "unavailable",
141
+ reason: "invoice_history_incomplete",
142
+ retryable: true,
143
+ }
144
+ : ambiguous
145
+ ? {
146
+ status: "unavailable",
147
+ reason: "ambiguous_invoice_items",
148
+ retryable: false,
149
+ }
150
+ : !lines.length
151
+ ? {
152
+ status: "unavailable",
153
+ reason: "metered_lines_not_observed",
154
+ retryable: true,
155
+ }
156
+ : {
157
+ status: "available",
158
+ observedAt,
159
+ value: {
160
+ amount: lines
161
+ .reduce((sum, line) => sum + BigInt(line.amount), 0n)
162
+ .toString(),
163
+ currency: invoice.currency,
164
+ },
165
+ };
166
+ return {
167
+ status: "available",
168
+ observedAt,
169
+ value: {
170
+ kind: invoiceId ? "invoice" : "preview",
171
+ invoiceId: invoice.id,
172
+ status: status.data,
173
+ finalized:
174
+ invoiceId !== undefined &&
175
+ invoice.status !== "draft" &&
176
+ Number.isSafeInteger(invoice.status_transitions?.finalized_at),
177
+ amountDue: amount(invoice.amount_due),
178
+ amountPaid: amount(invoice.amount_paid),
179
+ total: amount(invoice.total),
180
+ currency: invoice.currency,
181
+ linesComplete,
182
+ lines,
183
+ meterAmount,
184
+ paymentEvidence: "not_resolved",
185
+ },
186
+ };
187
+ } catch (error) {
188
+ if (
189
+ error instanceof UsageCatalogError &&
190
+ error.code === "unsupported_scope"
191
+ )
192
+ return {
193
+ status: "unsupported",
194
+ reason: "unsupported_scope",
195
+ retryable: false,
196
+ };
197
+ return {
198
+ status: "unavailable",
199
+ reason: "invoice_unavailable",
200
+ retryable: true,
201
+ };
202
+ }
203
+ }
@@ -0,0 +1,233 @@
1
+ import type { Doc } from "../../component/_generated/dataModel.js";
2
+ import type { UsageDeliveryRef } from "./deliveryClient.js";
3
+ import { observeUsageInvoice } from "./invoiceObservation.js";
4
+ import Stripe from "stripe";
5
+ import type { RunCtx } from "../helpers.js";
6
+ import { runMutationOrThrow } from "../helpers.js";
7
+ import { componentRef } from "../webhooks/helpers.js";
8
+ import type { StripeApiVersion } from "../stripe-types.js";
9
+ import { UsageDeliveryClient } from "./deliveryClient.js";
10
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
11
+ import { observeProviderUsage } from "./providerObservation.js";
12
+ import {
13
+ observationOptions,
14
+ observationKeyOptions,
15
+ type UsageObservationOptions,
16
+ type UsageAggregateObservation,
17
+ } from "./observationTypes.js";
18
+ import type { UsageLocalSummary } from "./summary.js";
19
+ import type { UsageScope } from "./records.js";
20
+ import { scopeSchema } from "./records.js";
21
+ import { validateUsagePageRequest, type UsagePeriod } from "./boundaries.js";
22
+ import { compareUsageObservations } from "./reconciliation.js";
23
+ export type UsageReconciliationOptions = UsageObservationOptions & {
24
+ maxRecords?: number;
25
+ maxAgeSeconds?: number;
26
+ };
27
+ /** Host authorizes the exact scope and original binding before every call. */
28
+ export class UsageObservationClient extends UsageDeliveryClient {
29
+ async getSummary(
30
+ ctx: RunCtx,
31
+ input: { scope: UsageScope; period: UsagePeriod; maxRecords?: number },
32
+ ): Promise<UsageLocalSummary> {
33
+ const scope = scopeSchema.parse(input.scope),
34
+ { period } = validateUsagePageRequest({
35
+ period: input.period,
36
+ limit: 1,
37
+ cursor: null,
38
+ });
39
+ const json = await ctx.runQuery(
40
+ componentRef(this.component, "usageObservations/queries/summary"),
41
+ { scope, period, maxRecords: input.maxRecords ?? 100 },
42
+ );
43
+ return JSON.parse(json) as UsageLocalSummary;
44
+ }
45
+ async getProviderUsage(
46
+ ctx: RunCtx,
47
+ input: UsageReconciliationOptions,
48
+ ): Promise<UsageAggregateObservation> {
49
+ const opts = observationOptions(input),
50
+ { maxAgeSeconds } = observationKeyOptions.parse({
51
+ maxAgeSeconds: input.maxAgeSeconds,
52
+ });
53
+ const json = await ctx.runQuery(
54
+ componentRef(this.component, "usageObservations/queries/cached"),
55
+ { sourceJson: JSON.stringify(opts) },
56
+ );
57
+ if (json === null)
58
+ return {
59
+ status: "unavailable",
60
+ reason: "provider_not_observed",
61
+ retryable: true,
62
+ };
63
+ const result = JSON.parse(json) as UsageAggregateObservation;
64
+ if (result.status === "available")
65
+ return {
66
+ ...result,
67
+ value: {
68
+ ...result.value,
69
+ stale:
70
+ Math.floor(Date.now() / 1000) - result.observedAt > maxAgeSeconds,
71
+ },
72
+ };
73
+ return result;
74
+ }
75
+ async observeProviderUsage(
76
+ ctx: RunCtx,
77
+ input: UsageObservationOptions,
78
+ options: UsageDeliveryProviderOptions,
79
+ ): Promise<UsageAggregateObservation> {
80
+ const opts = observationOptions(input),
81
+ startedAt = Date.now();
82
+ const observation = options.stripeSecretKey
83
+ ? await observeProviderUsage(
84
+ new Stripe(options.stripeSecretKey, {
85
+ apiVersion: opts.binding.apiVersion as StripeApiVersion,
86
+ maxNetworkRetries: 0,
87
+ timeout: 15000,
88
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
89
+ }),
90
+ opts,
91
+ )
92
+ : {
93
+ status: "unavailable" as const,
94
+ reason: "provider_unavailable",
95
+ retryable: true,
96
+ };
97
+ await runMutationOrThrow(
98
+ ctx,
99
+ componentRef(this.component, "usageObservations/mutations/save"),
100
+ {
101
+ sourceJson: JSON.stringify(opts),
102
+ observationJson: JSON.stringify(observation),
103
+ startedAt,
104
+ },
105
+ );
106
+ return observation;
107
+ }
108
+ async readDeliveryHistory(
109
+ ctx: RunCtx,
110
+ input: UsageDeliveryRef & { limit: number; cursor: string | null },
111
+ ) {
112
+ const page = validateUsagePageRequest({
113
+ period: { start: 0, end: 1 },
114
+ limit: input.limit,
115
+ cursor: input.cursor,
116
+ });
117
+ const result = (await ctx.runQuery(
118
+ componentRef(this.component, "usageObservations/queries/deliveryHistory"),
119
+ {
120
+ scope: scopeSchema.parse(input.scope),
121
+ eventId: input.eventId,
122
+ paginationOpts: { numItems: page.limit, cursor: page.cursor },
123
+ },
124
+ )) as {
125
+ page: Doc<"usageDeliveryHistory">[];
126
+ isDone: boolean;
127
+ continueCursor: string;
128
+ legacyHistoryMissing: boolean;
129
+ };
130
+ return {
131
+ records: result.page.map(
132
+ ({ sequence, attempt, phase, recordedAt, created }) => ({
133
+ sequence,
134
+ attempt,
135
+ phase,
136
+ recordedAt,
137
+ created: created ?? null,
138
+ }),
139
+ ),
140
+ isDone: result.isDone,
141
+ cursor: result.isDone ? null : result.continueCursor,
142
+ legacyHistoryMissing: result.legacyHistoryMissing,
143
+ };
144
+ }
145
+ async readValidationHistory(
146
+ ctx: RunCtx,
147
+ input: UsageDeliveryRef & { limit: number; cursor: string | null },
148
+ ) {
149
+ const page = validateUsagePageRequest({
150
+ period: { start: 0, end: 1 },
151
+ limit: input.limit,
152
+ cursor: input.cursor,
153
+ });
154
+ const result = (await ctx.runQuery(
155
+ componentRef(
156
+ this.component,
157
+ "usageObservations/queries/validationHistory",
158
+ ),
159
+ {
160
+ scope: scopeSchema.parse(input.scope),
161
+ eventId: input.eventId,
162
+ paginationOpts: { numItems: page.limit, cursor: page.cursor },
163
+ },
164
+ )) as {
165
+ page: Doc<"usageDeliveryErrors">[];
166
+ isDone: boolean;
167
+ continueCursor: string;
168
+ };
169
+ return {
170
+ records: result.page.map(({ providerEventId, code, observedAt }) => ({
171
+ providerEventId,
172
+ code,
173
+ observedAt,
174
+ })),
175
+ isDone: result.isDone,
176
+ cursor: result.isDone ? null : result.continueCursor,
177
+ };
178
+ }
179
+ async readInvoiceUsage(
180
+ _ctx: RunCtx,
181
+ input: UsageObservationOptions & { invoiceId?: string },
182
+ options: UsageDeliveryProviderOptions,
183
+ ) {
184
+ const opts = observationOptions(input);
185
+ if (!options.stripeSecretKey)
186
+ return {
187
+ status: "unavailable" as const,
188
+ reason: "provider_unavailable",
189
+ retryable: true,
190
+ };
191
+ const stripe = new Stripe(options.stripeSecretKey, {
192
+ apiVersion: opts.binding.apiVersion as StripeApiVersion,
193
+ maxNetworkRetries: 0,
194
+ timeout: 15000,
195
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
196
+ });
197
+ return observeUsageInvoice(stripe, opts, input.invoiceId);
198
+ }
199
+ async getReconciliation(ctx: RunCtx, input: UsageReconciliationOptions) {
200
+ const opts = observationOptions(input);
201
+ const [local, aggregate] = await Promise.all([
202
+ this.getSummary(ctx, {
203
+ scope: opts.scope,
204
+ period: opts.period,
205
+ maxRecords: input.maxRecords,
206
+ }),
207
+ this.getProviderUsage(ctx, input),
208
+ ]);
209
+ return {
210
+ local,
211
+ aggregate,
212
+ comparison: compareUsageObservations(local, aggregate, opts.binding),
213
+ invoice: {
214
+ status: "unavailable" as const,
215
+ reason: "invoice_not_observed",
216
+ retryable: true,
217
+ },
218
+ correctionHistory: {
219
+ status: "unsupported" as const,
220
+ reason: "corrections_not_configured",
221
+ retryable: false,
222
+ },
223
+ };
224
+ }
225
+ async reconcile(
226
+ ctx: RunCtx,
227
+ input: UsageReconciliationOptions,
228
+ options: UsageDeliveryProviderOptions,
229
+ ) {
230
+ await this.observeProviderUsage(ctx, input, options);
231
+ return this.getReconciliation(ctx, input);
232
+ }
233
+ }
@@ -0,0 +1,101 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import {
4
+ prepareUsageRecord,
5
+ type PreparedUsageRecord,
6
+ type UsageScope,
7
+ } from "./records.js";
8
+ import {
9
+ validateUsagePageRequest,
10
+ type UsageAvailability,
11
+ type UsagePeriod,
12
+ type UsageSubscriptionBinding,
13
+ } from "./boundaries.js";
14
+ import { subscriptionSnapshot } from "../../component/usage/helpers.js";
15
+ import { verifyRealm, verifyMeter } from "./catalogTypes.js";
16
+ export type UsageObservationOptions = {
17
+ scope: UsageScope;
18
+ binding: PreparedUsageRecord["binding"];
19
+ subscription: UsageSubscriptionBinding;
20
+ period: UsagePeriod;
21
+ limit?: number;
22
+ cursor?: string | null;
23
+ };
24
+ export type UsageAggregateValue = {
25
+ period: UsagePeriod;
26
+ quantity: string;
27
+ scaledQuantity: string;
28
+ complete: boolean;
29
+ nextCursor: string | null;
30
+ aggregationLagPossible: true;
31
+ stale: boolean;
32
+ entries: Array<{
33
+ id: string;
34
+ start: number;
35
+ end: number;
36
+ scaledQuantity: string;
37
+ }>;
38
+ };
39
+ export type UsageAggregateObservation = UsageAvailability<UsageAggregateValue>;
40
+ export function observationOptions(input: UsageObservationOptions) {
41
+ const page = validateUsagePageRequest({
42
+ period: input.period,
43
+ limit: input.limit ?? 100,
44
+ cursor: input.cursor ?? null,
45
+ });
46
+ const { scope, binding } = prepareUsageRecord({
47
+ scope: input.scope,
48
+ binding: input.binding,
49
+ sourceEventId: "observation",
50
+ quantity: "0",
51
+ occurredAt: page.period.start,
52
+ });
53
+ const subscription = subscriptionSnapshot(JSON.stringify(input.subscription));
54
+ if (subscription.stripePriceId !== binding.stripePriceId)
55
+ throw new Error("Usage observation price binding mismatch");
56
+ return {
57
+ scope,
58
+ binding,
59
+ subscription,
60
+ period: page.period,
61
+ limit: page.limit,
62
+ cursor: page.cursor,
63
+ };
64
+ }
65
+ export async function verifyObservationSource(
66
+ stripe: Stripe,
67
+ opts: ReturnType<typeof observationOptions>,
68
+ ): Promise<boolean> {
69
+ await verifyRealm(stripe, {
70
+ stripeAccountId: opts.scope.stripeAccountId,
71
+ livemode: opts.scope.livemode,
72
+ });
73
+ const [meter, subscription] = await Promise.all([
74
+ stripe.billing.meters.retrieve(opts.scope.meterId),
75
+ stripe.subscriptions.retrieve(opts.subscription.subscriptionId),
76
+ ]);
77
+ if (
78
+ meter.id !== opts.scope.meterId ||
79
+ subscription.id !== opts.subscription.subscriptionId ||
80
+ subscription.livemode !== opts.scope.livemode ||
81
+ subscription.customer_account !== opts.scope.customerAccount ||
82
+ (typeof subscription.customer === "string"
83
+ ? subscription.customer
84
+ : subscription.customer?.id) !== opts.binding.stripeCustomerId
85
+ )
86
+ return false;
87
+ verifyMeter(
88
+ meter,
89
+ {
90
+ scope: opts.scope,
91
+ plan: opts.binding.plan,
92
+ eventName: opts.binding.eventName,
93
+ displayName: meter.display_name,
94
+ },
95
+ false,
96
+ );
97
+ return true;
98
+ }
99
+ export const observationKeyOptions = z.strictObject({
100
+ maxAgeSeconds: z.number().int().min(1).max(86400).default(60),
101
+ });