@mccaskie-labs/workbench-plans 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # @mccaskie-labs/workbench-plans
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - No code change. The first version published by the publish workflow, which confirms the package's npm trusted publisher.
8
+
9
+ ## 0.1.0
10
+
11
+ - First version (`docs/capabilities/06-plans-limits.md`, the free part): `createPlans` over the app's own database with `plansMigration` (free monthly allowances from `workbench/plans.json`, per-account feature switches, `use()` checking and counting in one locked step with idempotency keys, `release()`, top-ups, plan changes logged, a daily clean-up, service role only); the sign-up checks in `./signup` (email code, Turnstile, one free account per business identity, a device cookie, keyed hashes only, repeats held for review); the usage card and limit notices in `./ui` (`wb-plan-*`, `PLAN_STYLES`, words in English, Tagalog and Taglish); and `npx workbench-plans generate|migration`, which prints what free costs and refuses a free plan over the Gateway ai cap.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # @mccaskie-labs/workbench-plans
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Plans and usage limits for apps built on Workbench, a private platform: each of the app's own accounts (a venue, a shop) gets a plan with free monthly allowances and feature switches, and repeat free sign-ups are held for review. Spec: `docs/capabilities/06-plans-limits.md`. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
4
+
5
+ ```sh
6
+ npm install @mccaskie-labs/workbench-plans
7
+ ```
8
+
9
+ Two layers, kept apart: the Gateway's budgets cap what the **project** spends in a month and stay the safety net; plans cap what each **account inside the app** may use.
10
+
11
+ ## Set up
12
+
13
+ 1. Write `workbench/plans.json` (the client questions in `capabilities/plans.json` fill it):
14
+
15
+ ```json
16
+ {
17
+ "format": 1,
18
+ "period": "calendar_month",
19
+ "time_zone": "Asia/Manila",
20
+ "meters": { "messages_read": { "label": "Messages read", "unit": "message", "cost_usd": 0.015 } },
21
+ "features": ["quote_links", "ai_scenes"],
22
+ "plans": {
23
+ "free": { "label": "Free", "features": ["quote_links"], "meters": { "messages_read": 30 } },
24
+ "pro": { "label": "Pro", "features": "all", "meters": { "messages_read": 2000 } }
25
+ },
26
+ "default_plan": "free",
27
+ "signup": { "checks": ["email_code", "turnstile", "business_identity", "device_signal"] },
28
+ "budget": { "free_accounts": 50, "ai_cap_usd": 10 }
29
+ }
30
+ ```
31
+
32
+ Plans are in upgrade order, smallest first. `cost_usd` is what one use costs at most through the Gateway; `budget` is how many free accounts to plan for and the project's Gateway `ai` cap a month.
33
+
34
+ 2. `npx workbench-plans generate` checks it, prints what one free account (and all of them) can cost, refuses a free plan over the cap, and writes `src/plans.generated.ts` (`PLANS`, typed). Checks can run `npx workbench-plans generate --check`.
35
+ 3. `npx workbench-plans migration` writes `plansMigration` and its down file into `supabase/migrations` and `supabase/rollback`. It creates functions, so Control asks for approval even on staging.
36
+ 4. Set `PLANS_SIGNAL_SECRET` (at least 32 random characters) as a Worker secret, for the sign-up checks.
37
+
38
+ ## Use
39
+
40
+ ```ts
41
+ import { createPlans } from '@mccaskie-labs/workbench-plans'
42
+ import { PLANS } from './plans.generated'
43
+
44
+ const plans = createPlans({ db: serviceClient, plans: PLANS })
45
+
46
+ const use = await plans.use(venue.id, 'messages_read', { idempotencyKey: requestId, subject: `message:${id}` })
47
+ if (!use.ok) {
48
+ // use.reason: 'allowance_used' (with resets_at and upgrade_to), 'not_on_plan', 'switched_off' or 'account_held'
49
+ }
50
+ try {
51
+ await ai.intake({ text })
52
+ } catch (e) {
53
+ await plans.release(use.useId!) // the paid call failed: give the use back
54
+ throw e
55
+ }
56
+ ```
57
+
58
+ - `use()` is one database function that locks the account's row, so ten parallel calls with one left can't each see "1 left". A refusal counts nothing. The same `idempotencyKey` twice counts once.
59
+ - A meter's allowance on the account's plan decides `use()` (an allowance of 0 answers `not_on_plan`). A feature with the same name as a meter, switched off for the account, stops the meter too.
60
+ - `can(account, feature)`: on the plan **and** switched on (Imprint's rule). No counting.
61
+ - `status(account)`: the plan, each feature's state, each meter's used, limit and left, and `resets_at` (midnight on the 1st in `time_zone`).
62
+ - `setPlan`, `setSwitch` (off works on anything; on only what the plan has), `grant(account, meter, extra, until, by, reason)` for a one-off top-up. Each is logged in `plan_changes` with who and why. `setPlan` is where a payments webhook will call later.
63
+ - `cleanup()` once a day from the app's cron: uses and top-ups go after 13 months, sign-up signals after 12.
64
+ - Use the service client, server side: the functions are the service role's only, because the allowances come from the repo and a signed-in user calling them directly could pass their own.
65
+
66
+ ## Sign-up checks
67
+
68
+ ```ts
69
+ import { createSignup, deviceCookie } from '@mccaskie-labs/workbench-plans/signup'
70
+
71
+ const device = deviceCookie(request) // { id, setCookie? }: send setCookie back when present
72
+ const r = await createSignup({ db: serviceClient, plans: PLANS, secret: env.PLANS_SIGNAL_SECRET }).check({
73
+ account: venue.id,
74
+ email: user.email, emailVerified: true, // after the emailed-code sign-in
75
+ turnstile: true, // after verifying the form's Turnstile token
76
+ page: form.page, businessName: form.name, city: form.city, phone: form.phone,
77
+ deviceId: device.id, ip: request.headers.get('cf-connecting-ip') ?? undefined, userAgent: request.headers.get('user-agent') ?? undefined,
78
+ })
79
+ // r.status 'active' | 'held' (or 'refused' with "repeats": "refuse"); r.matches [{ kind: 'page', accounts: ['villa-sol'] }]
80
+ ```
81
+
82
+ | Check | Matches |
83
+ | --- | --- |
84
+ | `email_code` | The signed-in address, with `+tags` dropped and Gmail's dots ignored |
85
+ | `turnstile` | Nothing: the app's Turnstile pass is required |
86
+ | `business_identity` | The Facebook Page address in any form (`fb.com/villasol`, `https://www.facebook.com/villasol/`, `m.facebook.com/villasol?ref=…`), the business name with its city, and the phone number (`0917…` and `+63 917…` alike). One free account per identity |
87
+ | `device_signal` | The `wb_device` cookie: more than 2 sign-ups from one device in 30 days. A hash of the day, the network (IP /24) and the browser is kept too, never matched |
88
+
89
+ Everything is stored as an HMAC with `PLANS_SIGNAL_SECRET`, never the value; no IP address is stored. A repeat is created **held**: it can set up, but `use()` answers `account_held` until the admin clears it with `plans.clearHold(account, by, reason)`. `plans.held()` lists them with what each matched. The app's privacy notice must say it keeps a device cookie.
90
+
91
+ ## Usage card and notices
92
+
93
+ ```ts
94
+ import { renderLimit, renderUsage, PLAN_WORDS } from '@mccaskie-labs/workbench-plans/ui'
95
+
96
+ renderUsage(await plans.status(venue.id), PLANS, { t, upgradeHref: '/account/plan', upgrade: { key: 'basic', label: 'Basic' } })
97
+ renderLimit(use, 'messages_read', PLANS, { plan: 'free', t, upgradeHref: '/account/plan' })
98
+ // "You've used this month's 30 free messages read. They come back on 1 Dec, or switch to Basic."
99
+ ```
100
+
101
+ Every element has a `wb-plan-*` class with a default rule in `PLAN_STYLES` (`./styles`); `npx workbench-ui styles` writes them into the project's `public/styles/workbench.css`, and the project restyles them in `project.css`. The words are `ui.wbplan.*` in English, Tagalog and Taglish (`PLAN_WORDS`); have a fluent reader check the Tagalog and Taglish before a client sees them.
102
+
103
+ ## Not yet
104
+
105
+ Paid tiers wait for payments (a paid plan is set by hand with `setPlan` until then). Phone codes need a text-message service, and Facebook sign-up needs Meta; the generator refuses both checks until they exist.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import type { PlansConfig } from "./types.ts";
3
+ export declare const PLANS_FILE = "workbench/plans.json";
4
+ export declare const PLANS_MODULE = "src/plans.generated.ts";
5
+ /** What the free plan costs, in lines for the owner. */
6
+ export declare function costLines(c: PlansConfig): string[];
7
+ /** The generated module for a checked config. */
8
+ export declare function moduleText(c: PlansConfig): string;
9
+ /** Reads and checks the project's plans.json. Throws naming every problem. */
10
+ export declare function readPlans(dir: string): PlansConfig;
11
+ /** Runs one command; returns the exit code. */
12
+ export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
package/dist/cli.js ADDED
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ // `npx workbench-plans generate [--check] [dir]`, run in a project's folder:
3
+ // reads workbench/plans.json, checks it (unknown features, meters no plan
4
+ // uses, a free plan that could pass the Gateway ai cap), prints what the free
5
+ // plan can cost, and writes src/plans.generated.ts: PLANS for createPlans and
6
+ // createSignup, typed so a misspelt meter or feature fails the typecheck.
7
+ // --check writes nothing and fails when the file is out of date or wrong.
8
+ //
9
+ // `npx workbench-plans migration [dir]` writes plansMigration into
10
+ // supabase/migrations/<timestamp>_workbench_plans.sql with its down file in
11
+ // supabase/rollback/, unless a plans migration is already there.
12
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { freeCost, plansProblems } from "./config.js";
16
+ import { plansMigration } from "./migration.js";
17
+ const USAGE = "usage: workbench-plans generate [--check] [dir]\n workbench-plans migration [dir]";
18
+ export const PLANS_FILE = "workbench/plans.json";
19
+ export const PLANS_MODULE = "src/plans.generated.ts";
20
+ const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
21
+ const dollars = (n) => `US$${n.toFixed(2)}`;
22
+ /** A unit cost as given (US$0.015), with at least two decimals. */
23
+ const unitDollars = (n) => (Number.isInteger(Math.round(n * 1e6) / 1e4) ? dollars(n) : `US$${n}`);
24
+ /** What the free plan costs, in lines for the owner. */
25
+ export function costLines(c) {
26
+ const f = freeCost(c);
27
+ const plan = c.plans[c.default_plan].label;
28
+ const lines = [`What one ${plan} account costs at most a month, using every allowance:`];
29
+ for (const m of f.meters) {
30
+ if (m.allowance === 0)
31
+ continue;
32
+ lines.push(` ${c.meters[m.meter].label}: ${m.allowance} × ${m.cost_usd === null ? "no cost given" : unitDollars(m.cost_usd)} = ${dollars(m.usd)}`);
33
+ }
34
+ lines.push(` Total: ${dollars(f.per_account_usd)} an account`);
35
+ if (f.free_accounts !== null) {
36
+ lines.push(`With ${f.free_accounts} ${plan} accounts: ${dollars(f.total_usd)} a month, against the Gateway ai cap of ${dollars(f.cap_usd)}${f.over_cap ? " (OVER)" : ""}.`);
37
+ }
38
+ else {
39
+ lines.push(`Add "budget": { "free_accounts": <how many you expect>, "ai_cap_usd": <the Gateway ai cap> } to check it against the cap.`);
40
+ }
41
+ return lines;
42
+ }
43
+ /** The generated module for a checked config. */
44
+ export function moduleText(c) {
45
+ return [
46
+ `// Generated by \`npx workbench-plans generate\` from ${PLANS_FILE}. Don't edit: change the`,
47
+ "// JSON and generate again (Checks runs `npx workbench-plans generate --check`).",
48
+ "",
49
+ 'import type { PlansConfig } from "@mccaskie-labs/workbench-plans";',
50
+ "",
51
+ `export const PLANS = ${JSON.stringify(c, null, 2)} as const satisfies PlansConfig;`,
52
+ "",
53
+ "export type MeterKey = keyof typeof PLANS.meters;",
54
+ "export type FeatureKey = (typeof PLANS.features)[number];",
55
+ "export type PlanKey = keyof typeof PLANS.plans;",
56
+ "",
57
+ ].join("\n");
58
+ }
59
+ /** Reads and checks the project's plans.json. Throws naming every problem. */
60
+ export function readPlans(dir) {
61
+ const path = join(dir, PLANS_FILE);
62
+ if (!existsSync(path))
63
+ throw new Error(`${PLANS_FILE} is missing: answer the plans questions first (capabilities/plans.json, offer)`);
64
+ let parsed;
65
+ try {
66
+ parsed = JSON.parse(read(path));
67
+ }
68
+ catch (e) {
69
+ throw new Error(`${PLANS_FILE}: not valid JSON (${e.message})`);
70
+ }
71
+ const problems = plansProblems(parsed, PLANS_FILE);
72
+ if (problems.length)
73
+ throw new Error(problems.join("\n"));
74
+ return parsed;
75
+ }
76
+ function migrationStamp(at) {
77
+ return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
78
+ }
79
+ /** Runs one command; returns the exit code. */
80
+ export function run(argv, log = console.log, err = console.error) {
81
+ const [command, ...rest] = argv;
82
+ const check = rest.includes("--check");
83
+ const bad = rest.find((a) => a.startsWith("--") && a !== "--check");
84
+ if (bad || (command !== "generate" && command !== "migration") || (command === "migration" && check)) {
85
+ err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
86
+ return 2;
87
+ }
88
+ const dir = resolve(rest.find((a) => !a.startsWith("--")) ?? ".");
89
+ try {
90
+ if (command === "migration") {
91
+ const folder = join(dir, "supabase/migrations");
92
+ if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_plans.sql"))) {
93
+ log("supabase/migrations already has the plans migration; nothing written");
94
+ return 0;
95
+ }
96
+ const name = `${migrationStamp(new Date())}_workbench_plans.sql`;
97
+ mkdirSync(folder, { recursive: true });
98
+ mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
99
+ writeFileSync(join(folder, name), `-- workbench-plans: plans and usage limits (docs/capabilities/06-plans-limits.md)\n${plansMigration.up}`);
100
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${plansMigration.down}`);
101
+ log(`wrote supabase/migrations/${name} and its down file`);
102
+ return 0;
103
+ }
104
+ const c = readPlans(dir);
105
+ for (const line of costLines(c))
106
+ log(line);
107
+ const out = join(dir, PLANS_MODULE);
108
+ const text = moduleText(c);
109
+ const current = existsSync(out) ? read(out) : null;
110
+ if (check) {
111
+ if (current !== text) {
112
+ err(`${PLANS_MODULE} is out of date: run \`npx workbench-plans generate\` and commit it`);
113
+ return 1;
114
+ }
115
+ log(`${PLANS_MODULE} is current`);
116
+ return 0;
117
+ }
118
+ if (current !== text) {
119
+ mkdirSync(dirname(out), { recursive: true });
120
+ writeFileSync(out, text);
121
+ log(`wrote ${PLANS_MODULE}`);
122
+ }
123
+ else
124
+ log(`${PLANS_MODULE} is current`);
125
+ return 0;
126
+ }
127
+ catch (e) {
128
+ err(e.message);
129
+ return 1;
130
+ }
131
+ }
132
+ const isMain = (() => {
133
+ try {
134
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ })();
140
+ if (isMain)
141
+ process.exitCode = run(process.argv.slice(2));
@@ -0,0 +1,29 @@
1
+ import type { PlansConfig } from "./types.ts";
2
+ /** Every problem with the file, or none. */
3
+ export declare function plansProblems(input: unknown, where?: string): string[];
4
+ /** The file, checked: throws a PlansError naming every problem. */
5
+ export declare function checkPlans<C extends PlansConfig>(input: C, where?: string): C;
6
+ export interface FreeCost {
7
+ /** One free account using every allowance, in US dollars. */
8
+ per_account_usd: number;
9
+ /** Each meter's share of that. */
10
+ meters: {
11
+ meter: string;
12
+ allowance: number;
13
+ cost_usd: number | null;
14
+ usd: number;
15
+ }[];
16
+ free_accounts: number | null;
17
+ /** per_account_usd × free_accounts, or per_account_usd when the file has no budget. */
18
+ total_usd: number;
19
+ cap_usd: number | null;
20
+ over_cap: boolean;
21
+ }
22
+ /** What the default (free) plan costs if every free account uses all of it. */
23
+ export declare function freeCost(c: PlansConfig): FreeCost;
24
+ /** The plan's features. */
25
+ export declare function planFeatures(c: PlansConfig, plan: string): readonly string[];
26
+ /** The plans that include a feature, in upgrade order. */
27
+ export declare function plansWith(c: PlansConfig, feature: string): string[];
28
+ /** The first plan after `plan` (in upgrade order) that passes the test, if any. */
29
+ export declare function upgradeFrom(c: PlansConfig, plan: string, test: (k: string) => boolean): string | undefined;
package/dist/config.js ADDED
@@ -0,0 +1,174 @@
1
+ // Checks workbench/plans.json (docs/capabilities/06-plans-limits.md, "Config
2
+ // format") and works out what the free plan can cost. The generator runs
3
+ // these before it writes src/plans.generated.ts, and createPlans runs the
4
+ // check again at startup, so a bad file never reaches an account.
5
+ import { PlansError } from "./errors.js";
6
+ const KEY = /^[a-z][a-z0-9_]{0,39}$/;
7
+ /** Checks a project can switch on today. */
8
+ const BUILT_CHECKS = ["email_code", "turnstile", "business_identity", "device_signal"];
9
+ /** Checks the spec lists that wait for a vendor. */
10
+ const LATER_CHECKS = {
11
+ phone_code: "phone codes need a text-message service, which Workbench doesn't have yet",
12
+ facebook_login: "Facebook sign-up needs Meta, which is deferred (docs/capabilities/meta-api.md)",
13
+ };
14
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
15
+ const isWhole = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
16
+ function validTimeZone(tz) {
17
+ try {
18
+ new Intl.DateTimeFormat("en", { timeZone: tz });
19
+ return true;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ /** Every problem with the file, or none. */
26
+ export function plansProblems(input, where = "workbench/plans.json") {
27
+ const p = [];
28
+ if (!isObject(input))
29
+ return [`${where}: not a JSON object`];
30
+ const c = input;
31
+ if (c.format !== 1)
32
+ p.push(`${where}: "format" must be 1`);
33
+ if (c.period !== "calendar_month")
34
+ p.push(`${where}: "period" must be "calendar_month" (the only period so far)`);
35
+ if (typeof c.time_zone !== "string" || !validTimeZone(c.time_zone))
36
+ p.push(`${where}: "time_zone" must be a time zone name, such as "Asia/Manila"`);
37
+ const meters = isObject(c.meters) ? c.meters : {};
38
+ if (!isObject(c.meters) || Object.keys(meters).length === 0)
39
+ p.push(`${where}: "meters" must name at least one meter`);
40
+ for (const [k, m] of Object.entries(meters)) {
41
+ if (!KEY.test(k))
42
+ p.push(`${where}: meter "${k}" must be lower case letters, digits and _`);
43
+ if (!isObject(m) || typeof m.label !== "string" || !m.label.trim() || typeof m.unit !== "string" || !m.unit.trim()) {
44
+ p.push(`${where}: meter "${k}" needs a "label" and a "unit"`);
45
+ }
46
+ else if (m.cost_usd !== undefined && (typeof m.cost_usd !== "number" || !(m.cost_usd >= 0))) {
47
+ p.push(`${where}: meter "${k}": "cost_usd" must be a number, 0 or more`);
48
+ }
49
+ }
50
+ const features = Array.isArray(c.features) ? c.features : [];
51
+ if (!Array.isArray(c.features))
52
+ p.push(`${where}: "features" must be a list`);
53
+ const seen = new Set();
54
+ for (const f of features) {
55
+ if (typeof f !== "string" || !KEY.test(f))
56
+ p.push(`${where}: feature ${JSON.stringify(f)} must be lower case letters, digits and _`);
57
+ else if (seen.has(f))
58
+ p.push(`${where}: feature "${f}" is listed twice`);
59
+ else
60
+ seen.add(f);
61
+ }
62
+ const plans = isObject(c.plans) ? c.plans : {};
63
+ if (!isObject(c.plans) || Object.keys(plans).length === 0)
64
+ p.push(`${where}: "plans" must name at least one plan`);
65
+ const usedMeters = new Set();
66
+ for (const [k, plan] of Object.entries(plans)) {
67
+ if (!KEY.test(k))
68
+ p.push(`${where}: plan "${k}" must be lower case letters, digits and _`);
69
+ if (!isObject(plan) || typeof plan.label !== "string" || !plan.label.trim()) {
70
+ p.push(`${where}: plan "${k}" needs a "label"`);
71
+ continue;
72
+ }
73
+ if (plan.features !== "all") {
74
+ if (!Array.isArray(plan.features))
75
+ p.push(`${where}: plan "${k}": "features" must be a list or "all"`);
76
+ else
77
+ for (const f of plan.features)
78
+ if (!seen.has(f))
79
+ p.push(`${where}: plan "${k}" names an unknown feature ${JSON.stringify(f)}`);
80
+ }
81
+ if (!isObject(plan.meters)) {
82
+ p.push(`${where}: plan "${k}": "meters" must be an object of monthly allowances`);
83
+ continue;
84
+ }
85
+ for (const [m, n] of Object.entries(plan.meters)) {
86
+ if (!Object.hasOwn(meters, m))
87
+ p.push(`${where}: plan "${k}" names an unknown meter "${m}"`);
88
+ else
89
+ usedMeters.add(m);
90
+ if (!isWhole(n))
91
+ p.push(`${where}: plan "${k}": the allowance of "${m}" must be a whole number, 0 or more`);
92
+ }
93
+ }
94
+ for (const m of Object.keys(meters))
95
+ if (!usedMeters.has(m))
96
+ p.push(`${where}: meter "${m}" is used by no plan`);
97
+ if (typeof c.default_plan !== "string" || !Object.hasOwn(plans, c.default_plan))
98
+ p.push(`${where}: "default_plan" must name one of the plans`);
99
+ if (c.signup !== undefined) {
100
+ const s = c.signup;
101
+ if (!isObject(s) || !Array.isArray(s.checks))
102
+ p.push(`${where}: "signup" needs a "checks" list`);
103
+ else {
104
+ for (const check of s.checks) {
105
+ if (typeof check === "string" && LATER_CHECKS[check])
106
+ p.push(`${where}: sign-up check "${check}" isn't built yet: ${LATER_CHECKS[check]}`);
107
+ else if (!BUILT_CHECKS.includes(check))
108
+ p.push(`${where}: unknown sign-up check ${JSON.stringify(check)}`);
109
+ }
110
+ if (s.free_accounts_per_identity !== undefined && !(isWhole(s.free_accounts_per_identity) && s.free_accounts_per_identity >= 1)) {
111
+ p.push(`${where}: "signup.free_accounts_per_identity" must be a whole number, 1 or more`);
112
+ }
113
+ if (s.repeats !== undefined && s.repeats !== "hold" && s.repeats !== "refuse")
114
+ p.push(`${where}: "signup.repeats" must be "hold" or "refuse"`);
115
+ if (s.device !== undefined) {
116
+ const d = s.device;
117
+ if (!isObject(d) || (d.max !== undefined && !(isWhole(d.max) && d.max >= 1)) || (d.window_days !== undefined && !(isWhole(d.window_days) && d.window_days >= 1 && d.window_days <= 365))) {
118
+ p.push(`${where}: "signup.device" takes "max" (1 or more) and "window_days" (1 to 365)`);
119
+ }
120
+ }
121
+ }
122
+ }
123
+ if (c.budget !== undefined) {
124
+ const b = c.budget;
125
+ if (!isObject(b) || !(isWhole(b.free_accounts) && b.free_accounts >= 1) || typeof b.ai_cap_usd !== "number" || !(b.ai_cap_usd >= 0)) {
126
+ p.push(`${where}: "budget" needs "free_accounts" (1 or more) and "ai_cap_usd" (the project's Gateway ai cap a month)`);
127
+ }
128
+ }
129
+ if (p.length === 0) {
130
+ const cost = freeCost(c);
131
+ if (cost.over_cap) {
132
+ p.push(`${where}: the free plan could cost US$${cost.total_usd.toFixed(2)} a month (${cost.free_accounts} free accounts × US$${cost.per_account_usd.toFixed(2)}), over the Gateway ai cap of US$${cost.cap_usd.toFixed(2)}. Lower the free allowances or raise the cap first.`);
133
+ }
134
+ }
135
+ return p;
136
+ }
137
+ /** The file, checked: throws a PlansError naming every problem. */
138
+ export function checkPlans(input, where) {
139
+ const p = plansProblems(input, where);
140
+ if (p.length)
141
+ throw new PlansError("bad_config", p.join("\n"));
142
+ return input;
143
+ }
144
+ /** What the default (free) plan costs if every free account uses all of it. */
145
+ export function freeCost(c) {
146
+ const plan = c.plans[c.default_plan];
147
+ const meters = Object.entries(c.meters).map(([meter, m]) => {
148
+ const allowance = plan.meters[meter] ?? 0;
149
+ const cost = m.cost_usd ?? null;
150
+ return { meter, allowance, cost_usd: cost, usd: allowance * (cost ?? 0) };
151
+ });
152
+ const per = meters.reduce((s, m) => s + m.usd, 0);
153
+ const n = c.budget?.free_accounts ?? null;
154
+ const total = per * (n ?? 1);
155
+ const cap = c.budget?.ai_cap_usd ?? null;
156
+ return { per_account_usd: per, meters, free_accounts: n, total_usd: total, cap_usd: cap, over_cap: cap !== null && total > cap + 1e-9 };
157
+ }
158
+ /** The plan's features. */
159
+ export function planFeatures(c, plan) {
160
+ const p = c.plans[plan];
161
+ if (!p)
162
+ return [];
163
+ return p.features === "all" ? c.features : p.features;
164
+ }
165
+ /** The plans that include a feature, in upgrade order. */
166
+ export function plansWith(c, feature) {
167
+ return Object.keys(c.plans).filter((k) => planFeatures(c, k).includes(feature));
168
+ }
169
+ /** The first plan after `plan` (in upgrade order) that passes the test, if any. */
170
+ export function upgradeFrom(c, plan, test) {
171
+ const keys = Object.keys(c.plans);
172
+ const from = keys.indexOf(plan);
173
+ return keys.slice(from + 1).find(test);
174
+ }
@@ -0,0 +1,19 @@
1
+ export type PlansErrorCode =
2
+ /** workbench/plans.json is out of shape. */
3
+ "bad_config"
4
+ /** A call's arguments are out of shape: an unknown meter, feature or plan, a bad amount. */
5
+ | "bad_input"
6
+ /** No such account yet: sign it up first (the project has sign-up checks). */
7
+ | "unknown_account"
8
+ /** The account is already signed up. */
9
+ | "account_exists"
10
+ /** setSwitch tried to turn on a feature the account's plan lacks. */
11
+ | "not_on_plan"
12
+ /** A sign-up check the project switched on had no evidence (no verified email code, no Turnstile pass). */
13
+ | "check_missing"
14
+ /** The database refused or failed. */
15
+ | "store_failed";
16
+ export declare class PlansError extends Error {
17
+ readonly code: PlansErrorCode;
18
+ constructor(code: PlansErrorCode, message: string);
19
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,11 @@
1
+ // Every failure carries a permanent code, so an app can act on it without
2
+ // reading the words. A refusal (allowance used, account held) is not an
3
+ // error: use() and can() answer it as { ok: false }.
4
+ export class PlansError extends Error {
5
+ code;
6
+ constructor(code, message) {
7
+ super(message);
8
+ this.name = "PlansError";
9
+ this.code = code;
10
+ }
11
+ }
@@ -0,0 +1,6 @@
1
+ export { createPlans, type Plans, type PlansClient, type PlansOptions } from "./plans.ts";
2
+ export { checkPlans, plansProblems, freeCost, type FreeCost } from "./config.ts";
3
+ export { periodOf, resetsAt } from "./period.ts";
4
+ export { plansMigration } from "./migration.ts";
5
+ export { PlansError, type PlansErrorCode } from "./errors.ts";
6
+ export type { Allowed, FeatureKey, FeatureState, FreeBudget, HoldMatch, MeterConfig, MeterKey, MeterStatus, PlanConfig, PlanKey, PlansConfig, PlanStatus, RefusalReason, SignupCheck, SignupConfig, Subject, UseRequest, } from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // @mccaskie-labs/workbench-plans: plans and usage limits for the app's own
2
+ // accounts (docs/capabilities/06-plans-limits.md): free monthly allowances,
3
+ // per-account feature switches, and use(), which checks and counts in one
4
+ // locked step. Tables in the app's own database (plansMigration). The sign-up
5
+ // checks are in the ./signup entry, the usage card in ./ui.
6
+ export { createPlans } from "./plans.js";
7
+ export { checkPlans, plansProblems, freeCost } from "./config.js";
8
+ export { periodOf, resetsAt } from "./period.js";
9
+ export { plansMigration } from "./migration.js";
10
+ export { PlansError } from "./errors.js";
@@ -0,0 +1,4 @@
1
+ export declare const plansMigration: {
2
+ up: string;
3
+ down: string;
4
+ };