anhedral 0.12.0 → 0.15.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/README.md +35 -172
- package/assets/patches/audit-deps.mjs +12 -2
- package/assets/ui/LICENSE.shadcn +21 -0
- package/assets/ui/UPSTREAM.json +33 -0
- package/assets/ui/native/button.tsx +85 -0
- package/assets/ui/native/card.tsx +33 -0
- package/assets/ui/native/dialog.tsx +75 -0
- package/assets/ui/native/input.tsx +27 -0
- package/assets/ui/native/label.tsx +4 -0
- package/assets/ui/native/layout.tsx +26 -0
- package/assets/ui/native/text.tsx +20 -0
- package/assets/ui/native/theme-switcher.tsx +22 -0
- package/assets/ui/theme-storage.ts +25 -0
- package/assets/ui/theme.tsx +66 -0
- package/assets/ui/web/button.tsx +59 -0
- package/assets/ui/web/input.tsx +21 -0
- package/assets/ui/web/label.tsx +19 -0
- package/dist/capabilities.d.ts +5 -5
- package/dist/capabilities.js +3 -21
- package/dist/capability-contract.d.ts +3 -3
- package/dist/capability-contract.js +11 -39
- package/dist/cli-delivery.d.ts +1 -1
- package/dist/cli-delivery.js +5 -65
- package/dist/cli-output.js +3 -3
- package/dist/command-schema.js +35 -80
- package/dist/command.js +9 -11
- package/dist/delivery-evidence.d.ts +1 -1
- package/dist/delivery-evidence.js +7 -36
- package/dist/delivery.d.ts +2 -8
- package/dist/delivery.js +23 -102
- package/dist/dependencies.d.ts +12 -58
- package/dist/dependencies.js +67 -189
- package/dist/index.d.ts +1 -3
- package/dist/index.js +1 -3
- package/dist/inspector-model.d.ts +2 -2
- package/dist/integration-service-readers.d.ts +1 -2
- package/dist/integration-service-readers.js +3 -84
- package/dist/lifecycle-model.d.ts +1 -1
- package/dist/lifecycle-model.js +1 -1
- package/dist/mobile-delivery.d.ts +1 -1
- package/dist/mobile-delivery.js +4 -0
- package/dist/platforms/mobile.d.ts +1 -1
- package/dist/platforms/mobile.js +64 -114
- package/dist/platforms/web.d.ts +3 -0
- package/dist/platforms/web.js +299 -0
- package/dist/project-config.d.ts +1 -1
- package/dist/project-config.js +0 -1
- package/dist/project-inspector.js +5 -36
- package/dist/project-state.d.ts +1 -3
- package/dist/project-state.js +6 -86
- package/dist/provider-auth.js +3 -32
- package/dist/provider-readiness.d.ts +1 -1
- package/dist/provider-readiness.js +5 -24
- package/dist/providers/adapters.js +9 -178
- package/dist/providers/api.d.ts +1 -1
- package/dist/providers/api.js +3 -3
- package/dist/providers/config.js +2 -48
- package/dist/providers/definitions.d.ts +1 -204
- package/dist/providers/definitions.js +0 -85
- package/dist/providers/provision.d.ts +1 -1
- package/dist/providers/receipts.js +1 -11
- package/dist/providers/recovery-verification.js +1 -61
- package/dist/providers/runtime.js +15 -35
- package/dist/providers/state.js +1 -7
- package/dist/provision.d.ts +5 -13
- package/dist/provision.js +4 -80
- package/dist/readiness.d.ts +1 -1
- package/dist/readiness.js +3 -6
- package/dist/registry/add.js +11 -38
- package/dist/registry/bootstrap.d.ts +3 -2
- package/dist/registry/bootstrap.js +4 -13
- package/dist/registry/commands.js +8 -10
- package/dist/registry/context.js +0 -1
- package/dist/registry/options.js +8 -26
- package/dist/registry/resolve.d.ts +3 -2
- package/dist/registry/resolve.js +26 -82
- package/dist/registry/types.d.ts +2 -7
- package/dist/registry/usage.js +2 -2
- package/dist/runtime-policy.d.ts +0 -2
- package/dist/runtime-policy.js +0 -13
- package/dist/scaffold/api.js +10 -2
- package/dist/scaffold/auth.d.ts +1 -2
- package/dist/scaffold/auth.js +57 -116
- package/dist/scaffold/backend.d.ts +2 -0
- package/dist/scaffold/backend.js +39 -0
- package/dist/scaffold/billing-config.d.ts +1 -0
- package/dist/scaffold/billing-config.js +73 -0
- package/dist/scaffold/billing-contracts.d.ts +2 -0
- package/dist/scaffold/billing-contracts.js +48 -0
- package/dist/scaffold/billing-providers.d.ts +1 -0
- package/dist/scaffold/billing-providers.js +249 -0
- package/dist/scaffold/billing-schema.d.ts +1 -0
- package/dist/scaffold/billing-schema.js +34 -0
- package/dist/scaffold/billing-security.d.ts +1 -0
- package/dist/scaffold/billing-security.js +46 -0
- package/dist/scaffold/billing-server.d.ts +1 -0
- package/dist/scaffold/billing-server.js +139 -0
- package/dist/scaffold/billing-store.d.ts +1 -0
- package/dist/scaffold/billing-store.js +72 -0
- package/dist/scaffold/billing.d.ts +2 -0
- package/dist/scaffold/billing.js +208 -0
- package/dist/scaffold/bootstrap.d.ts +2 -3
- package/dist/scaffold/bootstrap.js +37 -43
- package/dist/scaffold/compose.js +2 -12
- package/dist/scaffold/database.d.ts +1 -1
- package/dist/scaffold/database.js +20 -111
- package/dist/scaffold/documentation.d.ts +0 -1
- package/dist/scaffold/documentation.js +22 -82
- package/dist/scaffold/expo-auth.d.ts +3 -0
- package/dist/scaffold/expo-auth.js +203 -0
- package/dist/scaffold/expo-billing.d.ts +3 -0
- package/dist/scaffold/expo-billing.js +257 -0
- package/dist/scaffold/expo-runtime.d.ts +3 -0
- package/dist/scaffold/expo-runtime.js +43 -0
- package/dist/scaffold/integrations.d.ts +1 -2
- package/dist/scaffold/integrations.js +9 -5
- package/dist/scaffold/managed-email.d.ts +3 -0
- package/dist/scaffold/managed-email.js +47 -0
- package/dist/scaffold/native-ui.d.ts +2 -0
- package/dist/scaffold/native-ui.js +69 -0
- package/dist/scaffold/password-reset.d.ts +1 -0
- package/dist/scaffold/password-reset.js +99 -0
- package/dist/scaffold/private-files.d.ts +2 -0
- package/dist/scaffold/private-files.js +78 -0
- package/dist/scaffold/stack-documentation.d.ts +0 -1
- package/dist/scaffold/stack-documentation.js +3 -49
- package/dist/scaffold/styling.d.ts +1 -1
- package/dist/scaffold/styling.js +20 -28
- package/dist/scaffold/web-billing.d.ts +2 -0
- package/dist/scaffold/web-billing.js +48 -0
- package/dist/scaffold/workspace.js +53 -189
- package/dist/service-deletion.js +1 -1
- package/dist/service-descriptor.js +5 -12
- package/dist/service-model.d.ts +1 -1
- package/dist/service-operations.js +2 -32
- package/dist/service-readers.js +1 -32
- package/dist/services-command.d.ts +1 -1
- package/dist/services-command.js +3 -9
- package/dist/ship.d.ts +3 -316
- package/dist/ship.js +13 -143
- package/dist/stack-registry.d.ts +2 -43
- package/dist/stack-registry.js +80 -308
- package/dist/standard.js +7 -14
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +23 -0
- package/docs/assets/anhedral-stack-light.png +0 -0
- package/docs/assets/anhedral-stack.png +0 -0
- package/docs/software-factory.md +25 -499
- package/docs/stack-standard.md +48 -226
- package/docs/verification.md +433 -0
- package/package.json +22 -21
- package/dist/neon-service-data.d.ts +0 -8
- package/dist/neon-service-data.js +0 -117
- package/dist/platforms/desktop.d.ts +0 -2
- package/dist/platforms/desktop.js +0 -415
- package/dist/platforms/extension.d.ts +0 -2
- package/dist/platforms/extension.js +0 -328
- package/dist/scaffold/lint.d.ts +0 -4
- package/dist/scaffold/lint.js +0 -56
- package/dist/scaffold/neon-realtime.d.ts +0 -2
- package/dist/scaffold/neon-realtime.js +0 -97
- package/dist/scaffold/services.d.ts +0 -5
- package/dist/scaffold/services.js +0 -108
- package/dist/scaffold/stream.d.ts +0 -2
- package/dist/scaffold/stream.js +0 -114
- package/dist/scaffold/void.d.ts +0 -4
- package/dist/scaffold/void.js +0 -256
- package/dist/scaffold/web.d.ts +0 -2
- package/dist/scaffold/web.js +0 -128
- package/dist/vercel-project.d.ts +0 -101
- package/dist/vercel-project.js +0 -305
- package/dist/vercel.d.ts +0 -67
- package/dist/vercel.js +0 -581
- package/dist/vinext.d.ts +0 -2
- package/dist/vinext.js +0 -86
- package/dist/void-execution.d.ts +0 -10
- package/dist/void-execution.js +0 -94
- package/dist/void-migrations.d.ts +0 -6
- package/dist/void-migrations.js +0 -110
- package/dist/void-state.d.ts +0 -16
- package/dist/void-state.js +0 -65
- package/dist/void.d.ts +0 -3
- package/dist/void.js +0 -5
|
@@ -1,100 +1,40 @@
|
|
|
1
|
-
import { usesVoidSelection } from '../runtime-policy.js';
|
|
2
|
-
import { markdownHeading } from '../render.js';
|
|
3
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
1
|
import { put } from './files.js';
|
|
6
|
-
export function workerBuildSuffix(options) {
|
|
7
|
-
return options.products.includes('next') && options.hosting === 'cloudflare'
|
|
8
|
-
? ' && pnpm build:worker'
|
|
9
|
-
: '';
|
|
10
|
-
}
|
|
11
2
|
export function writeSetupDocumentation(root, options) {
|
|
12
|
-
|
|
13
|
-
const agentsFile = path.join(root, 'AGENTS.md');
|
|
14
|
-
const voidSelected = usesVoidSelection(options.products, options.hosting);
|
|
15
|
-
const existingAgents = existsSync(agentsFile) && (has('next') || has('vinext'))
|
|
16
|
-
? readFileSync(agentsFile, 'utf8') + '\n'
|
|
17
|
-
: '';
|
|
18
|
-
put(root, 'AGENTS.md', existingAgents +
|
|
19
|
-
`# Anhedral delivery standard
|
|
20
|
-
|
|
21
|
-
Keep accounts, source, infrastructure, billing, and recovery client-owned. Use the available developer tools and the selected platforms’ native toolchains for implementation and verification. Use provider plugins, APIs/MCP and CLIs for operations; Void owns Cloudflare provisioning and deployment for supported selections; Anhedral owns composition, customer ownership and verification. Explicit OpenNext, queue/DLQ and Basin selections use Wrangler delivery.
|
|
22
|
-
|
|
23
|
-
Vinext on Cloudflare Workers by default; native Next.js on Vercel is an explicit option. Free-to-start where suitable, within provider eligibility and limits. Respect the existing account, budget, audience and release authorization. Request only missing approval for paid activation, material spending, architecture changes or release. Do not deploy or activate providers as part of initialization.
|
|
3
|
+
put(root, 'AGENTS.md', `# Anhedral application
|
|
24
4
|
|
|
25
|
-
|
|
5
|
+
This project uses Next.js App Router/OpenNext for web and Expo for iOS/Android, a Hono Cloudflare Worker, Drizzle/D1, and private R2. Better Auth supplies the identity needed for private storage and payments. Shared styling tokens are in packages/styling; native components use the Anhedral-maintained shadcn port in packages/native-ui. Optional integrations are Stripe and RevenueCat only.
|
|
26
6
|
|
|
27
|
-
|
|
7
|
+
Hono owns authentication, authorization, persistence, and provider credentials. Clients use API contracts in packages/contracts and never import database/auth server code. Apps must not import each other's source. Keep one root pnpm lockfile. No secrets belong in client bundles.
|
|
28
8
|
|
|
29
|
-
|
|
9
|
+
Review SQL produced by pnpm db:generate. Apply local migrations explicitly using pnpm db:migrate. Remote migrations require an explicit --remote and reviewed target. Builds and startup never migrate databases. R2 stays private; the API derives object namespaces from the verified user, never client-supplied ownership.
|
|
30
10
|
|
|
31
|
-
|
|
11
|
+
Run pnpm lint, pnpm typecheck, and pnpm build. Verify signup/signin/signout, anonymous rejection and cross-user file isolation. Payment additions require provider sandbox purchase/restore/webhook verification. Keep architecture and dated acceptance evidence in docs/architecture.md and docs/verification.md. Init does not provision, deploy or activate payment services.
|
|
12
|
+
`);
|
|
13
|
+
put(root, 'README.md', `# ${options.name}
|
|
32
14
|
|
|
33
|
-
|
|
15
|
+
Next.js web + native Expo + Hono + Drizzle/D1 + private R2. Better Auth provides email/password accounts for private files. ${options.products.includes('stripe') ? 'Stripe is selected. ' : ''}${options.products.includes('revenuecat') ? 'RevenueCat is selected.' : ''}
|
|
34
16
|
|
|
35
|
-
|
|
17
|
+
## Local setup
|
|
36
18
|
|
|
37
|
-
|
|
38
|
-
`);
|
|
39
|
-
put(root, 'README.md', `# ${markdownHeading(options.name)}
|
|
19
|
+
Use the Node and pnpm versions in package.json. Install dependencies if initialization used --skip-install.
|
|
40
20
|
|
|
41
|
-
|
|
21
|
+
1. Copy apps/api/.dev.vars.example to apps/api/.dev.vars. Set BETTER_AUTH_SECRET to at least 32 random characters and keep BETTER_AUTH_URL=http://localhost:3000 for local web.
|
|
22
|
+
2. Run pnpm db:generate, review the generated SQL, then pnpm db:migrate (local D1 only by default).
|
|
23
|
+
3. Run pnpm dev. Open http://localhost:3000. Create an account using the Sign in / account link.
|
|
24
|
+
4. Native development uses pnpm --dir apps/mobile start. Configure EXPO_PUBLIC_API_URL in apps/mobile/.env for an API address reachable by the device and set BETTER_AUTH_URL to that origin when testing native. Use HTTPS outside local development.
|
|
42
25
|
|
|
43
|
-
|
|
26
|
+
## Private files
|
|
44
27
|
|
|
45
|
-
|
|
28
|
+
Authenticated POST /api/files accepts raw bytes up to 1 MiB and returns an opaque id. GET /api/files/:id downloads it; DELETE /api/files/:id deletes it. Every operation is scoped to the signed-in user. Files are forced to download as application/octet-stream; bucket credentials and public bucket URLs are never sent to clients. Applications add their own file picker, quotas, retention and product UI.
|
|
46
29
|
|
|
47
|
-
|
|
30
|
+
## Cloud resources and delivery
|
|
48
31
|
|
|
49
|
-
|
|
32
|
+
Initialization is local source generation. Configure the intended Cloudflare account, provision a D1 database and private R2 bucket using the CLI provider workflow, and review apps/api/wrangler.jsonc. Keep public R2 access disabled. Set production secrets through Wrangler. Review/apply remote migrations explicitly before deployment. Ship the API before the Next.js OpenNext Worker, then verify real authentication and file isolation. See docs/stack.md and anhedral.json for setup requirements.
|
|
50
33
|
|
|
51
|
-
|
|
52
|
-
${has('neon') ? 'Configure DATABASE_URL_UNPOOLED separately in packages/db/.env for transactional migrations on the intended branch. Configure server-only DATABASE_URL for the intended Neon branch and role. Direct HTTP needs no Hyperdrive or connection cleanup. Review migrations and authorization; interactive transactions require a reviewed WebSocket or PostgreSQL adapter.\n' : ''}
|
|
53
|
-
${has('neon') || has('d1') ? 'packages/db/src owns the reusable database factory, schema and migration entry point. Generated SQL lives in packages/db/drizzle; the config resolves paths from its own directory. Run pnpm db:generate, review SQL, then pnpm db:migrate. These tasks are uncached and separate from application builds. D1 defaults to local; pass -- --remote explicitly for the selected Worker database. Browser and native interfaces use an API, never database credentials.\n' : ''}
|
|
54
|
-
${has('better-auth') ? 'Core Better Auth tables are included in the Drizzle schema. Review and apply migrations before using /api/auth. Configure BETTER_AUTH_SECRET, BETTER_AUTH_URL and trusted origins for the correct environment.\n' : ''}
|
|
55
|
-
${has('clerk') ? `${has('next') || has('vinext') ? 'The web starter includes ClerkProvider, middleware and sign-in/sign-up pages. Configure NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and server-only CLERK_SECRET_KEY. ' : ''}${has('hono') ? 'packages/auth exports a Clerk request authentication helper. Configure its server secret and publishable key, supply explicit authorized origins, and wire it into product routes; the API health route remains public. ' : ''}Authentication does not establish resource authorization.\n` : ''}
|
|
56
|
-
${has('r2') ? 'FILES is a private R2 binding. Implement authentication and file-level authorization before exposing file routes. Clients never receive R2 credentials.\n' : ''}
|
|
57
|
-
${has('neon-realtime') ? 'Neon Realtime is an optional beta live SQL foundation, separate from Durable Object rooms. Read [packages/neon-realtime/README.md](packages/neon-realtime/README.md) for the server/client factories and Drizzle adapter. Manually enable the intended branch, configure exact allowed origins and set server-only NEON_REALTIME_SECRET with DATABASE_URL; NEON_REALTIME_URL is public client transport configuration. Authenticate sealing requests and scope every query to verified user/tenant access. Implement subscriptions, authorized renewal and isolation tests; RLS, automatic Realtime provisioning and a public SQL endpoint are not provided. Live behavior remains unverified.\n' : ''}
|
|
58
|
-
${has('stream') ? 'Cloudflare Stream provides optional one-to-many WHIP/WHEP live video. Follow packages/stream/README.md and import the management factory only from @workspace/stream/server. Configure server-only STREAM_API_TOKEN and STREAM_ACCOUNT_ID manually. Authorize creators and input ownership; never return secret WHIP URLs to viewers. Implement playback token issuance for private media, browser signaling/UI and session cleanup. Stream activation, live inputs and runtime credentials are not automatically provisioned; live behavior remains unverified.\n' : ''}
|
|
59
|
-
${has('realtime') ? 'Durable Object rooms support hibernating WebSockets; the public entrypoint remains disabled until room authorization and short-lived tickets are implemented.\n' : ''}
|
|
60
|
-
${has('queues') ? 'Queue processing retries unimplemented jobs and uses a dead-letter queue. Add product processing and transactional idempotency before acknowledging messages.\n' : ''}
|
|
61
|
-
${has('basin') ? 'Basin uses a Pipelines stream binding. Configure its stream, sink, R2/catalog and SQL in client-owned infrastructure; it is distinct from operational logs.\n' : ''}
|
|
62
|
-
${has('neon') ? 'Neon provisioning configures the server runtime DATABASE_URL only. Set a separate direct DATABASE_URL_UNPOOLED in ignored packages/db/.env for the intended migration database and role. Run pnpm db:generate, review SQL, then pnpm db:migrate before testing authentication or application data.\n' : ''}
|
|
63
|
-
The root pnpm test command runs workspace test tasks; no application tests or test:live script are generated. Implement them for the product before verification.\n\nProvider packages are SDK factories or integration boundaries, not finished business features. Connect only needed packages to server entrypoints. Billing needs verified webhooks and idempotent consumption; RevenueCat adds cross-store entitlement configuration. Local data needs a platform-specific SQLite/filesystem adapter. Sentry needs a platform SDK and runtime initialization. Native auth and subscriptions need platform-specific setup.
|
|
34
|
+
Next.js supports request-rendered HTML and React Server Components. Production requires the ANHEDRAL_API service binding; API_INTERNAL_URL is restricted to loopback development. The default OpenNext adapter does not provision persistent ISR/cache storage. Private R2 and all database/auth/provider credentials belong only to Hono.
|
|
64
35
|
|
|
65
|
-
|
|
66
|
-
`);
|
|
67
|
-
put(root, '.github/workflows/check.yml', `name: Check
|
|
68
|
-
on:
|
|
69
|
-
pull_request:
|
|
70
|
-
push:
|
|
71
|
-
branches: [main]
|
|
72
|
-
permissions:
|
|
73
|
-
contents: read
|
|
74
|
-
jobs:
|
|
75
|
-
check:
|
|
76
|
-
runs-on: ubuntu-latest
|
|
77
|
-
timeout-minutes: 20
|
|
78
|
-
steps:
|
|
79
|
-
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
|
|
80
|
-
with:
|
|
81
|
-
fetch-depth: 0
|
|
82
|
-
persist-credentials: false
|
|
83
|
-
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271
|
|
84
|
-
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38
|
|
85
|
-
with:
|
|
86
|
-
node-version: '${voidSelected ? '24.21.0' : '22'}'
|
|
87
|
-
cache: pnpm
|
|
88
|
-
- run: pnpm install --frozen-lockfile
|
|
89
|
-
- run: pnpm lint && pnpm typecheck && pnpm audit:deps
|
|
90
|
-
- name: Audit pull request
|
|
91
|
-
if: github.event_name == 'pull_request'
|
|
92
|
-
env:
|
|
93
|
-
AUDIT_BASE: \${{ github.event.pull_request.base.sha }}
|
|
94
|
-
run: pnpm exec fallow audit --base "$AUDIT_BASE"
|
|
95
|
-
- name: Audit branch
|
|
96
|
-
if: github.event_name != 'pull_request'
|
|
97
|
-
run: pnpm audit:full
|
|
98
|
-
- run: pnpm test && pnpm build${workerBuildSuffix(options)}
|
|
36
|
+
Stripe and RevenueCat remain inactive until client-owned provider products, credentials, origins and webhooks are configured. Verify sandbox flows before live activation.
|
|
99
37
|
`);
|
|
38
|
+
put(root, 'docs/architecture.md', '# Architecture\n\nNext.js web / Expo native → Hono Worker → Drizzle/D1 and private R2. Better Auth identifies users. Record application flows, access boundaries and selected payment providers here.\n');
|
|
39
|
+
put(root, 'docs/verification.md', '# Verification\n\nRecord dates, environments, commands, denied-access checks and unresolved acceptance gaps. Generated source is not production acceptance.\n');
|
|
100
40
|
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
4
|
+
import { jsString } from '../render.js';
|
|
5
|
+
import { json, patchPackage, put, readJson } from './files.js';
|
|
6
|
+
export function expoAuthScheme(root) {
|
|
7
|
+
const config = readJson(root, 'apps/mobile/app.json');
|
|
8
|
+
const scheme = config.expo?.scheme;
|
|
9
|
+
if (typeof scheme !== 'string' || !/^[a-z][a-z0-9+.-]*$/i.test(scheme))
|
|
10
|
+
throw new Error('Expo authentication requires one explicit valid app.json URL scheme.');
|
|
11
|
+
return scheme;
|
|
12
|
+
}
|
|
13
|
+
/** Platform resolution keeps SecureStore and the native plugin out of the browser bundle. */
|
|
14
|
+
export function scaffoldExpoAuth(root, scheme, linkHome = true) {
|
|
15
|
+
const directory = 'apps/mobile';
|
|
16
|
+
patchPackage(root, `${directory}/package.json`, {
|
|
17
|
+
dependencies: {
|
|
18
|
+
'better-auth': STACK_DEPENDENCIES['better-auth'],
|
|
19
|
+
'@better-auth/expo': STACK_DEPENDENCIES['@better-auth/expo'],
|
|
20
|
+
'expo-secure-store': STACK_DEPENDENCIES['expo-secure-store'],
|
|
21
|
+
'expo-network': STACK_DEPENDENCIES['expo-network'],
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
const config = readJson(root, `${directory}/app.json`);
|
|
25
|
+
const expo = config.expo;
|
|
26
|
+
const plugins = expo.plugins ?? [];
|
|
27
|
+
if (!plugins.some((plugin) => (Array.isArray(plugin) ? plugin[0] : plugin) === 'expo-secure-store'))
|
|
28
|
+
expo.plugins = [...plugins, 'expo-secure-store'];
|
|
29
|
+
json(root, `${directory}/app.json`, config);
|
|
30
|
+
put(root, `${directory}/lib/auth-client.ts`, `export { getAuthClient, authConfigurationError } from './auth-client.native';\n`);
|
|
31
|
+
put(root, `${directory}/lib/auth-client.native.ts`, `import { createAuthClient } from 'better-auth/react';
|
|
32
|
+
import { expoClient } from '@better-auth/expo/client';
|
|
33
|
+
import * as SecureStore from 'expo-secure-store';
|
|
34
|
+
import { nativeApiOrigin } from './api-client';
|
|
35
|
+
|
|
36
|
+
export function authConfigurationError(): string | null {
|
|
37
|
+
try { nativeApiOrigin(); return null; }
|
|
38
|
+
catch (error) { return error instanceof Error ? error.message : 'Invalid product API origin.'; }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function createNativeClient() {
|
|
42
|
+
return createAuthClient({
|
|
43
|
+
baseURL: nativeApiOrigin(),
|
|
44
|
+
plugins: [expoClient({ scheme: ${jsString(scheme)}, storagePrefix: ${jsString(scheme)}, storage: SecureStore })],
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
let client: ReturnType<typeof createNativeClient> | undefined;
|
|
48
|
+
export function getAuthClient() { return client ??= createNativeClient(); }
|
|
49
|
+
`);
|
|
50
|
+
put(root, `${directory}/lib/session-api.ts`, `export { sessionApi } from './session-api.native';\n`);
|
|
51
|
+
put(root, `${directory}/lib/session-api.native.ts`, `import { createApplicationApiClient } from './api-client';
|
|
52
|
+
import { getAuthClient } from './auth-client.native';
|
|
53
|
+
|
|
54
|
+
export const sessionApi = createApplicationApiClient({ headers: async () => {
|
|
55
|
+
const cookie = await getAuthClient().getCookie();
|
|
56
|
+
const headers = new Headers();
|
|
57
|
+
if (cookie) headers.set('cookie', cookie);
|
|
58
|
+
return headers;
|
|
59
|
+
} });
|
|
60
|
+
`);
|
|
61
|
+
put(root, `${directory}/components/auth-configuration.tsx`, `import { Text, Screen } from '@workspace/native-ui';
|
|
62
|
+
import { authConfigurationError } from '@/lib/auth-client';
|
|
63
|
+
|
|
64
|
+
export function AuthConfiguration({ children }: { children: React.ReactNode }) {
|
|
65
|
+
const error = authConfigurationError();
|
|
66
|
+
if (error) return <Screen><Text accessibilityRole="header">Configure the product API</Text><Text selectable>{error}</Text></Screen>;
|
|
67
|
+
return <>{children}</>;
|
|
68
|
+
}
|
|
69
|
+
`);
|
|
70
|
+
put(root, `${directory}/app/sign-in.tsx`, `import { useState } from 'react';
|
|
71
|
+
import { Link, router } from 'expo-router';
|
|
72
|
+
import * as Linking from 'expo-linking';
|
|
73
|
+
import { Screen, Text, Input as TextInput } from '@workspace/native-ui';
|
|
74
|
+
import { Button } from '@/components/ui/button';
|
|
75
|
+
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
76
|
+
import { getAuthClient } from '@/lib/auth-client';
|
|
77
|
+
import { sessionApi } from '@/lib/session-api';
|
|
78
|
+
|
|
79
|
+
export default function SignInRoute() { return <AuthConfiguration><SignIn /></AuthConfiguration>; }
|
|
80
|
+
|
|
81
|
+
function verificationPending(create: boolean, signedIn: boolean): boolean { return create && !signedIn; }
|
|
82
|
+
function modeLabel(create: boolean): string { return create ? 'Create account' : 'Sign in'; }
|
|
83
|
+
function submitLabel(pending: boolean, create: boolean): string { return pending ? 'Working…' : modeLabel(create); }
|
|
84
|
+
function switchLabel(create: boolean): string { return create ? 'Use an existing account' : 'Create an account'; }
|
|
85
|
+
function authenticationError(error: unknown): string {
|
|
86
|
+
return error instanceof Error ? error.message : 'Unable to verify the session. Check the connection and try again.';
|
|
87
|
+
}
|
|
88
|
+
async function authenticate(values: { create: boolean; name: string; email: string; password: string }) {
|
|
89
|
+
const auth = getAuthClient();
|
|
90
|
+
const result = values.create ? await auth.signUp.email({ ...values, callbackURL: Linking.createURL('sign-in') }) : await auth.signIn.email(values);
|
|
91
|
+
if (result.error) throw new Error('Sign in failed. Verify your email or check your details.');
|
|
92
|
+
return Boolean(result.data?.token);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function SignIn() {
|
|
96
|
+
const { refetch } = getAuthClient().useSession();
|
|
97
|
+
const [create, setCreate] = useState(false);
|
|
98
|
+
const [name, setName] = useState('');
|
|
99
|
+
const [email, setEmail] = useState('');
|
|
100
|
+
const [password, setPassword] = useState('');
|
|
101
|
+
const [pending, setPending] = useState(false);
|
|
102
|
+
const [message, setMessage] = useState('');
|
|
103
|
+
async function submit() {
|
|
104
|
+
if (pending) return;
|
|
105
|
+
setPending(true); setMessage('');
|
|
106
|
+
try {
|
|
107
|
+
const signedIn = await authenticate({ create, name, email, password });
|
|
108
|
+
if (verificationPending(create, signedIn)) { setPassword(''); setMessage('Check your email to verify your account, then sign in.'); setCreate(false); return; }
|
|
109
|
+
await sessionApi.session();
|
|
110
|
+
await refetch();
|
|
111
|
+
setPassword('');
|
|
112
|
+
router.replace('/account');
|
|
113
|
+
} catch (error) { setMessage(authenticationError(error)); }
|
|
114
|
+
finally { setPending(false); }
|
|
115
|
+
}
|
|
116
|
+
async function resend() {
|
|
117
|
+
if (pending) return; setPending(true); setMessage('');
|
|
118
|
+
try {
|
|
119
|
+
const result = await getAuthClient().sendVerificationEmail({ email, callbackURL: Linking.createURL('sign-in') });
|
|
120
|
+
if (result.error) throw Error('Verification unavailable');
|
|
121
|
+
setMessage('If verification is needed, check your email for the link.');
|
|
122
|
+
} catch { setMessage('Unable to request verification. Please retry.'); }
|
|
123
|
+
finally { setPending(false); }
|
|
124
|
+
}
|
|
125
|
+
return <Screen>
|
|
126
|
+
<Text accessibilityRole="header">{modeLabel(create)}</Text>
|
|
127
|
+
{create && <TextInput accessibilityLabel="Name" placeholder="Name" value={name} onChangeText={setName} autoComplete="name" />}
|
|
128
|
+
<TextInput accessibilityLabel="Email" placeholder="Email" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" autoComplete="email" />
|
|
129
|
+
<TextInput accessibilityLabel="Password" placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry autoComplete={create ? 'new-password' : 'current-password'} />
|
|
130
|
+
<Button disabled={pending} onPress={() => void submit()}>{submitLabel(pending, create)}</Button>
|
|
131
|
+
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
132
|
+
<Link href="/reset-password">Forgot your password?</Link>
|
|
133
|
+
<Button disabled={pending || !email} onPress={() => void resend()}>Resend verification email</Button>
|
|
134
|
+
<Button disabled={pending} onPress={() => { setCreate(!create); setMessage(''); }}>{switchLabel(create)}</Button>
|
|
135
|
+
</Screen>;
|
|
136
|
+
}
|
|
137
|
+
`);
|
|
138
|
+
put(root, `${directory}/app/account.tsx`, `import { useEffect, useState } from 'react';
|
|
139
|
+
import { Link, Redirect, router } from 'expo-router';
|
|
140
|
+
import { Text, Screen } from '@workspace/native-ui';
|
|
141
|
+
import type { Session } from '@workspace/contracts';
|
|
142
|
+
import { Button } from '@/components/ui/button';
|
|
143
|
+
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
144
|
+
import { getAuthClient } from '@/lib/auth-client';
|
|
145
|
+
import { sessionApi } from '@/lib/session-api';
|
|
146
|
+
|
|
147
|
+
export default function AccountRoute() { return <AuthConfiguration><Account /></AuthConfiguration>; }
|
|
148
|
+
|
|
149
|
+
function Account() {
|
|
150
|
+
const { data: session, isPending, refetch } = getAuthClient().useSession();
|
|
151
|
+
const userId = session?.user.id;
|
|
152
|
+
const [verified, setVerified] = useState<Session['user'] | null>(null);
|
|
153
|
+
const [message, setMessage] = useState('');
|
|
154
|
+
const [pending, setPending] = useState(false);
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
let active = true;
|
|
157
|
+
if (userId) void sessionApi.session().then(
|
|
158
|
+
(current) => { if (active) { setVerified(current.user); setMessage(''); } },
|
|
159
|
+
() => { if (active) { setVerified(null); setMessage('The server could not verify this session. Sign in again or retry when connected.'); } },
|
|
160
|
+
);
|
|
161
|
+
return () => { active = false; };
|
|
162
|
+
}, [userId]);
|
|
163
|
+
async function signOut() {
|
|
164
|
+
setVerified(null); setPending(true); setMessage('');
|
|
165
|
+
try {
|
|
166
|
+
const result = await getAuthClient().signOut();
|
|
167
|
+
if (result.error) { setMessage(result.error.message ?? 'Sign out failed.'); return; }
|
|
168
|
+
await refetch(); router.replace('/sign-in');
|
|
169
|
+
} catch { setMessage('Unable to sign out. Check the connection and retry.'); }
|
|
170
|
+
finally { setPending(false); }
|
|
171
|
+
}
|
|
172
|
+
if (isPending) return <Screen><Text>Restoring session…</Text></Screen>;
|
|
173
|
+
if (!session) return <Redirect href="/sign-in" />;
|
|
174
|
+
return <AccountContent userId={session.user.id} verified={verified} message={message} pending={pending} signOut={signOut} />;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function accountMessage(userId: string, verified: Session['user'] | null, message: string): string {
|
|
178
|
+
if (verified?.id === userId) return verified.email;
|
|
179
|
+
return message || 'Verifying with the API…';
|
|
180
|
+
}
|
|
181
|
+
function AccountContent({ userId, verified, message, pending, signOut }: {
|
|
182
|
+
userId: string; verified: Session['user'] | null; message: string; pending: boolean; signOut: () => Promise<void>;
|
|
183
|
+
}) {
|
|
184
|
+
return <Screen>
|
|
185
|
+
<Text accessibilityRole="header">Account</Text>
|
|
186
|
+
<Text>{accountMessage(userId, verified, message)}</Text>
|
|
187
|
+
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
188
|
+
<Button disabled={pending} onPress={() => void signOut()}>{pending ? 'Signing out…' : 'Sign out'}</Button>
|
|
189
|
+
<Link href="/sign-in">Sign in again</Link>
|
|
190
|
+
<Link href="/">Home</Link>
|
|
191
|
+
</Screen>;
|
|
192
|
+
}
|
|
193
|
+
`);
|
|
194
|
+
// Additions expose /account and /sign-in without rewriting existing product screens.
|
|
195
|
+
if (!linkHome)
|
|
196
|
+
return;
|
|
197
|
+
const home = `${directory}/app/index.tsx`;
|
|
198
|
+
const source = readFileSync(path.join(root, home), 'utf8');
|
|
199
|
+
if (source.includes('<Link href="/account">'))
|
|
200
|
+
return;
|
|
201
|
+
put(root, home, "import { Link } from 'expo-router';\n" +
|
|
202
|
+
source.replace("<Button onPress={() => void Linking.openURL('https://docs.expo.dev')}>Learn more</Button>", '<Link href="/account">Account and sign in</Link>\n <Button onPress={() => void Linking.openURL(\'https://docs.expo.dev\')}>Learn more</Button>'));
|
|
203
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { writeEnvironmentFile } from './environment.js';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
5
|
+
import { patchPackage, put } from './files.js';
|
|
6
|
+
/** Native store purchases and web Stripe checkout share only server-verified entitlements. */
|
|
7
|
+
export function scaffoldExpoBilling({ root, has }) {
|
|
8
|
+
const directory = 'apps/mobile';
|
|
9
|
+
put(root, `${directory}/lib/billing-types.ts`, 'export interface StoreOffer { id: string; label: string; price: string }\n');
|
|
10
|
+
if (has('revenuecat')) {
|
|
11
|
+
writeEnvironmentFile(root, `${directory}/.env.example`, {
|
|
12
|
+
EXPO_PUBLIC_REVENUECAT_IOS_API_KEY: '',
|
|
13
|
+
EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY: '',
|
|
14
|
+
});
|
|
15
|
+
patchPackage(root, `${directory}/package.json`, {
|
|
16
|
+
dependencies: { 'react-native-purchases': STACK_DEPENDENCIES['react-native-purchases'] },
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
put(root, `${directory}/lib/billing-api.ts`, `export { billingApi } from './billing-api.native';\n`);
|
|
20
|
+
put(root, `${directory}/lib/billing-api.native.ts`, `import { createBillingClient } from '@workspace/contracts';
|
|
21
|
+
import { nativeApiOrigin } from './api-client';
|
|
22
|
+
import { getAuthClient } from './auth-client.native';
|
|
23
|
+
|
|
24
|
+
function client() {
|
|
25
|
+
return createBillingClient(nativeApiOrigin() + '/api/billing', {
|
|
26
|
+
credentials: 'omit', headers: async () => {
|
|
27
|
+
const headers = new Headers();
|
|
28
|
+
headers.set('cookie', await getAuthClient().getCookie());
|
|
29
|
+
return headers;
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
export const billingApi = {
|
|
34
|
+
identity: () => client().identity(), entitlements: () => client().entitlements(),
|
|
35
|
+
refresh: () => client().refresh(), checkout: (plan: string, key: string) => client().checkout(plan, key),
|
|
36
|
+
portal: () => client().portal(),
|
|
37
|
+
};
|
|
38
|
+
`);
|
|
39
|
+
put(root, `${directory}/lib/billing-platform.ts`, `export type { StoreOffer } from './billing-types';
|
|
40
|
+
export * from './billing-platform.native';
|
|
41
|
+
`);
|
|
42
|
+
if (has('revenuecat'))
|
|
43
|
+
put(root, `${directory}/lib/billing-platform.native.ts`, nativeStoreSource());
|
|
44
|
+
else
|
|
45
|
+
put(root, `${directory}/lib/billing-platform.native.ts`, `export type { StoreOffer } from './billing-types';
|
|
46
|
+
export async function connectStore(_userId: string): Promise<void> {}
|
|
47
|
+
export async function disconnectStore(): Promise<void> {}
|
|
48
|
+
export async function storeOffers(): Promise<import('./billing-types').StoreOffer[]> { return []; }
|
|
49
|
+
export async function purchaseStoreOffer(_id: string): Promise<void> { throw new Error('RevenueCat is not selected.'); }
|
|
50
|
+
export async function restoreStorePurchases(): Promise<void> { throw new Error('RevenueCat is not selected.'); }
|
|
51
|
+
export async function manageStorePurchases(): Promise<void> { throw new Error('RevenueCat is not selected.'); }
|
|
52
|
+
`);
|
|
53
|
+
put(root, `${directory}/app/billing.tsx`, billingScreenSource());
|
|
54
|
+
const account = `${directory}/app/account.tsx`;
|
|
55
|
+
const source = readFileSync(path.join(root, account), 'utf8');
|
|
56
|
+
const linked = source.includes('href="/billing"')
|
|
57
|
+
? source
|
|
58
|
+
: source.replace('<Link href="/">Home</Link>', '<Link href="/billing">Subscription and entitlements</Link>\n <Link href="/">Home</Link>');
|
|
59
|
+
if (linked.includes('await disconnectStore();'))
|
|
60
|
+
return;
|
|
61
|
+
put(root, account, "import { disconnectStore } from '@/lib/billing-platform';\n" +
|
|
62
|
+
linked.replace('const result = await getAuthClient().signOut();', 'await disconnectStore();\n const result = await getAuthClient().signOut();'));
|
|
63
|
+
}
|
|
64
|
+
function nativeStoreSource() {
|
|
65
|
+
return `import Purchases from 'react-native-purchases';
|
|
66
|
+
import { Linking, Platform } from 'react-native';
|
|
67
|
+
import type { StoreOffer } from './billing-types';
|
|
68
|
+
let generation = 0;
|
|
69
|
+
let account: string | null = null;
|
|
70
|
+
let queue: Promise<void> = Promise.resolve();
|
|
71
|
+
|
|
72
|
+
function serial<T>(action: () => Promise<T>): Promise<T> {
|
|
73
|
+
const next = queue.then(action, action);
|
|
74
|
+
queue = next.then(() => undefined, () => undefined);
|
|
75
|
+
return next;
|
|
76
|
+
}
|
|
77
|
+
function platformKey(): string {
|
|
78
|
+
const keys: Partial<Record<string, string>> = {
|
|
79
|
+
ios: process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY,
|
|
80
|
+
android: process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY,
|
|
81
|
+
};
|
|
82
|
+
return keys[Platform.OS] ?? '';
|
|
83
|
+
}
|
|
84
|
+
function assertIdentity(token: number): void {
|
|
85
|
+
if (token !== generation) throw new Error('The signed-in account changed. Refresh subscriptions.');
|
|
86
|
+
if (!account) throw new Error('Sign in before using purchases.');
|
|
87
|
+
}
|
|
88
|
+
async function assertStoreIdentity(token: number): Promise<void> {
|
|
89
|
+
assertIdentity(token);
|
|
90
|
+
if (await Purchases.getAppUserID() !== account) throw new Error('The store account differs from the verified application account.');
|
|
91
|
+
assertIdentity(token);
|
|
92
|
+
}
|
|
93
|
+
export async function connectStore(userId: string): Promise<void> {
|
|
94
|
+
const token = ++generation;
|
|
95
|
+
account = null;
|
|
96
|
+
await serial(async () => {
|
|
97
|
+
await configureIdentity(userId);
|
|
98
|
+
if (token === generation) account = userId;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
async function configureIdentity(userId: string): Promise<void> {
|
|
102
|
+
const apiKey = platformKey();
|
|
103
|
+
if (!apiKey) throw new Error('Configure the platform public RevenueCat SDK key and rebuild the native app.');
|
|
104
|
+
if (await Purchases.isConfigured()) await Purchases.logIn(userId);
|
|
105
|
+
else Purchases.configure({ apiKey, appUserID: userId });
|
|
106
|
+
await verifyConfiguredIdentity(userId);
|
|
107
|
+
}
|
|
108
|
+
async function verifyConfiguredIdentity(userId: string): Promise<void> {
|
|
109
|
+
if (await Purchases.getAppUserID() !== userId) throw new Error('Store identity synchronization failed.');
|
|
110
|
+
}
|
|
111
|
+
export async function disconnectStore(): Promise<void> {
|
|
112
|
+
++generation; account = null;
|
|
113
|
+
const operation = serial(async () => {
|
|
114
|
+
if (!(await Purchases.isConfigured())) return;
|
|
115
|
+
if (!(await Purchases.isAnonymous())) await Purchases.logOut();
|
|
116
|
+
});
|
|
117
|
+
await bestEffortLogout(operation);
|
|
118
|
+
}
|
|
119
|
+
async function bestEffortLogout(operation: Promise<void>): Promise<void> {
|
|
120
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
121
|
+
try {
|
|
122
|
+
await Promise.race([operation.catch(() => undefined), new Promise<void>((resolve) => { timer = setTimeout(resolve, 5000); })]);
|
|
123
|
+
} finally { clearTimeout(timer); }
|
|
124
|
+
}
|
|
125
|
+
async function availablePackages() {
|
|
126
|
+
const offerings = await Purchases.getOfferings();
|
|
127
|
+
return offerings.current?.availablePackages ?? [];
|
|
128
|
+
}
|
|
129
|
+
export async function storeOffers(): Promise<StoreOffer[]> {
|
|
130
|
+
const token = generation;
|
|
131
|
+
return serial(async () => {
|
|
132
|
+
await assertStoreIdentity(token);
|
|
133
|
+
const items = await availablePackages();
|
|
134
|
+
await assertStoreIdentity(token);
|
|
135
|
+
return items.map((item) => ({ id: item.identifier, label: item.product.title, price: item.product.priceString }));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
export async function purchaseStoreOffer(id: string): Promise<void> {
|
|
139
|
+
const token = generation;
|
|
140
|
+
await serial(async () => {
|
|
141
|
+
await assertStoreIdentity(token);
|
|
142
|
+
const item = (await availablePackages()).find((entry) => entry.identifier === id);
|
|
143
|
+
if (!item) throw new Error('This offering is no longer available. Refresh subscriptions.');
|
|
144
|
+
await assertStoreIdentity(token);
|
|
145
|
+
await Purchases.purchasePackage(item);
|
|
146
|
+
await assertStoreIdentity(token);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
export async function restoreStorePurchases(): Promise<void> {
|
|
150
|
+
const token = generation;
|
|
151
|
+
await serial(async () => { await assertStoreIdentity(token); await Purchases.restorePurchases(); await assertStoreIdentity(token); });
|
|
152
|
+
}
|
|
153
|
+
export async function manageStorePurchases(): Promise<void> {
|
|
154
|
+
const token = generation;
|
|
155
|
+
await serial(async () => {
|
|
156
|
+
await assertStoreIdentity(token);
|
|
157
|
+
const info = await Purchases.getCustomerInfo();
|
|
158
|
+
await assertStoreIdentity(token);
|
|
159
|
+
if (!info.managementURL) throw new Error('No store subscription management link is available.');
|
|
160
|
+
const url = new URL(info.managementURL);
|
|
161
|
+
if (url.protocol !== 'https:') throw new Error('Store management requires HTTPS.');
|
|
162
|
+
await Linking.openURL(url.href);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
`;
|
|
166
|
+
}
|
|
167
|
+
function billingScreenSource() {
|
|
168
|
+
return `import { useCallback, useEffect, useRef, useState } from 'react';
|
|
169
|
+
import { Redirect } from 'expo-router';
|
|
170
|
+
import { View } from 'react-native';
|
|
171
|
+
import { Screen, Text } from '@workspace/native-ui';
|
|
172
|
+
import type { BillingIdentity, BillingEntitlements } from '@workspace/contracts';
|
|
173
|
+
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
174
|
+
import { Button } from '@/components/ui/button';
|
|
175
|
+
import { getAuthClient } from '@/lib/auth-client';
|
|
176
|
+
import { billingApi } from '@/lib/billing-api';
|
|
177
|
+
import { connectStore, disconnectStore, manageStorePurchases, purchaseStoreOffer, restoreStorePurchases, storeOffers, type StoreOffer } from '@/lib/billing-platform';
|
|
178
|
+
|
|
179
|
+
export default function BillingRoute() { return <AuthConfiguration><Billing /></AuthConfiguration>; }
|
|
180
|
+
type Data = { identity: BillingIdentity; state: BillingEntitlements; offers: StoreOffer[] };
|
|
181
|
+
function billingError(error: unknown): string {
|
|
182
|
+
const message = error instanceof Error ? error.message : 'Billing is unavailable. Try again later.';
|
|
183
|
+
if (message === 'API request failed (409).') return 'A checkout, subscription, or billing update already exists. Retry shortly, continue your checkout, or manage your current subscription.';
|
|
184
|
+
return message;
|
|
185
|
+
}
|
|
186
|
+
function assertAccount(identity: BillingIdentity, userId: string, isCurrent: () => boolean) {
|
|
187
|
+
if (!isCurrent()) throw new Error('The signed-in account changed.');
|
|
188
|
+
if (identity.appUserId !== userId) throw new Error('The signed-in billing account changed.');
|
|
189
|
+
}
|
|
190
|
+
async function connectIdentity(identity: BillingIdentity, userId: string, isCurrent: () => boolean) {
|
|
191
|
+
assertAccount(identity, userId, isCurrent);
|
|
192
|
+
if (identity.providers.revenuecat) await connectStore(identity.appUserId);
|
|
193
|
+
assertAccount(identity, userId, isCurrent);
|
|
194
|
+
}
|
|
195
|
+
async function loadBilling(userId: string, isCurrent: () => boolean): Promise<Data> {
|
|
196
|
+
const identity = await billingApi.identity();
|
|
197
|
+
await connectIdentity(identity, userId, isCurrent);
|
|
198
|
+
const state = await billingApi.entitlements();
|
|
199
|
+
const offers = identity.providers.revenuecat ? await storeOffers() : [];
|
|
200
|
+
return { identity, state, offers };
|
|
201
|
+
}
|
|
202
|
+
function Billing() {
|
|
203
|
+
const { data: session, isPending } = getAuthClient().useSession();
|
|
204
|
+
const userId = session?.user.id;
|
|
205
|
+
const [data, setData] = useState<Data | null>(null);
|
|
206
|
+
const [message, setMessage] = useState('');
|
|
207
|
+
const [pending, setPending] = useState(false);
|
|
208
|
+
const [reload, setReload] = useState(0);
|
|
209
|
+
const generation = useRef(0);
|
|
210
|
+
const invalidate = useCallback(() => { ++generation.current; void disconnectStore(); }, []);
|
|
211
|
+
useEffect(() => {
|
|
212
|
+
const token = ++generation.current;
|
|
213
|
+
if (userId) void loadBilling(userId, () => token === generation.current).then(
|
|
214
|
+
(current) => { if (token === generation.current) setData(current); },
|
|
215
|
+
(error) => { if (token === generation.current) setMessage(billingError(error)); },
|
|
216
|
+
);
|
|
217
|
+
return invalidate;
|
|
218
|
+
}, [userId, reload, invalidate]);
|
|
219
|
+
function updateCurrent(token: number, action: () => void) { if (token === generation.current) action(); }
|
|
220
|
+
async function run(action: () => Promise<void>) {
|
|
221
|
+
const token = generation.current;
|
|
222
|
+
setPending(true); setMessage('');
|
|
223
|
+
try {
|
|
224
|
+
await action();
|
|
225
|
+
const state = await billingApi.refresh();
|
|
226
|
+
updateCurrent(token, () => setData((previous) => previous && { ...previous, state }));
|
|
227
|
+
} catch (error) { updateCurrent(token, () => setMessage(billingError(error))); }
|
|
228
|
+
finally { updateCurrent(token, () => setPending(false)); }
|
|
229
|
+
}
|
|
230
|
+
if (isPending) return <Text>Restoring session…</Text>;
|
|
231
|
+
if (!session) return <Redirect href="/sign-in" />;
|
|
232
|
+
return <SessionBilling userId={session.user.id} data={data} message={message} pending={pending} run={run} retry={() => setReload((value) => value + 1)} />;
|
|
233
|
+
}
|
|
234
|
+
function SessionBilling({ userId, data, message, pending, run, retry }: Actions & { userId: string; data: Data | null; message: string; retry: () => void }) {
|
|
235
|
+
if (data?.identity.appUserId !== userId) return <View style={{ padding: 24, gap: 12 }}><Text>{message || 'Loading subscriptions…'}</Text><Button onPress={retry}>Retry subscriptions</Button></View>;
|
|
236
|
+
return <BillingContent data={data} message={message} pending={pending} run={run} />;
|
|
237
|
+
}
|
|
238
|
+
function Entitlements({ state }: { state: BillingEntitlements }) {
|
|
239
|
+
return <View><Text accessibilityRole="header">Last server-verified access</Text>{state.entitlements.map((item) => <Text key={item.key}>{item.key}: {item.active ? 'Active' : 'Inactive'}</Text>)}<Text>Checked: {state.checkedAt}</Text></View>;
|
|
240
|
+
}
|
|
241
|
+
type Actions = { pending: boolean; run: (action: () => Promise<void>) => Promise<void> };
|
|
242
|
+
function NativePlans({ data, pending, run }: Actions & { data: Data }) {
|
|
243
|
+
if (!data.identity.providers.revenuecat) return <Text>Native store purchases are not selected.</Text>;
|
|
244
|
+
return <View style={{ gap: 12 }}>{data.offers.map((offer) => <Button key={offer.id} disabled={pending} onPress={() => void run(() => purchaseStoreOffer(offer.id))}>{offer.label + ' — ' + offer.price}</Button>)}<Button disabled={pending} onPress={() => void run(restoreStorePurchases)}>Restore purchases</Button><Button disabled={pending} onPress={() => void run(manageStorePurchases)}>Manage store subscription</Button></View>;
|
|
245
|
+
}
|
|
246
|
+
function BillingContent({ data, message, pending, run }: Actions & { data: Data; message: string }) {
|
|
247
|
+
return <Screen>
|
|
248
|
+
<Text accessibilityRole="header">Subscriptions</Text>
|
|
249
|
+
<Entitlements state={data.state} />
|
|
250
|
+
<NativePlans data={data} pending={pending} run={run} />
|
|
251
|
+
<Button disabled={pending} onPress={() => void run(async () => undefined)}>Refresh server access</Button>
|
|
252
|
+
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
253
|
+
<Text>Purchases grant access only after server verification. Store account transfers follow the configured provider policy.</Text>
|
|
254
|
+
</Screen>;
|
|
255
|
+
}
|
|
256
|
+
`;
|
|
257
|
+
}
|