anhedral 0.23.0 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +3 -3
  2. package/assets/launch/AGENTS.md.txt +7 -0
  3. package/assets/launch/README.md.txt +40 -0
  4. package/assets/launch/application.server.ts.txt +19 -7
  5. package/assets/launch/application.test.mjs.txt +8 -0
  6. package/assets/launch/backend-vite.config.ts.txt +18 -0
  7. package/assets/launch/home.tsx.txt +25 -2
  8. package/assets/launch/minimal-application.server.ts.txt +2 -2
  9. package/assets/launch/root.tsx.txt +38 -5
  10. package/assets/launch/router.tsx.txt +3 -2
  11. package/assets/launch/sign-in.tsx.txt +68 -5
  12. package/assets/launch/storage-page.tsx.txt +57 -0
  13. package/assets/launch/styles.css.txt +55 -16
  14. package/assets/launch/styling-tokens.cjs +45 -0
  15. package/assets/launch/vite.config.ts.txt +13 -0
  16. package/assets/stack/api-eslint.config.mjs.txt +2 -0
  17. package/assets/stack/api-index.ts.txt +1 -0
  18. package/assets/stack/api-proxy.ts.txt +112 -0
  19. package/assets/stack/auth-routes.ts.txt +3 -1
  20. package/assets/stack/auth.ts.txt +5 -4
  21. package/assets/stack/backend.test.mjs.txt +10 -0
  22. package/assets/stack/base-eslint.js.txt +16 -0
  23. package/assets/stack/billing-mode.ts.txt +2 -0
  24. package/assets/stack/billing-providers.ts.txt +8 -0
  25. package/assets/stack/db-index.ts.txt +7 -0
  26. package/assets/stack/db-migrate.mjs.txt +23 -0
  27. package/assets/stack/drizzle.config.ts.txt +2 -0
  28. package/assets/stack/entitlement-guard.ts.txt +2 -0
  29. package/assets/stack/entitlements.ts.txt +3 -1
  30. package/assets/stack/payment.test.mjs.txt +61 -0
  31. package/assets/stack/security.ts.txt +2 -0
  32. package/assets/stack/shared-eslint.config.mjs.txt +6 -0
  33. package/assets/stack/storage.test.mjs.txt +47 -0
  34. package/assets/stack/storage.ts.txt +3 -1
  35. package/assets/stack/stripe.ts.txt +4 -2
  36. package/dist/bounded-file.d.ts +2 -1
  37. package/dist/bounded-file.js +3 -2
  38. package/dist/cli-output.js +1 -1
  39. package/dist/composition/command.js +5 -2
  40. package/dist/composition/composition.d.ts +1 -0
  41. package/dist/composition/composition.js +9 -0
  42. package/dist/composition/editor.d.ts +2 -1
  43. package/dist/composition/editor.js +15 -3
  44. package/dist/composition/recipes.d.ts +2 -2
  45. package/dist/composition/recipes.js +62 -52
  46. package/dist/composition/update.js +15 -15
  47. package/dist/dependencies.d.ts +5 -6
  48. package/dist/dependencies.js +9 -1
  49. package/dist/launch.d.ts +1 -1
  50. package/dist/launch.js +26 -91
  51. package/dist/platform/deploy.js +5 -13
  52. package/dist/platform/environment.js +10 -2
  53. package/dist/platform/source.d.ts +2 -0
  54. package/dist/platform/source.js +52 -11
  55. package/dist/platform/state.js +9 -2
  56. package/dist/pnpm-policy.d.ts +1 -0
  57. package/dist/pnpm-policy.js +27 -0
  58. package/dist/render.d.ts +0 -10
  59. package/dist/render.js +1 -38
  60. package/dist/scaffold/bootstrap.d.ts +1 -2
  61. package/dist/scaffold/bootstrap.js +4 -8
  62. package/dist/scaffold/files.d.ts +12 -24
  63. package/dist/scaffold/files.js +9 -103
  64. package/dist/scaffold/styling.d.ts +2 -4
  65. package/dist/scaffold/styling.js +46 -69
  66. package/dist/scaffold/tanstack.d.ts +2 -2
  67. package/dist/scaffold/tanstack.js +37 -39
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/docs/capabilities.md +8 -0
  71. package/docs/software-factory.md +16 -7
  72. package/package.json +4 -2
  73. package/dist/api-proxy.d.ts +0 -1
  74. package/dist/api-proxy.js +0 -48
@@ -1,9 +1,9 @@
1
1
  import { readFileSync } from 'node:fs';
2
- import { ANHEDRAL_STACK_DEPENDENCIES, WEB_DEPENDENCIES } from '../dependencies.js';
3
2
  import { CapabilityEditor, fingerprint } from '../composition/editor.js';
3
+ import { ANHEDRAL_STACK_DEPENDENCIES, WEB_DEPENDENCIES } from '../dependencies.js';
4
+ import { secureWorkspacePolicy } from '../pnpm-policy.js';
4
5
  import { resourceName } from '../render.js';
5
- import { json, put, workerConfig } from './files.js';
6
- const template = (name) => readFileSync(new URL(`../../assets/launch/${name}`, import.meta.url), 'utf8');
6
+ import { json, launchTemplate, put, workerConfig } from './files.js';
7
7
  /** The launch foundation is a web service; Hono owns application services and data. */
8
8
  export function scaffoldTanstack(root, name) {
9
9
  const app = 'apps/web';
@@ -15,10 +15,8 @@ export function scaffoldTanstack(root, name) {
15
15
  version: '0.1.0',
16
16
  type: 'module',
17
17
  scripts: {
18
- dev: 'node ../../scripts/oj.mjs dev . --host=0.0.0.0 --port 3000',
19
- build: 'node ../../scripts/oj.mjs build .',
20
- preview: 'wrangler dev --config dist/ssr/wrangler.json --port 3000',
21
- deploy: 'wrangler deploy --config dist/ssr/wrangler.json',
18
+ test: 'node --experimental-strip-types --test tests/*.test.mjs',
19
+ ...ojScripts,
22
20
  typecheck: 'wrangler types && tsr generate && tsc --noEmit',
23
21
  lint: 'eslint . --max-warnings 0',
24
22
  },
@@ -50,9 +48,7 @@ export function scaffoldTanstack(root, name) {
50
48
  },
51
49
  });
52
50
  json(root, `${app}/wrangler.jsonc`, {
53
- ...workerConfig(resourceName(name, 'web')),
54
- main: 'src/server.ts',
55
- compatibility_date: '2026-11-02',
51
+ ...workerConfig(resourceName(name, 'web'), 'src/server.ts', '2026-11-02'),
56
52
  services: [],
57
53
  });
58
54
  json(root, `${app}/tsconfig.json`, {
@@ -79,7 +75,10 @@ export function scaffoldTanstack(root, name) {
79
75
  generatedRouteTree: './src/routeTree.gen.ts',
80
76
  });
81
77
  put(root, `${app}/eslint.config.mjs`, `import { config } from '@workspace/eslint-config/react-internal';
82
- export default [...config, { ignores: ['dist/**', '.wrangler/**', 'src/routeTree.gen.ts', 'worker-configuration.d.ts'] }];
78
+ export default [
79
+ ...config,
80
+ { ignores: ['dist/**', '.wrangler/**', 'src/routeTree.gen.ts', 'worker-configuration.d.ts'] },
81
+ ];
83
82
  `);
84
83
  json(root, `${app}/components.json`, {
85
84
  $schema: 'https://ui.shadcn.com/schema.json',
@@ -98,15 +97,18 @@ export default [...config, { ignores: ['dist/**', '.wrangler/**', 'src/routeTree
98
97
  });
99
98
  put(root, `${app}/src/lib/utils.ts`, `import { clsx, type ClassValue } from 'clsx';
100
99
  import { twMerge } from 'tailwind-merge';
101
- export function cn(...values: ClassValue[]) { return twMerge(clsx(values)); }
100
+ export function cn(...values: ClassValue[]) {
101
+ return twMerge(clsx(values));
102
+ }
102
103
  `);
103
104
  for (const component of ['button', 'input', 'label'])
104
105
  put(root, `${app}/src/components/ui/${component}.tsx`, readFileSync(new URL(`../../assets/ui/web/${component}.tsx`, import.meta.url), 'utf8'));
105
106
  for (const file of ['LICENSE.shadcn', 'UPSTREAM.json'])
106
107
  put(root, `${app}/${file}`, readFileSync(new URL(`../../assets/ui/${file}`, import.meta.url), 'utf8'));
107
108
  put(root, `${app}/postcss.config.mjs`, "export default { plugins: { '@tailwindcss/postcss': {} } };\n");
108
- put(root, `${app}/src/starter.ts`, `export const starterTitle = ${JSON.stringify(name)};\n`);
109
+ put(root, `${app}/src/starter.ts`, `export const starterTitle = ${/^[a-z0-9._-]+$/.test(name) ? `'${name}'` : JSON.stringify(name)};\n`);
109
110
  const files = {
111
+ 'tests/application.test.mjs': 'application.test.mjs.txt',
110
112
  'src/router.tsx': 'router.tsx.txt',
111
113
  'src/lib/request-context.ts': 'request-context.ts.txt',
112
114
  'src/routes/__root.tsx': 'root.tsx.txt',
@@ -114,7 +116,7 @@ export function cn(...values: ClassValue[]) { return twMerge(clsx(values)); }
114
116
  'src/styles.css': 'styles.css.txt',
115
117
  };
116
118
  for (const [destination, source] of Object.entries(files))
117
- put(root, `${app}/${destination}`, template(source).replaceAll('__APPLICATION_NAME__', JSON.stringify(name)));
119
+ put(root, `${app}/${destination}`, launchTemplate(source));
118
120
  put(root, `${app}/public/robots.txt`, 'User-agent: *\nAllow: /\n');
119
121
  put(root, `${app}/public/_headers`, '/assets/*\n Cache-Control: public, max-age=31536000, immutable\n/*\n X-Content-Type-Options: nosniff\n');
120
122
  }
@@ -139,21 +141,7 @@ const ojFiles = {
139
141
  'scripts/OJ.LICENSE': 'oj/OJ.LICENSE',
140
142
  };
141
143
  function tanstackViteConfiguration(installed) {
142
- const backend = installed.includes('hono');
143
- return `import { fileURLToPath } from 'node:url';
144
- import { defineConfig } from 'vite';
145
- import { cloudflare } from '@cloudflare/vite-plugin';
146
- import { tanstackStart } from '@tanstack/react-start/plugin/vite';
147
- import react from '@vitejs/plugin-react';
148
- export default defineConfig(${backend ? '({ command }) => (' : ''}{
149
- resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
150
- plugins: [
151
- cloudflare({ viteEnvironment: { name: 'ssr' }, ${backend ? "auxiliaryWorkers: command === 'serve' ? [{ configPath: '../api/wrangler.jsonc' }] : [], persistState: { path: fileURLToPath(new URL('../api/.wrangler/state', import.meta.url)) }, " : ''}remoteBindings: false }),
152
- tanstackStart({ server: { entry: './server.ts' } }),
153
- react(),
154
- ],
155
- }${backend ? ')' : ''});
156
- `;
144
+ return launchTemplate(installed.includes('hono') ? 'backend-vite.config.ts.txt' : 'vite.config.ts.txt');
157
145
  }
158
146
  /** One-time source upgrade, planned in the same bounded overlay as each addition. */
159
147
  export function normalizeOjFoundation(e, installed, refreshConfiguration = false) {
@@ -170,7 +158,14 @@ export function normalizeOjFoundation(e, installed, refreshConfiguration = false
170
158
  if (current !== undefined && current !== desired && current !== previous && !previousOjDev)
171
159
  throw Error(`Preserve customized web launcher scripts.${name}. Reconcile it with the pinned OJ runtime before adding capabilities. No files were changed.`);
172
160
  }
173
- let changed = false;
161
+ const workspace = 'pnpm-workspace.yaml';
162
+ const previousPolicy = e.read(workspace);
163
+ if (previousPolicy === null)
164
+ throw Error('Missing pnpm workspace configuration.');
165
+ const policy = secureWorkspacePolicy(previousPolicy);
166
+ let changed = policy !== previousPolicy;
167
+ if (changed)
168
+ e.writes.set(workspace, policy);
174
169
  const serverEntry = 'apps/web/src/server.ts';
175
170
  const currentEntry = e.read(serverEntry);
176
171
  // Repair only the exact shipped adapter whose default-entry shim drops Start context in OJ.
@@ -179,7 +174,7 @@ export function normalizeOjFoundation(e, installed, refreshConfiguration = false
179
174
  fingerprint(currentEntry) ===
180
175
  '703adff2e57adfbbdb7fa90b4dadffde8617c86cc31a185943931ef7c623eca7' &&
181
176
  e.managed[serverEntry] === fingerprint(currentEntry)) {
182
- e.owned(serverEntry, template('server.ts.txt'));
177
+ e.owned(serverEntry, launchTemplate('server.ts.txt'));
183
178
  changed = true;
184
179
  }
185
180
  const rootRoute = 'apps/web/src/routes/__root.tsx';
@@ -187,7 +182,7 @@ export function normalizeOjFoundation(e, installed, refreshConfiguration = false
187
182
  // A one-way repair of the exact shipped document, without owning customer routes.
188
183
  if (rootSource !== null &&
189
184
  fingerprint(rootSource) === '21af7892e39130c9ec3d7ffb583b3f5d24bee771440ca253d8d7b8ce41be9801') {
190
- e.writes.set(rootRoute, template('root.tsx.txt'));
185
+ e.writes.set(rootRoute, launchTemplate('root.tsx.txt'));
191
186
  changed = true;
192
187
  }
193
188
  else if (rootSource !== null && /\bfrom\s*(['"])\.\.\/styles\.css\?url\1/.test(rootSource))
@@ -199,7 +194,7 @@ export function normalizeOjFoundation(e, installed, refreshConfiguration = false
199
194
  }
200
195
  }
201
196
  for (const [destination, asset] of Object.entries(ojFiles)) {
202
- const desired = template(asset);
197
+ const desired = launchTemplate(asset);
203
198
  if (e.read(destination) !== desired) {
204
199
  e.owned(destination, desired);
205
200
  changed = true;
@@ -228,18 +223,21 @@ export function normalizeOjFoundation(e, installed, refreshConfiguration = false
228
223
  return changed;
229
224
  }
230
225
  /** Fingerprinted composition adapters; application routes stay source-owned. */
231
- export function composeTanstack(e, installed) {
226
+ export function composeTanstack(e, installed, refreshConfiguration = false) {
232
227
  assertTanstack(e);
233
- normalizeOjFoundation(e, installed);
228
+ normalizeOjFoundation(e, installed, refreshConfiguration);
234
229
  const backend = installed.includes('hono');
235
230
  const auth = installed.includes('database-auth');
236
- e.owned('apps/web/src/server.ts', template(backend ? 'server.ts.txt' : 'minimal-server.ts.txt'));
237
- e.owned('apps/web/src/lib/application.server.ts', template(backend ? 'application.server.ts.txt' : 'minimal-application.server.ts.txt').replaceAll('__AUTHENTICATION__', String(auth)));
231
+ e.owned('apps/web/src/server.ts', launchTemplate(backend ? 'server.ts.txt' : 'minimal-server.ts.txt'));
232
+ e.owned('apps/web/src/lib/application.server.ts', launchTemplate(backend ? 'application.server.ts.txt' : 'minimal-application.server.ts.txt')
233
+ .replaceAll('__AUTHENTICATION__', String(auth))
234
+ .replaceAll('__STORAGE__', String(installed.includes('r2')))
235
+ .replaceAll('__PAYMENT__', String(installed.includes('stripe'))));
238
236
  e.owned('apps/web/vite.config.ts', tanstackViteConfiguration(installed));
239
237
  }
240
238
  /** Install account source only when the backend authentication capability is added. */
241
239
  export function addTanstackAuth(e) {
242
240
  assertTanstack(e);
243
- e.create('apps/web/src/lib/auth-client.ts', template('auth-client.ts.txt'));
244
- e.create('apps/web/src/routes/sign-in.tsx', template('sign-in.tsx.txt'));
241
+ e.create('apps/web/src/lib/auth-client.ts', launchTemplate('auth-client.ts.txt'));
242
+ e.create('apps/web/src/routes/sign-in.tsx', launchTemplate('sign-in.tsx.txt'));
245
243
  }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const GENERATOR_VERSION = "0.23.0";
1
+ export declare const GENERATOR_VERSION = "0.24.1";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const GENERATOR_VERSION = '0.23.0';
1
+ export const GENERATOR_VERSION = '0.24.1';
@@ -21,6 +21,12 @@ Use `add storage` in place of `add r2`, and `add payment` in place of `add strip
21
21
 
22
22
  `backend` is one public selection; its provenance records the concrete Hono and database/auth capabilities. Use `--with-dependencies` to include missing prerequisites in the same planned source transaction. `stack list` describes this stack's additions. `status`/`doctor` check source completeness, not live service activation.
23
23
 
24
+ ## Updating an existing app
25
+
26
+ Run `pnpm dlx anhedral@latest stack update --dry-run --human` from the project. Review the diff, then run the version-pinned apply command in the preview. It checks that the plan still matches. After applying, run `pnpm install` and `pnpm check`. Use `--offline` for a local source update with deployment provenance pending.
27
+
28
+ Updates refresh the managed web and API adapters for the installed additions. Product routes, feature implementations and migrations stay application-owned. The updater preserves local adapter edits when the release still supplies the same baseline. If both changed differently, the preview identifies the conflicting file before any writes.
29
+
24
30
  ## Source protection
25
31
 
26
32
  Adding a capability also upgrades a canonical earlier TanStack Start foundation to the pinned OJ launchers and runtime helpers in the same source transaction, including when that capability is already installed. The exact earlier canonical document also receives the OJ-compatible side-effect CSS import; safe customized documents stay untouched, while edited documents retaining the earlier stylesheet URL import require reconciliation. Customized launchers or generated configuration require reconciliation before any writes. Additions never reinitialize an application. They plan all selected changes before writing, reject collisions and preserve unrelated JSON/JSONC settings. Composition adapters are fingerprinted in `anhedral.json`; modified adapters require reconciliation instead of silent replacement. Add product routes in `apps/api/src/index.ts`, custom types in `custom-environment.ts`, and auth method configuration in `auth-features.ts`/`auth.ts`.
@@ -43,4 +49,6 @@ Stripe adds source/schema, not a live payment service. Generate and review its b
43
49
 
44
50
  `anhedral.json` records nonsecret generator/capability versions and identity. Source provenance never grants hosting authority. The public deployment manifest uses runtime profile `anhedral-stack` for the web foundation and selected backend/R2/Stripe composition. Artifact identity, resource provisioning, secrets, migrations, runtime checks and production approval remain server-owned. See [the workflow](software-factory.md#platform-cli-access-and-source-upload).
45
51
 
52
+ The starter includes local tests for each installed addition. Storage tests use ephemeral Worker bindings. Payment tests generate and apply SQL only to a disposable fixture and sign webhook events locally. The workspace scopes security overrides to the affected transitive dependency versions.
53
+
46
54
  Run `pnpm check` and `pnpm audit:deps` in generated applications. Framework/runtime, provider and browser acceptance are distinct; source installation alone establishes none of them.
@@ -39,7 +39,7 @@ with revision, checks, failures and remaining gaps. Keep raw reports in ignored
39
39
  `.artifacts/`. Historical notes are not current instructions.
40
40
 
41
41
  Canonical docs live in `docs/`; `pnpm build` refreshes bundled plugin references.
42
- Current generated app guidance lives in `src/launch.ts`. OJ runs development and builds for the single TanStack Start foundation. Preserve shipped
42
+ Current generated app guidance lives in `assets/launch/README.md.txt` and `assets/launch/AGENTS.md.txt`. OJ runs development and builds for the single TanStack Start foundation. Preserve shipped
43
43
  reference paths, source-generation safety, dependency patch gates, UI provenance,
44
44
  licenses and exact-artifact packaging. A build does not publish npm or update an
45
45
  installed plugin. See [Contributing](https://github.com/anhedral/anhedral-cli/blob/main/.github/CONTRIBUTING.md)
@@ -107,9 +107,10 @@ Use the host's configured marketplace: Codex refreshes its marketplace with
107
107
  and reload/restart the host when required before relying on its new guidance.
108
108
  Run `stack update --dry-run --json`, inspect the bounded file diffs and conflicts,
109
109
  then apply `stack update --expect-plan <planId> --json`. The plan binds source
110
- preimages, target generator and resolved release artifact. Changed plans and
111
- customized generated files stop the update; authored routes and assets remain
112
- owned by the application. This operation uses the existing journaled transaction
110
+ preimages, target generator and resolved release artifact. A stale plan requires
111
+ a new preview. Fingerprinted adapters retain local edits when their release
112
+ baseline is unchanged. Divergent edits to the same adapter require reconciliation.
113
+ The application owns its routes and assets. This operation uses the existing journaled transaction
113
114
  without installing dependencies or running project scripts. Resolve source
114
115
  conflicts before another preview, then install dependencies and run application
115
116
  checks/build separately. It never changes authentication or deployment authority.
@@ -175,8 +176,13 @@ responses. `source status` reads its server receipt. Changed source requires an
175
176
  explicit `source upload --new`; an expired request also requires a new request.
176
177
  The client honors nested `.gitignore`, excludes generated output and secret paths,
177
178
  rejects symlinks and recognized credential material, and hashes every bounded
178
- chunk plus the complete archive and canonical source inventory. The generated
179
- `apps/web/src/routeTree.gen.ts` is excluded because the router regenerates it during
179
+ chunk plus the complete archive and canonical source inventory.
180
+
181
+ Source packaging holds directory handles throughout traversal. It requires Linux
182
+ with procfs or a macOS filesystem supporting volume file IDs. Run the CLI in WSL
183
+ for Windows source uploads.
184
+
185
+ The generated `apps/web/src/routeTree.gen.ts` is excluded because the router regenerates it during
180
186
  checks/builds; authored routes, router configuration and server source remain
181
187
  included. Credential scanning is deliberately conservative; inspect source before uploading.
182
188
 
@@ -230,7 +236,10 @@ pipe. `env set <NAME>` reads one literal value from a file or pipe. Values are
230
236
  never arguments, output or retry-state contents. Non-public names default to
231
237
  secrets; `--type config` is explicit readable configuration. Public-prefixed
232
238
  secrets, reserved names, duplicate names and oversized input fail before upload.
233
- Files require owner-only permissions and a regular non-symlink final file;
239
+ Use stdin, an owner-only file outside the project, or an input under the
240
+ project’s always-excluded `.anhedral/` directory. Project `.env*` and `.dev.vars*`
241
+ filenames are also excluded. A project-specific gitignore rule alone is insufficient.
242
+ Files must have a single hard link and a regular non-symlink final component;
234
243
  ancestor checks reject observed symlinks but are not an atomic directory lock.
235
244
  Use `--dry-run` without authentication for names/types only. Actual imports bind
236
245
  API origin, principal, team, project and environment, require `--replace` for
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anhedral",
3
- "version": "0.23.0",
3
+ "version": "0.24.1",
4
4
  "description": "The open-source Anhedral API client for building, configuring and deploying apps, with editable source generation.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -89,7 +89,9 @@
89
89
  "test:patch": "node tests/test-braces-install.mjs && node tests/test-forge-install.mjs",
90
90
  "check:boundaries": "node scripts/checks/repository-boundaries.mjs",
91
91
  "test:tanstack-runtime": "pnpm build && node scripts/runtime/tanstack-runtime-smoke.mjs",
92
- "check:standalone": "node scripts/checks/standalone-checkout.mjs"
92
+ "check:standalone": "node scripts/checks/standalone-checkout.mjs",
93
+ "examples:check": "node scripts/checks/generated-examples.mjs",
94
+ "examples:refresh": "node scripts/checks/generated-examples.mjs --write"
93
95
  },
94
96
  "keywords": [
95
97
  "cli",
@@ -1 +0,0 @@
1
- export declare const WEB_API_PROXY = "export interface ApiBinding { fetch(request: Request): Promise<Response> }\ntype Options = { binding?: ApiBinding; development: boolean; devOrigin?: string; send?: typeof fetch };\nfunction developmentOrigin(configured?: string): string {\n const url = new URL(configured || 'http://127.0.0.1:8787');\n const loopback = new Set(['127.0.0.1', 'localhost', '[::1]']);\n const invalid = [url.protocol !== 'http:', !loopback.has(url.hostname), url.username, url.password, url.pathname !== '/', url.search, url.hash];\n if (invalid.some(Boolean)) throw Error('API_INTERNAL_URL must be a loopback HTTP origin.');\n return url.origin;\n}\nfunction backendOrigin(options: Options): string {\n if (options.development) return developmentOrigin(options.devOrigin);\n if ([!options.binding, options.devOrigin].some(Boolean)) throw Error('Production requires the API service binding.');\n return 'https://api.internal';\n}\nfunction apiTarget(request: Request, origin: string): URL {\n const url = new URL(request.url);\n if (!/^\\/api(?:\\/|$)/.test(url.pathname)) throw Error('Unexpected API path.');\n return new URL(url.pathname + url.search, origin);\n}\nfunction forwardedHeaders(request: Request): Headers {\n const headers = new Headers();\n for (const name of ['accept', 'content-type', 'cookie', 'origin', 'authorization', 'sec-fetch-site', 'expo-origin', 'idempotency-key']) {\n const value = request.headers.get(name); if (value) headers.set(name, value);\n }\n return headers;\n}\nfunction upstreamRequest(request: Request, target: URL): Request {\n const settings: RequestInit & { duplex?: 'half' } = { method: request.method, headers: forwardedHeaders(request), redirect: 'manual', signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]) };\n if (!['GET', 'HEAD'].includes(request.method)) { settings.body = request.body; settings.duplex = 'half'; }\n return new Request(target, settings);\n}\nfunction privateResponse(response: Response, development: boolean): Response {\n const headers = new Headers(response.headers);\n for (const name of ['connection', 'transfer-encoding', 'access-control-allow-origin', 'access-control-allow-credentials']) headers.delete(name);\n // Node fetch already decoded the local HTTP response. The server must frame/compress\n // those decoded bytes itself; the sidecar's wire headers no longer describe them.\n if (development) { headers.delete('content-encoding'); headers.delete('content-length'); }\n headers.set('cache-control', 'private, no-store');\n return new Response(response.body, { status: response.status, headers });\n}\nexport async function proxyApi(request: Request, options: Options): Promise<Response> {\n try {\n const upstream = upstreamRequest(request, apiTarget(request, backendOrigin(options)));\n const response = options.development ? await (options.send ?? fetch)(upstream) : await options.binding!.fetch(upstream);\n return privateResponse(response, options.development);\n } catch { return Response.json({ error: 'API unavailable' }, { status: 503, headers: { 'cache-control': 'private, no-store' } }); }\n}\n";
package/dist/api-proxy.js DELETED
@@ -1,48 +0,0 @@
1
- export const WEB_API_PROXY = `export interface ApiBinding { fetch(request: Request): Promise<Response> }
2
- type Options = { binding?: ApiBinding; development: boolean; devOrigin?: string; send?: typeof fetch };
3
- function developmentOrigin(configured?: string): string {
4
- const url = new URL(configured || 'http://127.0.0.1:8787');
5
- const loopback = new Set(['127.0.0.1', 'localhost', '[::1]']);
6
- const invalid = [url.protocol !== 'http:', !loopback.has(url.hostname), url.username, url.password, url.pathname !== '/', url.search, url.hash];
7
- if (invalid.some(Boolean)) throw Error('API_INTERNAL_URL must be a loopback HTTP origin.');
8
- return url.origin;
9
- }
10
- function backendOrigin(options: Options): string {
11
- if (options.development) return developmentOrigin(options.devOrigin);
12
- if ([!options.binding, options.devOrigin].some(Boolean)) throw Error('Production requires the API service binding.');
13
- return 'https://api.internal';
14
- }
15
- function apiTarget(request: Request, origin: string): URL {
16
- const url = new URL(request.url);
17
- if (!/^\\/api(?:\\/|$)/.test(url.pathname)) throw Error('Unexpected API path.');
18
- return new URL(url.pathname + url.search, origin);
19
- }
20
- function forwardedHeaders(request: Request): Headers {
21
- const headers = new Headers();
22
- for (const name of ['accept', 'content-type', 'cookie', 'origin', 'authorization', 'sec-fetch-site', 'expo-origin', 'idempotency-key']) {
23
- const value = request.headers.get(name); if (value) headers.set(name, value);
24
- }
25
- return headers;
26
- }
27
- function upstreamRequest(request: Request, target: URL): Request {
28
- const settings: RequestInit & { duplex?: 'half' } = { method: request.method, headers: forwardedHeaders(request), redirect: 'manual', signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]) };
29
- if (!['GET', 'HEAD'].includes(request.method)) { settings.body = request.body; settings.duplex = 'half'; }
30
- return new Request(target, settings);
31
- }
32
- function privateResponse(response: Response, development: boolean): Response {
33
- const headers = new Headers(response.headers);
34
- for (const name of ['connection', 'transfer-encoding', 'access-control-allow-origin', 'access-control-allow-credentials']) headers.delete(name);
35
- // Node fetch already decoded the local HTTP response. The server must frame/compress
36
- // those decoded bytes itself; the sidecar's wire headers no longer describe them.
37
- if (development) { headers.delete('content-encoding'); headers.delete('content-length'); }
38
- headers.set('cache-control', 'private, no-store');
39
- return new Response(response.body, { status: response.status, headers });
40
- }
41
- export async function proxyApi(request: Request, options: Options): Promise<Response> {
42
- try {
43
- const upstream = upstreamRequest(request, apiTarget(request, backendOrigin(options)));
44
- const response = options.development ? await (options.send ?? fetch)(upstream) : await options.binding!.fetch(upstream);
45
- return privateResponse(response, options.development);
46
- } catch { return Response.json({ error: 'API unavailable' }, { status: 503, headers: { 'cache-control': 'private, no-store' } }); }
47
- }
48
- `;