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.
Files changed (184) hide show
  1. package/README.md +35 -172
  2. package/assets/patches/audit-deps.mjs +12 -2
  3. package/assets/ui/LICENSE.shadcn +21 -0
  4. package/assets/ui/UPSTREAM.json +33 -0
  5. package/assets/ui/native/button.tsx +85 -0
  6. package/assets/ui/native/card.tsx +33 -0
  7. package/assets/ui/native/dialog.tsx +75 -0
  8. package/assets/ui/native/input.tsx +27 -0
  9. package/assets/ui/native/label.tsx +4 -0
  10. package/assets/ui/native/layout.tsx +26 -0
  11. package/assets/ui/native/text.tsx +20 -0
  12. package/assets/ui/native/theme-switcher.tsx +22 -0
  13. package/assets/ui/theme-storage.ts +25 -0
  14. package/assets/ui/theme.tsx +66 -0
  15. package/assets/ui/web/button.tsx +59 -0
  16. package/assets/ui/web/input.tsx +21 -0
  17. package/assets/ui/web/label.tsx +19 -0
  18. package/dist/capabilities.d.ts +5 -5
  19. package/dist/capabilities.js +3 -21
  20. package/dist/capability-contract.d.ts +3 -3
  21. package/dist/capability-contract.js +11 -39
  22. package/dist/cli-delivery.d.ts +1 -1
  23. package/dist/cli-delivery.js +5 -65
  24. package/dist/cli-output.js +3 -3
  25. package/dist/command-schema.js +35 -80
  26. package/dist/command.js +9 -11
  27. package/dist/delivery-evidence.d.ts +1 -1
  28. package/dist/delivery-evidence.js +7 -36
  29. package/dist/delivery.d.ts +2 -8
  30. package/dist/delivery.js +23 -102
  31. package/dist/dependencies.d.ts +12 -58
  32. package/dist/dependencies.js +67 -189
  33. package/dist/index.d.ts +1 -3
  34. package/dist/index.js +1 -3
  35. package/dist/inspector-model.d.ts +2 -2
  36. package/dist/integration-service-readers.d.ts +1 -2
  37. package/dist/integration-service-readers.js +3 -84
  38. package/dist/lifecycle-model.d.ts +1 -1
  39. package/dist/lifecycle-model.js +1 -1
  40. package/dist/mobile-delivery.d.ts +1 -1
  41. package/dist/mobile-delivery.js +4 -0
  42. package/dist/platforms/mobile.d.ts +1 -1
  43. package/dist/platforms/mobile.js +64 -114
  44. package/dist/platforms/web.d.ts +3 -0
  45. package/dist/platforms/web.js +299 -0
  46. package/dist/project-config.d.ts +1 -1
  47. package/dist/project-config.js +0 -1
  48. package/dist/project-inspector.js +5 -36
  49. package/dist/project-state.d.ts +1 -3
  50. package/dist/project-state.js +6 -86
  51. package/dist/provider-auth.js +3 -32
  52. package/dist/provider-readiness.d.ts +1 -1
  53. package/dist/provider-readiness.js +5 -24
  54. package/dist/providers/adapters.js +9 -178
  55. package/dist/providers/api.d.ts +1 -1
  56. package/dist/providers/api.js +3 -3
  57. package/dist/providers/config.js +2 -48
  58. package/dist/providers/definitions.d.ts +1 -204
  59. package/dist/providers/definitions.js +0 -85
  60. package/dist/providers/provision.d.ts +1 -1
  61. package/dist/providers/receipts.js +1 -11
  62. package/dist/providers/recovery-verification.js +1 -61
  63. package/dist/providers/runtime.js +15 -35
  64. package/dist/providers/state.js +1 -7
  65. package/dist/provision.d.ts +5 -13
  66. package/dist/provision.js +4 -80
  67. package/dist/readiness.d.ts +1 -1
  68. package/dist/readiness.js +3 -6
  69. package/dist/registry/add.js +11 -38
  70. package/dist/registry/bootstrap.d.ts +3 -2
  71. package/dist/registry/bootstrap.js +4 -13
  72. package/dist/registry/commands.js +8 -10
  73. package/dist/registry/context.js +0 -1
  74. package/dist/registry/options.js +8 -26
  75. package/dist/registry/resolve.d.ts +3 -2
  76. package/dist/registry/resolve.js +26 -82
  77. package/dist/registry/types.d.ts +2 -7
  78. package/dist/registry/usage.js +2 -2
  79. package/dist/runtime-policy.d.ts +0 -2
  80. package/dist/runtime-policy.js +0 -13
  81. package/dist/scaffold/api.js +10 -2
  82. package/dist/scaffold/auth.d.ts +1 -2
  83. package/dist/scaffold/auth.js +57 -116
  84. package/dist/scaffold/backend.d.ts +2 -0
  85. package/dist/scaffold/backend.js +39 -0
  86. package/dist/scaffold/billing-config.d.ts +1 -0
  87. package/dist/scaffold/billing-config.js +73 -0
  88. package/dist/scaffold/billing-contracts.d.ts +2 -0
  89. package/dist/scaffold/billing-contracts.js +48 -0
  90. package/dist/scaffold/billing-providers.d.ts +1 -0
  91. package/dist/scaffold/billing-providers.js +249 -0
  92. package/dist/scaffold/billing-schema.d.ts +1 -0
  93. package/dist/scaffold/billing-schema.js +34 -0
  94. package/dist/scaffold/billing-security.d.ts +1 -0
  95. package/dist/scaffold/billing-security.js +46 -0
  96. package/dist/scaffold/billing-server.d.ts +1 -0
  97. package/dist/scaffold/billing-server.js +139 -0
  98. package/dist/scaffold/billing-store.d.ts +1 -0
  99. package/dist/scaffold/billing-store.js +72 -0
  100. package/dist/scaffold/billing.d.ts +2 -0
  101. package/dist/scaffold/billing.js +208 -0
  102. package/dist/scaffold/bootstrap.d.ts +2 -3
  103. package/dist/scaffold/bootstrap.js +37 -43
  104. package/dist/scaffold/compose.js +2 -12
  105. package/dist/scaffold/database.d.ts +1 -1
  106. package/dist/scaffold/database.js +20 -111
  107. package/dist/scaffold/documentation.d.ts +0 -1
  108. package/dist/scaffold/documentation.js +22 -82
  109. package/dist/scaffold/expo-auth.d.ts +3 -0
  110. package/dist/scaffold/expo-auth.js +203 -0
  111. package/dist/scaffold/expo-billing.d.ts +3 -0
  112. package/dist/scaffold/expo-billing.js +257 -0
  113. package/dist/scaffold/expo-runtime.d.ts +3 -0
  114. package/dist/scaffold/expo-runtime.js +43 -0
  115. package/dist/scaffold/integrations.d.ts +1 -2
  116. package/dist/scaffold/integrations.js +9 -5
  117. package/dist/scaffold/managed-email.d.ts +3 -0
  118. package/dist/scaffold/managed-email.js +47 -0
  119. package/dist/scaffold/native-ui.d.ts +2 -0
  120. package/dist/scaffold/native-ui.js +69 -0
  121. package/dist/scaffold/password-reset.d.ts +1 -0
  122. package/dist/scaffold/password-reset.js +99 -0
  123. package/dist/scaffold/private-files.d.ts +2 -0
  124. package/dist/scaffold/private-files.js +78 -0
  125. package/dist/scaffold/stack-documentation.d.ts +0 -1
  126. package/dist/scaffold/stack-documentation.js +3 -49
  127. package/dist/scaffold/styling.d.ts +1 -1
  128. package/dist/scaffold/styling.js +20 -28
  129. package/dist/scaffold/web-billing.d.ts +2 -0
  130. package/dist/scaffold/web-billing.js +48 -0
  131. package/dist/scaffold/workspace.js +53 -189
  132. package/dist/service-deletion.js +1 -1
  133. package/dist/service-descriptor.js +5 -12
  134. package/dist/service-model.d.ts +1 -1
  135. package/dist/service-operations.js +2 -32
  136. package/dist/service-readers.js +1 -32
  137. package/dist/services-command.d.ts +1 -1
  138. package/dist/services-command.js +3 -9
  139. package/dist/ship.d.ts +3 -316
  140. package/dist/ship.js +13 -143
  141. package/dist/stack-registry.d.ts +2 -43
  142. package/dist/stack-registry.js +80 -308
  143. package/dist/standard.js +7 -14
  144. package/dist/version.d.ts +1 -1
  145. package/dist/version.js +1 -1
  146. package/docs/anhedral-stack.md +23 -0
  147. package/docs/assets/anhedral-stack-light.png +0 -0
  148. package/docs/assets/anhedral-stack.png +0 -0
  149. package/docs/software-factory.md +25 -499
  150. package/docs/stack-standard.md +48 -226
  151. package/docs/verification.md +433 -0
  152. package/package.json +22 -21
  153. package/dist/neon-service-data.d.ts +0 -8
  154. package/dist/neon-service-data.js +0 -117
  155. package/dist/platforms/desktop.d.ts +0 -2
  156. package/dist/platforms/desktop.js +0 -415
  157. package/dist/platforms/extension.d.ts +0 -2
  158. package/dist/platforms/extension.js +0 -328
  159. package/dist/scaffold/lint.d.ts +0 -4
  160. package/dist/scaffold/lint.js +0 -56
  161. package/dist/scaffold/neon-realtime.d.ts +0 -2
  162. package/dist/scaffold/neon-realtime.js +0 -97
  163. package/dist/scaffold/services.d.ts +0 -5
  164. package/dist/scaffold/services.js +0 -108
  165. package/dist/scaffold/stream.d.ts +0 -2
  166. package/dist/scaffold/stream.js +0 -114
  167. package/dist/scaffold/void.d.ts +0 -4
  168. package/dist/scaffold/void.js +0 -256
  169. package/dist/scaffold/web.d.ts +0 -2
  170. package/dist/scaffold/web.js +0 -128
  171. package/dist/vercel-project.d.ts +0 -101
  172. package/dist/vercel-project.js +0 -305
  173. package/dist/vercel.d.ts +0 -67
  174. package/dist/vercel.js +0 -581
  175. package/dist/vinext.d.ts +0 -2
  176. package/dist/vinext.js +0 -86
  177. package/dist/void-execution.d.ts +0 -10
  178. package/dist/void-execution.js +0 -94
  179. package/dist/void-migrations.d.ts +0 -6
  180. package/dist/void-migrations.js +0 -110
  181. package/dist/void-state.d.ts +0 -16
  182. package/dist/void-state.js +0 -65
  183. package/dist/void.d.ts +0 -3
  184. package/dist/void.js +0 -5
@@ -0,0 +1,43 @@
1
+ import { writeEnvironmentFile } from './environment.js';
2
+ import { patchPackage, put } from './files.js';
3
+ /** Native uses the public product origin; all browser transport belongs to Next. */
4
+ export function scaffoldExpoRuntime({ root }) {
5
+ const directory = 'apps/mobile';
6
+ patchPackage(root, `${directory}/package.json`, {
7
+ dependencies: { '@workspace/contracts': 'workspace:*' },
8
+ });
9
+ put(root, `${directory}/lib/api-client.ts`, `import { createApiClient } from '@workspace/contracts';
10
+
11
+ type Options = NonNullable<Parameters<typeof createApiClient>[1]>;
12
+
13
+ function validProtocol(url: URL): boolean {
14
+ return url.protocol === 'https:' || (__DEV__ && url.protocol === 'http:');
15
+ }
16
+ export function nativeApiOrigin(): string {
17
+ const configured = process.env.EXPO_PUBLIC_API_URL;
18
+ if (!configured) throw new Error('Configure EXPO_PUBLIC_API_URL with the product origin reachable from this device.');
19
+ const origin = new URL(configured);
20
+ if (!validProtocol(origin)) throw new Error('EXPO_PUBLIC_API_URL requires HTTPS outside development.');
21
+ if ([origin.username, origin.password, origin.pathname !== '/', origin.search, origin.hash].some(Boolean))
22
+ throw new Error('EXPO_PUBLIC_API_URL must be an origin without credentials, path, query or fragment.');
23
+ return origin.origin;
24
+ }
25
+ function apiBaseURL(): string {
26
+ return nativeApiOrigin() + '/api';
27
+ }
28
+
29
+ // A native auth adapter can provide its own session headers. No server secret belongs here.
30
+ export function createApplicationApiClient(options: Options = {}) {
31
+ const client = () => createApiClient(apiBaseURL(), {
32
+ ...options, credentials: 'omit',
33
+ });
34
+ return {
35
+ health: (init?: RequestInit) => client().health(init),
36
+ session: (init?: RequestInit) => client().session(init),
37
+ };
38
+ }
39
+
40
+ export const api = createApplicationApiClient();
41
+ `);
42
+ writeEnvironmentFile(root, `${directory}/.env.example`, { EXPO_PUBLIC_API_URL: '' });
43
+ }
@@ -1,3 +1,2 @@
1
1
  import type { RecipeContext } from '../registry/types.js';
2
- export declare function scaffoldPrivateFiles({ root, runtimeApp }: RecipeContext): void;
3
- export declare function scaffoldRevenueCat({ root }: RecipeContext): void;
2
+ export declare function scaffoldPrivateFiles({ root }: RecipeContext): void;
@@ -1,7 +1,11 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
1
3
  import { put } from './files.js';
2
- export function scaffoldPrivateFiles({ root, runtimeApp }) {
3
- put(root, `apps/${runtimeApp}/private-files.md`, '# Private files\n\nFILES is a private R2 Worker binding. Authenticate the request and enforce file-level product authorization before calling get/put/delete. No public buckets, R2 keys, generic download endpoints, or client credentials are generated. Use the binding directly in Hono or import env from cloudflare:workers in Vinext; explicit OpenNext uses getCloudflareContext.\n');
4
- }
5
- export function scaffoldRevenueCat({ root }) {
6
- put(root, 'packages/billing/revenuecat.md', '# RevenueCat + Stripe\n\nConfigure web/App Store/Play Store products and offerings in client-owned accounts. Add the platform SDK to each selected app. Verify signed provider webhooks, reconcile entitlement authority, and keep transactional idempotent credits/quotas separate from subscription status. No payment activation occurs during init.\n');
4
+ import { PRIVATE_FILES_SOURCE } from './private-files.js';
5
+ export function scaffoldPrivateFiles({ root }) {
6
+ put(root, 'apps/api/src/private-files.ts', PRIVATE_FILES_SOURCE);
7
+ const file = 'apps/api/src/index.ts';
8
+ const source = readFileSync(path.join(root, file), 'utf8');
9
+ put(root, file, "import { privateFileRoutes } from './private-files';\n" +
10
+ source.replace('export default app;', "app.route('/api/files', privateFileRoutes);\nexport default app;"));
7
11
  }
@@ -0,0 +1,3 @@
1
+ /** Generated apps receive a scoped capability, never the broker's provider credentials. */
2
+ export declare function scaffoldManagedEmail(root: string): void;
3
+ export declare const MANAGED_EMAIL_SOURCE = "export type EmailTemplate = 'verify-email' | 'reset-password';\nexport interface EmailEnvironment {\n ANHEDRAL_EMAIL?: { fetch(request: Request): Promise<Response> };\n ANHEDRAL_EMAIL_SCOPE?: string;\n ANHEDRAL_EMAIL_CAPABILITY?: string;\n}\nfunction validConfiguration(env: EmailEnvironment): boolean {\n return [typeof env.ANHEDRAL_EMAIL?.fetch === 'function', /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(env.ANHEDRAL_EMAIL_SCOPE ?? ''), /^[a-f0-9]{72}$/.test(env.ANHEDRAL_EMAIL_CAPABILITY ?? '')].every(Boolean);\n}\nexport function createManagedEmail(env: EmailEnvironment) {\n const { ANHEDRAL_EMAIL: binding, ANHEDRAL_EMAIL_SCOPE: scope, ANHEDRAL_EMAIL_CAPABILITY: capability } = env;\n if (![binding, scope, capability].some(Boolean)) return undefined;\n if (!validConfiguration(env))\n throw new Error('Managed email configuration is incomplete.');\n return async (template: EmailTemplate, to: string, url: string) => {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([template, to, url])));\n const id = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');\n try {\n const response = await binding!.fetch(new Request('https://email.internal/scopes/' + encodeURIComponent(scope!) + '/send', {\n method: 'POST', redirect: 'error',\n headers: { authorization: 'Bearer ' + capability, 'content-type': 'application/json' },\n body: JSON.stringify({ id, template, to, url }), signal: AbortSignal.timeout(15000),\n }));\n if (!response.ok) throw new Error('Email rejected');\n } catch { throw new Error('Application email could not be accepted. Please try again.'); }\n };\n}\n";
@@ -0,0 +1,47 @@
1
+ import { put, sharedPackage } from './files.js';
2
+ /** Generated apps receive a scoped capability, never the broker's provider credentials. */
3
+ export function scaffoldManagedEmail(root) {
4
+ sharedPackage(root, 'managed-email', MANAGED_EMAIL_SOURCE, {});
5
+ put(root, 'packages/managed-email/README.md', `# Managed authentication email
6
+
7
+ Anhedral provisions the ANHEDRAL_EMAIL service binding, ANHEDRAL_EMAIL_SCOPE and
8
+ ANHEDRAL_EMAIL_CAPABILITY in the API Worker only. No provider keys belong in clients.
9
+ The broker owns sender/provider configuration, scope/origin checks, quotas and receipts.
10
+ Configure the scope with this app's public Better Auth origin and exact native URL scheme.
11
+
12
+ With no binding or scope/capability, standalone email/password sessions keep their
13
+ existing behavior. Any partial configuration fails closed. A complete configuration
14
+ requires verified email and enables password reset with session revocation. Do not
15
+ remove configuration to bypass verification. Use a local mail sink in tests; never
16
+ log token URLs or use a production capability in fixtures. Request acceptance does
17
+ not establish inbox delivery. Initialization never provisions the broker or sends mail.
18
+ `);
19
+ }
20
+ export const MANAGED_EMAIL_SOURCE = `export type EmailTemplate = 'verify-email' | 'reset-password';
21
+ export interface EmailEnvironment {
22
+ ANHEDRAL_EMAIL?: { fetch(request: Request): Promise<Response> };
23
+ ANHEDRAL_EMAIL_SCOPE?: string;
24
+ ANHEDRAL_EMAIL_CAPABILITY?: string;
25
+ }
26
+ function validConfiguration(env: EmailEnvironment): boolean {
27
+ return [typeof env.ANHEDRAL_EMAIL?.fetch === 'function', /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(env.ANHEDRAL_EMAIL_SCOPE ?? ''), /^[a-f0-9]{72}$/.test(env.ANHEDRAL_EMAIL_CAPABILITY ?? '')].every(Boolean);
28
+ }
29
+ export function createManagedEmail(env: EmailEnvironment) {
30
+ const { ANHEDRAL_EMAIL: binding, ANHEDRAL_EMAIL_SCOPE: scope, ANHEDRAL_EMAIL_CAPABILITY: capability } = env;
31
+ if (![binding, scope, capability].some(Boolean)) return undefined;
32
+ if (!validConfiguration(env))
33
+ throw new Error('Managed email configuration is incomplete.');
34
+ return async (template: EmailTemplate, to: string, url: string) => {
35
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([template, to, url])));
36
+ const id = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
37
+ try {
38
+ const response = await binding!.fetch(new Request('https://email.internal/scopes/' + encodeURIComponent(scope!) + '/send', {
39
+ method: 'POST', redirect: 'error',
40
+ headers: { authorization: 'Bearer ' + capability, 'content-type': 'application/json' },
41
+ body: JSON.stringify({ id, template, to, url }), signal: AbortSignal.timeout(15000),
42
+ }));
43
+ if (!response.ok) throw new Error('Email rejected');
44
+ } catch { throw new Error('Application email could not be accepted. Please try again.'); }
45
+ };
46
+ }
47
+ `;
@@ -0,0 +1,2 @@
1
+ /** Anhedral-maintained native shadcn port. Never imported by the DOM application. */
2
+ export declare function scaffoldNativeUI(root: string): void;
@@ -0,0 +1,69 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { NATIVE_ESLINT_VERSION, NATIVE_UI_DEPENDENCIES, MOBILE_APP_DEPENDENCIES, } from '../dependencies.js';
4
+ import { json, put } from './files.js';
5
+ import { writeReactLintConfig } from '../platforms/lint.js';
6
+ /** Anhedral-maintained native shadcn port. Never imported by the DOM application. */
7
+ export function scaffoldNativeUI(root) {
8
+ const components = [
9
+ 'button',
10
+ 'card',
11
+ 'dialog',
12
+ 'input',
13
+ 'label',
14
+ 'layout',
15
+ 'text',
16
+ 'theme-switcher',
17
+ ];
18
+ for (const file of [
19
+ 'theme.tsx',
20
+ 'theme-storage.ts',
21
+ 'LICENSE.shadcn',
22
+ 'UPSTREAM.json',
23
+ ...components.map((name) => `native/${name}.tsx`),
24
+ ]) {
25
+ const source = readFileSync(fileURLToPath(new URL(`../../assets/ui/${file}`, import.meta.url)), 'utf8');
26
+ put(root, `packages/native-ui/${file.endsWith('.tsx') || file.endsWith('.ts') ? 'src/' : ''}${file}`, source);
27
+ }
28
+ put(root, 'packages/native-ui/src/index.ts', `export * from './theme';\n` +
29
+ components.map((name) => `export * from './native/${name}';\n`).join(''));
30
+ json(root, 'packages/native-ui/package.json', {
31
+ name: '@workspace/native-ui',
32
+ private: true,
33
+ type: 'module',
34
+ exports: { '.': './src/index.ts' },
35
+ scripts: { typecheck: 'tsc --noEmit', lint: 'eslint . --max-warnings 0' },
36
+ dependencies: {
37
+ ...NATIVE_UI_DEPENDENCIES.dependencies,
38
+ 'react-native-safe-area-context': MOBILE_APP_DEPENDENCIES.dependencies['react-native-safe-area-context'],
39
+ '@workspace/styling': 'workspace:*',
40
+ },
41
+ peerDependencies: {
42
+ react: MOBILE_APP_DEPENDENCIES.dependencies.react,
43
+ 'react-native': MOBILE_APP_DEPENDENCIES.dependencies['react-native'],
44
+ },
45
+ devDependencies: {
46
+ typescript: MOBILE_APP_DEPENDENCIES.devDependencies.typescript,
47
+ '@types/react': MOBILE_APP_DEPENDENCIES.devDependencies['@types/react'],
48
+ react: MOBILE_APP_DEPENDENCIES.dependencies.react,
49
+ 'react-native': MOBILE_APP_DEPENDENCIES.dependencies['react-native'],
50
+ '@workspace/eslint-config': 'workspace:*',
51
+ eslint: NATIVE_ESLINT_VERSION,
52
+ },
53
+ });
54
+ json(root, 'packages/native-ui/tsconfig.json', {
55
+ compilerOptions: {
56
+ target: 'ES2022',
57
+ lib: ['ES2022'],
58
+ module: 'ESNext',
59
+ moduleResolution: 'Bundler',
60
+ strict: true,
61
+ jsx: 'react-jsx',
62
+ noEmit: true,
63
+ skipLibCheck: true,
64
+ esModuleInterop: true,
65
+ },
66
+ include: ['src/**/*.ts', 'src/**/*.tsx'],
67
+ });
68
+ writeReactLintConfig(root + '/packages/native-ui');
69
+ }
@@ -0,0 +1 @@
1
+ export declare function scaffoldPasswordReset(root: string): void;
@@ -0,0 +1,99 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { put } from './files.js';
4
+ export function scaffoldPasswordReset(root) {
5
+ put(root, 'packages/contracts/src/password-reset.ts', PASSWORD_RESET_CLIENT);
6
+ const contracts = readFileSync(path.join(root, 'packages/contracts/src/index.ts'), 'utf8');
7
+ put(root, 'packages/contracts/src/index.ts', contracts + "\nexport { submitPasswordReset, passwordResetLabel } from './password-reset';\n");
8
+ put(root, 'apps/web/app/reset-password/page.tsx', `import { PasswordReset } from '@/components/password-reset';
9
+ export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
10
+ const params = await searchParams;
11
+ return <PasswordReset key={JSON.stringify([params.token, params.error])} token={typeof params.token === 'string' ? params.token : undefined} invalid={Boolean(params.error)} />;
12
+ }
13
+ `);
14
+ put(root, 'apps/web/components/password-reset.tsx', WEB_PASSWORD_RESET);
15
+ put(root, 'apps/mobile/app/reset-password.tsx', NATIVE_PASSWORD_RESET);
16
+ }
17
+ const WEB_PASSWORD_RESET = `'use client';
18
+ import { useState, type FormEvent } from 'react';
19
+ import Link from 'next/link';
20
+ import { authClient } from '@/lib/auth-client';
21
+ import { Button } from '@/components/ui/button';
22
+ import { Input } from '@/components/ui/input';
23
+ import { Label } from '@/components/ui/label';
24
+ import { submitPasswordReset, passwordResetLabel } from '@workspace/contracts';
25
+ function ResetFields({ token }: { token?: string }) {
26
+ return token ? <Label>New password<Input name="password" type="password" autoComplete="new-password" minLength={8} required /></Label> : <Label>Email<Input name="email" type="email" autoComplete="email" required /></Label>;
27
+ }
28
+ export function PasswordReset({ token, invalid }: { token?: string; invalid: boolean }) {
29
+ const [pending, setPending] = useState(false);
30
+ const [complete, setComplete] = useState(false);
31
+ const [message, setMessage] = useState(invalid ? 'This link is invalid or expired. Request a new one.' : '');
32
+ async function submit(event: FormEvent<HTMLFormElement>) {
33
+ event.preventDefault(); if (pending) return;
34
+ const form = event.currentTarget; const data = new FormData(form);
35
+ setPending(true); setMessage('');
36
+ try {
37
+ const message = await submitPasswordReset(authClient, { token, email: String(data.get('email')), password: String(data.get('password')) }, new URL('/reset-password', window.location.origin).href);
38
+ form.reset(); setComplete(Boolean(token)); setMessage(message);
39
+ } catch { setMessage('Unable to complete this request. Try again or request a new link.'); }
40
+ finally { setPending(false); }
41
+ }
42
+ return <section className="stack"><h1>Reset password</h1>{!complete && <form onSubmit={submit}>
43
+ <ResetFields token={token} />
44
+ <Button disabled={pending} type="submit">{passwordResetLabel(pending, token)}</Button>
45
+ </form>}<p role="status">{message}</p><Link href="/reset-password">Request a new link</Link><Link href="/sign-in">Back to sign in</Link></section>;
46
+ }
47
+ `;
48
+ const NATIVE_PASSWORD_RESET = `import { useState } from 'react';
49
+ import { Link, useLocalSearchParams } from 'expo-router';
50
+ import * as Linking from 'expo-linking';
51
+ import { Screen, Text, Input } from '@workspace/native-ui';
52
+ import { Button } from '@/components/ui/button';
53
+ import { getAuthClient } from '@/lib/auth-client';
54
+ import { AuthConfiguration } from '@/components/auth-configuration';
55
+ import { submitPasswordReset, passwordResetLabel } from '@workspace/contracts';
56
+ function disabled(pending: boolean, token: string | undefined, password: string, email: string): boolean { return pending || (token ? password.length < 8 : !email); }
57
+ function ResetFields({ token, password, setPassword, email, setEmail }: { token?: string; password: string; setPassword: (value: string) => void; email: string; setEmail: (value: string) => void }) {
58
+ return token ? <Input accessibilityLabel="New password" value={password} onChangeText={setPassword} secureTextEntry autoComplete="new-password" /> : <Input accessibilityLabel="Email" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" autoComplete="email" />;
59
+ }
60
+ export default function ResetPasswordRoute() {
61
+ const params = useLocalSearchParams<{ token?: string; error?: string }>();
62
+ return <AuthConfiguration><ResetPassword key={JSON.stringify([params.token, params.error])} /></AuthConfiguration>;
63
+ }
64
+ function ResetPassword() {
65
+ const params = useLocalSearchParams<{ token?: string; error?: string }>();
66
+ const token = typeof params.token === 'string' ? params.token : undefined;
67
+ const [email, setEmail] = useState(''); const [password, setPassword] = useState('');
68
+ const [message, setMessage] = useState(params.error ? 'This link is invalid or expired. Request a new one.' : '');
69
+ const [complete, setComplete] = useState(false); const [pending, setPending] = useState(false);
70
+ async function submit() {
71
+ if (pending) return; setPending(true); setMessage('');
72
+ try {
73
+ const message = await submitPasswordReset(getAuthClient(), { token, email, password }, Linking.createURL('reset-password'));
74
+ setPassword(''); setComplete(Boolean(token)); setMessage(message);
75
+ } catch { setMessage('Unable to complete this request. Try again or request a new link.'); }
76
+ finally { setPending(false); }
77
+ }
78
+ return <Screen><Text accessibilityRole="header">Reset password</Text>{!complete && <>
79
+ <ResetFields token={token} password={password} setPassword={setPassword} email={email} setEmail={setEmail} />
80
+ <Button disabled={disabled(pending, token, password, email)} onPress={() => void submit()}>{passwordResetLabel(pending, token)}</Button>
81
+ </>}<Text accessibilityLiveRegion="polite">{message}</Text><Link href="/reset-password">Request a new link</Link><Link href="/sign-in">Back to sign in</Link></Screen>;
82
+ }
83
+ `;
84
+ const PASSWORD_RESET_CLIENT = `interface PasswordResetClient {
85
+ resetPassword(input: { token: string; newPassword: string }): Promise<{ error: unknown }>;
86
+ requestPasswordReset(input: { email: string; redirectTo: string }): Promise<{ error: unknown }>;
87
+ }
88
+ export async function submitPasswordReset(client: PasswordResetClient, values: { token?: string; email: string; password: string }, redirectTo: string): Promise<string> {
89
+ const result = values.token
90
+ ? await client.resetPassword({ token: values.token, newPassword: values.password })
91
+ : await client.requestPasswordReset({ email: values.email, redirectTo });
92
+ if (result.error) throw Error('Reset unavailable');
93
+ return values.token ? 'Password updated. Sign in again.' : 'If an account exists, check your email for the reset link.';
94
+ }
95
+ export function passwordResetLabel(pending: boolean, token?: string): string {
96
+ if (pending) return 'Working…';
97
+ return token ? 'Update password' : 'Send reset link';
98
+ }
99
+ `;
@@ -0,0 +1,2 @@
1
+ /** Generated server code: the caller never selects the owner's R2 namespace. */
2
+ export declare const PRIVATE_FILES_SOURCE = "import { Hono } from 'hono';\nimport { createAuth } from '@workspace/auth';\nimport { createDatabase } from '@workspace/db';\n\nconst MAX_FILE_BYTES = 1024 * 1024;\ntype Identity = (request: Request, env: Env) => Promise<string | null>;\nasync function authenticate(request: Request, env: Env): Promise<string | null> {\n const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });\n return session?.user.id ?? null;\n}\nasync function readFileBody(request: Request): Promise<Uint8Array | null> {\n if (!request.body) return new Uint8Array();\n return readFileStream(request.body);\n}\nasync function readFileStream(body: ReadableStream<Uint8Array>): Promise<Uint8Array | null> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > MAX_FILE_BYTES) { await reader.cancel(); return null; }\n chunks.push(value);\n }\n } finally { reader.releaseLock(); }\n return combineChunks(chunks, size);\n}\nfunction combineChunks(chunks: Uint8Array[], size: number): Uint8Array {\n const result = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }\n return result;\n}\nfunction trustedMutation(request: Request, baseURL: string): boolean {\n if (request.headers.get('sec-fetch-site') === 'cross-site') return false;\n const origin = request.headers.get('origin');\n return !origin || origin === new URL(baseURL).origin;\n}\nfunction createPrivateFileRoutes(identity: Identity = authenticate) {\n const routes = new Hono<{ Bindings: Env; Variables: { fileOwner: string } }>();\n routes.use('*', async (c, next) => {\n c.header('cache-control', 'private, no-store');\n const userId = await identity(c.req.raw, c.env);\n if (!userId) return c.json({ error: 'Unauthorized' }, 401);\n c.set('fileOwner', encodeURIComponent(userId));\n const mutation = !['GET', 'HEAD'].includes(c.req.method);\n if (mutation && !trustedMutation(c.req.raw, c.env.BETTER_AUTH_URL)) return c.json({ error: 'Unexpected request origin' }, 403);\n await next();\n });\n routes.post('/', async (c) => {\n // Raw bytes keep upload memory bounded. Only the server creates keys.\n const bytes = await readFileBody(c.req.raw);\n if (!bytes) return c.json({ error: 'File exceeds 1 MiB' }, 413);\n if (!bytes.byteLength) return c.json({ error: 'An empty file is not allowed' }, 400);\n const id = crypto.randomUUID();\n await c.env.FILES.put(c.get('fileOwner') + '/' + id, bytes, { httpMetadata: { contentType: 'application/octet-stream' } });\n return c.json({ id, size: bytes.byteLength }, 201);\n });\n routes.use('/:id', async (c, next) => {\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.req.param('id') ?? '')) return c.json({ error: 'Not found' }, 404);\n await next();\n });\n routes.get('/:id', async (c) => {\n const object = await c.env.FILES.get(c.get('fileOwner') + '/' + c.req.param('id'));\n if (!object) return c.json({ error: 'Not found' }, 404);\n return new Response(object.body, { headers: { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename=\"download\"', 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' } });\n });\n routes.delete('/:id', async (c) => {\n await c.env.FILES.delete(c.get('fileOwner') + '/' + c.req.param('id'));\n return c.body(null, 204);\n });\n return routes;\n}\nexport const privateFileRoutes = createPrivateFileRoutes();\n";
@@ -0,0 +1,78 @@
1
+ /** Generated server code: the caller never selects the owner's R2 namespace. */
2
+ export const PRIVATE_FILES_SOURCE = `import { Hono } from 'hono';
3
+ import { createAuth } from '@workspace/auth';
4
+ import { createDatabase } from '@workspace/db';
5
+
6
+ const MAX_FILE_BYTES = 1024 * 1024;
7
+ type Identity = (request: Request, env: Env) => Promise<string | null>;
8
+ async function authenticate(request: Request, env: Env): Promise<string | null> {
9
+ const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });
10
+ return session?.user.id ?? null;
11
+ }
12
+ async function readFileBody(request: Request): Promise<Uint8Array | null> {
13
+ if (!request.body) return new Uint8Array();
14
+ return readFileStream(request.body);
15
+ }
16
+ async function readFileStream(body: ReadableStream<Uint8Array>): Promise<Uint8Array | null> {
17
+ const reader = body.getReader();
18
+ const chunks: Uint8Array[] = [];
19
+ let size = 0;
20
+ try {
21
+ while (true) {
22
+ const { done, value } = await reader.read();
23
+ if (done) break;
24
+ size += value.byteLength;
25
+ if (size > MAX_FILE_BYTES) { await reader.cancel(); return null; }
26
+ chunks.push(value);
27
+ }
28
+ } finally { reader.releaseLock(); }
29
+ return combineChunks(chunks, size);
30
+ }
31
+ function combineChunks(chunks: Uint8Array[], size: number): Uint8Array {
32
+ const result = new Uint8Array(size);
33
+ let offset = 0;
34
+ for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }
35
+ return result;
36
+ }
37
+ function trustedMutation(request: Request, baseURL: string): boolean {
38
+ if (request.headers.get('sec-fetch-site') === 'cross-site') return false;
39
+ const origin = request.headers.get('origin');
40
+ return !origin || origin === new URL(baseURL).origin;
41
+ }
42
+ function createPrivateFileRoutes(identity: Identity = authenticate) {
43
+ const routes = new Hono<{ Bindings: Env; Variables: { fileOwner: string } }>();
44
+ routes.use('*', async (c, next) => {
45
+ c.header('cache-control', 'private, no-store');
46
+ const userId = await identity(c.req.raw, c.env);
47
+ if (!userId) return c.json({ error: 'Unauthorized' }, 401);
48
+ c.set('fileOwner', encodeURIComponent(userId));
49
+ const mutation = !['GET', 'HEAD'].includes(c.req.method);
50
+ if (mutation && !trustedMutation(c.req.raw, c.env.BETTER_AUTH_URL)) return c.json({ error: 'Unexpected request origin' }, 403);
51
+ await next();
52
+ });
53
+ routes.post('/', async (c) => {
54
+ // Raw bytes keep upload memory bounded. Only the server creates keys.
55
+ const bytes = await readFileBody(c.req.raw);
56
+ if (!bytes) return c.json({ error: 'File exceeds 1 MiB' }, 413);
57
+ if (!bytes.byteLength) return c.json({ error: 'An empty file is not allowed' }, 400);
58
+ const id = crypto.randomUUID();
59
+ await c.env.FILES.put(c.get('fileOwner') + '/' + id, bytes, { httpMetadata: { contentType: 'application/octet-stream' } });
60
+ return c.json({ id, size: bytes.byteLength }, 201);
61
+ });
62
+ routes.use('/:id', async (c, next) => {
63
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.req.param('id') ?? '')) return c.json({ error: 'Not found' }, 404);
64
+ await next();
65
+ });
66
+ routes.get('/:id', async (c) => {
67
+ const object = await c.env.FILES.get(c.get('fileOwner') + '/' + c.req.param('id'));
68
+ if (!object) return c.json({ error: 'Not found' }, 404);
69
+ return new Response(object.body, { headers: { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename="download"', 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' } });
70
+ });
71
+ routes.delete('/:id', async (c) => {
72
+ await c.env.FILES.delete(c.get('fileOwner') + '/' + c.req.param('id'));
73
+ return c.body(null, 204);
74
+ });
75
+ return routes;
76
+ }
77
+ export const privateFileRoutes = createPrivateFileRoutes();
78
+ `;
@@ -1,3 +1,2 @@
1
1
  import type { ResolvedStackRegistry } from '../registry/resolve.js';
2
- /** Human-readable companion to the current resolved registry, refreshed by add. */
3
2
  export declare function writeStackDocumentation(root: string, registry: ResolvedStackRegistry): void;
@@ -1,52 +1,6 @@
1
- import { WORKER_DEV_PORTS } from '../dependencies.js';
2
1
  import { put } from './files.js';
3
- /** Human-readable companion to the current resolved registry, refreshed by add. */
4
2
  export function writeStackDocumentation(root, registry) {
5
- const sections = registry.items.map((item) => {
6
- const lines = [
7
- `## ${item.name}`,
8
- '',
9
- item.description + '.',
10
- '',
11
- `Targets: ${item.targets.map((target) => `\`${target}\``).join(', ')}.`,
12
- ];
13
- if (item.environment.length)
14
- lines.push(`Environment: ${item.environment.map((key) => `\`${key}\``).join(', ')}.`);
15
- if (item.bindings)
16
- lines.push('', 'Worker configuration:', '', '```json', JSON.stringify(item.bindings, null, 2), '```');
17
- if (item.setup) {
18
- for (const [label, entries] of [
19
- ['Required setup', item.setup.resources],
20
- ['Credentials', item.setup.credentials],
21
- ['Verify before delivery', item.setup.verify],
22
- ]) {
23
- if (!entries.length)
24
- continue;
25
- lines.push('', `${label}:`, '', ...entries.map((entry) => `- ${entry}`));
26
- }
27
- }
28
- return lines.join('\n');
29
- });
30
- const ports = Object.entries(WORKER_DEV_PORTS)
31
- .filter(([app]) => registry.items.some((item) => item.targets.includes(`apps/${app}`)))
32
- .map(([app, port]) => `| ${app} | ${port.http} | ${port.inspector} |`);
33
- put(root, 'docs/stack.md', [
34
- '# Selected stack',
35
- '',
36
- `Generated from the bundled Anhedral ${registry.cliVersion} registry. Project configuration lives in anhedral.json; setup and registry record the current selection and generated source, providers holds integration settings, and cloudflare/vercel hold selected hosting configuration. This document is refreshed by add. Keep product decisions in docs/architecture.md and acceptance evidence in docs/verification.md.`,
37
- '',
38
- 'These are scaffolds and integration boundaries. Provider access, migrations, authorization and live behavior require the setup and checks listed below.',
39
- ...(ports.length
40
- ? [
41
- '',
42
- '## Local Worker ports',
43
- '',
44
- '| Application | HTTP | Inspector |',
45
- '| --- | --- | --- |',
46
- ...ports,
47
- ]
48
- : []),
49
- '',
50
- ...sections.flatMap((section) => [section, '']),
51
- ].join('\n'));
3
+ const sections = registry.items.map((item) => `## ${item.name}\n\n${item.description}.\n\nTargets: ${item.targets.join(', ')}.\n\n${item.environment.length ? 'Environment: ' + item.environment.join(', ') + '.\n\n' : ''}${item.setup ? 'Setup: ' + item.setup.resources.join('; ') + '.\n\nVerify: ' + item.setup.verify.join('; ') + '.\n' : ''}`);
4
+ put(root, 'docs/stack.md', '# Application stack\n\nEvery application uses Next.js App Router/OpenNext for web, Expo for iOS/Android, Hono, Drizzle/D1 and private R2. Better Auth and shared styling are included supporting foundations. Stripe and RevenueCat are optional additions.\n\nInit generates source and configuration only. Cloud provisioning, secrets, database migrations and deployment are explicit operations.\n\n' +
5
+ sections.join('\n'));
52
6
  }
@@ -1,3 +1,3 @@
1
1
  import type { RecipeContext } from '../registry/types.js';
2
- /** Shared data and a Tailwind v3 preset for Expo/NativeWind and WXT. */
2
+ /** One shared token source for native components and DOM CSS. */
3
3
  export declare function scaffoldStyling({ root }: RecipeContext): void;
@@ -1,5 +1,7 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
1
3
  import { json, patchPackage, put, readJson } from './files.js';
2
- /** Shared data and a Tailwind v3 preset for Expo/NativeWind and WXT. */
4
+ /** One shared token source for native components and DOM CSS. */
3
5
  export function scaffoldStyling({ root }) {
4
6
  put(root, 'packages/styling/src/tokens.cjs', `exports.light = {
5
7
  '--background': '0 0% 100%',
@@ -46,39 +48,29 @@ exports.dark = {
46
48
  };
47
49
 
48
50
  exports.spacing = { small: 4, medium: 8, large: 16 };
49
- `);
50
- put(root, 'packages/styling/tailwind.cjs', `const { light, dark } = require('./src/tokens.cjs');
51
- const color = (name) => 'hsl(var(--' + name + '))';
52
- const surface = (name) => ({ DEFAULT: color(name), foreground: color(name + '-foreground') });
53
-
54
- module.exports = {
55
- darkMode: 'class',
56
- theme: {
57
- extend: {
58
- colors: {
59
- border: color('border'), input: color('input'), ring: color('ring'),
60
- background: color('background'), foreground: color('foreground'),
61
- primary: surface('primary'), secondary: surface('secondary'),
62
- destructive: surface('destructive'), muted: surface('muted'),
63
- accent: surface('accent'), popover: surface('popover'), card: surface('card'),
64
- },
65
- borderRadius: {
66
- lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)',
67
- },
68
- },
69
- },
70
- plugins: [function themeVariables({ addBase }) {
71
- addBase({ ':root': light, '.dark:root': dark });
72
- }],
73
- };
74
51
  `);
75
52
  patchPackage(root, 'packages/styling/package.json', {
76
- exports: { '.': './src/index.ts', './tailwind': './tailwind.cjs' },
53
+ exports: {
54
+ '.': './src/index.ts',
55
+ './globals.css': './globals.css',
56
+ },
77
57
  });
58
+ const tokens = createRequire(import.meta.url)(path.join(root, 'packages/styling/src/tokens.cjs'));
59
+ const rule = (selector, values) => selector +
60
+ ' {\n' +
61
+ Object.entries(values)
62
+ .map(([key, value]) => ' ' + key + ': ' + value + ';')
63
+ .join('\n') +
64
+ '\n}\n';
65
+ put(root, 'packages/styling/globals.css', rule(':root', tokens.light) +
66
+ '@media (prefers-color-scheme: dark) {\n' +
67
+ rule(':root', tokens.dark) +
68
+ '}\n');
69
+ put(root, 'packages/styling/src/tokens.d.cts', 'export const light: Record<string, string>;\nexport const dark: Record<string, string>;\nexport const spacing: { small: number; medium: number; large: number };\n');
78
70
  const config = readJson(root, 'packages/styling/tsconfig.json');
79
71
  json(root, 'packages/styling/tsconfig.json', {
80
72
  ...config,
81
73
  compilerOptions: { ...config.compilerOptions, allowJs: true },
82
- include: ['src/**/*.ts', 'src/**/*.cjs', 'tailwind.cjs'],
74
+ include: ['src/**/*.ts', 'src/**/*.cjs'],
83
75
  });
84
76
  }
@@ -0,0 +1,2 @@
1
+ import type { RecipeContext } from '../registry/types.js';
2
+ export declare function scaffoldWebBilling({ root }: RecipeContext): void;
@@ -0,0 +1,48 @@
1
+ import { put } from './files.js';
2
+ export function scaffoldWebBilling({ root }) {
3
+ put(root, 'apps/web/components/billing.tsx', WEB_BILLING);
4
+ put(root, 'apps/web/app/account/page.tsx', `import { headers } from 'next/headers';
5
+ import { redirect } from 'next/navigation';
6
+ import { sessionSchema } from '@workspace/contracts';
7
+ import { apiRequest } from '@/lib/server-api';
8
+ import { SignOut } from '@/components/sign-out';
9
+ import { Billing } from '@/components/billing';
10
+ export default async function Account() {
11
+ const incoming = await headers();
12
+ const response = await apiRequest(new Request('https://app.internal/api/session', { headers: { cookie: incoming.get('cookie') ?? '' } }));
13
+ if (response.status === 401) redirect('/sign-in');
14
+ if (!response.ok) throw Error('Session verification is unavailable.');
15
+ const { user } = sessionSchema.parse(await response.json());
16
+ return <section className="stack"><h1>Account</h1><p>{user.email}</p><Billing key={user.id} /><SignOut /></section>;
17
+ }
18
+ `);
19
+ }
20
+ const WEB_BILLING = `'use client';
21
+ import { useEffect, useRef, useState } from 'react';
22
+ import { createBillingClient, type BillingIdentity, type BillingEntitlements } from '@workspace/contracts';
23
+ import { Button } from '@/components/ui/button';
24
+ const api = createBillingClient();
25
+ function navigate(value: string) {
26
+ const url = new URL(value);
27
+ const invalid = [url.protocol !== 'https:', !['checkout.stripe.com', 'billing.stripe.com'].includes(url.hostname), url.username, url.password];
28
+ if (invalid.some(Boolean)) throw Error('Unrecognized billing destination.');
29
+ window.location.assign(url.href);
30
+ }
31
+ export function Billing() {
32
+ const [identity, setIdentity] = useState<BillingIdentity | null>(null);
33
+ const [entitlements, setEntitlements] = useState<BillingEntitlements | null>(null);
34
+ const [pending, setPending] = useState(false); const [error, setError] = useState('');
35
+ const intents = useRef(new Map<string, string>());
36
+ useEffect(() => { let active = true; void Promise.all([api.identity(), api.entitlements()]).then(([user, access]) => { if (active) { setIdentity(user); setEntitlements(access); } }).catch(() => { if (active) setError('Unable to verify subscriptions.'); }); return () => { active = false; }; }, []);
37
+ function checkoutIntent(plan: string) { const key = intents.current.get(plan) ?? crypto.randomUUID(); intents.current.set(plan, key); return key; }
38
+ async function checkout(plan: string) {
39
+ if (pending || !identity) return;
40
+ setPending(true); setError('');
41
+ // Keep one intent through uncertain retries. The server controls customer, price and return URL.
42
+ const key = checkoutIntent(plan);
43
+ try { navigate((await api.checkout(plan, key)).url); } catch { setError('Checkout is unavailable. Retry to resume the same checkout.'); } finally { setPending(false); }
44
+ }
45
+ async function portal() { if (pending || !identity) return; setPending(true); setError(''); try { navigate((await api.portal()).url); } catch { setError('Billing management is unavailable.'); } finally { setPending(false); } }
46
+ return <section className="stack" aria-label="Subscription"><h2>Subscription</h2><p>{entitlements?.entitlements.some((grant) => grant.active) ? 'Active access' : 'No verified subscription'}</p>{identity?.providers.stripe && <>{identity.plans.map((plan) => <Button key={plan.id} disabled={pending} onClick={() => void checkout(plan.id)}>{plan.label}</Button>)}<Button disabled={pending} onClick={() => void portal()}>Manage web subscription</Button></>}<p role="status">{error}</p></section>;
47
+ }
48
+ `;