@shware/purchase 7.2.0 → 7.5.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/dist/index.cjs +4 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/stripe/decline.cjs +48 -0
- package/dist/stripe/decline.cjs.map +1 -0
- package/dist/stripe/decline.d.cts +33 -0
- package/dist/stripe/decline.d.cts.map +1 -0
- package/dist/stripe/decline.d.mts +33 -0
- package/dist/stripe/decline.d.mts.map +1 -0
- package/dist/stripe/decline.mjs +46 -0
- package/dist/stripe/decline.mjs.map +1 -0
- package/dist/stripe/index.cjs +12 -0
- package/dist/stripe/index.d.cts +5 -2
- package/dist/stripe/index.d.mts +5 -2
- package/dist/stripe/index.mjs +5 -2
- package/dist/stripe/mapper.cjs +44 -2
- package/dist/stripe/mapper.cjs.map +1 -1
- package/dist/stripe/mapper.d.cts +14 -2
- package/dist/stripe/mapper.d.cts.map +1 -1
- package/dist/stripe/mapper.d.mts +14 -2
- package/dist/stripe/mapper.d.mts.map +1 -1
- package/dist/stripe/mapper.mjs +43 -4
- package/dist/stripe/mapper.mjs.map +1 -1
- package/dist/stripe/payment-method.cjs +34 -0
- package/dist/stripe/payment-method.cjs.map +1 -0
- package/dist/stripe/payment-method.d.cts +22 -0
- package/dist/stripe/payment-method.d.cts.map +1 -0
- package/dist/stripe/payment-method.d.mts +22 -0
- package/dist/stripe/payment-method.d.mts.map +1 -0
- package/dist/stripe/payment-method.mjs +32 -0
- package/dist/stripe/payment-method.mjs.map +1 -0
- package/dist/stripe/subscription.cjs +35 -0
- package/dist/stripe/subscription.cjs.map +1 -0
- package/dist/stripe/subscription.d.cts +33 -0
- package/dist/stripe/subscription.d.cts.map +1 -0
- package/dist/stripe/subscription.d.mts +33 -0
- package/dist/stripe/subscription.d.mts.map +1 -0
- package/dist/stripe/subscription.mjs +33 -0
- package/dist/stripe/subscription.mjs.map +1 -0
- package/dist/subscription/index.cjs +59 -0
- package/dist/subscription/index.cjs.map +1 -1
- package/dist/subscription/index.d.cts +26 -0
- package/dist/subscription/index.d.cts.map +1 -1
- package/dist/subscription/index.d.mts +26 -0
- package/dist/subscription/index.d.mts.map +1 -1
- package/dist/subscription/index.mjs +56 -1
- package/dist/subscription/index.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mapper.d.mts","names":[],"sources":["../../src/stripe/mapper.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"mapper.d.mts","names":[],"sources":["../../src/stripe/mapper.ts"],"mappings":";;;;wBAegB,QAAQ,yBACtB,wBAAwB,IACvB;YAKS;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,gBAAgB,OAAO,MAAM;EAC7B,UAAU,OAAO;EACjB;EACA;EACA,WAAW,OAAO,MAAM;;wBAGV,SAAS,OAAO,OAAO,QAAQ;iBAa9B;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;;wBAGO,YAAY,MAAM,OAAO,WAAW;YAoBxC,gBAAgB,OAAO,SAAS,QAAQ;iBAMnC;EACf;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;EACA,YAAY;;wBAGE,mBAAmB,SAAS,OAAO,SAAS,UAAU;wBA0BtD,WAAW,GAAG,OAAO;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,gBAAc,OAAA,QAAA;EACd;EACA;EACA;EACA,QAAM,OAAA,QAAA;EACN;EACA;EACA;;wBAIY,iBAAiB,QAAQ,OAAO;EAE5C;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,cAAA;EACN;;wBAIY,UAAU,QAAQ,OAAO;EAErC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAM,OAAA,OAAA;EACN;EACA;;;;;;;;;;;;YAOQ;EACV;EACA,MAAM,OAAO,MAAM;EACnB;EACA,UAAU,OAAO;EACjB;IACE,IAAI,OAAO;IACX,MAAM,OAAO;IACb,aAAa,OAAO;IACpB,UAAU,OAAO;;;wBAIL,sBAAsB,QAAQ,OAAO,aAAa,SAAS;;;;;;wBA8B3D,eACd,SAAS,KAAK,OAAO,oCACpB,QAAQ;;wBA8BK,gBAAgB,QAAQ,KAAK,OAAO,2BAA2B;;wBAO/D,iBAAiB,SAAS,KAAK,OAAO,4BAA4B;;wBAUlE,WAAW;wBAIX,MAAM,eAAe;YAIzB;EAAU;EAAgB;;;wBAGtB,MAAM,eAAe,mBAAmB;iBAIvC;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;;iBAGO;EACf;EACA;EACA;EACA,OAAO;;wBAqCO,sBAAsB,SAAS,kBAAkB;wBA2BjD,2BAA2B,GAAG,eAAe;;;;;;;wBAoB7C,sBACd,SACA,qBACC,KAAK;;;;;;;;wBAmBQ,uBACd,cAAc,KAAK,OAAO,wCACzB"}
|
package/dist/stripe/mapper.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CANCELLATION_FEEDBACKS } from "../subscription/index.mjs";
|
|
1
|
+
import { CANCELLATION_FEEDBACKS, DISPUTE_STATUSES, RESUBSCRIBE_INTENTS } from "../subscription/index.mjs";
|
|
2
2
|
import { ZERO_DECIMAL_CURRENCIES, stripeMinorUnits } from "@shware/utils";
|
|
3
3
|
//#region src/stripe/mapper.ts
|
|
4
4
|
function mapTime(stripeTimestampSeconds) {
|
|
@@ -130,6 +130,27 @@ function mapPaymentType(invoice) {
|
|
|
130
130
|
return "SUBSCRIPTION_UPDATE";
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
|
+
/** `refund.status` is an untyped string in stripe-node; these are the documented values. */
|
|
134
|
+
const REFUND_STATUS = {
|
|
135
|
+
pending: "PENDING",
|
|
136
|
+
requires_action: "PENDING",
|
|
137
|
+
succeeded: "SUCCEEDED",
|
|
138
|
+
failed: "FAILED",
|
|
139
|
+
canceled: "CANCELED"
|
|
140
|
+
};
|
|
141
|
+
/** A Stripe refund's status; a refund that has none yet is pending. Throws on an unknown one. */
|
|
142
|
+
function mapRefundStatus(refund) {
|
|
143
|
+
const status = REFUND_STATUS[refund.status ?? "pending"];
|
|
144
|
+
if (!status) throw new Error(`Unknown refund status ${refund.status}: ${refund.id}`);
|
|
145
|
+
return status;
|
|
146
|
+
}
|
|
147
|
+
/** A Stripe dispute's status, upper-cased into {@link DISPUTE_STATUSES}. Throws on an unknown one. */
|
|
148
|
+
function mapDisputeStatus(dispute) {
|
|
149
|
+
const status = dispute.status.toUpperCase();
|
|
150
|
+
const known = DISPUTE_STATUSES.find((item) => item === status);
|
|
151
|
+
if (!known) throw new Error(`Unknown dispute status ${dispute.status}: ${dispute.id}`);
|
|
152
|
+
return known;
|
|
153
|
+
}
|
|
133
154
|
/** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */
|
|
134
155
|
function minorUnits(currency) {
|
|
135
156
|
return stripeMinorUnits(currency);
|
|
@@ -206,10 +227,28 @@ function getBeginCheckoutProperties(p) {
|
|
|
206
227
|
};
|
|
207
228
|
}
|
|
208
229
|
/**
|
|
230
|
+
* The `cancellation_details.comment` to send Stripe for a cancel dialog's answers. Stripe stores
|
|
231
|
+
* reason, feedback and comment, one field short of `resubscribeIntent`, so the intent travels as a
|
|
232
|
+
* `[maybe]` / `[no]` / `[yes]` prefix on the comment, which {@link mapCancellationDetails} takes
|
|
233
|
+
* back out.
|
|
234
|
+
*/
|
|
235
|
+
function cancellationComment({ comment, resubscribeIntent }) {
|
|
236
|
+
return `${resubscribeIntent ? `[${resubscribeIntent}]` : ""}${comment ?? ""}`;
|
|
237
|
+
}
|
|
238
|
+
function parseCancellationComment(comment) {
|
|
239
|
+
const [, intent, rest] = comment && /^\[(\w+)\](.*)$/s.exec(comment) || [];
|
|
240
|
+
if (!intent || !RESUBSCRIBE_INTENTS.includes(intent)) return { comment };
|
|
241
|
+
return {
|
|
242
|
+
comment: rest || null,
|
|
243
|
+
resubscribeIntent: intent
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
209
247
|
* Stripe's `cancellation_details` in the shared shape. The object is present on every
|
|
210
248
|
* subscription with all three fields null, so an active one maps to null rather than an empty
|
|
211
249
|
* record. `reason` says who acted: `cancellation_requested` is the customer (or us on their
|
|
212
|
-
* behalf), the payment reasons are Stripe ending it.
|
|
250
|
+
* behalf), the payment reasons are Stripe ending it. A comment written by
|
|
251
|
+
* {@link cancellationComment} is split back into the comment and `resubscribeIntent`.
|
|
213
252
|
*/
|
|
214
253
|
function mapCancellationDetails(subscription) {
|
|
215
254
|
const details = subscription.cancellation_details;
|
|
@@ -218,10 +257,10 @@ function mapCancellationDetails(subscription) {
|
|
|
218
257
|
initiator: details.reason === "payment_failed" || details.reason === "payment_disputed" ? "system" : "user",
|
|
219
258
|
reason: details.reason ?? null,
|
|
220
259
|
feedback: details.feedback ? CANCELLATION_FEEDBACKS.includes(details.feedback) ? details.feedback : "other" : null,
|
|
221
|
-
|
|
260
|
+
...parseCancellationComment(details.comment ?? null)
|
|
222
261
|
};
|
|
223
262
|
}
|
|
224
263
|
//#endregion
|
|
225
|
-
export { ZERO_DECIMAL_CURRENCIES, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapInvoice, mapLineItem, mapPaymentIntent, mapPaymentType, mapPrice, mapSubscriptionStatus, mapTime, minorUnits, money, price };
|
|
264
|
+
export { ZERO_DECIMAL_CURRENCIES, cancellationComment, getBeginCheckoutProperties, getPurchaseProperties, mapCancellationDetails, mapCharge, mapCheckoutSession, mapDisputeStatus, mapInvoice, mapLineItem, mapPaymentIntent, mapPaymentType, mapPrice, mapRefundStatus, mapSubscriptionStatus, mapTime, minorUnits, money, price };
|
|
226
265
|
|
|
227
266
|
//# sourceMappingURL=mapper.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mapper.mjs","names":[],"sources":["../../src/stripe/mapper.ts"],"sourcesContent":["import { stripeMinorUnits } from '@shware/utils';\nimport type { Stripe } from 'stripe';\nimport {\n CANCELLATION_FEEDBACKS,\n type CancellationDetails,\n type CancellationFeedback,\n type PaymentType,\n type SubscriptionStatus,\n} from '../subscription/index';\n\nexport function mapTime<T extends number | null>(\n stripeTimestampSeconds: T\n): T extends number ? string : null {\n if (!stripeTimestampSeconds) return null as T extends number ? string : null;\n return new Date(stripeTimestampSeconds * 1000).toISOString() as T extends number ? string : null;\n}\n\nexport type Price = {\n id: string;\n type: Stripe.Price.Type;\n active: boolean;\n billing_scheme: Stripe.Price.BillingScheme;\n currency: Stripe.Price['currency'];\n unit_amount: number | null;\n unit_amount_decimal: string | null;\n recurring: Stripe.Price.Recurring | null;\n};\n\nexport function mapPrice(price: Stripe.Price): Price {\n return {\n id: price.id,\n type: price.type,\n active: price.active,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n unit_amount: price.unit_amount,\n unit_amount_decimal: price.unit_amount_decimal?.toString() ?? null,\n recurring: price.recurring,\n };\n}\n\nexport interface LineItem {\n id: string;\n currency: string;\n quantity: number | null;\n description: string | null;\n amount_tax: number;\n amount_total: number;\n amount_subtotal: number;\n amount_discount: number;\n price: Price | null;\n}\n\nexport function mapLineItem(item: Stripe.LineItem): LineItem {\n return {\n id: item.price\n ? typeof item.price.product === 'string'\n ? item.price.product\n : item.price.product.id\n : item.id,\n currency: item.currency,\n quantity: item.quantity,\n description: item.description,\n amount_tax: item.amount_tax,\n amount_total: item.amount_total,\n amount_subtotal: item.amount_subtotal,\n amount_discount: item.amount_discount,\n price: item.price ? mapPrice(item.price) : null,\n };\n}\n\n// Re-exported under our own name so consumers need not reach into stripe's namespace.\n// Open-ended since stripe 22.4: a status the API adds later is not a type error.\nexport type PaymentStatus = Stripe.Checkout.Session.PaymentStatus;\n\n// Declared rather than inferred from mapCheckoutSession: an inferred shape is\n// structural, so a consumer's declaration emit has to spell out payment_status\n// through stripe's internal module path — TS2883 in any package that reaches\n// stripe transitively instead of depending on it (see line_items/price too).\nexport interface CheckoutSession {\n id: string;\n url: string | null;\n coupon: string | undefined;\n livemode: boolean;\n expires_at: number;\n payment_status: PaymentStatus;\n currency: string | null;\n amount_total: number | null;\n line_items: LineItem[] | undefined;\n}\n\nexport function mapCheckoutSession(session: Stripe.Checkout.Session): CheckoutSession {\n let coupon: string | undefined = undefined;\n if (Array.isArray(session.discounts) && session.discounts.length !== 0) {\n const discount = session.discounts[0];\n if (discount.coupon && typeof discount.coupon === 'object') {\n coupon = discount.coupon.id;\n } else if (typeof discount.coupon === 'string') {\n coupon = discount.coupon;\n } else {\n coupon = undefined;\n }\n }\n\n return {\n id: session.id,\n url: session.url,\n coupon,\n livemode: session.livemode,\n expires_at: session.expires_at,\n payment_status: session.payment_status,\n currency: session.currency,\n amount_total: session.amount_total,\n line_items: session.line_items?.data.map(mapLineItem),\n };\n}\n\nexport function mapInvoice(i: Stripe.Invoice) {\n return {\n id: i.id,\n number: i.number,\n total: i.total,\n subtotal: i.subtotal,\n amount_due: i.amount_due,\n amount_paid: i.amount_paid,\n amount_remaining: i.amount_remaining,\n currency: i.currency,\n billing_reason: i.billing_reason,\n hosted_invoice_url: i.hosted_invoice_url,\n invoice_pdf: i.invoice_pdf,\n receipt_number: i.receipt_number,\n status: i.status,\n created: i.created,\n period_start: i.period_start,\n period_end: i.period_end,\n };\n}\n\nexport function mapPaymentIntent(intent: Stripe.PaymentIntent) {\n return {\n id: intent.id,\n amount: intent.amount,\n amount_capturable: intent.amount_capturable,\n amount_received: intent.amount_received,\n currency: intent.currency,\n client_secret: intent.client_secret,\n description: intent.description,\n status: intent.status,\n created: intent.created,\n };\n}\n\nexport function mapCharge(charge: Stripe.Charge) {\n return {\n id: charge.id,\n description: charge.description,\n currency: charge.currency,\n amount: charge.amount,\n amount_captured: charge.amount_captured,\n amount_refunded: charge.amount_refunded,\n receipt_email: charge.receipt_email,\n receipt_number: charge.receipt_number,\n receipt_url: charge.receipt_url,\n status: charge.status,\n created: charge.created,\n payment_intent:\n charge.payment_intent && typeof charge.payment_intent === 'object'\n ? mapPaymentIntent(charge.payment_intent)\n : undefined,\n };\n}\n\nexport type ProductPrice = {\n id: string;\n type: Stripe.Price.Type;\n unit_amount: number;\n currency: Stripe.Price['currency'];\n product: {\n id: Stripe.Product['id'];\n name: Stripe.Product['name'];\n description: Stripe.Product['description'];\n livemode: Stripe.Product['livemode'];\n };\n};\n\nexport function mapSubscriptionStatus(status: Stripe.Subscription.Status): SubscriptionStatus {\n switch (status) {\n case 'active':\n return 'ACTIVE';\n case 'canceled':\n return 'CANCELED';\n case 'incomplete':\n return 'INCOMPLETE';\n case 'incomplete_expired':\n return 'INCOMPLETE_EXPIRED';\n case 'past_due':\n return 'PAST_DUE';\n case 'paused':\n return 'PAUSED';\n case 'trialing':\n return 'TRIALING';\n case 'unpaid':\n return 'UNPAID';\n default: {\n console.error(`Invalid stripe status: ${String(status)}`);\n throw new Error(`Invalid stripe status: ${String(status)}`);\n }\n }\n}\n\n/**\n * What a paid subscription invoice was for, by its `billing_reason`. Only `subscription_cycle` is\n * a renewal: a plan change invoices its proration mid-period (`subscription_update`), and counting\n * that as a renewal would inflate the renewal rate by every upgrade.\n */\nexport function mapPaymentType(\n invoice: Pick<Stripe.Invoice, 'id' | 'billing_reason'>\n): Exclude<PaymentType, 'ONE_TIME'> {\n switch (invoice.billing_reason) {\n // Exactly once per subscription: its first invoice (after a trial, the first paid one is a cycle).\n case 'subscription_create':\n return 'SUBSCRIPTION_START';\n case 'subscription_cycle':\n return 'SUBSCRIPTION_RENEWAL';\n case 'subscription_update':\n return 'SUBSCRIPTION_UPDATE';\n // An invoice made by hand on the subscription (dashboard or API): off-cycle money, not a renewal.\n case 'manual':\n return 'SUBSCRIPTION_UPDATE';\n default:\n // subscription_threshold (metered billing) and the rest are not reasons flat-priced\n // subscriptions produce. Off-cycle is the safe reading: it leaves renewals alone.\n console.warn(`Invoice ${invoice.id} has billing_reason ${invoice.billing_reason}`);\n return 'SUBSCRIPTION_UPDATE';\n }\n}\n\nexport { ZERO_DECIMAL_CURRENCIES } from '@shware/utils';\n\n/** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */\nexport function minorUnits(currency: string) {\n return stripeMinorUnits(currency);\n}\n\nexport function price(value: number, currency: string) {\n return value / minorUnits(currency);\n}\n\nexport type Money = { amount: number; currency: string };\n\n/** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */\nexport function money(value: number, currency: string): Money {\n return { amount: price(value, currency), currency };\n}\n\nexport interface Item {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface PurchaseProperties {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n}\n\nexport interface BeginCheckoutProperties {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n}\n\n// Google Ads rejects conversion transaction IDs longer than 64 characters.\n// https://support.google.com/google-ads/answer/6386790\nconst GOOGLE_ADS_TRANSACTION_ID_MAX = 64;\n\n/**\n * GA4 purchase events feed Google Ads conversions, whose transaction IDs are\n * capped at 64 characters — but Stripe checkout session ids exceed that:\n * around 2021 they grew from ~32 chars (`cs_live_` + 24 random chars) to ~66\n * (`cs_live_a` + 57), with no announcement. Stripe treats id length/format as\n * opaque and backwards-compatible, guaranteeing only that ids never exceed\n * 255 chars, so they may grow again at any time.\n *\n * Dropping the fixed `cs_live_`/`cs_test_` prefix brings the id under 64\n * while staying reversible: prepend the prefix (livemode tells which) to\n * reconstruct the full session id for Stripe dashboard lookups. The payment\n * intent id (~27 chars) is not a substitute — it only exists on\n * `mode: 'payment'` sessions (subscription-mode sessions carry it on the\n * invoice instead), and its short length is just as unguaranteed as the\n * session id's was.\n *\n * Must stay deterministic: GA4/Google Ads dedupe purchases by\n * transaction_id, and the same session may be tracked from multiple paths.\n */\nfunction toTransactionId(sessionId: string): string {\n const stripped = sessionId.replace(/^cs_(live|test)_/, '');\n if (stripped.length > GOOGLE_ADS_TRANSACTION_ID_MAX) {\n console.warn(\n `transaction_id still exceeds ${GOOGLE_ADS_TRANSACTION_ID_MAX} chars after stripping ` +\n `the prefix — Stripe may have lengthened session ids again; truncating: ${sessionId}`\n );\n }\n return stripped.slice(0, GOOGLE_ADS_TRANSACTION_ID_MAX);\n}\n\nexport function getPurchaseProperties(session: CheckoutSession): PurchaseProperties {\n let value: number;\n let currency: string;\n if (!session.amount_total || !session.currency) {\n value = session.line_items?.reduce((acc, item) => acc + item.amount_total, 0) ?? 0;\n currency = session.line_items?.[0]?.currency ?? 'usd';\n } else {\n value = session.amount_total;\n currency = session.currency;\n }\n\n return {\n transaction_id: toTransactionId(session.id),\n value: price(value, currency),\n currency: currency.toUpperCase(),\n coupon: session.coupon,\n items: session.line_items?.map((item, index) => ({\n index,\n item_id: item.id,\n item_name: item.description ?? '',\n price: price(item.amount_total, item.currency),\n quantity: item.quantity ?? 1,\n discount: price(item.amount_discount, item.currency),\n })),\n };\n}\n\nexport function getBeginCheckoutProperties(p: ProductPrice): BeginCheckoutProperties {\n return {\n currency: p.currency.toUpperCase(),\n value: price(p.unit_amount, p.currency),\n items: [\n {\n item_id: p.product.id,\n item_name: p.product.name,\n price: price(p.unit_amount, p.currency),\n },\n ],\n };\n}\n\n/**\n * Stripe's `cancellation_details` in the shared shape. The object is present on every\n * subscription with all three fields null, so an active one maps to null rather than an empty\n * record. `reason` says who acted: `cancellation_requested` is the customer (or us on their\n * behalf), the payment reasons are Stripe ending it.\n */\nexport function mapCancellationDetails(\n subscription: Pick<Stripe.Subscription, 'cancellation_details'>\n): CancellationDetails | null {\n const details = subscription.cancellation_details;\n if (!details || (!details.reason && !details.feedback && !details.comment)) return null;\n return {\n initiator:\n details.reason === 'payment_failed' || details.reason === 'payment_disputed'\n ? 'system'\n : 'user',\n reason: details.reason ?? null,\n // Stripe's feedback vocabulary is ours; anything it adds later is reported as \"other\".\n feedback: details.feedback\n ? (CANCELLATION_FEEDBACKS as readonly string[]).includes(details.feedback)\n ? (details.feedback as CancellationFeedback)\n : 'other'\n : null,\n comment: details.comment ?? null,\n };\n}\n"],"mappings":";;;AAUA,SAAgB,QACd,wBACkC;CAClC,IAAI,CAAC,wBAAwB,OAAO;CACpC,wBAAO,IAAI,KAAK,yBAAyB,GAAI,EAAA,CAAE,YAAY;AAC7D;AAaA,SAAgB,SAAS,OAA4B;CACnD,OAAO;EACL,IAAI,MAAM;EACV,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,gBAAgB,MAAM;EACtB,UAAU,MAAM;EAChB,aAAa,MAAM;EACnB,qBAAqB,MAAM,qBAAqB,SAAS,KAAK;EAC9D,WAAW,MAAM;CACnB;AACF;AAcA,SAAgB,YAAY,MAAiC;CAC3D,OAAO;EACL,IAAI,KAAK,QACL,OAAO,KAAK,MAAM,YAAY,WAC5B,KAAK,MAAM,UACX,KAAK,MAAM,QAAQ,KACrB,KAAK;EACT,UAAU,KAAK;EACf,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,YAAY,KAAK;EACjB,cAAc,KAAK;EACnB,iBAAiB,KAAK;EACtB,iBAAiB,KAAK;EACtB,OAAO,KAAK,QAAQ,SAAS,KAAK,KAAK,IAAI;CAC7C;AACF;AAsBA,SAAgB,mBAAmB,SAAmD;CACpF,IAAI,SAA6B,KAAA;CACjC,IAAI,MAAM,QAAQ,QAAQ,SAAS,KAAK,QAAQ,UAAU,WAAW,GAAG;EACtE,MAAM,WAAW,QAAQ,UAAU;EACnC,IAAI,SAAS,UAAU,OAAO,SAAS,WAAW,UAChD,SAAS,SAA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O;EACL,QAAQ,QAAQ;EAChB,WAAW,QAAQ;CACrB;CAEA,OAAO;EACL,gBAAgB,gBAAgB,QAAQ,EAAE;EAC1C,OAAO,MAAM,OAAO,QAAQ;EAC5B,UAAU,SAAS,YAAY;EAC/B,QAAQ,QAAQ;EAChB,OAAO,QAAQ,YAAY,KAAK,MAAM,WAAW;GAC/C;GACA,SAAS,KAAK;GACd,WAAW,KAAK,eAAe;GAC/B,OAAO,MAAM,KAAK,cAAc,KAAK,QAAQ;GAC7C,UAAU,KAAK,YAAY;GAC3B,UAAU,MAAM,KAAK,iBAAiB,KAAK,QAAQ;EACrD,EAAE;CACJ;AACF;AAEA,SAAgB,2BAA2B,GAA0C;CACnF,OAAO;EACL,UAAU,EAAE,SAAS,YAAY;EACjC,OAAO,MAAM,EAAE,aAAa,EAAE,QAAQ;EACtC,OAAO,CACL;GACE,SAAS,EAAE,QAAQ;GACnB,WAAW,EAAE,QAAQ;GACrB,OAAO,MAAM,EAAE,aAAa,EAAE,QAAQ;EACxC,CACF;CACF;AACF;;;;;;;AAQA,SAAgB,uBACd,cAC4B;CAC5B,MAAM,UAAU,aAAa;CAC7B,IAAI,CAAC,WAAY,CAAC,QAAQ,UAAU,CAAC,QAAQ,YAAY,CAAC,QAAQ,SAAU,OAAO;CACnF,OAAO;EACL,WACE,QAAQ,WAAW,oBAAoB,QAAQ,WAAW,qBACtD,WACA;EACN,QAAQ,QAAQ,UAAU;EAE1B,UAAU,QAAQ,WACb,uBAA6C,SAAS,QAAQ,QAAQ,IACpE,QAAQ,WACT,UACF;EACJ,SAAS,QAAQ,WAAW;CAC9B;AACF"}
|
|
1
|
+
{"version":3,"file":"mapper.mjs","names":[],"sources":["../../src/stripe/mapper.ts"],"sourcesContent":["import { stripeMinorUnits } from '@shware/utils';\nimport type { Stripe } from 'stripe';\nimport {\n CANCELLATION_FEEDBACKS,\n type CancellationDetails,\n type CancellationFeedback,\n DISPUTE_STATUSES,\n type DisputeStatus,\n type PaymentType,\n RESUBSCRIBE_INTENTS,\n type RefundStatus,\n type ResubscribeIntent,\n type SubscriptionStatus,\n} from '../subscription/index';\n\nexport function mapTime<T extends number | null>(\n stripeTimestampSeconds: T\n): T extends number ? string : null {\n if (!stripeTimestampSeconds) return null as T extends number ? string : null;\n return new Date(stripeTimestampSeconds * 1000).toISOString() as T extends number ? string : null;\n}\n\nexport type Price = {\n id: string;\n type: Stripe.Price.Type;\n active: boolean;\n billing_scheme: Stripe.Price.BillingScheme;\n currency: Stripe.Price['currency'];\n unit_amount: number | null;\n unit_amount_decimal: string | null;\n recurring: Stripe.Price.Recurring | null;\n};\n\nexport function mapPrice(price: Stripe.Price): Price {\n return {\n id: price.id,\n type: price.type,\n active: price.active,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n unit_amount: price.unit_amount,\n unit_amount_decimal: price.unit_amount_decimal?.toString() ?? null,\n recurring: price.recurring,\n };\n}\n\nexport interface LineItem {\n id: string;\n currency: string;\n quantity: number | null;\n description: string | null;\n amount_tax: number;\n amount_total: number;\n amount_subtotal: number;\n amount_discount: number;\n price: Price | null;\n}\n\nexport function mapLineItem(item: Stripe.LineItem): LineItem {\n return {\n id: item.price\n ? typeof item.price.product === 'string'\n ? item.price.product\n : item.price.product.id\n : item.id,\n currency: item.currency,\n quantity: item.quantity,\n description: item.description,\n amount_tax: item.amount_tax,\n amount_total: item.amount_total,\n amount_subtotal: item.amount_subtotal,\n amount_discount: item.amount_discount,\n price: item.price ? mapPrice(item.price) : null,\n };\n}\n\n// Re-exported under our own name so consumers need not reach into stripe's namespace.\n// Open-ended since stripe 22.4: a status the API adds later is not a type error.\nexport type PaymentStatus = Stripe.Checkout.Session.PaymentStatus;\n\n// Declared rather than inferred from mapCheckoutSession: an inferred shape is\n// structural, so a consumer's declaration emit has to spell out payment_status\n// through stripe's internal module path — TS2883 in any package that reaches\n// stripe transitively instead of depending on it (see line_items/price too).\nexport interface CheckoutSession {\n id: string;\n url: string | null;\n coupon: string | undefined;\n livemode: boolean;\n expires_at: number;\n payment_status: PaymentStatus;\n currency: string | null;\n amount_total: number | null;\n line_items: LineItem[] | undefined;\n}\n\nexport function mapCheckoutSession(session: Stripe.Checkout.Session): CheckoutSession {\n let coupon: string | undefined = undefined;\n if (Array.isArray(session.discounts) && session.discounts.length !== 0) {\n const discount = session.discounts[0];\n if (discount.coupon && typeof discount.coupon === 'object') {\n coupon = discount.coupon.id;\n } else if (typeof discount.coupon === 'string') {\n coupon = discount.coupon;\n } else {\n coupon = undefined;\n }\n }\n\n return {\n id: session.id,\n url: session.url,\n coupon,\n livemode: session.livemode,\n expires_at: session.expires_at,\n payment_status: session.payment_status,\n currency: session.currency,\n amount_total: session.amount_total,\n line_items: session.line_items?.data.map(mapLineItem),\n };\n}\n\nexport function mapInvoice(i: Stripe.Invoice) {\n return {\n id: i.id,\n number: i.number,\n total: i.total,\n subtotal: i.subtotal,\n amount_due: i.amount_due,\n amount_paid: i.amount_paid,\n amount_remaining: i.amount_remaining,\n currency: i.currency,\n billing_reason: i.billing_reason,\n hosted_invoice_url: i.hosted_invoice_url,\n invoice_pdf: i.invoice_pdf,\n receipt_number: i.receipt_number,\n status: i.status,\n created: i.created,\n period_start: i.period_start,\n period_end: i.period_end,\n };\n}\n\nexport function mapPaymentIntent(intent: Stripe.PaymentIntent) {\n return {\n id: intent.id,\n amount: intent.amount,\n amount_capturable: intent.amount_capturable,\n amount_received: intent.amount_received,\n currency: intent.currency,\n client_secret: intent.client_secret,\n description: intent.description,\n status: intent.status,\n created: intent.created,\n };\n}\n\nexport function mapCharge(charge: Stripe.Charge) {\n return {\n id: charge.id,\n description: charge.description,\n currency: charge.currency,\n amount: charge.amount,\n amount_captured: charge.amount_captured,\n amount_refunded: charge.amount_refunded,\n receipt_email: charge.receipt_email,\n receipt_number: charge.receipt_number,\n receipt_url: charge.receipt_url,\n status: charge.status,\n created: charge.created,\n payment_intent:\n charge.payment_intent && typeof charge.payment_intent === 'object'\n ? mapPaymentIntent(charge.payment_intent)\n : undefined,\n };\n}\n\nexport type ProductPrice = {\n id: string;\n type: Stripe.Price.Type;\n unit_amount: number;\n currency: Stripe.Price['currency'];\n product: {\n id: Stripe.Product['id'];\n name: Stripe.Product['name'];\n description: Stripe.Product['description'];\n livemode: Stripe.Product['livemode'];\n };\n};\n\nexport function mapSubscriptionStatus(status: Stripe.Subscription.Status): SubscriptionStatus {\n switch (status) {\n case 'active':\n return 'ACTIVE';\n case 'canceled':\n return 'CANCELED';\n case 'incomplete':\n return 'INCOMPLETE';\n case 'incomplete_expired':\n return 'INCOMPLETE_EXPIRED';\n case 'past_due':\n return 'PAST_DUE';\n case 'paused':\n return 'PAUSED';\n case 'trialing':\n return 'TRIALING';\n case 'unpaid':\n return 'UNPAID';\n default: {\n console.error(`Invalid stripe status: ${String(status)}`);\n throw new Error(`Invalid stripe status: ${String(status)}`);\n }\n }\n}\n\n/**\n * What a paid subscription invoice was for, by its `billing_reason`. Only `subscription_cycle` is\n * a renewal: a plan change invoices its proration mid-period (`subscription_update`), and counting\n * that as a renewal would inflate the renewal rate by every upgrade.\n */\nexport function mapPaymentType(\n invoice: Pick<Stripe.Invoice, 'id' | 'billing_reason'>\n): Exclude<PaymentType, 'ONE_TIME'> {\n switch (invoice.billing_reason) {\n // Exactly once per subscription: its first invoice (after a trial, the first paid one is a cycle).\n case 'subscription_create':\n return 'SUBSCRIPTION_START';\n case 'subscription_cycle':\n return 'SUBSCRIPTION_RENEWAL';\n case 'subscription_update':\n return 'SUBSCRIPTION_UPDATE';\n // An invoice made by hand on the subscription (dashboard or API): off-cycle money, not a renewal.\n case 'manual':\n return 'SUBSCRIPTION_UPDATE';\n default:\n // subscription_threshold (metered billing) and the rest are not reasons flat-priced\n // subscriptions produce. Off-cycle is the safe reading: it leaves renewals alone.\n console.warn(`Invoice ${invoice.id} has billing_reason ${invoice.billing_reason}`);\n return 'SUBSCRIPTION_UPDATE';\n }\n}\n\n/** `refund.status` is an untyped string in stripe-node; these are the documented values. */\nconst REFUND_STATUS: Partial<Record<string, RefundStatus>> = {\n pending: 'PENDING',\n requires_action: 'PENDING',\n succeeded: 'SUCCEEDED',\n failed: 'FAILED',\n canceled: 'CANCELED',\n};\n\n/** A Stripe refund's status; a refund that has none yet is pending. Throws on an unknown one. */\nexport function mapRefundStatus(refund: Pick<Stripe.Refund, 'id' | 'status'>): RefundStatus {\n const status = REFUND_STATUS[refund.status ?? 'pending'];\n if (!status) throw new Error(`Unknown refund status ${refund.status}: ${refund.id}`);\n return status;\n}\n\n/** A Stripe dispute's status, upper-cased into {@link DISPUTE_STATUSES}. Throws on an unknown one. */\nexport function mapDisputeStatus(dispute: Pick<Stripe.Dispute, 'id' | 'status'>): DisputeStatus {\n const status = dispute.status.toUpperCase();\n const known = DISPUTE_STATUSES.find((item) => item === status);\n if (!known) throw new Error(`Unknown dispute status ${dispute.status}: ${dispute.id}`);\n return known;\n}\n\nexport { ZERO_DECIMAL_CURRENCIES } from '@shware/utils';\n\n/** How many Stripe API amount units make one unit of `currency` (1, 100 or 1000). */\nexport function minorUnits(currency: string) {\n return stripeMinorUnits(currency);\n}\n\nexport function price(value: number, currency: string) {\n return value / minorUnits(currency);\n}\n\nexport type Money = { amount: number; currency: string };\n\n/** A Stripe amount in minor units (cents, yen, fils) as an amount in `currency` itself. */\nexport function money(value: number, currency: string): Money {\n return { amount: price(value, currency), currency };\n}\n\nexport interface Item {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface PurchaseProperties {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n}\n\nexport interface BeginCheckoutProperties {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n}\n\n// Google Ads rejects conversion transaction IDs longer than 64 characters.\n// https://support.google.com/google-ads/answer/6386790\nconst GOOGLE_ADS_TRANSACTION_ID_MAX = 64;\n\n/**\n * GA4 purchase events feed Google Ads conversions, whose transaction IDs are\n * capped at 64 characters — but Stripe checkout session ids exceed that:\n * around 2021 they grew from ~32 chars (`cs_live_` + 24 random chars) to ~66\n * (`cs_live_a` + 57), with no announcement. Stripe treats id length/format as\n * opaque and backwards-compatible, guaranteeing only that ids never exceed\n * 255 chars, so they may grow again at any time.\n *\n * Dropping the fixed `cs_live_`/`cs_test_` prefix brings the id under 64\n * while staying reversible: prepend the prefix (livemode tells which) to\n * reconstruct the full session id for Stripe dashboard lookups. The payment\n * intent id (~27 chars) is not a substitute — it only exists on\n * `mode: 'payment'` sessions (subscription-mode sessions carry it on the\n * invoice instead), and its short length is just as unguaranteed as the\n * session id's was.\n *\n * Must stay deterministic: GA4/Google Ads dedupe purchases by\n * transaction_id, and the same session may be tracked from multiple paths.\n */\nfunction toTransactionId(sessionId: string): string {\n const stripped = sessionId.replace(/^cs_(live|test)_/, '');\n if (stripped.length > GOOGLE_ADS_TRANSACTION_ID_MAX) {\n console.warn(\n `transaction_id still exceeds ${GOOGLE_ADS_TRANSACTION_ID_MAX} chars after stripping ` +\n `the prefix — Stripe may have lengthened session ids again; truncating: ${sessionId}`\n );\n }\n return stripped.slice(0, GOOGLE_ADS_TRANSACTION_ID_MAX);\n}\n\nexport function getPurchaseProperties(session: CheckoutSession): PurchaseProperties {\n let value: number;\n let currency: string;\n if (!session.amount_total || !session.currency) {\n value = session.line_items?.reduce((acc, item) => acc + item.amount_total, 0) ?? 0;\n currency = session.line_items?.[0]?.currency ?? 'usd';\n } else {\n value = session.amount_total;\n currency = session.currency;\n }\n\n return {\n transaction_id: toTransactionId(session.id),\n value: price(value, currency),\n currency: currency.toUpperCase(),\n coupon: session.coupon,\n items: session.line_items?.map((item, index) => ({\n index,\n item_id: item.id,\n item_name: item.description ?? '',\n price: price(item.amount_total, item.currency),\n quantity: item.quantity ?? 1,\n discount: price(item.amount_discount, item.currency),\n })),\n };\n}\n\nexport function getBeginCheckoutProperties(p: ProductPrice): BeginCheckoutProperties {\n return {\n currency: p.currency.toUpperCase(),\n value: price(p.unit_amount, p.currency),\n items: [\n {\n item_id: p.product.id,\n item_name: p.product.name,\n price: price(p.unit_amount, p.currency),\n },\n ],\n };\n}\n\n/**\n * The `cancellation_details.comment` to send Stripe for a cancel dialog's answers. Stripe stores\n * reason, feedback and comment, one field short of `resubscribeIntent`, so the intent travels as a\n * `[maybe]` / `[no]` / `[yes]` prefix on the comment, which {@link mapCancellationDetails} takes\n * back out.\n */\nexport function cancellationComment({\n comment,\n resubscribeIntent,\n}: Pick<CancellationDetails, 'comment' | 'resubscribeIntent'>): string {\n return `${resubscribeIntent ? `[${resubscribeIntent}]` : ''}${comment ?? ''}`;\n}\n\nfunction parseCancellationComment(\n comment: string | null\n): Pick<CancellationDetails, 'comment' | 'resubscribeIntent'> {\n const [, intent, rest] = (comment && /^\\[(\\w+)\\](.*)$/s.exec(comment)) || [];\n if (!intent || !(RESUBSCRIBE_INTENTS as readonly string[]).includes(intent)) return { comment };\n return { comment: rest || null, resubscribeIntent: intent as ResubscribeIntent };\n}\n\n/**\n * Stripe's `cancellation_details` in the shared shape. The object is present on every\n * subscription with all three fields null, so an active one maps to null rather than an empty\n * record. `reason` says who acted: `cancellation_requested` is the customer (or us on their\n * behalf), the payment reasons are Stripe ending it. A comment written by\n * {@link cancellationComment} is split back into the comment and `resubscribeIntent`.\n */\nexport function mapCancellationDetails(\n subscription: Pick<Stripe.Subscription, 'cancellation_details'>\n): CancellationDetails | null {\n const details = subscription.cancellation_details;\n if (!details || (!details.reason && !details.feedback && !details.comment)) return null;\n return {\n initiator:\n details.reason === 'payment_failed' || details.reason === 'payment_disputed'\n ? 'system'\n : 'user',\n reason: details.reason ?? null,\n // Stripe's feedback vocabulary is ours; anything it adds later is reported as \"other\".\n feedback: details.feedback\n ? (CANCELLATION_FEEDBACKS as readonly string[]).includes(details.feedback)\n ? (details.feedback as CancellationFeedback)\n : 'other'\n : null,\n ...parseCancellationComment(details.comment ?? null),\n };\n}\n"],"mappings":";;;AAeA,SAAgB,QACd,wBACkC;CAClC,IAAI,CAAC,wBAAwB,OAAO;CACpC,wBAAO,IAAI,KAAK,yBAAyB,GAAI,EAAA,CAAE,YAAY;AAC7D;AAaA,SAAgB,SAAS,OAA4B;CACnD,OAAO;EACL,IAAI,MAAM;EACV,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,gBAAgB,MAAM;EACtB,UAAU,MAAM;EAChB,aAAa,MAAM;EACnB,qBAAqB,MAAM,qBAAqB,SAAS,KAAK;EAC9D,WAAW,MAAM;CACnB;AACF;AAcA,SAAgB,YAAY,MAAiC;CAC3D,OAAO;EACL,IAAI,KAAK,QACL,OAAO,KAAK,MAAM,YAAY,WAC5B,KAAK,MAAM,UACX,KAAK,MAAM,QAAQ,KACrB,KAAK;EACT,UAAU,KAAK;EACf,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,YAAY,KAAK;EACjB,cAAc,KAAK;EACnB,iBAAiB,KAAK;EACtB,iBAAiB,KAAK;EACtB,OAAO,KAAK,QAAQ,SAAS,KAAK,KAAK,IAAI;CAC7C;AACF;AAsBA,SAAgB,mBAAmB,SAAmD;CACpF,IAAI,SAA6B,KAAA;CACjC,IAAI,MAAM,QAAQ,QAAQ,SAAS,KAAK,QAAQ,UAAU,WAAW,GAAG;EACtE,MAAM,WAAW,QAAQ,UAAU;EACnC,IAAI,SAAS,UAAU,OAAO,SAAS,WAAW,UAChD,SAAS,SAAS,OAAO;OACpB,IAAI,OAAO,SAAS,WAAW,UACpC,SAAS,SAAS;OAElB,SAAS,KAAA;CAEb;CAEA,OAAO;EACL,IAAI,QAAQ;EACZ,KAAK,QAAQ;EACb;EACA,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,gBAAgB,QAAQ;EACxB,UAAU,QAAQ;EAClB,cAAc,QAAQ;EACtB,YA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;;;;;;AASA,SAAgB,uBACd,cAC4B;CAC5B,MAAM,UAAU,aAAa;CAC7B,IAAI,CAAC,WAAY,CAAC,QAAQ,UAAU,CAAC,QAAQ,YAAY,CAAC,QAAQ,SAAU,OAAO;CACnF,OAAO;EACL,WACE,QAAQ,WAAW,oBAAoB,QAAQ,WAAW,qBACtD,WACA;EACN,QAAQ,QAAQ,UAAU;EAE1B,UAAU,QAAQ,WACb,uBAA6C,SAAS,QAAQ,QAAQ,IACpE,QAAQ,WACT,UACF;EACJ,GAAG,yBAAyB,QAAQ,WAAW,IAAI;CACrD;AACF"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/stripe/payment-method.ts
|
|
3
|
+
/**
|
|
4
|
+
* Reusable payment methods whose outcome arrives days after the charge is attempted: Stripe's
|
|
5
|
+
* "payment methods with delayed notification" (https://docs.stripe.com/payments/payment-methods#payment-notification).
|
|
6
|
+
* A charge to one sits in `processing` until the bank answers, and can still fail then.
|
|
7
|
+
*
|
|
8
|
+
* Only types that can be saved and charged again (a subscription's or customer's default) are
|
|
9
|
+
* listed: the bank debits. One-off vouchers and transfers (Boleto, OXXO, Konbini, bank transfers)
|
|
10
|
+
* also notify late, but never come back as a saved payment method. A deny-list, so instant methods
|
|
11
|
+
* (cards, wallets, Link, PayPal, ...) need no entry; a delayed type Stripe adds later has to be
|
|
12
|
+
* added here.
|
|
13
|
+
*/
|
|
14
|
+
const DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES = /* @__PURE__ */ new Set([
|
|
15
|
+
"sepa_debit",
|
|
16
|
+
"us_bank_account",
|
|
17
|
+
"bacs_debit",
|
|
18
|
+
"au_becs_debit",
|
|
19
|
+
"acss_debit",
|
|
20
|
+
"nz_bank_account"
|
|
21
|
+
]);
|
|
22
|
+
/**
|
|
23
|
+
* Whether a charge to this payment method type is only known to have succeeded days later. Flows
|
|
24
|
+
* that need the money now (a Stripe pending update, which supports no such method and expires
|
|
25
|
+
* after ~23 hours) should refuse it up front rather than report a late failure.
|
|
26
|
+
*/
|
|
27
|
+
function hasDelayedNotification(type) {
|
|
28
|
+
return DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES.has(type);
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
exports.DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES = DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES;
|
|
32
|
+
exports.hasDelayedNotification = hasDelayedNotification;
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=payment-method.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-method.cjs","names":[],"sources":["../../src/stripe/payment-method.ts"],"sourcesContent":["import type { Stripe } from 'stripe';\n\n/**\n * Reusable payment methods whose outcome arrives days after the charge is attempted: Stripe's\n * \"payment methods with delayed notification\" (https://docs.stripe.com/payments/payment-methods#payment-notification).\n * A charge to one sits in `processing` until the bank answers, and can still fail then.\n *\n * Only types that can be saved and charged again (a subscription's or customer's default) are\n * listed: the bank debits. One-off vouchers and transfers (Boleto, OXXO, Konbini, bank transfers)\n * also notify late, but never come back as a saved payment method. A deny-list, so instant methods\n * (cards, wallets, Link, PayPal, ...) need no entry; a delayed type Stripe adds later has to be\n * added here.\n */\nexport const DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES: ReadonlySet<Stripe.PaymentMethod.Type> =\n new Set([\n 'sepa_debit',\n 'us_bank_account',\n 'bacs_debit',\n 'au_becs_debit',\n 'acss_debit',\n 'nz_bank_account',\n ]);\n\n/**\n * Whether a charge to this payment method type is only known to have succeeded days later. Flows\n * that need the money now (a Stripe pending update, which supports no such method and expires\n * after ~23 hours) should refuse it up front rather than report a late failure.\n */\nexport function hasDelayedNotification(type: Stripe.PaymentMethod.Type): boolean {\n return DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES.has(type);\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,4DACX,IAAI,IAAI;CACN;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOH,SAAgB,uBAAuB,MAA0C;CAC/E,OAAO,0CAA0C,IAAI,IAAI;AAC3D"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Stripe } from "stripe";
|
|
2
|
+
//#region src/stripe/payment-method.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Reusable payment methods whose outcome arrives days after the charge is attempted: Stripe's
|
|
5
|
+
* "payment methods with delayed notification" (https://docs.stripe.com/payments/payment-methods#payment-notification).
|
|
6
|
+
* A charge to one sits in `processing` until the bank answers, and can still fail then.
|
|
7
|
+
*
|
|
8
|
+
* Only types that can be saved and charged again (a subscription's or customer's default) are
|
|
9
|
+
* listed: the bank debits. One-off vouchers and transfers (Boleto, OXXO, Konbini, bank transfers)
|
|
10
|
+
* also notify late, but never come back as a saved payment method. A deny-list, so instant methods
|
|
11
|
+
* (cards, wallets, Link, PayPal, ...) need no entry; a delayed type Stripe adds later has to be
|
|
12
|
+
* added here.
|
|
13
|
+
*/
|
|
14
|
+
export declare const DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES: ReadonlySet<Stripe.PaymentMethod.Type>;
|
|
15
|
+
/**
|
|
16
|
+
* Whether a charge to this payment method type is only known to have succeeded days later. Flows
|
|
17
|
+
* that need the money now (a Stripe pending update, which supports no such method and expires
|
|
18
|
+
* after ~23 hours) should refuse it up front rather than report a late failure.
|
|
19
|
+
*/
|
|
20
|
+
export declare function hasDelayedNotification(type: Stripe.PaymentMethod.Type): boolean;
|
|
21
|
+
//#endregion
|
|
22
|
+
//# sourceMappingURL=payment-method.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-method.d.cts","names":[],"sources":["../../src/stripe/payment-method.ts"],"mappings":";;;;;;;;;;;;;qBAaa,2CAA2C,YAAY,OAAO,cAAc;;;;;;wBAezE,uBAAuB,MAAM,OAAO,cAAc"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Stripe } from "stripe";
|
|
2
|
+
//#region src/stripe/payment-method.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Reusable payment methods whose outcome arrives days after the charge is attempted: Stripe's
|
|
5
|
+
* "payment methods with delayed notification" (https://docs.stripe.com/payments/payment-methods#payment-notification).
|
|
6
|
+
* A charge to one sits in `processing` until the bank answers, and can still fail then.
|
|
7
|
+
*
|
|
8
|
+
* Only types that can be saved and charged again (a subscription's or customer's default) are
|
|
9
|
+
* listed: the bank debits. One-off vouchers and transfers (Boleto, OXXO, Konbini, bank transfers)
|
|
10
|
+
* also notify late, but never come back as a saved payment method. A deny-list, so instant methods
|
|
11
|
+
* (cards, wallets, Link, PayPal, ...) need no entry; a delayed type Stripe adds later has to be
|
|
12
|
+
* added here.
|
|
13
|
+
*/
|
|
14
|
+
export declare const DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES: ReadonlySet<Stripe.PaymentMethod.Type>;
|
|
15
|
+
/**
|
|
16
|
+
* Whether a charge to this payment method type is only known to have succeeded days later. Flows
|
|
17
|
+
* that need the money now (a Stripe pending update, which supports no such method and expires
|
|
18
|
+
* after ~23 hours) should refuse it up front rather than report a late failure.
|
|
19
|
+
*/
|
|
20
|
+
export declare function hasDelayedNotification(type: Stripe.PaymentMethod.Type): boolean;
|
|
21
|
+
//#endregion
|
|
22
|
+
//# sourceMappingURL=payment-method.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-method.d.mts","names":[],"sources":["../../src/stripe/payment-method.ts"],"mappings":";;;;;;;;;;;;;qBAaa,2CAA2C,YAAY,OAAO,cAAc;;;;;;wBAezE,uBAAuB,MAAM,OAAO,cAAc"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
//#region src/stripe/payment-method.ts
|
|
2
|
+
/**
|
|
3
|
+
* Reusable payment methods whose outcome arrives days after the charge is attempted: Stripe's
|
|
4
|
+
* "payment methods with delayed notification" (https://docs.stripe.com/payments/payment-methods#payment-notification).
|
|
5
|
+
* A charge to one sits in `processing` until the bank answers, and can still fail then.
|
|
6
|
+
*
|
|
7
|
+
* Only types that can be saved and charged again (a subscription's or customer's default) are
|
|
8
|
+
* listed: the bank debits. One-off vouchers and transfers (Boleto, OXXO, Konbini, bank transfers)
|
|
9
|
+
* also notify late, but never come back as a saved payment method. A deny-list, so instant methods
|
|
10
|
+
* (cards, wallets, Link, PayPal, ...) need no entry; a delayed type Stripe adds later has to be
|
|
11
|
+
* added here.
|
|
12
|
+
*/
|
|
13
|
+
const DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES = /* @__PURE__ */ new Set([
|
|
14
|
+
"sepa_debit",
|
|
15
|
+
"us_bank_account",
|
|
16
|
+
"bacs_debit",
|
|
17
|
+
"au_becs_debit",
|
|
18
|
+
"acss_debit",
|
|
19
|
+
"nz_bank_account"
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* Whether a charge to this payment method type is only known to have succeeded days later. Flows
|
|
23
|
+
* that need the money now (a Stripe pending update, which supports no such method and expires
|
|
24
|
+
* after ~23 hours) should refuse it up front rather than report a late failure.
|
|
25
|
+
*/
|
|
26
|
+
function hasDelayedNotification(type) {
|
|
27
|
+
return DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES.has(type);
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
export { DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES, hasDelayedNotification };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=payment-method.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"payment-method.mjs","names":[],"sources":["../../src/stripe/payment-method.ts"],"sourcesContent":["import type { Stripe } from 'stripe';\n\n/**\n * Reusable payment methods whose outcome arrives days after the charge is attempted: Stripe's\n * \"payment methods with delayed notification\" (https://docs.stripe.com/payments/payment-methods#payment-notification).\n * A charge to one sits in `processing` until the bank answers, and can still fail then.\n *\n * Only types that can be saved and charged again (a subscription's or customer's default) are\n * listed: the bank debits. One-off vouchers and transfers (Boleto, OXXO, Konbini, bank transfers)\n * also notify late, but never come back as a saved payment method. A deny-list, so instant methods\n * (cards, wallets, Link, PayPal, ...) need no entry; a delayed type Stripe adds later has to be\n * added here.\n */\nexport const DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES: ReadonlySet<Stripe.PaymentMethod.Type> =\n new Set([\n 'sepa_debit',\n 'us_bank_account',\n 'bacs_debit',\n 'au_becs_debit',\n 'acss_debit',\n 'nz_bank_account',\n ]);\n\n/**\n * Whether a charge to this payment method type is only known to have succeeded days later. Flows\n * that need the money now (a Stripe pending update, which supports no such method and expires\n * after ~23 hours) should refuse it up front rather than report a late failure.\n */\nexport function hasDelayedNotification(type: Stripe.PaymentMethod.Type): boolean {\n return DELAYED_NOTIFICATION_PAYMENT_METHOD_TYPES.has(type);\n}\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,4DACX,IAAI,IAAI;CACN;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOH,SAAgB,uBAAuB,MAA0C;CAC/E,OAAO,0CAA0C,IAAI,IAAI;AAC3D"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_stripe_mapper = require("./mapper.cjs");
|
|
3
|
+
//#region src/stripe/subscription.ts
|
|
4
|
+
/**
|
|
5
|
+
* The plan's list price, which is what "$X / month" promises. The latest invoice is deliberately
|
|
6
|
+
* not used: after an upgrade it is the prorated difference, and after a coupon the discounted
|
|
7
|
+
* amount, both of which belong in the invoice history rather than on the plan. Null for a tiered or
|
|
8
|
+
* custom-amount price, which has no flat unit amount.
|
|
9
|
+
*/
|
|
10
|
+
function mapListPrice({ items }) {
|
|
11
|
+
const item = items.data.at(0);
|
|
12
|
+
const price = item?.price;
|
|
13
|
+
if (!price || price.unit_amount === null) return null;
|
|
14
|
+
return require_stripe_mapper.money(price.unit_amount * (item.quantity ?? 1), price.currency);
|
|
15
|
+
}
|
|
16
|
+
function mapSubscription(sub) {
|
|
17
|
+
const periodEnd = sub.items.data.at(0)?.current_period_end ?? null;
|
|
18
|
+
return {
|
|
19
|
+
status: require_stripe_mapper.mapSubscriptionStatus(sub.status),
|
|
20
|
+
autoRenewEnabled: sub.status !== "canceled" && !sub.cancel_at_period_end && sub.cancel_at === null,
|
|
21
|
+
price: mapListPrice(sub),
|
|
22
|
+
startedAt: require_stripe_mapper.mapTime(sub.start_date),
|
|
23
|
+
createdAt: require_stripe_mapper.mapTime(sub.created),
|
|
24
|
+
renewalAt: sub.status === "paused" ? null : require_stripe_mapper.mapTime(periodEnd),
|
|
25
|
+
trialStart: require_stripe_mapper.mapTime(sub.trial_start),
|
|
26
|
+
trialEnd: require_stripe_mapper.mapTime(sub.trial_end),
|
|
27
|
+
canceledAt: require_stripe_mapper.mapTime(sub.canceled_at),
|
|
28
|
+
cancellationDetails: require_stripe_mapper.mapCancellationDetails(sub)
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
exports.mapListPrice = mapListPrice;
|
|
33
|
+
exports.mapSubscription = mapSubscription;
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=subscription.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subscription.cjs","names":["money","mapSubscriptionStatus","mapTime","mapCancellationDetails"],"sources":["../../src/stripe/subscription.ts"],"sourcesContent":["import type { Stripe } from 'stripe';\nimport type { CancellationDetails, SubscriptionStatus } from '../subscription/index';\nimport {\n type Money,\n mapCancellationDetails,\n mapSubscriptionStatus,\n mapTime,\n money,\n} from './mapper';\n\n/**\n * A Stripe subscription in the platform-neutral shape a subscription row stores. What it leaves out\n * is the app's: who the user is and which plan the product means (both from the subscription's\n * metadata and the app's config), the row id, and when the row was written.\n */\nexport interface StripeSubscriptionState {\n status: SubscriptionStatus;\n autoRenewEnabled: boolean;\n /** see {@link mapListPrice}; null for a price without a flat amount */\n price: Money | null;\n startedAt: string;\n createdAt: string;\n /** null while paused: a paused subscription has no date it comes back on */\n renewalAt: string | null;\n trialStart: string | null;\n trialEnd: string | null;\n canceledAt: string | null;\n cancellationDetails: CancellationDetails | null;\n}\n\n/**\n * The plan's list price, which is what \"$X / month\" promises. The latest invoice is deliberately\n * not used: after an upgrade it is the prorated difference, and after a coupon the discounted\n * amount, both of which belong in the invoice history rather than on the plan. Null for a tiered or\n * custom-amount price, which has no flat unit amount.\n */\nexport function mapListPrice({ items }: Pick<Stripe.Subscription, 'items'>): Money | null {\n const item = items.data.at(0);\n const price = item?.price;\n if (!price || price.unit_amount === null) return null;\n return money(price.unit_amount * (item.quantity ?? 1), price.currency);\n}\n\nexport function mapSubscription(sub: Stripe.Subscription): StripeSubscriptionState {\n const periodEnd = sub.items.data.at(0)?.current_period_end ?? null;\n return {\n status: mapSubscriptionStatus(sub.status),\n autoRenewEnabled:\n sub.status !== 'canceled' && !sub.cancel_at_period_end && sub.cancel_at === null,\n price: mapListPrice(sub),\n startedAt: mapTime(sub.start_date),\n createdAt: mapTime(sub.created),\n // A paused subscription (trial ended without a card, failed payment, or an explicit pause;\n // `status_details.paused` says which) stays paused until it is resumed, so the period end it\n // still reports is not a renewal.\n renewalAt: sub.status === 'paused' ? null : mapTime(periodEnd),\n trialStart: mapTime(sub.trial_start),\n trialEnd: mapTime(sub.trial_end),\n canceledAt: mapTime(sub.canceled_at),\n cancellationDetails: mapCancellationDetails(sub),\n };\n}\n"],"mappings":";;;;;;;;;AAoCA,SAAgB,aAAa,EAAE,SAA2D;CACxF,MAAM,OAAO,MAAM,KAAK,GAAG,CAAC;CAC5B,MAAM,QAAQ,MAAM;CACpB,IAAI,CAAC,SAAS,MAAM,gBAAgB,MAAM,OAAO;CACjD,OAAOA,sBAAAA,MAAM,MAAM,eAAe,KAAK,YAAY,IAAI,MAAM,QAAQ;AACvE;AAEA,SAAgB,gBAAgB,KAAmD;CACjF,MAAM,YAAY,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,EAAE,sBAAsB;CAC9D,OAAO;EACL,QAAQC,sBAAAA,sBAAsB,IAAI,MAAM;EACxC,kBACE,IAAI,WAAW,cAAc,CAAC,IAAI,wBAAwB,IAAI,cAAc;EAC9E,OAAO,aAAa,GAAG;EACvB,WAAWC,sBAAAA,QAAQ,IAAI,UAAU;EACjC,WAAWA,sBAAAA,QAAQ,IAAI,OAAO;EAI9B,WAAW,IAAI,WAAW,WAAW,OAAOA,sBAAAA,QAAQ,SAAS;EAC7D,YAAYA,sBAAAA,QAAQ,IAAI,WAAW;EACnC,UAAUA,sBAAAA,QAAQ,IAAI,SAAS;EAC/B,YAAYA,sBAAAA,QAAQ,IAAI,WAAW;EACnC,qBAAqBC,sBAAAA,uBAAuB,GAAG;CACjD;AACF"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { CancellationDetails, SubscriptionStatus } from "../subscription/index.cjs";
|
|
2
|
+
import { Money } from "./mapper.cjs";
|
|
3
|
+
import { Stripe } from "stripe";
|
|
4
|
+
//#region src/stripe/subscription.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* A Stripe subscription in the platform-neutral shape a subscription row stores. What it leaves out
|
|
7
|
+
* is the app's: who the user is and which plan the product means (both from the subscription's
|
|
8
|
+
* metadata and the app's config), the row id, and when the row was written.
|
|
9
|
+
*/
|
|
10
|
+
export interface StripeSubscriptionState {
|
|
11
|
+
status: SubscriptionStatus;
|
|
12
|
+
autoRenewEnabled: boolean;
|
|
13
|
+
/** see {@link mapListPrice}; null for a price without a flat amount */
|
|
14
|
+
price: Money | null;
|
|
15
|
+
startedAt: string;
|
|
16
|
+
createdAt: string;
|
|
17
|
+
/** null while paused: a paused subscription has no date it comes back on */
|
|
18
|
+
renewalAt: string | null;
|
|
19
|
+
trialStart: string | null;
|
|
20
|
+
trialEnd: string | null;
|
|
21
|
+
canceledAt: string | null;
|
|
22
|
+
cancellationDetails: CancellationDetails | null;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The plan's list price, which is what "$X / month" promises. The latest invoice is deliberately
|
|
26
|
+
* not used: after an upgrade it is the prorated difference, and after a coupon the discounted
|
|
27
|
+
* amount, both of which belong in the invoice history rather than on the plan. Null for a tiered or
|
|
28
|
+
* custom-amount price, which has no flat unit amount.
|
|
29
|
+
*/
|
|
30
|
+
export declare function mapListPrice({ items }: Pick<Stripe.Subscription, 'items'>): Money | null;
|
|
31
|
+
export declare function mapSubscription(sub: Stripe.Subscription): StripeSubscriptionState;
|
|
32
|
+
//#endregion
|
|
33
|
+
//# sourceMappingURL=subscription.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subscription.d.cts","names":[],"sources":["../../src/stripe/subscription.ts"],"mappings":";;;;;;;;;iBAeiB;EACf,QAAQ;EACR;;EAEA,OAAO;EACP;EACA;;EAEA;EACA;EACA;EACA;EACA,qBAAqB;;;;;;;;wBASP,eAAe,SAAS,KAAK,OAAO,yBAAyB;wBAO7D,gBAAgB,KAAK,OAAO,eAAe"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { CancellationDetails, SubscriptionStatus } from "../subscription/index.mjs";
|
|
2
|
+
import { Money } from "./mapper.mjs";
|
|
3
|
+
import { Stripe } from "stripe";
|
|
4
|
+
//#region src/stripe/subscription.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* A Stripe subscription in the platform-neutral shape a subscription row stores. What it leaves out
|
|
7
|
+
* is the app's: who the user is and which plan the product means (both from the subscription's
|
|
8
|
+
* metadata and the app's config), the row id, and when the row was written.
|
|
9
|
+
*/
|
|
10
|
+
export interface StripeSubscriptionState {
|
|
11
|
+
status: SubscriptionStatus;
|
|
12
|
+
autoRenewEnabled: boolean;
|
|
13
|
+
/** see {@link mapListPrice}; null for a price without a flat amount */
|
|
14
|
+
price: Money | null;
|
|
15
|
+
startedAt: string;
|
|
16
|
+
createdAt: string;
|
|
17
|
+
/** null while paused: a paused subscription has no date it comes back on */
|
|
18
|
+
renewalAt: string | null;
|
|
19
|
+
trialStart: string | null;
|
|
20
|
+
trialEnd: string | null;
|
|
21
|
+
canceledAt: string | null;
|
|
22
|
+
cancellationDetails: CancellationDetails | null;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The plan's list price, which is what "$X / month" promises. The latest invoice is deliberately
|
|
26
|
+
* not used: after an upgrade it is the prorated difference, and after a coupon the discounted
|
|
27
|
+
* amount, both of which belong in the invoice history rather than on the plan. Null for a tiered or
|
|
28
|
+
* custom-amount price, which has no flat unit amount.
|
|
29
|
+
*/
|
|
30
|
+
export declare function mapListPrice({ items }: Pick<Stripe.Subscription, 'items'>): Money | null;
|
|
31
|
+
export declare function mapSubscription(sub: Stripe.Subscription): StripeSubscriptionState;
|
|
32
|
+
//#endregion
|
|
33
|
+
//# sourceMappingURL=subscription.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subscription.d.mts","names":[],"sources":["../../src/stripe/subscription.ts"],"mappings":";;;;;;;;;iBAeiB;EACf,QAAQ;EACR;;EAEA,OAAO;EACP;EACA;;EAEA;EACA;EACA;EACA;EACA,qBAAqB;;;;;;;;wBASP,eAAe,SAAS,KAAK,OAAO,yBAAyB;wBAO7D,gBAAgB,KAAK,OAAO,eAAe"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { mapCancellationDetails, mapSubscriptionStatus, mapTime, money } from "./mapper.mjs";
|
|
2
|
+
//#region src/stripe/subscription.ts
|
|
3
|
+
/**
|
|
4
|
+
* The plan's list price, which is what "$X / month" promises. The latest invoice is deliberately
|
|
5
|
+
* not used: after an upgrade it is the prorated difference, and after a coupon the discounted
|
|
6
|
+
* amount, both of which belong in the invoice history rather than on the plan. Null for a tiered or
|
|
7
|
+
* custom-amount price, which has no flat unit amount.
|
|
8
|
+
*/
|
|
9
|
+
function mapListPrice({ items }) {
|
|
10
|
+
const item = items.data.at(0);
|
|
11
|
+
const price = item?.price;
|
|
12
|
+
if (!price || price.unit_amount === null) return null;
|
|
13
|
+
return money(price.unit_amount * (item.quantity ?? 1), price.currency);
|
|
14
|
+
}
|
|
15
|
+
function mapSubscription(sub) {
|
|
16
|
+
const periodEnd = sub.items.data.at(0)?.current_period_end ?? null;
|
|
17
|
+
return {
|
|
18
|
+
status: mapSubscriptionStatus(sub.status),
|
|
19
|
+
autoRenewEnabled: sub.status !== "canceled" && !sub.cancel_at_period_end && sub.cancel_at === null,
|
|
20
|
+
price: mapListPrice(sub),
|
|
21
|
+
startedAt: mapTime(sub.start_date),
|
|
22
|
+
createdAt: mapTime(sub.created),
|
|
23
|
+
renewalAt: sub.status === "paused" ? null : mapTime(periodEnd),
|
|
24
|
+
trialStart: mapTime(sub.trial_start),
|
|
25
|
+
trialEnd: mapTime(sub.trial_end),
|
|
26
|
+
canceledAt: mapTime(sub.canceled_at),
|
|
27
|
+
cancellationDetails: mapCancellationDetails(sub)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { mapListPrice, mapSubscription };
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=subscription.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subscription.mjs","names":[],"sources":["../../src/stripe/subscription.ts"],"sourcesContent":["import type { Stripe } from 'stripe';\nimport type { CancellationDetails, SubscriptionStatus } from '../subscription/index';\nimport {\n type Money,\n mapCancellationDetails,\n mapSubscriptionStatus,\n mapTime,\n money,\n} from './mapper';\n\n/**\n * A Stripe subscription in the platform-neutral shape a subscription row stores. What it leaves out\n * is the app's: who the user is and which plan the product means (both from the subscription's\n * metadata and the app's config), the row id, and when the row was written.\n */\nexport interface StripeSubscriptionState {\n status: SubscriptionStatus;\n autoRenewEnabled: boolean;\n /** see {@link mapListPrice}; null for a price without a flat amount */\n price: Money | null;\n startedAt: string;\n createdAt: string;\n /** null while paused: a paused subscription has no date it comes back on */\n renewalAt: string | null;\n trialStart: string | null;\n trialEnd: string | null;\n canceledAt: string | null;\n cancellationDetails: CancellationDetails | null;\n}\n\n/**\n * The plan's list price, which is what \"$X / month\" promises. The latest invoice is deliberately\n * not used: after an upgrade it is the prorated difference, and after a coupon the discounted\n * amount, both of which belong in the invoice history rather than on the plan. Null for a tiered or\n * custom-amount price, which has no flat unit amount.\n */\nexport function mapListPrice({ items }: Pick<Stripe.Subscription, 'items'>): Money | null {\n const item = items.data.at(0);\n const price = item?.price;\n if (!price || price.unit_amount === null) return null;\n return money(price.unit_amount * (item.quantity ?? 1), price.currency);\n}\n\nexport function mapSubscription(sub: Stripe.Subscription): StripeSubscriptionState {\n const periodEnd = sub.items.data.at(0)?.current_period_end ?? null;\n return {\n status: mapSubscriptionStatus(sub.status),\n autoRenewEnabled:\n sub.status !== 'canceled' && !sub.cancel_at_period_end && sub.cancel_at === null,\n price: mapListPrice(sub),\n startedAt: mapTime(sub.start_date),\n createdAt: mapTime(sub.created),\n // A paused subscription (trial ended without a card, failed payment, or an explicit pause;\n // `status_details.paused` says which) stays paused until it is resumed, so the period end it\n // still reports is not a renewal.\n renewalAt: sub.status === 'paused' ? null : mapTime(periodEnd),\n trialStart: mapTime(sub.trial_start),\n trialEnd: mapTime(sub.trial_end),\n canceledAt: mapTime(sub.canceled_at),\n cancellationDetails: mapCancellationDetails(sub),\n };\n}\n"],"mappings":";;;;;;;;AAoCA,SAAgB,aAAa,EAAE,SAA2D;CACxF,MAAM,OAAO,MAAM,KAAK,GAAG,CAAC;CAC5B,MAAM,QAAQ,MAAM;CACpB,IAAI,CAAC,SAAS,MAAM,gBAAgB,MAAM,OAAO;CACjD,OAAO,MAAM,MAAM,eAAe,KAAK,YAAY,IAAI,MAAM,QAAQ;AACvE;AAEA,SAAgB,gBAAgB,KAAmD;CACjF,MAAM,YAAY,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,EAAE,sBAAsB;CAC9D,OAAO;EACL,QAAQ,sBAAsB,IAAI,MAAM;EACxC,kBACE,IAAI,WAAW,cAAc,CAAC,IAAI,wBAAwB,IAAI,cAAc;EAC9E,OAAO,aAAa,GAAG;EACvB,WAAW,QAAQ,IAAI,UAAU;EACjC,WAAW,QAAQ,IAAI,OAAO;EAI9B,WAAW,IAAI,WAAW,WAAW,OAAO,QAAQ,SAAS;EAC7D,YAAY,QAAQ,IAAI,WAAW;EACnC,UAAU,QAAQ,IAAI,SAAS;EAC/B,YAAY,QAAQ,IAAI,WAAW;EACnC,qBAAqB,uBAAuB,GAAG;CACjD;AACF"}
|
|
@@ -21,6 +21,61 @@ const PAYMENT_TYPES = [
|
|
|
21
21
|
"SUBSCRIPTION_UPDATE"
|
|
22
22
|
];
|
|
23
23
|
/**
|
|
24
|
+
* Where a refund stands, on every platform. Stripe reports all of them; Apple and Google report a
|
|
25
|
+
* refund once it is done (SUCCEEDED), and Apple can take it back (REVERSED, `REFUND_REVERSED`).
|
|
26
|
+
*/
|
|
27
|
+
const REFUND_STATUSES = [
|
|
28
|
+
"PENDING",
|
|
29
|
+
"SUCCEEDED",
|
|
30
|
+
"FAILED",
|
|
31
|
+
"CANCELED",
|
|
32
|
+
"REVERSED"
|
|
33
|
+
];
|
|
34
|
+
/**
|
|
35
|
+
* Where a refund may move from the status it has. Notifications arrive out of order and are
|
|
36
|
+
* redelivered, so a status only ever moves forward along these edges:
|
|
37
|
+
* - PENDING settles into anything (Stripe: succeeded / failed / canceled).
|
|
38
|
+
* - SUCCEEDED can still become FAILED (Stripe: the money could not be returned after all) or
|
|
39
|
+
* REVERSED (Apple: REFUND_REVERSED).
|
|
40
|
+
* - FAILED, CANCELED and REVERSED are final: nothing a platform sends afterwards reopens them.
|
|
41
|
+
* Nothing moves back to PENDING, and a status never "moves" to itself (a redelivery is a no-op).
|
|
42
|
+
*/
|
|
43
|
+
const REFUND_STATUS_TRANSITIONS = {
|
|
44
|
+
PENDING: [
|
|
45
|
+
"SUCCEEDED",
|
|
46
|
+
"FAILED",
|
|
47
|
+
"CANCELED",
|
|
48
|
+
"REVERSED"
|
|
49
|
+
],
|
|
50
|
+
SUCCEEDED: ["FAILED", "REVERSED"],
|
|
51
|
+
FAILED: [],
|
|
52
|
+
CANCELED: [],
|
|
53
|
+
REVERSED: []
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Stripe's dispute statuses, as they are: the `warning_*` ones are inquiries and early fraud
|
|
57
|
+
* warnings that may never become a chargeback, `prevented` is one Stripe blocked before it was
|
|
58
|
+
* filed. Only LOST costs money. Stripe only: Apple and Google absorb chargebacks themselves and
|
|
59
|
+
* report them as refunds.
|
|
60
|
+
*/
|
|
61
|
+
const DISPUTE_STATUSES = [
|
|
62
|
+
"WARNING_NEEDS_RESPONSE",
|
|
63
|
+
"WARNING_UNDER_REVIEW",
|
|
64
|
+
"WARNING_CLOSED",
|
|
65
|
+
"NEEDS_RESPONSE",
|
|
66
|
+
"UNDER_REVIEW",
|
|
67
|
+
"PREVENTED",
|
|
68
|
+
"WON",
|
|
69
|
+
"LOST"
|
|
70
|
+
];
|
|
71
|
+
/** A dispute in one of these is over; nothing Stripe sends afterwards reopens it. */
|
|
72
|
+
const CLOSED_DISPUTE_STATUSES = [
|
|
73
|
+
"WON",
|
|
74
|
+
"LOST",
|
|
75
|
+
"WARNING_CLOSED",
|
|
76
|
+
"PREVENTED"
|
|
77
|
+
];
|
|
78
|
+
/**
|
|
24
79
|
* [Stripe Subscription Status](https://stripe.com/docs/api/subscriptions/object#subscription_object-status)
|
|
25
80
|
* [Stripe Subscription Lifecycle](https://docs.stripe.com/billing/subscriptions/overview)
|
|
26
81
|
*
|
|
@@ -74,8 +129,12 @@ const RESUBSCRIBE_INTENTS = [
|
|
|
74
129
|
exports.AVAILABLE_STATUSES = AVAILABLE_STATUSES;
|
|
75
130
|
exports.CANCELLATION_FEEDBACKS = CANCELLATION_FEEDBACKS;
|
|
76
131
|
exports.CANCELLATION_INITIATORS = CANCELLATION_INITIATORS;
|
|
132
|
+
exports.CLOSED_DISPUTE_STATUSES = CLOSED_DISPUTE_STATUSES;
|
|
133
|
+
exports.DISPUTE_STATUSES = DISPUTE_STATUSES;
|
|
77
134
|
exports.PAYMENT_TYPES = PAYMENT_TYPES;
|
|
78
135
|
exports.PLATFORMS = PLATFORMS;
|
|
136
|
+
exports.REFUND_STATUSES = REFUND_STATUSES;
|
|
137
|
+
exports.REFUND_STATUS_TRANSITIONS = REFUND_STATUS_TRANSITIONS;
|
|
79
138
|
exports.RESUBSCRIBE_INTENTS = RESUBSCRIBE_INTENTS;
|
|
80
139
|
exports.SUBSCRIPTION_STATUSES = SUBSCRIPTION_STATUSES;
|
|
81
140
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/subscription/index.ts"],"sourcesContent":["export const PLATFORMS = ['APPLE', 'GOOGLE', 'STRIPE'] as const;\n\nexport type Platform = (typeof PLATFORMS)[number];\n\n/**\n * What a payment was for, on every platform.\n *\n * - ONE_TIME: a one-time purchase.\n * - SUBSCRIPTION_START: the first paid charge of a subscription.\n * - SUBSCRIPTION_RENEWAL: a charge for a new billing period on the regular cycle.\n * - SUBSCRIPTION_UPDATE: a charge mid-period, outside the cycle: the proration of a plan change, or\n * a manual invoice on the subscription. Kept apart from renewals so renewal rates stay honest.\n */\nexport const PAYMENT_TYPES = [\n 'ONE_TIME',\n 'SUBSCRIPTION_START',\n 'SUBSCRIPTION_RENEWAL',\n 'SUBSCRIPTION_UPDATE',\n] as const;\n\nexport type PaymentType = (typeof PAYMENT_TYPES)[number];\n\n/**\n * [Stripe Subscription Status](https://stripe.com/docs/api/subscriptions/object#subscription_object-status)\n * [Stripe Subscription Lifecycle](https://docs.stripe.com/billing/subscriptions/overview)\n *\n * provision product for customer when Status = TRIALING, ACTIVE, IN_GRACE_PERIOD\n */\nexport const SUBSCRIPTION_STATUSES = [\n /**\n * The subscription is currently in a trial period and it’s safe to provision your product for\n * your customer. The subscription transitions automatically to active when the first payment\n * is made.\n *\n * Google: play(LineItems[0].OfferDetails.OfferId == 'xx')\n *\n * Platform: Apple, Google, Stripe\n * */\n 'TRIALING',\n\n /**\n * The subscription is in good standing and the most recent payment is successful. It’s safe to\n * provision your product for your customer.\n *\n * Platform: Apple, Google, Stripe\n * */\n 'ACTIVE',\n\n /**\n * Apple: The subscription enters the billing retry period. If the subtype is GRACE_PERIOD,\n * continue to provide service through the grace period. If the subtype is empty, the\n * subscription isn’t in a grace period and you can stop providing the subscription service.\n *\n * Google: Subscription is in grace period. The state is only available when the subscription\n * is an auto renewing plan. In this state, all items are in grace period.\n *\n * Platform: Apple, Google\n * */\n 'IN_GRACE_PERIOD',\n\n /**\n * A successful payment needs to be made within 23 hours to activate the subscription. Or the\n * payment requires action, like customer authentication. Subscriptions can also be incomplete\n * if there’s a pending payment and the PaymentIntent status would be processing.\n *\n * Platform: Stripe\n * */\n 'INCOMPLETE',\n\n /**\n * The initial payment on the subscription failed and no successful payment was made within 23\n * hours of creating the subscription. These subscriptions don’t bill customers. This status\n * exists so you can track customers that failed to activate their subscriptions.\n *\n * Platform: Stripe\n * */\n 'INCOMPLETE_EXPIRED',\n\n /**\n * Subscription was created but awaiting payment during signup. In this state, all items are\n * awaiting payment.\n *\n * Platform: Google\n * */\n 'PENDING',\n\n /**\n * Pending transaction for subscription is canceled. If this pending purchase was for an\n * existing subscription, use linkedPurchaseToken to get the current state of that subscription.\n *\n * Platform: Google\n * */\n 'PENDING_PURCHASE_CANCELED',\n\n /**\n * Payment on the latest finalized invoice either failed or wasn’t attempted. The subscription\n * continues to create invoices. Your subscription settings determine the subscription’s next\n * state. If the invoice is still unpaid after all Smart Retries have been attempted, you can\n * configure the subscription to move to canceled, unpaid, or leave it as past_due. To move the\n * subscription to active, pay the most recent invoice before its due date.\n *\n * Platform: Stripe\n * */\n 'PAST_DUE',\n\n /**\n * Subscription is on hold (suspended). The state is only available when the subscription is an\n * auto renewing plan. In this state, all items are on hold. Grace period ends or Active period\n * ends but not grace period\n *\n * Platform: Google\n * */\n 'ON_HOLD',\n\n /**\n * The subscription has been canceled. During cancellation, automatic collection for all unpaid\n * invoices is disabled (auto_advance=false). This is a terminal state that can’t be updated.\n *\n * Platform: Apple, Google, Stripe\n * */\n 'CANCELED',\n\n /**\n * The latest invoice hasn’t been paid but the subscription remains in place. The latest invoice\n * remains open and invoices continue to be generated but payments aren’t attempted. You should\n * revoke access to your product when the subscription is unpaid since payments were already\n * attempted and retried when it was past_due. To move the subscription to active, pay the most\n * recent invoice before its due date.\n *\n * Platform: Stripe\n * */\n 'UNPAID',\n\n /**\n * Google: Subscription is paused. The state is only available when the subscription is an auto\n * renewing plan. In this state, all items are in paused state.\n *\n * Stripe: The subscription has ended its trial period without a default payment method and the\n * trial_settings.end_behavior.missing_payment_method is set to pause. Invoices will no longer\n * be created for the subscription. After a default payment method has been attached to the\n * customer, you can resume the subscription.\n *\n * Platform: Google, Stripe\n * */\n 'PAUSED',\n\n /**\n * For example, a user buys a subscription and receives a purchase token A. The\n * linkedPurchaseToken field will not be set in the API response because the purchase token\n * belongs to a brand new subscription.\n *\n * If the user upgrades their subscription, a new purchase token B will be generated. Since the\n * upgrade is replacing the subscription from purchase token A, the linkedPurchaseToken field\n * for token B will be set to point to token A. Notice it points backwards in time to the\n * original purchase token.\n *\n * +---------------------------+ +------------------------+ +------------------------+\n * | Step 1 first purchase | | Step 2 upgrades | | Step 3 downgrades |\n * | purchaseToken: A |->| purchaseToken: B |->| purchaseToken: C |\n * | linkedPurchaseToken: null | | linkedPurchaseToken: A | | linkedPurchaseToken: B |\n * +---------------------------+ +------------------------+ +------------------------+\n *\n * Platform: Google\n * */\n 'REPLACED',\n\n /**\n * Google: Subscription is expired. All items have expiryTime in the past.\n *\n * Platform: Apple, Google\n * */\n 'EXPIRED',\n] as const;\n\nexport type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];\n\n/** statuses where it is safe to provision your product for the customer */\nexport const AVAILABLE_STATUSES = [\n 'ACTIVE',\n 'TRIALING',\n 'IN_GRACE_PERIOD',\n] as const satisfies readonly SubscriptionStatus[];\n\n/** Who stopped the subscription from renewing. */\nexport const CANCELLATION_INITIATORS = [\n /** The customer: the store's cancel flow, our own cancel dialog, or a declined price increase. */\n 'user',\n /** The platform: a failed payment, a refund or revocation, a product no longer for sale. */\n 'system',\n /** Us: a cancellation through the platform's API or console. */\n 'developer',\n] as const;\n\nexport type CancellationInitiator = (typeof CANCELLATION_INITIATORS)[number];\n\n/** What a cancel survey may report, whichever platform asked the question. */\nexport const CANCELLATION_FEEDBACKS = [\n 'customer_service',\n 'low_quality',\n 'missing_features',\n 'switched_service',\n 'too_complex',\n 'too_expensive',\n 'unused',\n 'other',\n] as const;\n\nexport type CancellationFeedback = (typeof CANCELLATION_FEEDBACKS)[number];\n\nexport const RESUBSCRIBE_INTENTS = ['maybe', 'no', 'yes'] as const;\n\nexport type ResubscribeIntent = (typeof RESUBSCRIBE_INTENTS)[number];\n\n/**\n * Why a subscription stopped renewing, in one record shared by every platform. Every key is\n * optional and every value a string, so a platform may add what only it reports without a\n * schema change; the keys below are the ones they have in common. When the subscription was\n * cancelled is not in here: it is a column of its own, `canceledAt`.\n *\n * - `initiator`: see {@link CANCELLATION_INITIATORS}.\n * - `reason`: the platform's own code, kept verbatim for analytics — Stripe's\n * `cancellation_details.reason`, Google's `cancelSurveyResult.reason`, Apple's notification\n * subtype or `expirationIntent`.\n * - `feedback`: the customer's survey answer in the shared vocabulary {@link CANCELLATION_FEEDBACKS}.\n * - `comment`: free text the customer typed.\n * - `resubscribeIntent`: whether they said they would come back, when the cancel flow asked.\n */\nexport interface CancellationDetails {\n [key: string]: string | null | undefined;\n initiator?: CancellationInitiator | null;\n reason?: string | null;\n feedback?: CancellationFeedback | null;\n comment?: string | null;\n resubscribeIntent?: ResubscribeIntent | null;\n}\n"],"mappings":";;AAAA,MAAa,YAAY;CAAC;CAAS;CAAU;AAAQ;;;;;;;;;;AAarD,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;AACF;;;;;;;AAUA,MAAa,wBAAwB;CAUnC;CAQA;CAYA;CASA;CASA;CAQA;CAQA;CAWA;CASA;CAQA;CAWA;CAaA;CAoBA;CAOA;AACF;;AAKA,MAAa,qBAAqB;CAChC;CACA;CACA;AACF;;AAGA,MAAa,0BAA0B;CAErC;CAEA;CAEA;AACF;;AAKA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,sBAAsB;CAAC;CAAS;CAAM;AAAK"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/subscription/index.ts"],"sourcesContent":["export const PLATFORMS = ['APPLE', 'GOOGLE', 'STRIPE'] as const;\n\nexport type Platform = (typeof PLATFORMS)[number];\n\n/**\n * What a payment was for, on every platform.\n *\n * - ONE_TIME: a one-time purchase.\n * - SUBSCRIPTION_START: the first paid charge of a subscription.\n * - SUBSCRIPTION_RENEWAL: a charge for a new billing period on the regular cycle.\n * - SUBSCRIPTION_UPDATE: a charge mid-period, outside the cycle: the proration of a plan change, or\n * a manual invoice on the subscription. Kept apart from renewals so renewal rates stay honest.\n */\nexport const PAYMENT_TYPES = [\n 'ONE_TIME',\n 'SUBSCRIPTION_START',\n 'SUBSCRIPTION_RENEWAL',\n 'SUBSCRIPTION_UPDATE',\n] as const;\n\nexport type PaymentType = (typeof PAYMENT_TYPES)[number];\n\n/**\n * Where a refund stands, on every platform. Stripe reports all of them; Apple and Google report a\n * refund once it is done (SUCCEEDED), and Apple can take it back (REVERSED, `REFUND_REVERSED`).\n */\nexport const REFUND_STATUSES = ['PENDING', 'SUCCEEDED', 'FAILED', 'CANCELED', 'REVERSED'] as const;\n\nexport type RefundStatus = (typeof REFUND_STATUSES)[number];\n\n/**\n * Where a refund may move from the status it has. Notifications arrive out of order and are\n * redelivered, so a status only ever moves forward along these edges:\n * - PENDING settles into anything (Stripe: succeeded / failed / canceled).\n * - SUCCEEDED can still become FAILED (Stripe: the money could not be returned after all) or\n * REVERSED (Apple: REFUND_REVERSED).\n * - FAILED, CANCELED and REVERSED are final: nothing a platform sends afterwards reopens them.\n * Nothing moves back to PENDING, and a status never \"moves\" to itself (a redelivery is a no-op).\n */\nexport const REFUND_STATUS_TRANSITIONS: Readonly<Record<RefundStatus, readonly RefundStatus[]>> = {\n PENDING: ['SUCCEEDED', 'FAILED', 'CANCELED', 'REVERSED'],\n SUCCEEDED: ['FAILED', 'REVERSED'],\n FAILED: [],\n CANCELED: [],\n REVERSED: [],\n};\n\n/**\n * Stripe's dispute statuses, as they are: the `warning_*` ones are inquiries and early fraud\n * warnings that may never become a chargeback, `prevented` is one Stripe blocked before it was\n * filed. Only LOST costs money. Stripe only: Apple and Google absorb chargebacks themselves and\n * report them as refunds.\n */\nexport const DISPUTE_STATUSES = [\n 'WARNING_NEEDS_RESPONSE',\n 'WARNING_UNDER_REVIEW',\n 'WARNING_CLOSED',\n 'NEEDS_RESPONSE',\n 'UNDER_REVIEW',\n 'PREVENTED',\n 'WON',\n 'LOST',\n] as const;\n\nexport type DisputeStatus = (typeof DISPUTE_STATUSES)[number];\n\n/** A dispute in one of these is over; nothing Stripe sends afterwards reopens it. */\nexport const CLOSED_DISPUTE_STATUSES: readonly DisputeStatus[] = [\n 'WON',\n 'LOST',\n 'WARNING_CLOSED',\n 'PREVENTED',\n];\n\n/**\n * [Stripe Subscription Status](https://stripe.com/docs/api/subscriptions/object#subscription_object-status)\n * [Stripe Subscription Lifecycle](https://docs.stripe.com/billing/subscriptions/overview)\n *\n * provision product for customer when Status = TRIALING, ACTIVE, IN_GRACE_PERIOD\n */\nexport const SUBSCRIPTION_STATUSES = [\n /**\n * The subscription is currently in a trial period and it’s safe to provision your product for\n * your customer. The subscription transitions automatically to active when the first payment\n * is made.\n *\n * Google: play(LineItems[0].OfferDetails.OfferId == 'xx')\n *\n * Platform: Apple, Google, Stripe\n * */\n 'TRIALING',\n\n /**\n * The subscription is in good standing and the most recent payment is successful. It’s safe to\n * provision your product for your customer.\n *\n * Platform: Apple, Google, Stripe\n * */\n 'ACTIVE',\n\n /**\n * Apple: The subscription enters the billing retry period. If the subtype is GRACE_PERIOD,\n * continue to provide service through the grace period. If the subtype is empty, the\n * subscription isn’t in a grace period and you can stop providing the subscription service.\n *\n * Google: Subscription is in grace period. The state is only available when the subscription\n * is an auto renewing plan. In this state, all items are in grace period.\n *\n * Platform: Apple, Google\n * */\n 'IN_GRACE_PERIOD',\n\n /**\n * A successful payment needs to be made within 23 hours to activate the subscription. Or the\n * payment requires action, like customer authentication. Subscriptions can also be incomplete\n * if there’s a pending payment and the PaymentIntent status would be processing.\n *\n * Platform: Stripe\n * */\n 'INCOMPLETE',\n\n /**\n * The initial payment on the subscription failed and no successful payment was made within 23\n * hours of creating the subscription. These subscriptions don’t bill customers. This status\n * exists so you can track customers that failed to activate their subscriptions.\n *\n * Platform: Stripe\n * */\n 'INCOMPLETE_EXPIRED',\n\n /**\n * Subscription was created but awaiting payment during signup. In this state, all items are\n * awaiting payment.\n *\n * Platform: Google\n * */\n 'PENDING',\n\n /**\n * Pending transaction for subscription is canceled. If this pending purchase was for an\n * existing subscription, use linkedPurchaseToken to get the current state of that subscription.\n *\n * Platform: Google\n * */\n 'PENDING_PURCHASE_CANCELED',\n\n /**\n * Payment on the latest finalized invoice either failed or wasn’t attempted. The subscription\n * continues to create invoices. Your subscription settings determine the subscription’s next\n * state. If the invoice is still unpaid after all Smart Retries have been attempted, you can\n * configure the subscription to move to canceled, unpaid, or leave it as past_due. To move the\n * subscription to active, pay the most recent invoice before its due date.\n *\n * Platform: Stripe\n * */\n 'PAST_DUE',\n\n /**\n * Subscription is on hold (suspended). The state is only available when the subscription is an\n * auto renewing plan. In this state, all items are on hold. Grace period ends or Active period\n * ends but not grace period\n *\n * Platform: Google\n * */\n 'ON_HOLD',\n\n /**\n * The subscription has been canceled. During cancellation, automatic collection for all unpaid\n * invoices is disabled (auto_advance=false). This is a terminal state that can’t be updated.\n *\n * Platform: Apple, Google, Stripe\n * */\n 'CANCELED',\n\n /**\n * The latest invoice hasn’t been paid but the subscription remains in place. The latest invoice\n * remains open and invoices continue to be generated but payments aren’t attempted. You should\n * revoke access to your product when the subscription is unpaid since payments were already\n * attempted and retried when it was past_due. To move the subscription to active, pay the most\n * recent invoice before its due date.\n *\n * Platform: Stripe\n * */\n 'UNPAID',\n\n /**\n * Google: Subscription is paused. The state is only available when the subscription is an auto\n * renewing plan. In this state, all items are in paused state.\n *\n * Stripe: The subscription has ended its trial period without a default payment method and the\n * trial_settings.end_behavior.missing_payment_method is set to pause. Invoices will no longer\n * be created for the subscription. After a default payment method has been attached to the\n * customer, you can resume the subscription.\n *\n * Platform: Google, Stripe\n * */\n 'PAUSED',\n\n /**\n * For example, a user buys a subscription and receives a purchase token A. The\n * linkedPurchaseToken field will not be set in the API response because the purchase token\n * belongs to a brand new subscription.\n *\n * If the user upgrades their subscription, a new purchase token B will be generated. Since the\n * upgrade is replacing the subscription from purchase token A, the linkedPurchaseToken field\n * for token B will be set to point to token A. Notice it points backwards in time to the\n * original purchase token.\n *\n * +---------------------------+ +------------------------+ +------------------------+\n * | Step 1 first purchase | | Step 2 upgrades | | Step 3 downgrades |\n * | purchaseToken: A |->| purchaseToken: B |->| purchaseToken: C |\n * | linkedPurchaseToken: null | | linkedPurchaseToken: A | | linkedPurchaseToken: B |\n * +---------------------------+ +------------------------+ +------------------------+\n *\n * Platform: Google\n * */\n 'REPLACED',\n\n /**\n * Google: Subscription is expired. All items have expiryTime in the past.\n *\n * Platform: Apple, Google\n * */\n 'EXPIRED',\n] as const;\n\nexport type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];\n\n/** statuses where it is safe to provision your product for the customer */\nexport const AVAILABLE_STATUSES = [\n 'ACTIVE',\n 'TRIALING',\n 'IN_GRACE_PERIOD',\n] as const satisfies readonly SubscriptionStatus[];\n\n/** Who stopped the subscription from renewing. */\nexport const CANCELLATION_INITIATORS = [\n /** The customer: the store's cancel flow, our own cancel dialog, or a declined price increase. */\n 'user',\n /** The platform: a failed payment, a refund or revocation, a product no longer for sale. */\n 'system',\n /** Us: a cancellation through the platform's API or console. */\n 'developer',\n] as const;\n\nexport type CancellationInitiator = (typeof CANCELLATION_INITIATORS)[number];\n\n/** What a cancel survey may report, whichever platform asked the question. */\nexport const CANCELLATION_FEEDBACKS = [\n 'customer_service',\n 'low_quality',\n 'missing_features',\n 'switched_service',\n 'too_complex',\n 'too_expensive',\n 'unused',\n 'other',\n] as const;\n\nexport type CancellationFeedback = (typeof CANCELLATION_FEEDBACKS)[number];\n\nexport const RESUBSCRIBE_INTENTS = ['maybe', 'no', 'yes'] as const;\n\nexport type ResubscribeIntent = (typeof RESUBSCRIBE_INTENTS)[number];\n\n/**\n * Why a subscription stopped renewing, in one record shared by every platform. Every key is\n * optional and every value a string, so a platform may add what only it reports without a\n * schema change; the keys below are the ones they have in common. When the subscription was\n * cancelled is not in here: it is a column of its own, `canceledAt`.\n *\n * - `initiator`: see {@link CANCELLATION_INITIATORS}.\n * - `reason`: the platform's own code, kept verbatim for analytics — Stripe's\n * `cancellation_details.reason`, Google's `cancelSurveyResult.reason`, Apple's notification\n * subtype or `expirationIntent`.\n * - `feedback`: the customer's survey answer in the shared vocabulary {@link CANCELLATION_FEEDBACKS}.\n * - `comment`: free text the customer typed.\n * - `resubscribeIntent`: whether they said they would come back, when the cancel flow asked.\n */\nexport interface CancellationDetails {\n [key: string]: string | null | undefined;\n initiator?: CancellationInitiator | null;\n reason?: string | null;\n feedback?: CancellationFeedback | null;\n comment?: string | null;\n resubscribeIntent?: ResubscribeIntent | null;\n}\n"],"mappings":";;AAAA,MAAa,YAAY;CAAC;CAAS;CAAU;AAAQ;;;;;;;;;;AAarD,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;AACF;;;;;AAQA,MAAa,kBAAkB;CAAC;CAAW;CAAa;CAAU;CAAY;AAAU;;;;;;;;;;AAaxF,MAAa,4BAAqF;CAChG,SAAS;EAAC;EAAa;EAAU;EAAY;CAAU;CACvD,WAAW,CAAC,UAAU,UAAU;CAChC,QAAQ,CAAC;CACT,UAAU,CAAC;CACX,UAAU,CAAC;AACb;;;;;;;AAQA,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAKA,MAAa,0BAAoD;CAC/D;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAa,wBAAwB;CAUnC;CAQA;CAYA;CASA;CASA;CAQA;CAQA;CAWA;CASA;CAQA;CAWA;CAaA;CAoBA;CAOA;AACF;;AAKA,MAAa,qBAAqB;CAChC;CACA;CACA;AACF;;AAGA,MAAa,0BAA0B;CAErC;CAEA;CAEA;AACF;;AAKA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,sBAAsB;CAAC;CAAS;CAAM;AAAK"}
|