create-disposabl-app 0.13.4 → 0.14.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/disposabl.js CHANGED
@@ -5,7 +5,7 @@ import { lock } from "proper-lockfile";
5
5
  // ../cli/package.json
6
6
  var package_default = {
7
7
  name: "@disposabl/cli",
8
- version: "0.13.4",
8
+ version: "0.14.0",
9
9
  type: "module",
10
10
  description: "Command-line access to your Disposabl app",
11
11
  license: "MIT",
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
8
8
  import { Command, CommanderError } from "commander";
9
9
  import * as p2 from "@clack/prompts";
10
10
  // package.json
11
- var version = "0.13.4";
11
+ var version = "0.14.0";
12
12
 
13
13
  // ../disposabl-kit/platforms.ts
14
14
  var platforms = [
@@ -131,6 +131,9 @@ jobs:
131
131
  target=()
132
132
  if [[ "$CHANNEL" != production ]]; then export AUTH_TARGET="--preview-name $CHANNEL"; target=(--preview-name "$CHANNEL"); fi
133
133
  bun x --no-install convex deploy --yes "${target[@]}" --cmd-url-env-var-name CONVEX_URL --cmd 'for name in CONVEX_URL CONVEX_SITE_URL; do value=$(printenv "$name"); test -n "$value" || exit 1; for prefix in "" VITE_ EXPO_PUBLIC_; do export "$prefix$name=$value"; printf "%s=%s\n" "$prefix$name" "$value" | tee -a "$GITHUB_ENV" >> "$GITHUB_OUTPUT"; done; done; bun run --cwd ../.. build --filter=@disposabl/web'
134
+ setup_target=(--prod)
135
+ if [[ "$CHANNEL" != production ]]; then setup_target=("${target[@]}"); fi
136
+ bun x --no-install convex run "${setup_target[@]}" billing:setup '{}'
134
137
  bun x --no-install static-hosting upload $AUTH_TARGET --no-spa --dist ../../apps/web/dist/client
135
138
  - name: Report web result
136
139
  if: always()
@@ -224,9 +227,19 @@ jobs:
224
227
  run: bash "$GITHUB_WORKSPACE/.github/scripts/mobile.sh" android-build
225
228
  - *publish
226
229
  - *artifacts
227
- - name: Report Android failure
228
- if: failure() || cancelled()
229
- run: node .github/scripts/disposabl.mjs report android failed
230
+ android-failure:
231
+ name: Report Android failure
232
+ needs: android
233
+ if: failure() && needs.android.result == 'failure'
234
+ permissions:
235
+ contents: read
236
+ id-token: write
237
+ runs-on: *linux-runner
238
+ timeout-minutes: 5
239
+ steps:
240
+ - *checkout
241
+ - *node
242
+ - run: node .github/scripts/disposabl.mjs report android failed
230
243
  ios-preview:
231
244
  name: iOS simulator preview
232
245
  needs: [changes, web]
@@ -1,4 +1,5 @@
1
1
  export {
2
+ setup,
2
3
  snapshot,
3
4
  checkout,
4
5
  portal,
@@ -5,7 +5,7 @@
5
5
  "scripts": {
6
6
  "generate": "bun generate.ts",
7
7
  "generate:watch": "bun generate.ts --watch",
8
- "dev": "convex dev",
8
+ "dev": "convex dev --run billing:setup",
9
9
  "logs": "convex logs",
10
10
  "typecheck": "tsc -p convex",
11
11
  "lint": "eslint . --report-unused-disable-directives --max-warnings 0",
@@ -2,9 +2,27 @@
2
2
 
3
3
  Payments is optional and includes authentication. Select `payments` in `disposabl.json`; the server checks this selection before reading credentials or calling Autumn. With it off, the pricing page blocks purchases and no billing credentials are needed. The authenticated Convex Auth user ID is the Autumn customer ID. Never use a client-supplied customer ID or price.
4
4
 
5
- Set the Autumn environment default currency to match `payments/config.ts` (USD by default) and verify both prices in the provider preview. For a separate Autumn test environment, configure `AUTUMN_SECRET_KEY` and `BILLING_RETURN_URL` on that app's Convex deployment. The latter must be the absolute HTTPS URL of its `/pricing` page (HTTP localhost is allowed for development), without query or fragment. Do not store the secret in the frontend or `disposabl.json`. Set the corresponding live values separately only when ready to launch.
5
+ Before first setup, the **Autumn organization's default currency must match `pricing.currency`** in `payments/config.ts`, USD in the starter. Base price amounts use that organization currency; the create-plan request does not select a currency. Setup neither changes nor verifies the organization currency. Autumn `accounts.get` describes a customer group, not the organization, and cannot verify this prerequisite. Check the organization settings and both prices in Autumn before accepting purchases.
6
6
 
7
- `payments/autumn.config.example` defines the `credits` consumable feature, $5 monthly plan with 500 credits per cycle, and $5 one-off prepaid top-up for 500 credits. The editable defaults live in `payments/config.ts`; checkout quantities, the web pricing page, mobile allowance text, and the Autumn example use this same configuration. Copy both files into a separate configuration project with `atmn@2.0.218` installed, naming the example `autumn.config.ts` and keeping `config.ts` alongside it. After editing prices or credits, apply the matching Autumn and store configuration before deploying the app. Changing the local file alone does not update provider prices. Preview with `atmn push` before applying to a dedicated Autumn environment. Its lists are complete: a push can delete unlisted plans and features. Review the diff and test repeated top-ups, renewals and cancellation in sandbox before taking payment. The one-off prepaid credits are documented to last forever; subscription credits reset each cycle. Autumn's docs do not establish that subscription credits survive cancellation. Do not promise that they do. The provider balance is authoritative; a redirect alone does not grant credits. This foundation does not implement usage charging.
7
+ Configure `AUTUMN_SECRET_KEY` and `BILLING_RETURN_URL` on this app's Convex deployment. The return URL is needed for checkout, not catalog setup; it must be the absolute HTTPS URL of the app's `/pricing` page, without query or fragment. HTTP localhost is allowed for development. Use sandbox credentials for development and preview deployments and configure live credentials separately when ready to launch. Never store the secret in the frontend or `disposabl.json`.
8
+
9
+ ## Catalog initialization
10
+
11
+ `payments/config.ts` is the editable source for plan IDs, prices, credits and currency. The default catalog has a consumable `credits` feature, a $5 monthly plan with 500 included credits resetting each month, and a $5 prepaid top-up with `billing_units: 500` and `interval: "one_off"`. Top-ups have no reset or expiry configuration. Web checkout sends exactly that credit quantity. The web pricing page, mobile allowance text and optional Autumn configuration example use the same source.
12
+
13
+ The internal Convex action `billing:setup` takes `{}` and returns `{ enabled, created, preserved }`. It is re-exported by both the app backend and starter backend. With payments disabled, it returns before reading credentials or calling Autumn. When enabled without `AUTUMN_SECRET_KEY`, it fails with a setup message identifying the missing deployment credential. Customer checkout never initializes the catalog.
14
+
15
+ Setup uses the existing REST helper with API version `2.6.0`. It reads `features.list` and `plans.list` with `include_archived` and `all_versions`, validates both responses, then creates only missing configured IDs through `features.create` and `plans.create`. There are at most two reads and three creates per invocation. It never updates, deletes, archives or reactivates entries. Existing custom prices, credit definitions, archived plans and unrelated entries remain untouched. A preserved entry means its ID already exists, not that its pricing or usability matches the app. Review existing entries manually.
16
+
17
+ Any read error, including unauthorized or 404, stops setup without writes. A failed or uncertain create stops the invocation without an automatic retry. Rerun setup after checking the provider: the next run reads provider state and resumes from entries already created. Concurrent runs may collide and one may fail; rerunning preserves the winning entries. There is no cross-provider transaction, rollback or automatic reconciliation.
18
+
19
+ `bun run dev` starts the backend with `convex dev --run billing:setup`. The installed Convex CLI runs it after the first successful push in each dev process, against that same selected deployment. CI runs setup after `convex deploy` succeeds and before the web upload, using the same preview name or an explicit production target and the existing deploy key. Setup failure prevents that upload but does not undo the backend deploy. No new deployment selection or credentials are introduced.
20
+
21
+ For a manual retry, run from `packages/backend` with an explicit target: `bun x --no-install convex run --preview-name <channel> billing:setup '{}'` for the existing preview, or `bun x --no-install convex run --prod billing:setup '{}'` for production. For development, restart the existing dev process. Verify the target and its Autumn key first.
22
+
23
+ After editing prices, credits or currency for existing IDs, apply matching changes in Autumn and the native stores before deploying the app. Editing the local file does not update existing provider entries. `payments/autumn.config.example` is an optional manual reference, not an initialization step. If used, copy it and `config.ts` into a separate project with `atmn@2.0.218`, renaming it `autumn.config.ts`. Never automate `atmn push`: its complete catalog lists can delete unlisted plans and features.
24
+
25
+ Autumn documents one-off prepaid credits as nonexpiring; subscription credits reset each cycle. Provider transactions, repeated top-ups, renewals, cancellation and refunds still need sandbox verification. Do not promise subscription credits survive cancellation. The provider balance is authoritative; a redirect alone does not grant credits. This foundation does not implement usage charging.
8
26
 
9
27
  The app calls Autumn API 2.6.0 `customers.get_or_create`, `billing.attach`, and `billing.open_customer_portal` server-side. Checkout uses server-owned plan IDs and the top-up quantity from `payments/config.ts`. Return to pricing may precede provider synchronization; use Refresh to read Autumn again. Setup and test Stripe checkout and portal in Autumn before enabling live use.
10
28
 
@@ -24,10 +42,12 @@ Autumn's integration documentation does not confirm repeatable consumable top-up
24
42
 
25
43
  ## Platform connection and starter packaging
26
44
 
27
- Autumn's Platform API is private preview; its documented OAuth connects Stripe to a managed Autumn organization, not an existing Autumn account to Disposabl. Disposabl Connections accepts an encrypted sandbox key and an optional live key. It verifies each through the read-only `plans.list` endpoint. Payments selection requires this connection; other apps remain unblocked. Generator setup installs the sandbox key only on the named development backend, and the live key only on production when supplied. The platform billing key is never copied. Setup initializes `BILLING_RETURN_URL` only when absent, using that deployment's `/pricing` page; change it to your verified custom web origin if needed. Plan catalogs are not changed automatically. Configure and test both plans in each Autumn environment. Disconnecting or omitting a live key does not revoke credentials previously installed on an app; rotate those in Autumn and update each app explicitly.
45
+ Autumn's Platform API is private preview; its documented OAuth connects Stripe to a managed Autumn organization, not an existing Autumn account to Disposabl. Disposabl Connections accepts an encrypted sandbox key and an optional live key. It verifies each through the read-only `plans.list` endpoint. Payments selection requires this connection; other apps remain unblocked. Generator setup installs the sandbox key only on the named development backend, and the live key only on production when supplied. The platform billing key is never copied. Setup initializes `BILLING_RETURN_URL` only when absent, using that deployment's `/pricing` page; change it to your verified custom web origin if needed. Provisioning only installs credentials and the return URL. The deployed app initializes missing catalog entries from its own config through `billing:setup`. Verify both plans in each Autumn environment. Disconnecting or omitting a live key does not revoke credentials previously installed on an app; rotate those in Autumn and update each app explicitly.
46
+
47
+ The parent `reset.ts` replaces backend functions from `starter/backend`; both backends re-export the billing functions, including internal setup. The generated package retains the kit, editable payment config and backend dev hook. Both Convex configs declare the optional billing variables. Regenerate API types after backend functions change. Do not copy any parent credentials.
28
48
 
29
- The parent `reset.ts` removes backend functions before copying `starter/backend`; this patch adds the thin billing wrapper to both places and declares the optional variables in both Convex configs. Preserve the `autumn/` config and kit files when packaging, and regenerate the generated API types after backend functions change. Do not copy any parent credentials.
49
+ Catalog contracts were checked against the official API 2.6.0 docs and `autumn-js` 1.5.64 schemas; no SDK dependency is added. The get endpoints do not specify missing-resource error codes, so initialization uses complete list responses instead.
30
50
 
31
- Provider references: [API attach](https://docs.useautumn.com/api-reference/billing/attach), [customer](https://docs.useautumn.com/api-reference/customers/getOrCreateCustomer), [portal](https://docs.useautumn.com/api-reference/billing/openCustomerPortal), [prepaid top-ups](https://docs.useautumn.com/examples/prepaid), [pricing config](https://docs.useautumn.com/cli/config), [RevenueCat](https://docs.useautumn.com/documentation/external-providers/revenuecat), [Platform API](https://docs.useautumn.com/api-reference/platform/overview).
51
+ Provider references: [create plan](https://docs.useautumn.com/api-reference/plans/createPlan), [get plan](https://docs.useautumn.com/api-reference/plans/getPlan), [list plans](https://docs.useautumn.com/api-reference/plans/listPlans), [create feature](https://docs.useautumn.com/api-reference/features/createFeature), [get feature](https://docs.useautumn.com/api-reference/features/getFeature), [list features](https://docs.useautumn.com/api-reference/features/listFeatures), [API attach](https://docs.useautumn.com/api-reference/billing/attach), [customer](https://docs.useautumn.com/api-reference/customers/getOrCreateCustomer), [portal](https://docs.useautumn.com/api-reference/billing/openCustomerPortal), [prepaid top-ups](https://docs.useautumn.com/examples/prepaid), [pricing config](https://docs.useautumn.com/cli/config), [RevenueCat](https://docs.useautumn.com/documentation/external-providers/revenuecat), [Platform API](https://docs.useautumn.com/api-reference/platform/overview).
32
52
 
33
53
  Native SDK is pinned to `react-native-purchases` 10.16.0 because its required `PurchasesHybridCommon` 19.17.0 is published in CocoaPods. At verification on 2026-11-07, npm 11.0.1 required 20.4.0, which was absent from the CocoaPods specs repository. Upgrade only after both native dependency graphs resolve and installed builds pass.
@@ -6,7 +6,7 @@ export type Pricing = {
6
6
  topup: { planId: string; price: number };
7
7
  };
8
8
 
9
- /** Editable starter example. Apply matching changes to Autumn before accepting purchases. */
9
+ /** Setup creates missing entries. Apply matching changes to existing Autumn plans manually. */
10
10
  export const pricing: Pricing = {
11
11
  currency: "USD",
12
12
  creditsPerDollar: 100,
@@ -1,8 +1,9 @@
1
1
  import type { Auth } from "convex/server";
2
- import { getSessionUserId } from "./lib/functions";
2
+ import { getSessionUserId, internalAction } from "./lib/functions";
3
3
  import { v } from "convex/values";
4
4
  import { action } from "../../backend/convex/_generated/server";
5
5
  import { paymentsEnabled } from "../features";
6
+ import { setupBilling } from "./billing-setup";
6
7
  import {
7
8
  balanceFromCustomer,
8
9
  monthlyPlanFromCustomer,
@@ -11,6 +12,16 @@ import {
11
12
  purchaseRequest,
12
13
  } from "./billing";
13
14
 
15
+ export const setup = internalAction({
16
+ args: {},
17
+ returns: v.object({
18
+ enabled: v.boolean(),
19
+ created: v.array(v.string()),
20
+ preserved: v.array(v.string()),
21
+ }),
22
+ handler: async () => setupBilling(paymentsEnabled, process.env),
23
+ });
24
+
14
25
  async function context(ctx: { auth: Auth }) {
15
26
  return billingContext(paymentsEnabled, process.env, () =>
16
27
  getSessionUserId(ctx),
@@ -0,0 +1,125 @@
1
+ import { creditQuantity, pricing, type Pricing } from "../payments/config";
2
+ import { billingRequest } from "./billing";
3
+
4
+ /** Create missing catalog entries only. Existing provider configuration is owner-managed. */
5
+ export async function setupBilling(
6
+ enabled: boolean,
7
+ env: Record<string, string | undefined>,
8
+ config: Pricing = pricing,
9
+ fetcher = fetch,
10
+ ) {
11
+ const result = {
12
+ enabled,
13
+ created: [] as string[],
14
+ preserved: [] as string[],
15
+ };
16
+ if (!enabled) return result;
17
+ const key = env.AUTUMN_SECRET_KEY?.trim();
18
+ if (!key)
19
+ throw new Error(
20
+ "Payments setup requires AUTUMN_SECRET_KEY on this Convex deployment. Configure this app's Autumn connection and retry.",
21
+ );
22
+ if (
23
+ !config.featureId.trim() ||
24
+ !/^[A-Z]{3}$/i.test(config.currency) ||
25
+ !Number.isFinite(config.creditsPerDollar) ||
26
+ config.creditsPerDollar <= 0 ||
27
+ config.monthly.planId === config.topup.planId ||
28
+ (["monthly", "topup"] as const).some(
29
+ (kind) =>
30
+ !/^[a-zA-Z0-9_-]+$/.test(config[kind].planId) ||
31
+ !Number.isFinite(config[kind].price) ||
32
+ config[kind].price <= 0 ||
33
+ !Number.isSafeInteger(creditQuantity(kind, config)) ||
34
+ creditQuantity(kind, config) <= 0,
35
+ )
36
+ )
37
+ throw new Error(
38
+ "Payments setup requires valid prices, credits and IDs in payments/config.ts.",
39
+ );
40
+
41
+ const request = async (method: string, body: object) => {
42
+ try {
43
+ return await billingRequest(key, method, body, fetcher);
44
+ } catch {
45
+ // Do not expose provider responses or retry a potentially committed create.
46
+ throw new Error(
47
+ `Payments setup failed at ${method}. Check this deployment's Autumn key and provider catalog, then retry. Existing entries will be preserved.`,
48
+ );
49
+ }
50
+ };
51
+ const list = async (kind: "features" | "plans") => {
52
+ // These API 2.6.0 endpoints return complete lists, not paginated results.
53
+ // Never infer absence from an error response, including 404 or unauthorized.
54
+ const response = await request(
55
+ `${kind}.list`,
56
+ kind === "plans" ? { include_archived: true, all_versions: true } : {},
57
+ );
58
+ if (
59
+ !Array.isArray(response.list) ||
60
+ response.list.some((entry) => !entry || typeof entry.id !== "string")
61
+ )
62
+ throw new Error(
63
+ `Payments setup received an invalid ${kind} list; no entries created.`,
64
+ );
65
+ return new Set<string>(response.list.map((entry) => entry.id));
66
+ };
67
+ // Validate both reads before the first write. At most two reads and three creates.
68
+ const features = await list("features");
69
+ const plans = await list("plans");
70
+ const ensure = async (
71
+ kind: "features" | "plans",
72
+ existing: Set<string>,
73
+ id: string,
74
+ body: object,
75
+ ) => {
76
+ const label = `${kind}:${id}`;
77
+ if (existing.has(id)) {
78
+ result.preserved.push(label);
79
+ return;
80
+ }
81
+ const created = await request(`${kind}.create`, body);
82
+ if (created.id !== id)
83
+ throw new Error(
84
+ `Payments setup could not confirm ${label}. Check Autumn and retry; existing entries will be preserved.`,
85
+ );
86
+ result.created.push(label);
87
+ };
88
+ await ensure("features", features, config.featureId, {
89
+ feature_id: config.featureId,
90
+ name: "Credits",
91
+ type: "metered",
92
+ consumable: true,
93
+ });
94
+ await ensure("plans", plans, config.monthly.planId, {
95
+ plan_id: config.monthly.planId,
96
+ name: "Monthly credits",
97
+ auto_enable: false,
98
+ price: { amount: config.monthly.price, interval: "month" },
99
+ items: [
100
+ {
101
+ feature_id: config.featureId,
102
+ included: creditQuantity("monthly", config),
103
+ reset: { interval: "month" },
104
+ },
105
+ ],
106
+ });
107
+ await ensure("plans", plans, config.topup.planId, {
108
+ plan_id: config.topup.planId,
109
+ name: "Credits top-up",
110
+ add_on: true,
111
+ auto_enable: false,
112
+ items: [
113
+ {
114
+ feature_id: config.featureId,
115
+ price: {
116
+ amount: config.topup.price,
117
+ billing_units: creditQuantity("topup", config),
118
+ interval: "one_off",
119
+ billing_method: "prepaid",
120
+ },
121
+ },
122
+ ],
123
+ });
124
+ return result;
125
+ }
@@ -39,6 +39,8 @@ export async function billingRequest(
39
39
  ): Promise<Record<string, unknown>> {
40
40
  const response = await fetcher(`https://api.useautumn.com/v1/${method}`, {
41
41
  method: "POST",
42
+ redirect: "error",
43
+ signal: AbortSignal.timeout(15000),
42
44
  headers: {
43
45
  Authorization: `Bearer ${key}`,
44
46
  "Content-Type": "application/json",
@@ -0,0 +1,42 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync } from "node:fs";
4
+ import { execFileSync } from "node:child_process";
5
+
6
+ // Keep Bun's YAML parser isolated from this workspace's Node-only type globals.
7
+ const workflow = JSON.parse(
8
+ execFileSync(
9
+ process.execPath,
10
+ [
11
+ "-e",
12
+ "console.log(JSON.stringify(Bun.YAML.parse(await Bun.stdin.text())))",
13
+ ],
14
+ {
15
+ input: readFileSync(
16
+ new URL("../../.github/workflows/pipeline.yml", import.meta.url),
17
+ ),
18
+ encoding: "utf8",
19
+ },
20
+ ),
21
+ );
22
+
23
+ test("Android failure reporting runs independently only for an Android failure", () => {
24
+ const job = workflow.jobs["android-failure"];
25
+ assert.equal(job.needs, "android");
26
+ assert.equal(job.if, "failure() && needs.android.result == 'failure'");
27
+ assert.deepEqual(job.permissions, { contents: "read", "id-token": "write" });
28
+ assert.equal(job["runs-on"], "ubuntu-24.04");
29
+ assert.equal(job["timeout-minutes"], 5);
30
+ assert.equal(job.steps[0].uses, "actions/checkout@v6");
31
+ assert.equal(job.steps[1].uses, "actions/setup-node@v6");
32
+ assert.equal(
33
+ job.steps[2].run,
34
+ "node .github/scripts/disposabl.mjs report android failed",
35
+ );
36
+ assert.equal(
37
+ workflow.jobs.android.steps.some((step: { run?: string }) =>
38
+ step.run?.includes("report android failed"),
39
+ ),
40
+ false,
41
+ );
42
+ });
@@ -0,0 +1,91 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFile } from "node:child_process";
4
+ import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { join, resolve } from "node:path";
7
+ import { promisify } from "node:util";
8
+ import { v } from "convex/values";
9
+ import { setup } from "../disposabl-kit/server/billing-functions";
10
+
11
+ const root = resolve(import.meta.dirname, "../..");
12
+ const exec = promisify(execFile);
13
+
14
+ test("catalog setup is internal, validated and runs on the dev deployment's first push", async () => {
15
+ assert.equal(setup.isInternal, true);
16
+ assert.ok("args" in setup);
17
+ assert.ok("returns" in setup);
18
+ assert.deepEqual(setup.args, {});
19
+ assert.deepEqual(
20
+ setup.returns,
21
+ v.object({
22
+ enabled: v.boolean(),
23
+ created: v.array(v.string()),
24
+ preserved: v.array(v.string()),
25
+ }),
26
+ );
27
+ const manifest = JSON.parse(
28
+ await readFile(join(root, "packages/backend/package.json"), "utf8"),
29
+ );
30
+ assert.equal(manifest.scripts.dev, "convex dev --run billing:setup");
31
+ });
32
+
33
+ test("CI uses the deployed target, runs setup before upload and stops on setup failure", async () => {
34
+ const workflow = await readFile(
35
+ join(root, ".github/workflows/pipeline.yml"),
36
+ "utf8",
37
+ );
38
+ const deploy = workflow
39
+ .match(
40
+ / - name: Deploy\n[\s\S]*? run: \|\n((?: .*\n)+)/,
41
+ )?.[1]
42
+ .replace(/^ {10}/gm, "");
43
+ assert.ok(deploy);
44
+ const temp = await mkdtemp(join(tmpdir(), "billing-deploy-hook-"));
45
+ try {
46
+ await mkdir(join(temp, "packages/backend"), { recursive: true });
47
+ await mkdir(join(temp, "bin"));
48
+ // Record the actual shell command boundaries without running any tools/providers.
49
+ await writeFile(
50
+ join(temp, "bin/bun"),
51
+ `#!/bin/sh
52
+ printf '%s\\n' "$*" >> "$CALLS"
53
+ case "$*" in *'convex run '*) exit "$SETUP_EXIT";; esac
54
+ `,
55
+ { mode: 0o755 },
56
+ );
57
+ const callsFile = join(temp, "calls");
58
+ for (const channel of ["production", "pr-42"]) {
59
+ for (const setupExit of ["0", "1"]) {
60
+ await writeFile(callsFile, "");
61
+ const run = exec("bash", ["-e", "-c", deploy], {
62
+ cwd: temp,
63
+ env: {
64
+ NODE_ENV: "test",
65
+ PATH: `${join(temp, "bin")}:${process.env.PATH}`,
66
+ TRUSTED: "true",
67
+ CONVEX_DEPLOY_KEY: "fixture",
68
+ CHANNEL: channel,
69
+ CALLS: callsFile,
70
+ SETUP_EXIT: setupExit,
71
+ },
72
+ });
73
+ if (setupExit === "0") await run;
74
+ else await assert.rejects(run);
75
+ const calls = (await readFile(callsFile, "utf8")).trim().split("\n");
76
+ assert.match(calls[0], /convex deploy --yes/);
77
+ const target =
78
+ channel === "production" ? "--prod" : "--preview-name pr-42";
79
+ assert.equal(
80
+ calls[1],
81
+ `x --no-install convex run ${target} billing:setup {}`,
82
+ );
83
+ assert.equal(calls.length, setupExit === "0" ? 3 : 2);
84
+ if (setupExit === "0")
85
+ assert.ok(calls[2].includes(`static-hosting upload ${target}`));
86
+ }
87
+ }
88
+ } finally {
89
+ await rm(temp, { recursive: true, force: true });
90
+ }
91
+ });
@@ -0,0 +1,292 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { setupBilling } from "../disposabl-kit/server/billing-setup";
4
+ import { pricing, type Pricing } from "../disposabl-kit/payments/config";
5
+
6
+ type Entry = { id: string; [key: string]: unknown };
7
+ type Call = { method: string; body: Record<string, unknown> };
8
+ const env = { AUTUMN_SECRET_KEY: "fixture-key" };
9
+ function provider() {
10
+ const features = new Map<string, Entry>();
11
+ const plans = new Map<string, Entry>();
12
+ const calls: Call[] = [];
13
+ const fetcher = (async (url, init) => {
14
+ assert.equal(init?.method, "POST");
15
+ assert.equal(new Headers(init?.headers).get("x-api-version"), "2.6.0");
16
+ assert.equal(
17
+ new Headers(init?.headers).get("Authorization"),
18
+ "Bearer fixture-key",
19
+ );
20
+ const method = String(url).replace("https://api.useautumn.com/v1/", "");
21
+ const body = JSON.parse(String(init?.body));
22
+ calls.push({ method, body });
23
+ const entries = method.startsWith("features.") ? features : plans;
24
+ if (method.endsWith(".list")) {
25
+ assert.deepEqual(
26
+ body,
27
+ method === "plans.list"
28
+ ? { include_archived: true, all_versions: true }
29
+ : {},
30
+ );
31
+ return Response.json({ list: [...entries.values()] });
32
+ }
33
+ assert.ok(["features.create", "plans.create"].includes(method));
34
+ const id = body.feature_id ?? body.plan_id;
35
+ if (entries.has(id))
36
+ return Response.json({ error: "duplicate" }, { status: 409 });
37
+ const entry = { ...body, id };
38
+ entries.set(id, entry);
39
+ return Response.json(entry);
40
+ }) as typeof fetch;
41
+ return { features, plans, calls, fetcher };
42
+ }
43
+
44
+ test("disabled setup reads neither credentials, pricing nor provider", async () => {
45
+ const unreadable = new Proxy(
46
+ {},
47
+ {
48
+ get() {
49
+ throw new Error("must not read");
50
+ },
51
+ },
52
+ );
53
+ const fetcher = (() => {
54
+ throw new Error("must not fetch");
55
+ }) as typeof fetch;
56
+ assert.deepEqual(
57
+ await setupBilling(false, unreadable, unreadable as Pricing, fetcher),
58
+ {
59
+ enabled: false,
60
+ created: [],
61
+ preserved: [],
62
+ },
63
+ );
64
+ });
65
+
66
+ test("enabled setup needs this deployment's key and valid pricing before requests", async () => {
67
+ const p = provider();
68
+ await assert.rejects(
69
+ setupBilling(true, {}, pricing, p.fetcher),
70
+ /AUTUMN_SECRET_KEY on this Convex deployment/,
71
+ );
72
+ for (const config of [
73
+ { ...pricing, creditsPerDollar: 0 },
74
+ { ...pricing, monthly: { ...pricing.monthly, price: NaN } },
75
+ { ...pricing, topup: { ...pricing.topup, planId: pricing.monthly.planId } },
76
+ ])
77
+ await assert.rejects(
78
+ setupBilling(true, env, config, p.fetcher),
79
+ /payments\/config.ts/,
80
+ );
81
+ assert.equal(p.calls.length, 0);
82
+ });
83
+
84
+ test("defaults create monthly included credits and nonexpiring prepaid top-ups once", async () => {
85
+ const p = provider();
86
+ const first = await setupBilling(true, env, pricing, p.fetcher);
87
+ assert.equal(first.created.length, 3);
88
+ assert.equal(p.calls.length, 5);
89
+ assert.deepEqual(p.calls.slice(2), [
90
+ {
91
+ method: "features.create",
92
+ body: {
93
+ feature_id: "credits",
94
+ name: "Credits",
95
+ type: "metered",
96
+ consumable: true,
97
+ },
98
+ },
99
+ {
100
+ method: "plans.create",
101
+ body: {
102
+ plan_id: "credits_monthly",
103
+ name: "Monthly credits",
104
+ auto_enable: false,
105
+ price: { amount: 5, interval: "month" },
106
+ items: [
107
+ {
108
+ feature_id: "credits",
109
+ included: 500,
110
+ reset: { interval: "month" },
111
+ },
112
+ ],
113
+ },
114
+ },
115
+ {
116
+ method: "plans.create",
117
+ body: {
118
+ plan_id: "credits_topup",
119
+ name: "Credits top-up",
120
+ add_on: true,
121
+ auto_enable: false,
122
+ items: [
123
+ {
124
+ feature_id: "credits",
125
+ price: {
126
+ amount: 5,
127
+ billing_units: 500,
128
+ interval: "one_off",
129
+ billing_method: "prepaid",
130
+ },
131
+ },
132
+ ],
133
+ },
134
+ },
135
+ ]);
136
+ for (let i = 0; i < 3; i++) {
137
+ const next = await setupBilling(true, env, pricing, p.fetcher);
138
+ assert.deepEqual(next.created, []);
139
+ assert.deepEqual(next.preserved, first.created);
140
+ }
141
+ assert.equal(
142
+ p.calls.filter((call) => call.method.endsWith(".create")).length,
143
+ 3,
144
+ );
145
+ });
146
+
147
+ test("edited config drives new IDs, prices and quantities without assuming USD", async () => {
148
+ const p = provider();
149
+ const config: Pricing = {
150
+ currency: "EUR",
151
+ featureId: "tokens",
152
+ creditsPerDollar: 80,
153
+ monthly: { planId: "custom_monthly", price: 12 },
154
+ topup: { planId: "custom_topup", price: 3 },
155
+ };
156
+ await setupBilling(true, env, config, p.fetcher);
157
+ assert.deepEqual(p.plans.get("custom_monthly")?.price, {
158
+ amount: 12,
159
+ interval: "month",
160
+ });
161
+ assert.deepEqual(p.plans.get("custom_monthly")?.items, [
162
+ { feature_id: "tokens", included: 960, reset: { interval: "month" } },
163
+ ]);
164
+ assert.deepEqual(p.plans.get("custom_topup")?.items, [
165
+ {
166
+ feature_id: "tokens",
167
+ price: {
168
+ amount: 3,
169
+ billing_units: 240,
170
+ interval: "one_off",
171
+ billing_method: "prepaid",
172
+ },
173
+ },
174
+ ]);
175
+ });
176
+
177
+ test("custom, archived and unrelated catalog entries remain byte-for-byte unchanged", async () => {
178
+ const p = provider();
179
+ p.features.set("credits", {
180
+ id: "credits",
181
+ type: "credit_system",
182
+ archived: true,
183
+ creditSchema: ["custom"],
184
+ });
185
+ p.plans.set("credits_monthly", {
186
+ id: "credits_monthly",
187
+ price: { amount: 37 },
188
+ version: 8,
189
+ archived: true,
190
+ });
191
+ p.plans.set("enterprise", { id: "enterprise", name: "Custom deal" });
192
+ const before = JSON.stringify([...p.features, ...p.plans]);
193
+ const result = await setupBilling(true, env, pricing, p.fetcher);
194
+ assert.deepEqual(result.created, ["plans:credits_topup"]);
195
+ p.plans.delete("credits_topup");
196
+ assert.equal(JSON.stringify([...p.features, ...p.plans]), before);
197
+ });
198
+
199
+ test("partial failure stops writes and a later run resumes from provider state", async () => {
200
+ const p = provider();
201
+ const failTopup = (async (url, init) => {
202
+ const body = JSON.parse(String(init?.body));
203
+ if (
204
+ String(url).endsWith("plans.create") &&
205
+ body.plan_id === "credits_topup"
206
+ )
207
+ return new Response("private error", { status: 500 });
208
+ return p.fetcher(url, init);
209
+ }) as typeof fetch;
210
+ await assert.rejects(
211
+ setupBilling(true, env, pricing, failTopup),
212
+ /Payments setup failed at plans.create/,
213
+ );
214
+ assert.equal(p.features.size, 1);
215
+ assert.equal(p.plans.size, 1);
216
+ const resumed = await setupBilling(true, env, pricing, p.fetcher);
217
+ assert.deepEqual(resumed.created, ["plans:credits_topup"]);
218
+ assert.equal(
219
+ p.calls.filter((call) => call.method.endsWith(".create")).length,
220
+ 3,
221
+ );
222
+ });
223
+
224
+ test("read errors and malformed lists are never treated as absence", async () => {
225
+ for (const response of [
226
+ ...[400, 401, 403, 404, 429, 500].map(
227
+ (status) => new Response("private error", { status }),
228
+ ),
229
+ Response.json({}),
230
+ Response.json({ list: [null] }),
231
+ Response.json({ list: [{ name: "missing ID" }] }),
232
+ ]) {
233
+ const p = provider();
234
+ const fetcher = (async (url, init) =>
235
+ String(url).endsWith("plans.list")
236
+ ? response
237
+ : p.fetcher(url, init)) as typeof fetch;
238
+ await assert.rejects(
239
+ setupBilling(true, env, pricing, fetcher),
240
+ /Payments setup/,
241
+ );
242
+ assert.equal(p.calls.length, 1);
243
+ assert.equal(p.features.size, 0);
244
+ }
245
+ });
246
+
247
+ test("uncertain create is not retried in place; next run discovers committed entry", async () => {
248
+ for (const failure of ["network", "malformed", "unauthorized"] as const) {
249
+ const p = provider();
250
+ const fetcher = (async (url, init) => {
251
+ const response = await p.fetcher(url, init);
252
+ if (String(url).endsWith("features.create")) {
253
+ if (failure === "network") throw new Error("private network error");
254
+ if (failure === "unauthorized")
255
+ return new Response("private error", { status: 401 });
256
+ return Response.json({ unexpected: true });
257
+ }
258
+ return response;
259
+ }) as typeof fetch;
260
+ await assert.rejects(
261
+ setupBilling(true, env, pricing, fetcher),
262
+ /Payments setup/,
263
+ );
264
+ assert.equal(p.calls.length, 3);
265
+ assert.equal(p.plans.size, 0);
266
+ const resumed = await setupBilling(true, env, pricing, p.fetcher);
267
+ assert.deepEqual(resumed.preserved, ["features:credits"]);
268
+ assert.equal(resumed.created.length, 2);
269
+ }
270
+ });
271
+
272
+ test("concurrent create conflicts fail safely and can be resumed", async () => {
273
+ const p = provider();
274
+ const results = await Promise.allSettled([
275
+ setupBilling(true, env, pricing, p.fetcher),
276
+ setupBilling(true, env, pricing, p.fetcher),
277
+ ]);
278
+ assert.equal(
279
+ results.filter((result) => result.status === "fulfilled").length,
280
+ 1,
281
+ );
282
+ assert.equal(
283
+ results.filter((result) => result.status === "rejected").length,
284
+ 1,
285
+ );
286
+ assert.equal(p.features.size, 1);
287
+ assert.equal(p.plans.size, 2);
288
+ assert.deepEqual(
289
+ (await setupBilling(true, env, pricing, p.fetcher)).created,
290
+ [],
291
+ );
292
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-disposabl-app",
3
- "version": "0.13.4",
3
+ "version": "0.14.0",
4
4
  "description": "Create a Disposabl app",
5
5
  "type": "module",
6
6
  "license": "MIT",