@ultimabase/stripe 0.0.0-first.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 (130) hide show
  1. package/README.md +7 -0
  2. package/dist/accounts.d.ts +9 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +20 -0
  5. package/dist/apply.d.ts +26 -0
  6. package/dist/apply.d.ts.map +1 -0
  7. package/dist/apply.js +73 -0
  8. package/dist/audit.d.ts +3 -0
  9. package/dist/audit.d.ts.map +1 -0
  10. package/dist/audit.js +123 -0
  11. package/dist/billing-gateway.d.ts +158 -0
  12. package/dist/billing-gateway.d.ts.map +1 -0
  13. package/dist/billing-gateway.js +23 -0
  14. package/dist/billing.d.ts +130 -0
  15. package/dist/billing.d.ts.map +1 -0
  16. package/dist/billing.js +128 -0
  17. package/dist/calls.d.ts +61 -0
  18. package/dist/calls.d.ts.map +1 -0
  19. package/dist/calls.js +172 -0
  20. package/dist/catalog.d.ts +54 -0
  21. package/dist/catalog.d.ts.map +1 -0
  22. package/dist/catalog.js +182 -0
  23. package/dist/credit.d.ts +16 -0
  24. package/dist/credit.d.ts.map +1 -0
  25. package/dist/credit.js +18 -0
  26. package/dist/credits.d.ts +38 -0
  27. package/dist/credits.d.ts.map +1 -0
  28. package/dist/credits.js +138 -0
  29. package/dist/customer.d.ts +25 -0
  30. package/dist/customer.d.ts.map +1 -0
  31. package/dist/customer.js +88 -0
  32. package/dist/describe.d.ts +4 -0
  33. package/dist/describe.d.ts.map +1 -0
  34. package/dist/describe.js +56 -0
  35. package/dist/duplicates.d.ts +12 -0
  36. package/dist/duplicates.d.ts.map +1 -0
  37. package/dist/duplicates.js +24 -0
  38. package/dist/fake-billing.d.ts +72 -0
  39. package/dist/fake-billing.d.ts.map +1 -0
  40. package/dist/fake-billing.js +290 -0
  41. package/dist/gateway.d.ts +108 -0
  42. package/dist/gateway.d.ts.map +1 -0
  43. package/dist/gateway.js +196 -0
  44. package/dist/index.d.ts +15 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +6 -0
  47. package/dist/job-input.d.ts +6 -0
  48. package/dist/job-input.d.ts.map +1 -0
  49. package/dist/job-input.js +20 -0
  50. package/dist/jobs.d.ts +16 -0
  51. package/dist/jobs.d.ts.map +1 -0
  52. package/dist/jobs.js +189 -0
  53. package/dist/keys.d.ts +10 -0
  54. package/dist/keys.d.ts.map +1 -0
  55. package/dist/keys.js +30 -0
  56. package/dist/kinds.d.ts +11 -0
  57. package/dist/kinds.d.ts.map +1 -0
  58. package/dist/kinds.js +4 -0
  59. package/dist/models.d.ts +71 -0
  60. package/dist/models.d.ts.map +1 -0
  61. package/dist/models.js +41 -0
  62. package/dist/plugin.d.ts +41 -0
  63. package/dist/plugin.d.ts.map +1 -0
  64. package/dist/plugin.js +229 -0
  65. package/dist/portal.d.ts +23 -0
  66. package/dist/portal.d.ts.map +1 -0
  67. package/dist/portal.js +66 -0
  68. package/dist/product.d.ts +57 -0
  69. package/dist/product.d.ts.map +1 -0
  70. package/dist/product.js +113 -0
  71. package/dist/running.d.ts +61 -0
  72. package/dist/running.d.ts.map +1 -0
  73. package/dist/running.js +35 -0
  74. package/dist/sdk-billing.d.ts +8 -0
  75. package/dist/sdk-billing.d.ts.map +1 -0
  76. package/dist/sdk-billing.js +200 -0
  77. package/dist/sdk-common.d.ts +13 -0
  78. package/dist/sdk-common.d.ts.map +1 -0
  79. package/dist/sdk-common.js +41 -0
  80. package/dist/sdk-customer.d.ts +9 -0
  81. package/dist/sdk-customer.d.ts.map +1 -0
  82. package/dist/sdk-customer.js +149 -0
  83. package/dist/sdk-invoices.d.ts +10 -0
  84. package/dist/sdk-invoices.d.ts.map +1 -0
  85. package/dist/sdk-invoices.js +53 -0
  86. package/dist/sdk-recovery.d.ts +5 -0
  87. package/dist/sdk-recovery.d.ts.map +1 -0
  88. package/dist/sdk-recovery.js +81 -0
  89. package/dist/sync.d.ts +8 -0
  90. package/dist/sync.d.ts.map +1 -0
  91. package/dist/sync.js +196 -0
  92. package/dist/testing.d.ts +24 -0
  93. package/dist/testing.d.ts.map +1 -0
  94. package/dist/testing.js +100 -0
  95. package/dist/webhook.d.ts +4 -0
  96. package/dist/webhook.d.ts.map +1 -0
  97. package/dist/webhook.js +73 -0
  98. package/package.json +51 -0
  99. package/src/accounts.ts +30 -0
  100. package/src/apply.ts +99 -0
  101. package/src/audit.ts +171 -0
  102. package/src/billing-gateway.ts +188 -0
  103. package/src/billing.ts +361 -0
  104. package/src/calls.ts +280 -0
  105. package/src/catalog.ts +327 -0
  106. package/src/credit.ts +36 -0
  107. package/src/credits.ts +206 -0
  108. package/src/customer.ts +113 -0
  109. package/src/describe.ts +76 -0
  110. package/src/duplicates.ts +45 -0
  111. package/src/fake-billing.ts +388 -0
  112. package/src/gateway.ts +333 -0
  113. package/src/index.ts +35 -0
  114. package/src/job-input.ts +24 -0
  115. package/src/jobs.ts +230 -0
  116. package/src/keys.ts +40 -0
  117. package/src/kinds.ts +15 -0
  118. package/src/models.ts +107 -0
  119. package/src/plugin.ts +307 -0
  120. package/src/portal.ts +95 -0
  121. package/src/product.ts +203 -0
  122. package/src/running.ts +104 -0
  123. package/src/sdk-billing.ts +220 -0
  124. package/src/sdk-common.ts +57 -0
  125. package/src/sdk-customer.ts +203 -0
  126. package/src/sdk-invoices.ts +81 -0
  127. package/src/sdk-recovery.ts +93 -0
  128. package/src/sync.ts +246 -0
  129. package/src/testing.ts +135 -0
  130. package/src/webhook.ts +100 -0
@@ -0,0 +1,128 @@
1
+ import { defineModel, Refused } from 'ultimabase';
2
+ import { knownKeys } from 'ultimabase/internal';
3
+ import { billingModels } from './kinds.js';
4
+ import { stripeUse } from './plugin.js';
5
+ const statuses = [
6
+ 'incomplete',
7
+ 'incomplete_expired',
8
+ 'trialing',
9
+ 'active',
10
+ 'past_due',
11
+ 'canceled',
12
+ 'unpaid',
13
+ 'paused',
14
+ ];
15
+ const intervals = ['day', 'week', 'month', 'year'];
16
+ const added = (f, kind, payer) => {
17
+ const ref = f.one(payer, { onDelete: 'cascade' });
18
+ const optional = { optional: true };
19
+ if (kind === 'subscription') {
20
+ return {
21
+ payer: ref,
22
+ stripeId: f.string({ unique: true }),
23
+ product: f.string(),
24
+ price: f.string(),
25
+ status: f.enumOf(statuses),
26
+ quantity: f.number({ integer: true }),
27
+ amount: f.number({ integer: true }),
28
+ every: f.enumOf(intervals),
29
+ everyCount: f.number({ integer: true }),
30
+ currentPeriodEnd: f.dateTime(),
31
+ cancelAt: f.dateTime(optional),
32
+ canceledAt: f.dateTime(optional),
33
+ trialEnd: f.dateTime(optional),
34
+ startedAt: f.dateTime(),
35
+ scheduledProduct: f.string(optional),
36
+ scheduledPrice: f.string(optional),
37
+ scheduledAt: f.dateTime(optional),
38
+ };
39
+ }
40
+ if (kind === 'purchase') {
41
+ return {
42
+ payer: ref,
43
+ stripeId: f.string({ unique: true }),
44
+ product: f.string(),
45
+ quantity: f.number({ integer: true }),
46
+ amount: f.number({ integer: true }),
47
+ refunded: f.number({ integer: true }),
48
+ status: f.enumOf(['paid', 'refunded']),
49
+ paidAt: f.dateTime(),
50
+ receiptUrl: f.string(optional),
51
+ };
52
+ }
53
+ if (kind === 'history') {
54
+ return {
55
+ owner: ref,
56
+ credit: f.string(),
57
+ change: f.number({ integer: true }),
58
+ reason: f.string(),
59
+ payment: f.string(optional),
60
+ };
61
+ }
62
+ return {
63
+ owner: ref,
64
+ credit: f.string(),
65
+ amount: f.number({ integer: true }),
66
+ };
67
+ };
68
+ /** The indexes the plugin's queries need. */
69
+ const indexesOf = (kind) => {
70
+ if (kind === 'balance')
71
+ return [{ fields: ['owner', 'credit'], unique: true }];
72
+ // A payment gives its credits once: its moves are looked up by it.
73
+ if (kind === 'history')
74
+ return [{ fields: ['payment'] }];
75
+ return [];
76
+ };
77
+ // The kernel checks the model the thunk returns.
78
+ const isThunk = (value) => typeof value === 'function';
79
+ const entries = {
80
+ subscription: ['defineSubscription', 'payer'],
81
+ purchase: ['definePurchase', 'payer'],
82
+ balance: ['defineBalance', 'owner'],
83
+ history: ['defineCreditHistory', 'owner'],
84
+ };
85
+ /** Builds a billing model of `kind` from the developer's definition. */
86
+ function billingModel(kind, definition) {
87
+ const [entry, key] = entries[kind];
88
+ const { name, fields } = definition;
89
+ const keys = ['name', 'dbName', key, 'use', 'fields', 'indexes'];
90
+ knownKeys(name, definition, keys, 'access, hooks and plugin options');
91
+ const payer = Reflect.get(definition, key);
92
+ if (!isThunk(payer)) {
93
+ throw new Refused(`${entry}(${name}): ${key} is () => its model.`);
94
+ }
95
+ const target = payer;
96
+ const model = defineModel({
97
+ name,
98
+ ...(definition.dbName === undefined ? {} : { dbName: definition.dbName }),
99
+ use: [stripeUse(), ...(definition.use ?? [])],
100
+ fields: (f) => {
101
+ const own = fields === undefined ? {} : Reflect.apply(fields, undefined, [f]);
102
+ if (typeof own !== 'object' || own === null) {
103
+ throw new Refused(`${entry}(${name}): fields returns an object.`);
104
+ }
105
+ const adds = added(f, kind, target);
106
+ const taken = Object.keys(adds).find((field) => Object.hasOwn(own, field));
107
+ if (taken !== undefined) {
108
+ throw new Refused(`${entry}(${name}): ${taken} is a field ${entry} adds.`);
109
+ }
110
+ return { ...own, ...adds };
111
+ },
112
+ indexes: [...indexesOf(kind), ...(definition.indexes ?? [])],
113
+ });
114
+ billingModels.set(model, { kind, payer: target });
115
+ return model;
116
+ }
117
+ export function defineSubscription(definition) {
118
+ return billingModel('subscription', definition);
119
+ }
120
+ export function definePurchase(definition) {
121
+ return billingModel('purchase', definition);
122
+ }
123
+ export function defineBalance(definition) {
124
+ return billingModel('balance', definition);
125
+ }
126
+ export function defineCreditHistory(definition) {
127
+ return billingModel('history', definition);
128
+ }
@@ -0,0 +1,61 @@
1
+ import type { Product, SubscriptionProduct } from './product.ts';
2
+ import { grant, spend } from './credits.ts';
3
+ type Payer = {
4
+ readonly id: string;
5
+ };
6
+ /** A product's price names: `'monthly' | 'yearly'`. */
7
+ type PriceOf<P> = P extends SubscriptionProduct<string, infer N> ? N : never;
8
+ /** What `stripe.checkout` takes (D-373 point 7). */
9
+ export interface CheckoutArgs<P extends Product = Product> {
10
+ /** The payer's row, as `{ id }`. */
11
+ readonly payer: Payer;
12
+ readonly product: P;
13
+ /** One of a subscription product's prices; its only one by default. */
14
+ readonly price?: PriceOf<P>;
15
+ /** 1 by default. */
16
+ readonly quantity?: number;
17
+ readonly trialDays?: number;
18
+ /** Whether the payer must accept the portal's `termsUrl`. */
19
+ readonly terms?: boolean;
20
+ readonly promotionCodes?: boolean;
21
+ /** Where Stripe sends the payer back; `{CHECKOUT_SESSION_ID}` is replaced. */
22
+ readonly successUrl: string;
23
+ readonly cancelUrl: string;
24
+ readonly metadata?: Readonly<Record<string, string>>;
25
+ }
26
+ /** What `stripe.portal` takes (D-373 point 8). */
27
+ export interface PortalArgs<P extends SubscriptionProduct = SubscriptionProduct> {
28
+ readonly payer: Payer;
29
+ /** The portal option's `returnUrl` by default. */
30
+ readonly returnUrl?: string;
31
+ /** Opens the confirmation of a move to another product or price. */
32
+ readonly change?: {
33
+ readonly product: P;
34
+ readonly price: PriceOf<P>;
35
+ /** The subscription row's id, when the payer has several live ones. */
36
+ readonly subscription?: string;
37
+ };
38
+ /** Opens the confirmation of a cancellation. */
39
+ readonly cancel?: {
40
+ readonly subscription?: string;
41
+ };
42
+ }
43
+ /** Opens a Checkout for the payer and returns its URL. */
44
+ export declare function checkout<const P extends Product>(args: CheckoutArgs<P>): Promise<string>;
45
+ /** Opens the payer's customer portal, or one change's confirmation. */
46
+ export declare function portal<const P extends SubscriptionProduct>(args: PortalArgs<P>): Promise<string>;
47
+ /**
48
+ * Syncs the payer's Checkout `sessionId` when the client comes back, without
49
+ * waiting for the webhook; `NOT_FOUND` for another payer's.
50
+ */
51
+ export declare function syncCheckout(sessionId: string, payer: Payer): Promise<void>;
52
+ /** The running plugin, from the application's functions (D-371 point 3). */
53
+ export declare const stripe: {
54
+ readonly checkout: typeof checkout;
55
+ readonly portal: typeof portal;
56
+ readonly syncCheckout: typeof syncCheckout;
57
+ readonly grant: typeof grant;
58
+ readonly spend: typeof spend;
59
+ };
60
+ export {};
61
+ //# sourceMappingURL=calls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calls.d.ts","sourceRoot":"","sources":["../src/calls.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAA;AAGhE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AAG3C,KAAK,KAAK,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAA;AACpC,uDAAuD;AACvD,KAAK,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;AAE5E,oDAAoD;AACpD,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,OAAO,GAAG,OAAO;IACxD,oCAAoC;IACpC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAA;IACrB,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAA;IACnB,uEAAuE;IACvE,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAA;IAC3B,oBAAoB;IACpB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,6DAA6D;IAC7D,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAA;IACxB,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAA;IACjC,8EAA8E;IAC9E,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAA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CAAA;IAC5B,QAAQ,CAAC,KAAK,EAAE,OAAO,KAAK,CAAA;CACuB,CAAA"}
package/dist/calls.js ADDED
@@ -0,0 +1,172 @@
1
+ // `stripe.checkout`, `stripe.portal` and `stripe.syncCheckout` (D-371 point
2
+ // 3, D-373 points 7 and 8): the server calls an application's functions make.
3
+ // Each runs under the payer's customer lock and expires the Checkouts the
4
+ // payer left open, so two tabs cannot both pay.
5
+ import { PublicError, Refused } from 'ultimabase';
6
+ import { liveStatuses, Missing } from './billing-gateway.js';
7
+ import { customerRow, ensureCustomer, locked, payerRow, renewed, } from './customer.js';
8
+ import { M, StripeCustomer } from './models.js';
9
+ import { runningOf, stripeOf } from './running.js';
10
+ import { grant, spend } from './credits.js';
11
+ import { syncCustomer } from './sync.js';
12
+ /** The catalog's product, or a bug: a product the plugin was not given. */
13
+ function catalogued(running, product) {
14
+ if (running.products.get(product.key) === product)
15
+ return product;
16
+ throw new Error(`${product.key} is not in stripePlugin's products.`);
17
+ }
18
+ /** The price's lookup key (D-372 point 3). */
19
+ function lookupKey(product, price) {
20
+ if (!('prices' in product))
21
+ return product.key;
22
+ const names = Object.keys(product.prices);
23
+ const [only] = names;
24
+ const name = price ?? (names.length === 1 ? only : undefined);
25
+ if (name === undefined || !names.includes(name)) {
26
+ throw new TypeError(`${product.key}'s price is one of ${names.join(', ')}.`);
27
+ }
28
+ return `${product.key}.${name}`;
29
+ }
30
+ /** The model naming the payers of a product: who the customer is for. */
31
+ function billingOf(running, product) {
32
+ const billing = 'prices' in product
33
+ ? running.subscription
34
+ : (running.purchase ?? running.balance);
35
+ if (billing !== undefined)
36
+ return billing;
37
+ throw new Error(`${product.key} needs a model definePurchase returned, to record its payments.`);
38
+ }
39
+ /**
40
+ * Runs `run` with the payer's customer at Stripe, under its lock, after
41
+ * expiring its open Checkouts; a customer deleted at Stripe is created again.
42
+ */
43
+ async function withCustomer(billing, payer, run) {
44
+ const { gateway } = stripeOf('stripe');
45
+ const read = await payerRow(billing.payer, payer.id);
46
+ const held = await customerRow(billing.payer.name, payer.id);
47
+ const done = await locked(held.id, async (row) => {
48
+ const attempt = async (current) => {
49
+ const { row: saved, stripeId } = await ensureCustomer(current, read);
50
+ try {
51
+ await gateway.expireCheckouts(stripeId);
52
+ return await run(gateway, stripeId, saved);
53
+ }
54
+ catch (error) {
55
+ if (!(error instanceof Missing) || current !== row)
56
+ throw error;
57
+ return attempt(await renewed(saved));
58
+ }
59
+ };
60
+ return { value: await attempt(row) };
61
+ });
62
+ if (done === undefined)
63
+ throw new Error('The payer’s customer was closed.');
64
+ return done.value;
65
+ }
66
+ const checkPositive = (name, value) => {
67
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
68
+ throw new TypeError(`stripe.checkout: ${name} is a positive integer.`);
69
+ }
70
+ };
71
+ /** Opens a Checkout for the payer and returns its URL. */
72
+ export async function checkout(args) {
73
+ const running = runningOf('stripe.checkout');
74
+ stripeOf('stripe.checkout');
75
+ const product = catalogued(running, args.product);
76
+ const key = lookupKey(product, args.price);
77
+ checkPositive('quantity', args.quantity);
78
+ checkPositive('trialDays', args.trialDays);
79
+ const subscribing = 'prices' in product;
80
+ return withCustomer(billingOf(running, product), args.payer, async (gateway, customerId) => {
81
+ if (subscribing && running.oneSubscription) {
82
+ const { subscriptions } = await gateway.readCustomer(customerId);
83
+ if (subscriptions.some(({ status }) => liveStatuses.includes(status))) {
84
+ throw new PublicError('ALREADY_SUBSCRIBED', 'The payer already has a subscription.');
85
+ }
86
+ }
87
+ return gateway.openCheckout({
88
+ customerId,
89
+ reference: args.payer.id,
90
+ mode: subscribing ? 'subscription' : 'payment',
91
+ product: product.key,
92
+ lookupKey: key,
93
+ quantity: args.quantity ?? 1,
94
+ trialDays: subscribing ? (args.trialDays ?? null) : null,
95
+ terms: args.terms ?? false,
96
+ promotionCodes: args.promotionCodes ?? false,
97
+ successUrl: args.successUrl,
98
+ cancelUrl: args.cancelUrl,
99
+ metadata: args.metadata ?? {},
100
+ });
101
+ });
102
+ }
103
+ /**
104
+ * The payer's subscription a deep link is about, or `NOT_SUBSCRIBED`; the
105
+ * code names one with `option` when the payer has several.
106
+ */
107
+ async function subscriptionOf(model, payer, id, option) {
108
+ const where = {
109
+ payer: { is: { id: payer.id } },
110
+ status: { in: liveStatuses },
111
+ ...(id === undefined ? {} : { id }),
112
+ };
113
+ const live = await model.queries.findMany({ where, take: 2 }, M);
114
+ const [one, other] = live;
115
+ if (one === undefined) {
116
+ throw new PublicError('NOT_SUBSCRIBED', 'The payer has no subscription.');
117
+ }
118
+ if (other !== undefined) {
119
+ throw new Refused(`stripe.portal: the payer has several live subscriptions; name the one with ${option}, a ${model.name} row’s id.`);
120
+ }
121
+ return one;
122
+ }
123
+ /** The portal's flow for the arguments. */
124
+ async function flowOf(running, model, args) {
125
+ const { change, cancel } = args;
126
+ if (change !== undefined && cancel !== undefined) {
127
+ throw new TypeError('stripe.portal takes change or cancel, not both.');
128
+ }
129
+ if (change !== undefined) {
130
+ const product = catalogued(running, change.product);
131
+ const lookup = lookupKey(product, change.price);
132
+ const row = await subscriptionOf(model, args.payer, change.subscription, 'change.subscription');
133
+ const subscriptionId = String(row['stripeId']);
134
+ return { kind: 'change', subscriptionId, lookupKey: lookup };
135
+ }
136
+ if (cancel !== undefined) {
137
+ const row = await subscriptionOf(model, args.payer, cancel.subscription, 'cancel.subscription');
138
+ return { kind: 'cancel', subscriptionId: String(row['stripeId']) };
139
+ }
140
+ return { kind: 'home' };
141
+ }
142
+ /** Opens the payer's customer portal, or one change's confirmation. */
143
+ export async function portal(args) {
144
+ const running = runningOf('stripe.portal');
145
+ const { gateway } = stripeOf('stripe.portal');
146
+ const model = running.subscription;
147
+ if (model === undefined) {
148
+ throw new Error('stripe.portal needs a model defineSubscription returned.');
149
+ }
150
+ const flow = await flowOf(running, model, args);
151
+ running.portal ??= (await gateway.readCatalog()).portal?.id ?? null;
152
+ const configuration = running.portal;
153
+ const returnUrl = args.returnUrl ?? running.catalog.portal.returnUrl;
154
+ return withCustomer(model, args.payer, async (_, customerId) => gateway.openPortal({ customerId, configuration, returnUrl, flow }));
155
+ }
156
+ /**
157
+ * Syncs the payer's Checkout `sessionId` when the client comes back, without
158
+ * waiting for the webhook; `NOT_FOUND` for another payer's.
159
+ */
160
+ export async function syncCheckout(sessionId, payer) {
161
+ const { gateway } = stripeOf('stripe.syncCheckout');
162
+ const customerId = await gateway.checkoutCustomer(sessionId);
163
+ const row = customerId === null
164
+ ? null
165
+ : await StripeCustomer.findUnique({ where: { stripeId: customerId } }, M);
166
+ if (row === null || row.payer !== payer.id) {
167
+ throw new PublicError('NOT_FOUND', 'No Checkout of the payer matches.');
168
+ }
169
+ await syncCustomer(row.id);
170
+ }
171
+ /** The running plugin, from the application's functions (D-371 point 3). */
172
+ export const stripe = { checkout, portal, syncCheckout, grant, spend };
@@ -0,0 +1,54 @@
1
+ import { type CatalogState, type ProductWrite, type Recurring, type StripeGateway, type StripePrice, type StripeProduct } from './gateway.ts';
2
+ import { type PortalOptions } from './portal.ts';
3
+ import type { Every, Product } from './product.ts';
4
+ /** What an application sells, and how its payers manage it. */
5
+ export interface Catalog {
6
+ /** Every price's currency, in lowercase: `eur`. */
7
+ readonly currency: string;
8
+ /** Whether the amounts include the taxes. */
9
+ readonly taxBehavior: 'inclusive' | 'exclusive';
10
+ readonly products: readonly Product[];
11
+ readonly portal: PortalOptions;
12
+ }
13
+ /** A price as the catalog wants it. */
14
+ export interface WantedPrice {
15
+ /** Its product's key. */
16
+ readonly product: string;
17
+ readonly lookupKey: string;
18
+ readonly amount: number;
19
+ /** `null` for a one-time price. */
20
+ readonly recurring: Recurring<Every> | null;
21
+ readonly metadata: Readonly<Record<string, string>>;
22
+ }
23
+ /** One change to the catalog. */
24
+ export type CatalogStep = {
25
+ readonly kind: 'createProduct';
26
+ readonly product: ProductWrite;
27
+ } | {
28
+ readonly kind: 'updateProduct';
29
+ readonly product: ProductWrite;
30
+ readonly was: StripeProduct;
31
+ } | {
32
+ readonly kind: 'archiveProduct';
33
+ readonly was: StripeProduct;
34
+ } | {
35
+ readonly kind: 'createPrice';
36
+ readonly price: WantedPrice;
37
+ /** The price whose lookup key it takes over, archived after. */
38
+ readonly replaces: StripePrice | null;
39
+ } | {
40
+ readonly kind: 'updatePrice';
41
+ readonly price: WantedPrice;
42
+ readonly was: StripePrice;
43
+ } | {
44
+ readonly kind: 'archivePrice';
45
+ readonly was: StripePrice;
46
+ } | {
47
+ readonly kind: 'savePortal';
48
+ readonly id: string | null;
49
+ };
50
+ /** The changes that bring `state` to `catalog`, in order. */
51
+ export declare const planCatalog: (catalog: Catalog, state: CatalogState) => CatalogStep[];
52
+ /** Applies `steps`, planned from `state`, through `gateway`. */
53
+ export declare const applyCatalog: (catalog: Catalog, gateway: StripeGateway, state: CatalogState, steps: readonly CatalogStep[]) => Promise<void>;
54
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAOA,OAAO,EACN,KAAK,YAAY,EAEjB,KAAK,YAAY,EACjB,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,aAAa,EAElB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,KAAK,aAAa,EAA8B,MAAM,aAAa,CAAA;AAC5E,OAAO,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAElD,+DAA+D;AAC/D,MAAM,WAAW,OAAO;IACvB,mDAAmD;IACnD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,6CAA6C;IAC7C,QAAQ,CAAC,WAAW,EAAE,WAAW,GAAG,WAAW,CAAA;IAC/C,QAAQ,CAAC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAA;IACrC,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAA;CAC9B;AAED,uCAAuC;AACvC,MAAM,WAAW,WAAW;IAC3B,yBAAyB;IACzB,QA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A6D;AAC7D,eAAO,MAAM,WAAW,YACd,OAAO,SACT,YAAY,KACjB,WAAW,EAuEb,CAAA;AAED,gEAAgE;AAChE,eAAO,MAAM,YAAY,YACf,OAAO,WACP,aAAa,SACf,YAAY,SACZ,SAAS,WAAW,EAAE,KAC3B,OAAO,CAAC,IAAI,CA2Dd,CAAA"}
@@ -0,0 +1,182 @@
1
+ // The catalog at Stripe, written from the products declared in code (D-372).
2
+ // A product is found by its `metadata.key`, a price by its lookup key:
3
+ // `<product>.<price>`, or the product's key for a one-time price. The plan
4
+ // lists the changes from what Stripe holds; applying them never deletes: a
5
+ // product left out is archived, and a price whose billing changed is
6
+ // replaced by a new one, which takes its lookup key over.
7
+ import { Refused } from 'ultimabase';
8
+ import { managedBy, } from './gateway.js';
9
+ import { portalSettings, samePortal } from './portal.js';
10
+ const productWrite = (product) => ({
11
+ key: product.key,
12
+ name: product.name,
13
+ taxCode: product.taxCode ?? null,
14
+ });
15
+ /** The prices of the catalog's products, in their order. */
16
+ const wantedPrices = (products) => products.flatMap((product) => 'prices' in product
17
+ ? Object.entries(product.prices).map(([name, price]) => ({
18
+ product: product.key,
19
+ lookupKey: `${product.key}.${name}`,
20
+ amount: price.amount,
21
+ recurring: { every: price.every, count: price.everyCount ?? 1 },
22
+ metadata: { managedBy, product: product.key, price: name },
23
+ }))
24
+ : [
25
+ {
26
+ product: product.key,
27
+ lookupKey: product.key,
28
+ amount: product.price.amount,
29
+ recurring: null,
30
+ metadata: { managedBy, product: product.key },
31
+ },
32
+ ]);
33
+ /** The product of each key: its active one first, else an archived one. */
34
+ const productsOf = (products, held) => new Map(products.flatMap(({ key }) => {
35
+ const ofKey = held.filter((product) => product.key === key);
36
+ const product = ofKey.find(({ active }) => active) ?? ofKey.at(0);
37
+ return product === undefined ? [] : [[key, product]];
38
+ }));
39
+ const sameRecurring = (held, wanted) => held === null || wanted === null
40
+ ? held === wanted
41
+ : held.every === wanted.every && held.count === wanted.count;
42
+ /** Whether `held` bills as `price`: what Stripe never changes of a price. */
43
+ const billsAs = (catalog, held, price, productId) => held.productId === productId &&
44
+ held.amount === price.amount &&
45
+ held.currency === catalog.currency &&
46
+ sameRecurring(held.recurring, price.recurring) &&
47
+ held.taxBehavior === catalog.taxBehavior;
48
+ /** Whether `held` carries `price`'s nickname and metadata. */
49
+ const describedAs = (held, price) => held.nickname === price.lookupKey &&
50
+ // Stripe merges metadata: a key someone added stays, and is let be.
51
+ Object.entries(price.metadata).every(([key, value]) => held.metadata[key] === value);
52
+ const productIs = (held, product) => held.active && held.name === product.name && held.taxCode === product.taxCode;
53
+ /** The active price of each lookup key. */
54
+ const activePrices = (prices) => new Map(prices.flatMap((price) => price.active && price.lookupKey !== null
55
+ ? [[price.lookupKey, price]]
56
+ : []));
57
+ /** The id `ids` holds for `key`, which the steps before have written. */
58
+ const idOf = (ids, key) => {
59
+ const id = ids.get(key);
60
+ if (id === undefined)
61
+ throw new Error(`The catalog has no id for ${key}.`);
62
+ return id;
63
+ };
64
+ /** The portal's products: the subscriptions, with their prices' ids. */
65
+ const portalProducts = (products, productIds, priceIds) => products.flatMap((product) => 'prices' in product
66
+ ? [
67
+ {
68
+ productId: idOf(productIds, product.key),
69
+ priceIds: Object.keys(product.prices).map((name) => idOf(priceIds, `${product.key}.${name}`)),
70
+ },
71
+ ]
72
+ : []);
73
+ /** The id of each key's product. */
74
+ const productIdsOf = (products, held) => new Map([...productsOf(products, held)].map(([key, { id }]) => [key, id]));
75
+ /** The changes that bring `state` to `catalog`, in order. */
76
+ export const planCatalog = (catalog, state) => {
77
+ const steps = [];
78
+ const kept = productsOf(catalog.products, state.products);
79
+ for (const product of catalog.products.map(productWrite)) {
80
+ const was = kept.get(product.key);
81
+ if (was === undefined)
82
+ steps.push({ kind: 'createProduct', product });
83
+ else if (!productIs(was, product)) {
84
+ steps.push({ kind: 'updateProduct', product, was });
85
+ }
86
+ }
87
+ const active = activePrices(state.prices);
88
+ const unchanged = new Map();
89
+ const wanted = wantedPrices(catalog.products);
90
+ for (const price of wanted) {
91
+ const was = active.get(price.lookupKey);
92
+ if (was !== undefined && was.metadata['managedBy'] !== managedBy) {
93
+ throw new Refused(`The price ${was.id} holds the lookup key ${price.lookupKey} but was not written by the catalog: archive it, or remove its lookup key, in the Stripe Dashboard.`);
94
+ }
95
+ if (was === undefined) {
96
+ steps.push({ kind: 'createPrice', price, replaces: null });
97
+ }
98
+ else if (!billsAs(catalog, was, price, kept.get(price.product)?.id)) {
99
+ // A price's billing never changes: a new one takes the key over.
100
+ steps.push({ kind: 'createPrice', price, replaces: was });
101
+ }
102
+ else {
103
+ unchanged.set(price.lookupKey, was.id);
104
+ if (!describedAs(was, price)) {
105
+ steps.push({ kind: 'updatePrice', price, was });
106
+ }
107
+ }
108
+ }
109
+ const lookupKeys = new Set(wanted.map(({ lookupKey }) => lookupKey));
110
+ for (const price of state.prices) {
111
+ if (price.active &&
112
+ price.metadata['managedBy'] === managedBy &&
113
+ (price.lookupKey === null || !lookupKeys.has(price.lookupKey))) {
114
+ steps.push({ kind: 'archivePrice', was: price });
115
+ }
116
+ }
117
+ // A product left out, or a key's second product.
118
+ const keptIds = new Set([...kept.values()].map(({ id }) => id));
119
+ for (const product of state.products) {
120
+ if (product.active && !keptIds.has(product.id)) {
121
+ steps.push({ kind: 'archiveProduct', was: product });
122
+ }
123
+ }
124
+ // A new subscription price changes the portal's list.
125
+ const moved = steps.some((step) => step.kind === 'createPrice' && step.price.recurring !== null);
126
+ if (moved ||
127
+ state.portal === null ||
128
+ !samePortal(state.portal.settings, portalSettings(catalog.portal, portalProducts(catalog.products, productIdsOf(catalog.products, state.products), unchanged)))) {
129
+ steps.push({ kind: 'savePortal', id: state.portal?.id ?? null });
130
+ }
131
+ return steps;
132
+ };
133
+ /** Applies `steps`, planned from `state`, through `gateway`. */
134
+ export const applyCatalog = async (catalog, gateway, state, steps) => {
135
+ const productIds = productIdsOf(catalog.products, state.products);
136
+ const priceIds = new Map([...activePrices(state.prices)].map(([key, { id }]) => [key, id]));
137
+ for (const step of steps) {
138
+ switch (step.kind) {
139
+ case 'createProduct':
140
+ productIds.set(step.product.key, await gateway.createProduct(step.product));
141
+ break;
142
+ case 'updateProduct':
143
+ await gateway.updateProduct(step.was.id, step.product);
144
+ break;
145
+ case 'archiveProduct':
146
+ await gateway.archiveProduct(step.was.id);
147
+ break;
148
+ case 'createPrice': {
149
+ const { price } = step;
150
+ const id = await gateway.createPrice({
151
+ productId: idOf(productIds, price.product),
152
+ lookupKey: price.lookupKey,
153
+ amount: price.amount,
154
+ currency: catalog.currency,
155
+ recurring: price.recurring,
156
+ taxBehavior: catalog.taxBehavior,
157
+ nickname: price.lookupKey,
158
+ metadata: price.metadata,
159
+ });
160
+ priceIds.set(price.lookupKey, id);
161
+ // After its successor: a payer never finds no price.
162
+ if (step.replaces !== null) {
163
+ await gateway.archivePrice(step.replaces.id);
164
+ }
165
+ break;
166
+ }
167
+ case 'updatePrice':
168
+ await gateway.updatePrice(step.was.id, {
169
+ nickname: step.price.lookupKey,
170
+ metadata: step.price.metadata,
171
+ });
172
+ break;
173
+ case 'archivePrice':
174
+ await gateway.archivePrice(step.was.id);
175
+ break;
176
+ case 'savePortal': {
177
+ await gateway.savePortal(step.id, portalSettings(catalog.portal, portalProducts(catalog.products, productIds, priceIds)));
178
+ break;
179
+ }
180
+ }
181
+ }
182
+ };
@@ -0,0 +1,16 @@
1
+ /** An amount of one credit: what a product gives. */
2
+ export interface CreditAmount<K extends string = string> {
3
+ readonly credit: K;
4
+ readonly amount: number;
5
+ }
6
+ /** A kind of credit: called with an amount, it gives that many of it. */
7
+ export interface Credit<K extends string = string> {
8
+ (amount: number): CreditAmount<K>;
9
+ /** The credit's name in the application, never changed. */
10
+ readonly key: K;
11
+ }
12
+ /** Declares a kind of credit (D-372). */
13
+ export declare function defineCredit<const K extends string>(definition: {
14
+ readonly key: K;
15
+ }): Credit<K>;
16
+ //# sourceMappingURL=credit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credit.d.ts","sourceRoot":"","sources":["../src/credit.ts"],"names":[],"mappings":"AAMA,qDAAqD;AACrD,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IACtD,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAA;IAClB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CACvB;AAED,yEAAyE;AACzE,MAAM,WAAW,MAAM,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IAChD,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,CAAA;IACjC,2DAA2D;IAC3D,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAA;CACf;AAED,yCAAyC;AACzC,wBAAgB,YAAY,CAAC,KAAK,CAAC,CAAC,SAAS,MAAM,EAAE,UAAU,EAAE;IAChE,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAA;CACf,GAAG,MAAM,CAAC,CAAC,CAAC,CAaZ"}
package/dist/credit.js ADDED
@@ -0,0 +1,18 @@
1
+ // `defineCredit` (D-372): a kind of credit, as blue gems. It is a function:
2
+ // `blueGems(500)` is 500 of them, a value a product gives and, later, the
3
+ // application spends.
4
+ import { Refused } from 'ultimabase';
5
+ import { checkKey, ownKeys } from './keys.js';
6
+ /** Declares a kind of credit (D-372). */
7
+ export function defineCredit(definition) {
8
+ ownKeys('defineCredit', definition, ['key']);
9
+ const { key } = definition;
10
+ checkKey('defineCredit', key);
11
+ const credit = (amount) => {
12
+ if (!Number.isSafeInteger(amount) || amount <= 0) {
13
+ throw new Refused(`${key}(${String(amount)}): an amount is a positive integer.`);
14
+ }
15
+ return Object.freeze({ credit: key, amount });
16
+ };
17
+ return Object.assign(credit, { key });
18
+ }