@midsummer-ai/sdk 0.1.0-staging.3587 → 0.1.0-staging.3590
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/billing/contract.d.mts +29 -0
- package/billing/contract.mjs +121 -0
- package/billing/index.d.mts +89 -0
- package/billing/index.mjs +137 -0
- package/billing/stand-in.d.mts +23 -0
- package/billing/stand-in.mjs +70 -0
- package/package.json +22 -1
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Billing } from "./index.mjs";
|
|
2
|
+
import { StandInProduct } from "./stand-in.mjs";
|
|
3
|
+
//#region src/billing/contract.d.ts
|
|
4
|
+
declare const CONTRACT_PRODUCT: {
|
|
5
|
+
readonly id: "prod_pro";
|
|
6
|
+
readonly name: "Pro";
|
|
7
|
+
readonly interval: "month";
|
|
8
|
+
readonly benefits: readonly [{
|
|
9
|
+
readonly id: "ben_exports";
|
|
10
|
+
readonly name: "Exports";
|
|
11
|
+
}];
|
|
12
|
+
};
|
|
13
|
+
declare const CONTRACT_ONCE: {
|
|
14
|
+
readonly id: "prod_lifetime";
|
|
15
|
+
readonly name: "Lifetime";
|
|
16
|
+
readonly benefits: readonly [{
|
|
17
|
+
readonly id: "ben_support";
|
|
18
|
+
readonly name: "Support";
|
|
19
|
+
}];
|
|
20
|
+
};
|
|
21
|
+
declare const CONTRACT_PRODUCTS: ReadonlyArray<StandInProduct>;
|
|
22
|
+
declare const CONTRACT_CUSTOMERS: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
23
|
+
interface ContractCase {
|
|
24
|
+
readonly name: string;
|
|
25
|
+
run(billing: Billing): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
declare const billingContract: ReadonlyArray<ContractCase>;
|
|
28
|
+
//#endregion
|
|
29
|
+
export { CONTRACT_CUSTOMERS, CONTRACT_ONCE, CONTRACT_PRODUCT, CONTRACT_PRODUCTS, ContractCase, billingContract };
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { BillingError } from "./index.mjs";
|
|
2
|
+
//#region src/billing/contract.ts
|
|
3
|
+
/**
|
|
4
|
+
* Billing's contract: what every engine promises, as cases any test runner can run. The Stand-in runs them in this
|
|
5
|
+
* package; the real Capability runs the same cases against a Project whose store sells `CONTRACT_PRODUCT` (`Pro`,
|
|
6
|
+
* monthly, granting the benefit `Exports`) and `CONTRACT_ONCE` (`Lifetime`, bought once, granting `Support`), where
|
|
7
|
+
* `ada` subscribes to Pro, `lin` bought Lifetime, and `grace` bought nothing.
|
|
8
|
+
*
|
|
9
|
+
* for (const c of billingContract) test(c.name, () => c.run(billing(standIn({ products: CONTRACT_PRODUCTS, customers: CONTRACT_CUSTOMERS }))))
|
|
10
|
+
*/
|
|
11
|
+
const CONTRACT_PRODUCT = {
|
|
12
|
+
id: "prod_pro",
|
|
13
|
+
name: "Pro",
|
|
14
|
+
interval: "month",
|
|
15
|
+
benefits: [{
|
|
16
|
+
id: "ben_exports",
|
|
17
|
+
name: "Exports"
|
|
18
|
+
}]
|
|
19
|
+
};
|
|
20
|
+
const CONTRACT_ONCE = {
|
|
21
|
+
id: "prod_lifetime",
|
|
22
|
+
name: "Lifetime",
|
|
23
|
+
benefits: [{
|
|
24
|
+
id: "ben_support",
|
|
25
|
+
name: "Support"
|
|
26
|
+
}]
|
|
27
|
+
};
|
|
28
|
+
const CONTRACT_PRODUCTS = [CONTRACT_PRODUCT, CONTRACT_ONCE];
|
|
29
|
+
const CONTRACT_CUSTOMERS = {
|
|
30
|
+
ada: ["prod_pro"],
|
|
31
|
+
lin: ["prod_lifetime"]
|
|
32
|
+
};
|
|
33
|
+
const billingContract = [
|
|
34
|
+
{
|
|
35
|
+
name: "a subscriber's state names the product they subscribe to and the benefit it grants",
|
|
36
|
+
async run(billing) {
|
|
37
|
+
const state = await billing.state("ada");
|
|
38
|
+
equal(state.user, "ada", "the user");
|
|
39
|
+
equal(state.subscriptions.map((one) => [
|
|
40
|
+
one.product.id,
|
|
41
|
+
one.product.name,
|
|
42
|
+
one.status
|
|
43
|
+
]), [[
|
|
44
|
+
"prod_pro",
|
|
45
|
+
"Pro",
|
|
46
|
+
"active"
|
|
47
|
+
]], "the subscriptions");
|
|
48
|
+
equal(state.benefits.map((one) => [one.id, one.name]), [["ben_exports", "Exports"]], "the benefits");
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: "has answers for a product by name in any case or by id, and for a benefit by name or id",
|
|
53
|
+
async run(billing) {
|
|
54
|
+
equal(await Promise.all([
|
|
55
|
+
"Pro",
|
|
56
|
+
"pro",
|
|
57
|
+
"prod_pro",
|
|
58
|
+
"Exports",
|
|
59
|
+
"ben_exports"
|
|
60
|
+
].map((one) => billing.has("ada", one))), [
|
|
61
|
+
true,
|
|
62
|
+
true,
|
|
63
|
+
true,
|
|
64
|
+
true,
|
|
65
|
+
true
|
|
66
|
+
], "what ada has");
|
|
67
|
+
equal(await Promise.all(["Lifetime", "Support"].map((one) => billing.has("ada", one))), [false, false], "what ada doesn't have");
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: "a one-time purchase is held by the benefit it grants, never as a subscription",
|
|
72
|
+
async run(billing) {
|
|
73
|
+
equal((await billing.state("lin")).subscriptions, [], "lin's subscriptions");
|
|
74
|
+
equal(await billing.has("lin", "Support"), true, "whether lin has Support");
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
name: "a customer who never bought holds nothing, which is no error",
|
|
79
|
+
async run(billing) {
|
|
80
|
+
equal(await billing.state("grace"), {
|
|
81
|
+
user: "grace",
|
|
82
|
+
subscriptions: [],
|
|
83
|
+
benefits: []
|
|
84
|
+
}, "grace's state");
|
|
85
|
+
equal(await billing.has("grace", "Pro"), false, "whether grace has Pro");
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: "a checkout for a product by name answers an address to send the customer to",
|
|
90
|
+
async run(billing) {
|
|
91
|
+
equal(new URL(await billing.checkout({
|
|
92
|
+
id: "grace",
|
|
93
|
+
email: "grace@example.com"
|
|
94
|
+
}, "Pro", { successUrl: "https://shop.acme.dev/thanks" })).protocol, "https:", "the checkout's protocol");
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
name: "a checkout for a product not sold, or for a customer or address that isn't one, is refused as invalid",
|
|
99
|
+
async run(billing) {
|
|
100
|
+
await refuses(() => billing.checkout("grace", "Platinum"), "invalid");
|
|
101
|
+
await refuses(() => billing.checkout("", "Pro"), "invalid");
|
|
102
|
+
await refuses(() => billing.checkout("grace/../ada", "Pro"), "invalid");
|
|
103
|
+
await refuses(() => billing.checkout("grace", "Pro", { successUrl: "thanks" }), "invalid");
|
|
104
|
+
await refuses(() => billing.has("ada", " "), "invalid");
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
];
|
|
108
|
+
function equal(actual, expected, what) {
|
|
109
|
+
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(`${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
|
|
110
|
+
}
|
|
111
|
+
async function refuses(call, code) {
|
|
112
|
+
try {
|
|
113
|
+
await call();
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (error instanceof BillingError && error.code === code) return;
|
|
116
|
+
throw new Error(`expected ${code}, got ${error instanceof Error ? error.message : String(error)}`);
|
|
117
|
+
}
|
|
118
|
+
throw new Error(`expected ${code}, but it was answered`);
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
export { CONTRACT_CUSTOMERS, CONTRACT_ONCE, CONTRACT_PRODUCT, CONTRACT_PRODUCTS, billingContract };
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
//#region src/billing/index.d.ts
|
|
2
|
+
type BillingErrorCode = "invalid" | "forbidden" | "unavailable";
|
|
3
|
+
declare class BillingError extends Error {
|
|
4
|
+
readonly code: BillingErrorCode;
|
|
5
|
+
constructor(code: BillingErrorCode, message: string);
|
|
6
|
+
}
|
|
7
|
+
/** A customer: your app's user id, or the user with it, and their email to fill in at the checkout. */
|
|
8
|
+
type Customer = string | {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly email?: string;
|
|
11
|
+
};
|
|
12
|
+
/** What a customer has now. Times are milliseconds since the epoch. */
|
|
13
|
+
interface BillingState {
|
|
14
|
+
readonly user: string;
|
|
15
|
+
/** What they subscribe to now, each with its product by id and name. */
|
|
16
|
+
readonly subscriptions: ReadonlyArray<{
|
|
17
|
+
readonly product: {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
};
|
|
21
|
+
readonly status: string;
|
|
22
|
+
readonly interval?: string;
|
|
23
|
+
readonly renewsAt?: number;
|
|
24
|
+
readonly endsAt?: number;
|
|
25
|
+
readonly cancelAtPeriodEnd?: boolean;
|
|
26
|
+
}>;
|
|
27
|
+
/** What they were granted by what they have or bought, such as access to a feature. */
|
|
28
|
+
readonly benefits: ReadonlyArray<{
|
|
29
|
+
readonly id: string;
|
|
30
|
+
readonly name: string;
|
|
31
|
+
}>;
|
|
32
|
+
}
|
|
33
|
+
/** A checkout as the engine takes it, checked. */
|
|
34
|
+
interface CheckedCheckout {
|
|
35
|
+
readonly user: string;
|
|
36
|
+
readonly email?: string;
|
|
37
|
+
readonly product: string;
|
|
38
|
+
readonly successUrl?: string;
|
|
39
|
+
}
|
|
40
|
+
/** Where billing's calls go: the Seam under `billing`. The Stand-in and the real Capability are its Adapters. */
|
|
41
|
+
interface BillingEngine {
|
|
42
|
+
checkout(input: CheckedCheckout): Promise<{
|
|
43
|
+
readonly url: string;
|
|
44
|
+
}>;
|
|
45
|
+
state(user: string): Promise<BillingState>;
|
|
46
|
+
}
|
|
47
|
+
interface Billing {
|
|
48
|
+
/** The address of a checkout for `product`, by name or id, to send the customer to; `successUrl` is where they go once they paid. */
|
|
49
|
+
checkout(customer: Customer, product: string, options?: {
|
|
50
|
+
readonly successUrl?: string;
|
|
51
|
+
}): Promise<string>;
|
|
52
|
+
/** What the customer has now; nothing yet for one who never bought, never an error. */
|
|
53
|
+
state(user: string): Promise<BillingState>;
|
|
54
|
+
/** Whether the customer subscribes to a product, or was granted a benefit, named by its name (any case) or id. */
|
|
55
|
+
has(user: string, benefitOrProduct: string): Promise<boolean>;
|
|
56
|
+
}
|
|
57
|
+
/** A checkout checked as the engine takes it; throws `BillingError("invalid")` saying what is wrong. */
|
|
58
|
+
declare function checkCheckout(customer: Customer, product: string, options?: {
|
|
59
|
+
readonly successUrl?: string;
|
|
60
|
+
}): CheckedCheckout;
|
|
61
|
+
/** Whether `state` has `wanted`: a product subscribed to, or a benefit granted, by name in any case or by id. */
|
|
62
|
+
declare function holds(state: BillingState, wanted: string): boolean;
|
|
63
|
+
/** Billing over `engine`. */
|
|
64
|
+
declare function billingOver(engine: BillingEngine): Billing;
|
|
65
|
+
/**
|
|
66
|
+
* Billing: `billing.has(…)` in a deployment, or `billing(engine).has(…)` over an engine you give, such as the Stand-in.
|
|
67
|
+
*/
|
|
68
|
+
declare const billing: Billing & ((engine?: BillingEngine) => Billing);
|
|
69
|
+
/** What a bound billing handle returns: the value asked for, or the refusal, which crosses a Service Binding as data. */
|
|
70
|
+
type BoundBillingAnswer = {
|
|
71
|
+
readonly value: unknown;
|
|
72
|
+
} | {
|
|
73
|
+
readonly error: {
|
|
74
|
+
readonly code: BillingErrorCode;
|
|
75
|
+
readonly message: string;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
type BillingCall = "checkout" | "state";
|
|
79
|
+
/** What Midsummer hands a deployment as `context.billing`: each call carries its op, and the platform reads what the environment binds. */
|
|
80
|
+
declare function boundBilling(handle: {
|
|
81
|
+
call(op: BillingCall, input: unknown): Promise<BoundBillingAnswer>;
|
|
82
|
+
}): BillingEngine;
|
|
83
|
+
/**
|
|
84
|
+
* The platform's side of a bound handle: checks each call again, as it comes from another Worker's code, and hands it
|
|
85
|
+
* to `engine`, the billing the environment binds. A refusal is returned as data.
|
|
86
|
+
*/
|
|
87
|
+
declare function serveBilling(engine: () => Promise<BillingEngine>): (op: unknown, input: unknown) => Promise<BoundBillingAnswer>;
|
|
88
|
+
//#endregion
|
|
89
|
+
export { Billing, BillingCall, BillingEngine, BillingError, BillingErrorCode, BillingState, BoundBillingAnswer, CheckedCheckout, Customer, billing, billingOver, boundBilling, checkCheckout, holds, serveBilling };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { n as late, r as processEnv, t as here } from "../here-1plIxb0D.mjs";
|
|
2
|
+
//#region src/billing/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* Billing from a Project's code: send a customer to a checkout, and ask what they have bought. Each customer is your
|
|
5
|
+
* app's own user id, so you keep no customer table of your own.
|
|
6
|
+
*
|
|
7
|
+
* import { billing } from "@midsummer-ai/sdk/billing"
|
|
8
|
+
*
|
|
9
|
+
* if (!(await billing.has(user.id, "Pro"))) return Response.redirect(await billing.checkout(user, "Pro", { successUrl: "https://shop.acme.dev/thanks" }))
|
|
10
|
+
* const { subscriptions, benefits } = await billing.state(user.id)
|
|
11
|
+
*
|
|
12
|
+
* In a deployment, in any framework, `billing` sells through what the environment binds (`midsummer billing set`): the
|
|
13
|
+
* live store in production, the sandbox in previews, where nothing is charged. `state` and `has` read what Midsummer
|
|
14
|
+
* keeps of each customer, updated by the store as it changes, so they cost no call to the store and return as fast as
|
|
15
|
+
* any read; a checkout is the one call that reaches it. A product and a benefit are named by their name or id;
|
|
16
|
+
* a name is the same in the sandbox and live, so code names `"Pro"` and works in both.
|
|
17
|
+
*
|
|
18
|
+
* Under `midsummer dev`, `billing` runs on the Stand-in (`@midsummer-ai/sdk/billing/stand-in`), which sells any product
|
|
19
|
+
* named: a checkout completes at once and returns `successUrl`, so the customer has the product right after. In tests,
|
|
20
|
+
* give it the Stand-in yourself: `billing(standIn({ products }))`. Every engine is held to the cases in
|
|
21
|
+
* `@midsummer-ai/sdk/billing/contract`. Every failure is a `BillingError`, whose `code` shows which kind.
|
|
22
|
+
*/
|
|
23
|
+
var BillingError = class extends Error {
|
|
24
|
+
code;
|
|
25
|
+
constructor(code, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.name = "BillingError";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
const USER = /^[^\s/?#][^/?#]{0,255}$/;
|
|
32
|
+
const checkUser = (user) => {
|
|
33
|
+
if (typeof user !== "string" || !USER.test(user)) throw new BillingError("invalid", "a customer is your app's user id: 1 to 256 characters, without / ? or #");
|
|
34
|
+
return user;
|
|
35
|
+
};
|
|
36
|
+
const checkName = (name, what) => {
|
|
37
|
+
if (typeof name !== "string" || !name.trim() || name.length > 200) throw new BillingError("invalid", `name the ${what} by its name or id`);
|
|
38
|
+
return name.trim();
|
|
39
|
+
};
|
|
40
|
+
/** A checkout checked as the engine takes it; throws `BillingError("invalid")` saying what is wrong. */
|
|
41
|
+
function checkCheckout(customer, product, options = {}) {
|
|
42
|
+
const user = checkUser(typeof customer === "string" ? customer : customer?.id);
|
|
43
|
+
const email = typeof customer === "object" ? customer.email : void 0;
|
|
44
|
+
if (email !== void 0 && (typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))) throw new BillingError("invalid", `${String(email)} is not an email address`);
|
|
45
|
+
const successUrl = options.successUrl;
|
|
46
|
+
if (successUrl !== void 0) {
|
|
47
|
+
const url = URL.parse(successUrl);
|
|
48
|
+
if (!url || url.protocol !== "https:" && url.protocol !== "http:") throw new BillingError("invalid", "successUrl is a full http or https address");
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
user,
|
|
52
|
+
product: checkName(product, "product"),
|
|
53
|
+
...email ? { email } : {},
|
|
54
|
+
...successUrl ? { successUrl } : {}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Whether `state` has `wanted`: a product subscribed to, or a benefit granted, by name in any case or by id. */
|
|
58
|
+
function holds(state, wanted) {
|
|
59
|
+
const name = wanted.trim().toLowerCase();
|
|
60
|
+
return state.subscriptions.filter((one) => one.status === "active" || one.status === "trialing").some((one) => one.product.id === wanted || one.product.name.toLowerCase() === name) || state.benefits.some((one) => one.id === wanted || one.name.toLowerCase() === name);
|
|
61
|
+
}
|
|
62
|
+
/** Billing over `engine`. */
|
|
63
|
+
function billingOver(engine) {
|
|
64
|
+
return {
|
|
65
|
+
async checkout(customer, product, options) {
|
|
66
|
+
return (await engine.checkout(checkCheckout(customer, product, options))).url;
|
|
67
|
+
},
|
|
68
|
+
state: async (user) => engine.state(checkUser(user)),
|
|
69
|
+
async has(user, benefitOrProduct) {
|
|
70
|
+
const wanted = checkName(benefitOrProduct, "product or benefit");
|
|
71
|
+
return holds(await engine.state(checkUser(user)), wanted);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** `midsummer dev`'s billing: one Stand-in for the process, sold any product named, its checkouts completing at once. */
|
|
76
|
+
let devEngine;
|
|
77
|
+
/**
|
|
78
|
+
* The engine of the environment this code runs in, made when each call is: what the deployment's request was handed,
|
|
79
|
+
* or under `midsummer dev` the process's Stand-in.
|
|
80
|
+
*/
|
|
81
|
+
function hereEngine() {
|
|
82
|
+
return late(() => {
|
|
83
|
+
const handle = here()?.billing;
|
|
84
|
+
if (handle) return boundBilling(handle);
|
|
85
|
+
if (processEnv().MIDSUMMER_DEV === "1") return devEngine ??= import("./stand-in.mjs").then((found) => found.standIn());
|
|
86
|
+
throw new BillingError("forbidden", "This code runs outside a deployment, so no environment binds billing for it. In tests, give billing an engine: the Stand-in from @midsummer-ai/sdk/billing/stand-in.");
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Billing: `billing.has(…)` in a deployment, or `billing(engine).has(…)` over an engine you give, such as the Stand-in.
|
|
91
|
+
*/
|
|
92
|
+
const billing = Object.assign((engine) => billingOver(engine ?? hereEngine()), billingOver(hereEngine()));
|
|
93
|
+
/** What Midsummer hands a deployment as `context.billing`: each call carries its op, and the platform reads what the environment binds. */
|
|
94
|
+
function boundBilling(handle) {
|
|
95
|
+
const call = async (op, input) => {
|
|
96
|
+
let answer;
|
|
97
|
+
try {
|
|
98
|
+
answer = await handle.call(op, input);
|
|
99
|
+
} catch {
|
|
100
|
+
throw new BillingError("unavailable", "Billing could not be reached");
|
|
101
|
+
}
|
|
102
|
+
if ("value" in answer) return answer.value;
|
|
103
|
+
throw new BillingError(answer.error.code, answer.error.message);
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
checkout: async (input) => await call("checkout", input),
|
|
107
|
+
state: async (user) => await call("state", { user })
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The platform's side of a bound handle: checks each call again, as it comes from another Worker's code, and hands it
|
|
112
|
+
* to `engine`, the billing the environment binds. A refusal is returned as data.
|
|
113
|
+
*/
|
|
114
|
+
function serveBilling(engine) {
|
|
115
|
+
return async (op, input) => {
|
|
116
|
+
try {
|
|
117
|
+
const given = typeof input === "object" && input !== null ? input : {};
|
|
118
|
+
if (op === "state") return { value: await (await engine()).state(checkUser(given.user)) };
|
|
119
|
+
if (op === "checkout") {
|
|
120
|
+
const checked = checkCheckout(typeof given.email === "string" ? {
|
|
121
|
+
id: given.user,
|
|
122
|
+
email: given.email
|
|
123
|
+
} : given.user, given.product, typeof given.successUrl === "string" ? { successUrl: given.successUrl } : {});
|
|
124
|
+
return { value: await (await engine()).checkout(checked) };
|
|
125
|
+
}
|
|
126
|
+
throw new BillingError("invalid", "billing takes checkout and state");
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof BillingError) return { error: {
|
|
129
|
+
code: error.code,
|
|
130
|
+
message: error.message
|
|
131
|
+
} };
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
//#endregion
|
|
137
|
+
export { BillingError, billing, billingOver, boundBilling, checkCheckout, holds, serveBilling };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { BillingEngine } from "./index.mjs";
|
|
2
|
+
//#region src/billing/stand-in.d.ts
|
|
3
|
+
interface StandInProduct {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly name: string;
|
|
6
|
+
/** `month` or `year` for a subscription; none for a one-time purchase, which grants only its benefits. */
|
|
7
|
+
readonly interval?: string;
|
|
8
|
+
readonly benefits?: ReadonlyArray<{
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly name: string;
|
|
11
|
+
}>;
|
|
12
|
+
}
|
|
13
|
+
declare function standIn(options?: {
|
|
14
|
+
readonly products?: ReadonlyArray<StandInProduct>;
|
|
15
|
+
readonly customers?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
16
|
+
}): BillingEngine & {
|
|
17
|
+
readonly checkouts: ReadonlyArray<{
|
|
18
|
+
readonly user: string;
|
|
19
|
+
readonly product: string;
|
|
20
|
+
}>;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { StandInProduct, standIn };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { BillingError } from "./index.mjs";
|
|
2
|
+
//#region src/billing/stand-in.ts
|
|
3
|
+
/**
|
|
4
|
+
* Billing's Stand-in: the Capability's behaviour in memory, for `midsummer dev` and tests. It charges nothing and calls
|
|
5
|
+
* nothing: a checkout completes at once, so the customer has the product (and its benefits) right after, and it
|
|
6
|
+
* returns `successUrl`, or an address that goes nowhere when none is given. It passes the contract
|
|
7
|
+
* (`@midsummer-ai/sdk/billing/contract`) except payment, durability and a store's own checkout page.
|
|
8
|
+
*
|
|
9
|
+
* const engine = standIn({ products: [{ id: "prod_pro", name: "Pro", benefits: [{ id: "ben_exports", name: "Exports" }] }], customers: { ada: ["prod_pro"] } })
|
|
10
|
+
* await billing(engine).has("ada", "Exports") // true
|
|
11
|
+
*
|
|
12
|
+
* With no `products`, any product named is sold, by that name, granting nothing more.
|
|
13
|
+
*/
|
|
14
|
+
function standIn(options = {}) {
|
|
15
|
+
const listed = options.products;
|
|
16
|
+
const held = /* @__PURE__ */ new Map();
|
|
17
|
+
const checkouts = [];
|
|
18
|
+
let count = 0;
|
|
19
|
+
const productNamed = (named) => {
|
|
20
|
+
if (!listed) return {
|
|
21
|
+
id: named,
|
|
22
|
+
name: named,
|
|
23
|
+
interval: "month"
|
|
24
|
+
};
|
|
25
|
+
return listed.find((one) => one.id === named) ?? listed.find((one) => one.name.toLowerCase() === named.toLowerCase());
|
|
26
|
+
};
|
|
27
|
+
const known = /* @__PURE__ */ new Map();
|
|
28
|
+
const hold = (user, product) => {
|
|
29
|
+
known.set(product.id, product);
|
|
30
|
+
held.set(user, (held.get(user) ?? /* @__PURE__ */ new Set()).add(product.id));
|
|
31
|
+
};
|
|
32
|
+
for (const [user, products] of Object.entries(options.customers ?? {})) for (const named of products) {
|
|
33
|
+
const product = productNamed(named);
|
|
34
|
+
if (!product) throw new Error(`The Stand-in sells no product ${named}.`);
|
|
35
|
+
hold(user, product);
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
checkouts,
|
|
39
|
+
async checkout(input) {
|
|
40
|
+
const product = productNamed(input.product);
|
|
41
|
+
if (!product) throw new BillingError("invalid", `No product ${input.product} is sold here.`);
|
|
42
|
+
hold(input.user, product);
|
|
43
|
+
checkouts.push({
|
|
44
|
+
user: input.user,
|
|
45
|
+
product: product.id
|
|
46
|
+
});
|
|
47
|
+
return { url: input.successUrl ?? `https://checkout.stand-in.invalid/${++count}` };
|
|
48
|
+
},
|
|
49
|
+
async state(user) {
|
|
50
|
+
const products = [...held.get(user) ?? []].map((id) => known.get(id));
|
|
51
|
+
return {
|
|
52
|
+
user,
|
|
53
|
+
subscriptions: products.filter((one) => one.interval).map((one) => ({
|
|
54
|
+
product: {
|
|
55
|
+
id: one.id,
|
|
56
|
+
name: one.name
|
|
57
|
+
},
|
|
58
|
+
status: "active",
|
|
59
|
+
interval: one.interval
|
|
60
|
+
})),
|
|
61
|
+
benefits: products.flatMap((one) => one.benefits ?? []).map((one) => ({
|
|
62
|
+
id: one.id,
|
|
63
|
+
name: one.name
|
|
64
|
+
}))
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
export { standIn };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midsummer-ai/sdk",
|
|
3
|
-
"version": "0.1.0-staging.
|
|
3
|
+
"version": "0.1.0-staging.3590",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",
|
|
@@ -127,6 +127,18 @@
|
|
|
127
127
|
"types": "./email/contract.d.mts",
|
|
128
128
|
"import": "./email/contract.mjs"
|
|
129
129
|
},
|
|
130
|
+
"./billing": {
|
|
131
|
+
"types": "./billing/index.d.mts",
|
|
132
|
+
"import": "./billing/index.mjs"
|
|
133
|
+
},
|
|
134
|
+
"./billing/stand-in": {
|
|
135
|
+
"types": "./billing/stand-in.d.mts",
|
|
136
|
+
"import": "./billing/stand-in.mjs"
|
|
137
|
+
},
|
|
138
|
+
"./billing/contract": {
|
|
139
|
+
"types": "./billing/contract.d.mts",
|
|
140
|
+
"import": "./billing/contract.mjs"
|
|
141
|
+
},
|
|
130
142
|
"./apps": {
|
|
131
143
|
"types": "./apps.d.mts",
|
|
132
144
|
"import": "./apps.mjs"
|
|
@@ -263,6 +275,15 @@
|
|
|
263
275
|
"email/contract": [
|
|
264
276
|
"./email/contract.d.mts"
|
|
265
277
|
],
|
|
278
|
+
"billing": [
|
|
279
|
+
"./billing/index.d.mts"
|
|
280
|
+
],
|
|
281
|
+
"billing/stand-in": [
|
|
282
|
+
"./billing/stand-in.d.mts"
|
|
283
|
+
],
|
|
284
|
+
"billing/contract": [
|
|
285
|
+
"./billing/contract.d.mts"
|
|
286
|
+
],
|
|
266
287
|
"apps": [
|
|
267
288
|
"./apps.d.mts"
|
|
268
289
|
],
|