anhedral 0.22.1 → 0.24.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 (44) hide show
  1. package/README.md +37 -53
  2. package/assets/contracts/environment-provenance.json +2 -2
  3. package/assets/launch/application.server.ts.txt +19 -7
  4. package/assets/launch/application.test.mjs.txt +8 -0
  5. package/assets/launch/home.tsx.txt +23 -1
  6. package/assets/launch/minimal-application.server.ts.txt +2 -2
  7. package/assets/launch/sign-in.tsx.txt +66 -4
  8. package/assets/launch/storage-page.tsx.txt +56 -0
  9. package/assets/stack/backend.test.mjs.txt +10 -0
  10. package/assets/stack/payment.test.mjs.txt +55 -0
  11. package/assets/stack/storage.test.mjs.txt +47 -0
  12. package/dist/bounded-file.d.ts +2 -1
  13. package/dist/bounded-file.js +3 -2
  14. package/dist/cli-output.js +1 -1
  15. package/dist/command-schema.js +5 -1
  16. package/dist/composition/catalog.d.ts +2 -2
  17. package/dist/composition/catalog.js +2 -2
  18. package/dist/composition/command.js +22 -12
  19. package/dist/composition/composition.d.ts +1 -0
  20. package/dist/composition/composition.js +9 -0
  21. package/dist/composition/editor.d.ts +2 -1
  22. package/dist/composition/editor.js +15 -3
  23. package/dist/composition/recipes.d.ts +1 -1
  24. package/dist/composition/recipes.js +17 -2
  25. package/dist/composition/update.js +15 -15
  26. package/dist/contracts/environment-file.d.ts +3 -0
  27. package/dist/contracts/environment-file.js +8 -5
  28. package/dist/dependencies.d.ts +6 -1
  29. package/dist/dependencies.js +10 -1
  30. package/dist/launch.js +17 -4
  31. package/dist/platform/deploy.js +5 -13
  32. package/dist/platform/environment.js +16 -8
  33. package/dist/platform/source.d.ts +2 -0
  34. package/dist/platform/source.js +52 -11
  35. package/dist/platform/state.js +9 -2
  36. package/dist/pnpm-policy.d.ts +1 -0
  37. package/dist/pnpm-policy.js +27 -0
  38. package/dist/scaffold/tanstack.d.ts +1 -1
  39. package/dist/scaffold/tanstack.js +17 -4
  40. package/dist/version.d.ts +1 -1
  41. package/dist/version.js +1 -1
  42. package/docs/capabilities.md +16 -6
  43. package/docs/software-factory.md +19 -6
  44. package/package.json +5 -5
package/README.md CHANGED
@@ -1,74 +1,58 @@
1
1
  # Anhedral CLI
2
2
 
3
3
  > [!WARNING]
4
- > Under construction. Commands, generated source and managed integration are evolving.
4
+ > **Under heavy construction.** CLI commands and generated app code may change.
5
5
 
6
- The open-source CLI for building and managing apps through the **Anhedral API**. Use it directly or through the Codex and Claude Code plugin to create projects, upload source, configure environments, deploy apps and read runtime logs.
6
+ Build an app one addition at a time. Generated applications are editable source. Start with a TanStack Start web app and ShadCN components. Add a backend when you need an API, authentication, or a database. Then choose storage, payments, or both.
7
7
 
8
- The plugin guides an agent through CLI commands so you can describe what you want to build in conversation. Platform enforces account, project and deployment permissions. The CLI also generates the **Anhedral Stack** as editable source, starting with web UI and adding backend, storage and payments when needed. Local source generation requires no account.
8
+ <picture>
9
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/anhedral/anhedral-cli/staging/docs/assets/anhedral-stack.png">
10
+ <img src="https://raw.githubusercontent.com/anhedral/anhedral-cli/staging/docs/assets/anhedral-stack-light.png" alt="The CLI creates a TanStack Start web app. The optional backend supports private file storage and subscription payments. An Expo client with Anhedral UI is upcoming.">
11
+ </picture>
9
12
 
10
- ## Start
13
+ **Upcoming** — `pnpm dlx anhedral@latest add cross-platform` will add an Expo client with Anhedral UI.
11
14
 
12
- ```sh
13
- anhedral init my-app
14
- cd my-app
15
- pnpm dev
16
- ```
15
+ ## How to use
17
16
 
18
- Init creates `apps/web` and shared tooling with OJ and TanStack Start server rendering/server functions and editable shadcn starter components. It does not add an API, database, authentication, storage or payments. Preview with `anhedral init my-app --dry-run --json`; use `--skip-install --no-git` for offline source generation.
19
-
20
- ## Add services
17
+ Start with the web app and stop at the stage you need. Storage and payments each require the backend and can be added independently.
21
18
 
22
19
  ```sh
23
- anhedral add backend --dry-run --json
24
- anhedral add backend
25
- anhedral add r2
26
- anhedral add stripe
27
- ```
28
-
29
- `backend` adds Hono, Better Auth and Drizzle/D1 together in one source transaction. `r2` adds private storage; `stripe` adds subscriptions. Both require the backend. Include missing prerequisites explicitly with `anhedral add r2 stripe --with-dependencies`.
30
-
31
- After adding backend, configure `apps/api/.dev.vars` from its example, review the initial SQL and apply it deliberately with `pnpm db:migrate --local`. The OJ development server then runs the web and auxiliary API Workers with local resources. Authentication methods start disabled and need explicit configuration. After adding Stripe, run `pnpm db:generate`, review the billing SQL and migrate before testing webhooks. Builds/startup never migrate databases or activate providers.
32
-
33
- Use `anhedral stack list`, `status` and `doctor` to inspect the Anhedral Stack and its additions. These checks describe source completeness, not live provider readiness. Current public generation is web-only. OJ runs development and builds. Historical generators and framework aliases are removed.
34
-
35
- ## Update an existing project
36
-
37
- Update your agent plugin through its host and select the matching published CLI version. Preview `anhedral stack update --dry-run --json`, review the returned diffs/conflicts, then apply `anhedral stack update --expect-plan <planId> --json`. Updates preserve authored source and stop on customized-file conflicts or a changed plan. They refresh generated runtime/configuration and deployment provenance without running project scripts or installing dependencies. Validate dependencies and the application separately before upload/deployment. See [the operating workflow](docs/software-factory.md).
20
+ # Create the web app
21
+ pnpm dlx anhedral@latest init my-app
22
+ cd my-app
38
23
 
39
- ## Web UI
24
+ # Add an API, authentication, and a database
25
+ pnpm dlx anhedral@latest add backend
40
26
 
41
- Init includes shadcn Button, Input and Label source with standard `components.json` configuration. Use upstream shadcn directly for more components, or replace the UI with any library. There is no Anhedral UI catalog or CLI wrapper.
27
+ # Add private file storage
28
+ pnpm dlx anhedral@latest add storage
42
29
 
43
- ```sh
44
- cd apps/web
45
- pnpm dlx shadcn@4.22.1 add card
30
+ # Add subscription payments
31
+ pnpm dlx anhedral@latest add payment
46
32
  ```
47
33
 
48
- Review diffs and preserve local edits and required upstream notices. The generated `LICENSE.shadcn` accompanies the bundled starter source. See [web UI](docs/ui.md).
49
-
50
- ## Connect to Anhedral
51
-
52
- Local generation requires no account. After browser-approved `login`, use `projects list --human` to discover projects and team IDs. Register your generated application with `projects create --name <name> --link --human`, or connect an existing project with `link --project <uuid> --team <uuid>`. `source upload --dry-run` inspects packaging without uploading; `source upload` sends a resumable immutable checkpoint.
53
-
54
- `deploy plan --manifest <file>`, `deploy prepare` and `deploy status` submit intent and read candidate receipts. Platform independently checks current authority, exact artifacts and runtime admission. Upload/build success does not publish production. Plans report current runtime compatibility and actionable remediation; candidate preparation does not require another person to review the CLI artifact. The current manifest runtime profile is `anhedral-stack`; an application cannot approve itself for hosting.
34
+ Run `pnpm dev` in the project directory to start the app. If you added services, configure them first. [Service setup](docs/capabilities.md) · [Source snapshot for each stage](https://github.com/anhedral/anhedral-cli/tree/staging/examples)
55
35
 
56
- `env list/import/set` manages variable metadata and private imports. Send values through an owner-only file or stdin, never command arguments or chat. `staging status/deploy` operates on ready candidates. `production status` reads production history; `production deploy --candidate <uuid> --name <slug>` requests publication with your existing production permissions, without a second approver for self-service teams. Explicit independent-review team policy remains enforced; `logs` reads redacted runtime events. The Codex and Claude Code plugin provides CLI usage guidance; authentication and managed project operations run through the CLI. See [the operating workflow](docs/software-factory.md#platform-cli-access-and-source-upload).
36
+ Upgrading from 0.22.1? Replace `add r2` with `add storage` and `add stripe` with `add payment`. Existing projects keep their R2 and Stripe configuration.
57
37
 
58
- ## Help and automation
59
-
60
- Run `anhedral --help` or `anhedral help <command>` for contextual examples. Use `--json` for machine-readable stdout, `--quiet` to suppress ordinary output, and `--non-interactive` to avoid approval polling. Platform retains compact JSON by default; `--human` selects readable summaries. Errors remain on stderr with a numeric failure status and recovery guidance.
61
-
62
- ```sh
63
- anhedral completion bash > ~/.anhedral-completion.bash
64
- # Or print zsh completion without changing your shell profile:
65
- anhedral completion zsh
66
- ```
38
+ ### Command reference
67
39
 
68
- ## Development and ownership
40
+ Use `pnpm dlx anhedral@latest <command>`. For arguments and flags, run `pnpm dlx anhedral@latest help <command>`.
69
41
 
70
- Use `pnpm install --frozen-lockfile`, `pnpm build` and focused tests when developing this repository. Generated applications use the versions recorded in their manifests. Run their `pnpm check` and `pnpm audit:deps` before deployment. Existing applications are never reinitialized or silently migrated.
42
+ | Task | Commands |
43
+ | --- | --- |
44
+ | Generate source | `init`, `add` |
45
+ | Inspect or update the stack | `stack list`, `stack status`, `stack doctor`, `stack update` |
46
+ | Manage your session | `login`, `whoami`, `logout` |
47
+ | Connect a project | `projects list`, `projects create`, `link`, `unlink` |
48
+ | Upload source | `source upload`, `source status` |
49
+ | Configure environment variables | `env list`, `env set`, `env import` |
50
+ | Prepare a deployment | `deploy plan`, `deploy prepare`, `deploy status` |
51
+ | Deploy to staging | `staging deploy`, `staging status` |
52
+ | Publish to production | `production deploy`, `production status` |
53
+ | Read runtime logs | `logs` |
54
+ | Get help and shell completions | `help`, `--version`, `completion bash`, `completion zsh` |
71
55
 
72
- See [stack conventions](docs/stack-standard.md), [additions](docs/capabilities.md), [UI](docs/ui.md) and [workflow](docs/software-factory.md).
56
+ Use the CLI directly or through the Codex and Claude Code plugin. To host on Anhedral, sign in, link a project, upload source, and deploy. [Platform workflow](docs/software-factory.md) · [Stack reference](docs/stack-standard.md)
73
57
 
74
- Apache-2.0. Generated applications are editable source that consumers may customize and license for their products. Retain applicable MIT notices for copied upstream UI source.
58
+ Apache-2.0. Retain the included third-party notices when distributing generated source.
@@ -2,10 +2,10 @@
2
2
  "contractVersion": 1,
3
3
  "owner": "anhedral/platform-contracts/environment",
4
4
  "license": "Apache-2.0",
5
- "sourceRevision": "0050910091dbc653c12118850af31655075f58c3",
5
+ "sourceRevision": "45e3cc484dd22f97344b5954852fa682b593a99a",
6
6
  "files": {
7
7
  "environment-transport.ts": "833b61ecb43c2cbc86c15ed07092ddb364469681d03a23af94e805463c201940",
8
- "environment-file.ts": "29b00c2babab896a6373f93ae5eb2672c00f25862b13b00c20e23a17d2dd83a3",
8
+ "environment-file.ts": "43766ccf3ce52a4a59638bcf3df3fea0d1b8d505bd5a3d694040fb744701f43d",
9
9
  "LICENSE": "6d89bce3e7760469015287d1b6a45d31ef7924475c9b54eabe974bcce373980b"
10
10
  }
11
11
  }
@@ -1,13 +1,25 @@
1
1
  import type { ApplicationContext } from './request-context';
2
2
 
3
- export async function readApplicationStatus(context: ApplicationContext): Promise<{ api: boolean | null; authentication: boolean }> {
3
+ async function backendConnected(api: ApplicationContext['api']): Promise<boolean> {
4
+ if (!api) return false;
4
5
  try {
5
- if (!context.api) return { api: false, authentication: __AUTHENTICATION__ };
6
- const response = await context.api.fetch(new Request('https://api.internal/api/health', { signal: AbortSignal.timeout(5000) }));
7
- if (!response.ok) return { api: false, authentication: __AUTHENTICATION__ };
8
- const result: unknown = await response.json();
9
- return { api: typeof result === 'object' && result !== null && Reflect.get(result, 'ok') === true, authentication: __AUTHENTICATION__ };
6
+ const request = new Request('https://api.internal/api/health', {
7
+ signal: AbortSignal.timeout(5000),
8
+ });
9
+ const response = await api.fetch(request);
10
+ if (!response.ok) return false;
11
+ const body: unknown = await response.json();
12
+ return typeof body === 'object' && body !== null && Reflect.get(body, 'ok') === true;
10
13
  } catch {
11
- return { api: false, authentication: __AUTHENTICATION__ };
14
+ return false;
12
15
  }
13
16
  }
17
+
18
+ export async function readApplicationStatus(context: ApplicationContext) {
19
+ return {
20
+ api: await backendConnected(context.api),
21
+ authentication: __AUTHENTICATION__,
22
+ storage: __STORAGE__,
23
+ payment: __PAYMENT__,
24
+ };
25
+ }
@@ -0,0 +1,8 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { readApplicationStatus } from '../src/lib/application.server.ts';
4
+
5
+ test('the starter renders when no API binding is available', async () => {
6
+ const status = await readApplicationStatus({});
7
+ assert.equal(status.api, status.authentication ? false : null);
8
+ });
@@ -16,5 +16,27 @@ export const Route = createFileRoute('/')({
16
16
  function Home() {
17
17
  const router = useRouter();
18
18
  const status = Route.useLoaderData();
19
- return <section className="stack"><h1>{starterTitle}</h1><p>Your web application is ready to build.</p><p data-rendering="server">Rendered on the server. {status.api === null ? 'Backend not added' : status.api ? 'API: connected' : 'API: unavailable'}.</p>{status.authentication && <a href="/sign-in">Your account</a>}<Button onClick={() => void router.invalidate()}>Check connection</Button></section>;
19
+ return (
20
+ <section className="stack">
21
+ <h1>{starterTitle}</h1>
22
+ <p>
23
+ Edit <code>apps/web/src/routes/index.tsx</code> to change this page.
24
+ </p>
25
+ <p data-rendering="server">
26
+ Rendered on the server.{' '}
27
+ {status.api === null
28
+ ? 'Backend not added'
29
+ : status.api
30
+ ? 'API: connected'
31
+ : 'API: unavailable'}
32
+ .
33
+ </p>
34
+ {status.authentication && <a href="/sign-in">Your account</a>}
35
+ {status.storage && <a href="/storage">Private files</a>}
36
+ {status.payment && <a href="/api/billing/status">Check subscription status</a>}
37
+ {status.api !== null && (
38
+ <Button onClick={() => void router.invalidate()}>Check connection</Button>
39
+ )}
40
+ </section>
41
+ );
20
42
  }
@@ -1,5 +1,5 @@
1
1
  import type { ApplicationContext } from './request-context';
2
2
 
3
- export async function readApplicationStatus(_context: ApplicationContext): Promise<{ api: boolean | null; authentication: boolean }> {
4
- return { api: null, authentication: false };
3
+ export async function readApplicationStatus(_context: ApplicationContext) {
4
+ return { api: null, authentication: false, storage: false, payment: false };
5
5
  }
@@ -24,7 +24,8 @@ function Account() {
24
24
  const result = creating
25
25
  ? await authClient.signUp.email({ email, password, name: String(data.get('name') ?? '') })
26
26
  : await authClient.signIn.email({ email, password });
27
- if (result.error) setError(result.error.message ?? 'Unable to sign in. Check your details and try again.');
27
+ if (result.error)
28
+ setError(result.error.message ?? 'Unable to sign in. Check your details and try again.');
28
29
  else await refetch();
29
30
  } catch {
30
31
  setError('Unable to reach the account service. Try again.');
@@ -47,7 +48,68 @@ function Account() {
47
48
  }
48
49
  }
49
50
  if (isPending) return <p role="status">Loading your account…</p>;
50
- if (sessionError) return <section className="stack"><h1>Account unavailable</h1><p role="alert">Unable to load your account. Check that the API and authentication are configured.</p><Button onClick={() => void refetch()}>Try again</Button></section>;
51
- if (session) return <section className="stack"><h1>Your account</h1><p>{session.user.email}</p>{error && <p role="alert">{error}</p>}<Button disabled={busy} onClick={() => void signOut()}>{busy ? 'Signing out…' : 'Sign out'}</Button></section>;
52
- return <section className="stack"><h1>{creating ? 'Create an account' : 'Sign in'}</h1><p className="muted">Email and password must be explicitly enabled in the API authentication configuration.</p><form onSubmit={submit}>{creating && <><Label htmlFor="name">Name</Label><Input id="name" name="name" autoComplete="name" required maxLength={160} /></>}<Label htmlFor="email">Email</Label><Input id="email" name="email" type="email" autoComplete="email" required maxLength={254} /><Label htmlFor="password">Password</Label><Input id="password" name="password" type="password" autoComplete={creating ? 'new-password' : 'current-password'} required minLength={8} maxLength={128} />{error && <p role="alert">{error}</p>}<Button type="submit" disabled={busy}>{busy ? 'Working…' : creating ? 'Create account' : 'Sign in'}</Button><Button type="button" variant="ghost" disabled={busy} onClick={() => { setCreating(!creating); setError(''); }}>{creating ? 'Already have an account? Sign in' : 'Create an account'}</Button></form></section>;
51
+ if (sessionError)
52
+ return (
53
+ <section className="stack">
54
+ <h1>Account unavailable</h1>
55
+ <p role="alert">
56
+ Unable to load your account. Check that the API and authentication are configured.
57
+ </p>
58
+ <Button onClick={() => void refetch()}>Try again</Button>
59
+ </section>
60
+ );
61
+ if (session)
62
+ return (
63
+ <section className="stack">
64
+ <h1>Your account</h1>
65
+ <p>{session.user.email}</p>
66
+ {error && <p role="alert">{error}</p>}
67
+ <Button disabled={busy} onClick={() => void signOut()}>
68
+ {busy ? 'Signing out…' : 'Sign out'}
69
+ </Button>
70
+ </section>
71
+ );
72
+ return (
73
+ <section className="stack">
74
+ <h1>{creating ? 'Create an account' : 'Sign in'}</h1>
75
+ <p className="muted">
76
+ Email and password must be explicitly enabled in the API authentication configuration.
77
+ </p>
78
+ <form onSubmit={submit}>
79
+ {creating && (
80
+ <>
81
+ <Label htmlFor="name">Name</Label>
82
+ <Input id="name" name="name" autoComplete="name" required maxLength={160} />
83
+ </>
84
+ )}
85
+ <Label htmlFor="email">Email</Label>
86
+ <Input id="email" name="email" type="email" autoComplete="email" required maxLength={254} />
87
+ <Label htmlFor="password">Password</Label>
88
+ <Input
89
+ id="password"
90
+ name="password"
91
+ type="password"
92
+ autoComplete={creating ? 'new-password' : 'current-password'}
93
+ required
94
+ minLength={8}
95
+ maxLength={128}
96
+ />
97
+ {error && <p role="alert">{error}</p>}
98
+ <Button type="submit" disabled={busy}>
99
+ {busy ? 'Working…' : creating ? 'Create account' : 'Sign in'}
100
+ </Button>
101
+ <Button
102
+ type="button"
103
+ variant="ghost"
104
+ disabled={busy}
105
+ onClick={() => {
106
+ setCreating(!creating);
107
+ setError('');
108
+ }}
109
+ >
110
+ {creating ? 'Already have an account? Sign in' : 'Create an account'}
111
+ </Button>
112
+ </form>
113
+ </section>
114
+ );
53
115
  }
@@ -0,0 +1,56 @@
1
+ import { createFileRoute } from '@tanstack/react-router';
2
+ import { useState, type FormEvent } from 'react';
3
+ import { Button } from '@/components/ui/button';
4
+
5
+ export const Route = createFileRoute('/storage')({ component: Storage });
6
+
7
+ function Storage() {
8
+ const [stored, setStored] = useState('');
9
+ const [message, setMessage] = useState('');
10
+ const [busy, setBusy] = useState(false);
11
+
12
+ async function upload(event: FormEvent<HTMLFormElement>) {
13
+ event.preventDefault();
14
+ const file = new FormData(event.currentTarget).get('file');
15
+ if (!(file instanceof File) || !file.name || busy) return;
16
+ setStored('');
17
+ setBusy(true);
18
+ try {
19
+ const path = '/api/files/' + encodeURIComponent(file.name);
20
+ const response = await fetch(path, { method: 'PUT', body: file });
21
+ if (response.ok) setStored(path);
22
+ setMessage(
23
+ response.ok
24
+ ? 'File stored.'
25
+ : response.status === 401
26
+ ? 'Sign in to upload.'
27
+ : 'Upload failed. Check the file name, size, and storage configuration.',
28
+ );
29
+ } catch {
30
+ setMessage('Storage is unavailable.');
31
+ } finally {
32
+ setBusy(false);
33
+ }
34
+ }
35
+
36
+ return (
37
+ <section className="stack">
38
+ <h1>Private files</h1>
39
+ <form onSubmit={upload}>
40
+ <label>
41
+ Choose a file up to 1 MiB <input type="file" name="file" required />
42
+ </label>
43
+ <Button disabled={busy} type="submit">
44
+ Upload
45
+ </Button>
46
+ </form>
47
+ <p role="status">{message}</p>
48
+ {stored && (
49
+ <a href={stored} download>
50
+ Download your file
51
+ </a>
52
+ )}
53
+ <a href="/sign-in">Your account</a>
54
+ </section>
55
+ );
56
+ }
@@ -0,0 +1,10 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import app from '../src/index.ts';
4
+
5
+ test('health is public and account data requires configured authentication', async () => {
6
+ const health = await app.request('/api/health', {}, {});
7
+ assert.deepEqual(await health.json(), { ok: true });
8
+ const session = await app.request('/api/session', {}, {});
9
+ assert.equal(session.status, 503);
10
+ });
@@ -0,0 +1,55 @@
1
+ import assert from 'node:assert/strict';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { createHmac, randomUUID } from 'node:crypto';
4
+ import { cp, mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import { tmpdir } from 'node:os';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { DatabaseSync } from 'node:sqlite';
10
+ import test from 'node:test';
11
+ import app from '../src/index.ts';
12
+
13
+ test('reviewable local migrations support idempotent signed webhook delivery', async (t) => {
14
+ const root = new URL('../../../packages/db/', import.meta.url);
15
+ const work = await mkdtemp(join(tmpdir(), 'billing-migrations-'));
16
+ t.after(() => rm(work, { recursive: true, force: true }));
17
+ const migrations = join(work, 'drizzle');
18
+ await cp(new URL('drizzle/', root), migrations, { recursive: true });
19
+ const require = createRequire(new URL('package.json', root));
20
+ const cli = join(dirname(require.resolve('drizzle-kit/api')), 'bin.cjs');
21
+ execFileSync(
22
+ process.execPath,
23
+ [cli, 'generate', '--dialect=sqlite', '--schema=' + fileURLToPath(new URL('src/schema.ts', root)), '--out=./drizzle'],
24
+ { cwd: work, stdio: 'pipe' },
25
+ );
26
+ const db = new DatabaseSync(':memory:');
27
+ t.after(() => db.close());
28
+ for (const file of (await readdir(migrations)).filter((name) => name.endsWith('.sql')).sort())
29
+ db.exec(await readFile(join(migrations, file), 'utf8'));
30
+ const env = {
31
+ DB: {
32
+ prepare: (sql) => ({ bind: (...params) => ({ run: () => db.prepare(sql).run(...params) }) }),
33
+ },
34
+ STRIPE_SECRET_KEY: 'sk_test_' + randomUUID(),
35
+ STRIPE_WEBHOOK_SECRET: randomUUID(),
36
+ };
37
+ const body = JSON.stringify({ id: 'evt_local', object: 'event', livemode: false });
38
+ const timestamp = Math.floor(Date.now() / 1000);
39
+ const signature = createHmac('sha256', env.STRIPE_WEBHOOK_SECRET)
40
+ .update(timestamp + '.' + body)
41
+ .digest('hex');
42
+ for (let delivery = 0; delivery < 2; delivery++) {
43
+ const result = await app.request(
44
+ '/api/webhooks/stripe',
45
+ {
46
+ method: 'POST',
47
+ headers: { 'stripe-signature': 't=' + timestamp + ',v1=' + signature },
48
+ body,
49
+ },
50
+ env,
51
+ );
52
+ assert.equal(result.status, 200);
53
+ }
54
+ assert.equal(db.prepare('SELECT COUNT(*) AS count FROM billing_receipt').get().count, 1);
55
+ });
@@ -0,0 +1,47 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import test from 'node:test';
5
+ import { getPlatformProxy } from 'wrangler';
6
+ import { betterAuth } from 'better-auth/minimal';
7
+ import { createAuth } from '../src/auth.ts';
8
+ import app from '../src/index.ts';
9
+
10
+ test('private file round trip and upload size boundary', async (t) => {
11
+ const proxy = await getPlatformProxy({ persist: false, remoteBindings: false, envFiles: [] });
12
+ t.after(() => proxy.dispose());
13
+ const origin = 'http://localhost';
14
+ const env = { ...proxy.env, PUBLIC_APP_URL: origin, BETTER_AUTH_SECRET: randomUUID() };
15
+ const sql = await readFile(
16
+ new URL('../../../packages/db/drizzle/0000_better_auth.sql', import.meta.url),
17
+ 'utf8',
18
+ );
19
+ for (const statement of sql.split('--> statement-breakpoint'))
20
+ await env.DB.prepare(statement.trim()).run();
21
+ const auth = betterAuth({ ...createAuth(env).options, emailAndPassword: { enabled: true } });
22
+ const signup = await auth.api.signUpEmail({
23
+ body: { name: 'Example', email: 'example@example.com', password: randomUUID() },
24
+ asResponse: true,
25
+ });
26
+ assert.equal(signup.status, 200);
27
+ const cookie = signup.headers
28
+ .getSetCookie()
29
+ .map((value) => value.split(';')[0])
30
+ .join('; ');
31
+ const file = '/api/files/sample.bin';
32
+ const limit = 1024 * 1024;
33
+ const bytes = new Uint8Array(limit).fill(42);
34
+ for (const size of [limit, limit + 1]) {
35
+ const body = new Blob([size === limit ? bytes : new Uint8Array(size)]).stream();
36
+ const result = await app.request(
37
+ file,
38
+ { method: 'PUT', headers: { cookie, origin }, body, duplex: 'half' },
39
+ env,
40
+ );
41
+ assert.equal(result.status, size === limit ? 201 : 413);
42
+ }
43
+ const download = await app.request(file, { headers: { cookie } }, env);
44
+ assert.equal(download.status, 200);
45
+ assert.deepEqual(new Uint8Array(await download.arrayBuffer()), bytes);
46
+ assert.equal((await app.request(file, {}, env)).status, 401);
47
+ });
@@ -1,3 +1,4 @@
1
+ import { type Stats } from 'node:fs';
1
2
  export declare const MAX_PROJECT_JSON_BYTES: number;
2
3
  /** Reject devices, links and oversized or growing files before parsing local input. */
3
- export declare function readBoundedFile(filePath: string, maximumBytes: number): Buffer;
4
+ export declare function readBoundedFile(filePath: string, maximumBytes: number, validate?: (opened: Stats) => void): Buffer;
@@ -1,7 +1,7 @@
1
- import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, } from 'node:fs';
2
2
  export const MAX_PROJECT_JSON_BYTES = 2 * 1024 * 1024;
3
3
  /** Reject devices, links and oversized or growing files before parsing local input. */
4
- export function readBoundedFile(filePath, maximumBytes) {
4
+ export function readBoundedFile(filePath, maximumBytes, validate) {
5
5
  const stat = lstatSync(filePath);
6
6
  if (!stat.isFile() || stat.isSymbolicLink())
7
7
  throw new Error(`Input file must be a regular file: ${filePath}`);
@@ -10,6 +10,7 @@ export function readBoundedFile(filePath, maximumBytes) {
10
10
  const opened = fstatSync(descriptor);
11
11
  if (!opened.isFile())
12
12
  throw new Error(`Input file must be a regular file: ${filePath}`);
13
+ validate?.(opened);
13
14
  if (opened.size > maximumBytes)
14
15
  throw new Error(`Input file exceeds size limit: ${filePath}`);
15
16
  const chunks = [];
@@ -38,7 +38,7 @@ export function formatResult(_command, value) {
38
38
  if (data.stack === 'anhedral-stack' && !data.generated)
39
39
  return `Foundation preview for ${data.root}.\nStack: Anhedral Stack.\nNo files were written or resources provisioned.`;
40
40
  if (data.stack === 'anhedral-stack' && data.generated)
41
- return `Created ${data.root}.\nStack: Anhedral Stack.\n${data.dependenciesInstalled ? 'Run pnpm dev' : 'Run pnpm install, then pnpm dev'} in the project directory.\nAdd services when needed: anhedral add backend, then anhedral add r2 or anhedral add stripe.\nReview README.md for configuration and deployment.`;
41
+ return `Created ${data.root}.\nStack: Anhedral Stack.\n${data.dependenciesInstalled ? 'Run pnpm dev' : 'Run pnpm install, then pnpm dev'} in the project directory.\nAdd services when needed: anhedral add backend, then anhedral add storage or anhedral add payment.\nReview README.md for configuration and deployment.`;
42
42
  return (`${data.generated ? 'Created' : 'Foundation preview for'} ${data.root}.\nComponents: ${data.products.join(', ')}.\n` +
43
43
  (data.generated
44
44
  ? 'Review README.md, then run pnpm dev in the project directory. You own development, integrations and hosting.'
@@ -472,7 +472,11 @@ export const COMMANDS = {
472
472
  },
473
473
  ],
474
474
  positional: { name: 'capabilities', min: 1, max: 50, kind: 'capability' },
475
- examples: ['add backend', 'add r2', 'add r2 stripe --with-dependencies --dry-run --json'],
475
+ examples: [
476
+ 'add backend',
477
+ 'add storage',
478
+ 'add storage payment --with-dependencies --dry-run --json',
479
+ ],
476
480
  note: 'Adds source and local configuration only. Existing edits are preserved. No provisioning, credential installation, migration or deployment.',
477
481
  },
478
482
  stack: {
@@ -44,13 +44,13 @@ export declare const ANHEDRAL_STACK: {
44
44
  readonly requires: string[];
45
45
  readonly targets: readonly ["apps/api/package.json", "apps/api/wrangler.jsonc", "apps/api/src/index.ts", "apps/api/src/environment.ts", "apps/api/src/capabilities.ts", "apps/api/src/custom-environment.ts", "packages/db/package.json", "packages/db/src/index.ts", "packages/db/src/schema.ts", "apps/api/src/auth.ts", "apps/api/src/auth-features.ts", "apps/api/src/security.ts", "apps/api/src/auth-platform.ts", "apps/api/src/features/auth.ts", "apps/web/src/lib/auth-client.ts"];
46
46
  };
47
- readonly r2: {
47
+ readonly storage: {
48
48
  readonly name: "Private storage";
49
49
  readonly description: "Authenticated, owner-scoped object storage.";
50
50
  readonly requires: readonly ["backend"];
51
51
  readonly targets: readonly ["apps/api/src/features/storage.ts"];
52
52
  };
53
- readonly stripe: {
53
+ readonly payment: {
54
54
  readonly name: "Payments and subscriptions";
55
55
  readonly description: "Stripe subscription and entitlement source.";
56
56
  readonly requires: readonly ["backend"];
@@ -102,13 +102,13 @@ export const ANHEDRAL_STACK = {
102
102
  requires: [],
103
103
  targets: [...CAPABILITIES.hono.targets, ...CAPABILITIES['database-auth'].targets],
104
104
  },
105
- r2: {
105
+ storage: {
106
106
  name: 'Private storage',
107
107
  description: 'Authenticated, owner-scoped object storage.',
108
108
  requires: ['backend'],
109
109
  targets: [...CAPABILITIES.r2.targets],
110
110
  },
111
- stripe: {
111
+ payment: {
112
112
  name: 'Payments and subscriptions',
113
113
  description: 'Stripe subscription and entitlement source.',
114
114
  requires: ['backend'],