anhedral 0.4.1 → 0.6.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 (85) hide show
  1. package/README.md +29 -256
  2. package/assets/anhedral-cli-init-technical.svg +322 -0
  3. package/assets/anhedral-cli-init.svg +257 -173
  4. package/dist/bin.js +28 -162
  5. package/dist/dependencies.d.ts +7 -56
  6. package/dist/dependencies.js +96 -305
  7. package/dist/index.d.ts +2 -7
  8. package/dist/index.js +1 -4
  9. package/dist/{templates → platforms}/desktop.d.ts +1 -1
  10. package/dist/{templates → platforms}/desktop.js +28 -266
  11. package/dist/{templates → platforms}/extension.d.ts +1 -1
  12. package/dist/platforms/extension.js +401 -0
  13. package/dist/{templates → platforms}/mobile.d.ts +1 -1
  14. package/dist/platforms/mobile.js +232 -0
  15. package/dist/project.d.ts +4 -0
  16. package/dist/project.js +1 -0
  17. package/dist/standard-products.d.ts +2 -0
  18. package/dist/standard-products.js +6 -0
  19. package/dist/standard.d.ts +18 -0
  20. package/dist/standard.js +578 -0
  21. package/dist/version.d.ts +1 -1
  22. package/dist/version.js +1 -1
  23. package/docs/application-stack-standard.md +700 -0
  24. package/package.json +34 -49
  25. package/CHANGELOG.md +0 -132
  26. package/CONTRIBUTING.md +0 -73
  27. package/SECURITY.md +0 -37
  28. package/SKILL.md +0 -244
  29. package/assets/images/svg/ably-symbol-color.svg +0 -8
  30. package/bin/anhedral.js +0 -2
  31. package/dist/architecture/contributions.d.ts +0 -28
  32. package/dist/architecture/contributions.js +0 -125
  33. package/dist/architecture/index.d.ts +0 -12
  34. package/dist/architecture/index.js +0 -6
  35. package/dist/architecture/manifest.d.ts +0 -53
  36. package/dist/architecture/manifest.js +0 -283
  37. package/dist/architecture/modules.d.ts +0 -37
  38. package/dist/architecture/modules.js +0 -184
  39. package/dist/architecture/plan.d.ts +0 -58
  40. package/dist/architecture/plan.js +0 -145
  41. package/dist/architecture/templates.d.ts +0 -10
  42. package/dist/architecture/templates.js +0 -23
  43. package/dist/cli.d.ts +0 -32
  44. package/dist/cli.js +0 -235
  45. package/dist/composers/root.d.ts +0 -6
  46. package/dist/composers/root.js +0 -35
  47. package/dist/print.d.ts +0 -8
  48. package/dist/print.js +0 -48
  49. package/dist/prompts.d.ts +0 -5
  50. package/dist/prompts.js +0 -19
  51. package/dist/scaffold.d.ts +0 -76
  52. package/dist/scaffold.js +0 -1895
  53. package/dist/template-source.d.ts +0 -20
  54. package/dist/template-source.js +0 -180
  55. package/dist/templates/api.d.ts +0 -2
  56. package/dist/templates/api.js +0 -3122
  57. package/dist/templates/assets-private-proxy.d.ts +0 -3
  58. package/dist/templates/assets-private-proxy.js +0 -277
  59. package/dist/templates/electron-updater.d.ts +0 -3
  60. package/dist/templates/electron-updater.js +0 -358
  61. package/dist/templates/extension.js +0 -732
  62. package/dist/templates/mobile.js +0 -720
  63. package/dist/templates/shared.d.ts +0 -2
  64. package/dist/templates/shared.js +0 -520
  65. package/dist/templates/web.d.ts +0 -2
  66. package/dist/templates/web.js +0 -412
  67. package/dist/toolchain.d.ts +0 -3
  68. package/dist/toolchain.js +0 -8
  69. package/dist/ui.d.ts +0 -33
  70. package/dist/ui.js +0 -199
  71. package/dist/workspace-config.d.ts +0 -11
  72. package/dist/workspace-config.js +0 -372
  73. package/docs/conventions.md +0 -92
  74. package/docs/master-stack-map.md +0 -199
  75. package/docs/output-tree-contract.md +0 -482
  76. package/docs/references/manual-scaffolding.md +0 -403
  77. package/docs/references/provisioning.md +0 -220
  78. package/scripts/render-master-stack-map.mjs +0 -510
  79. package/templates/api-fastify/apps/api/tsconfig.json +0 -20
  80. package/templates/catalog.json +0 -23
  81. package/templates/db-drizzle/packages/db/tsconfig.json +0 -14
  82. package/templates/desktop-electron/apps/desktop/tsconfig.json +0 -37
  83. package/templates/extension-wxt/apps/extension/tsconfig.json +0 -41
  84. package/templates/mobile-expo/apps/mobile/expo-env.d.ts +0 -1
  85. package/templates/web-next/apps/web/next-env.d.ts +0 -6
package/dist/scaffold.js DELETED
@@ -1,1895 +0,0 @@
1
- import { chmodSync, copyFileSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmdirSync, rmSync } from 'node:fs';
2
- import path from 'node:path';
3
- import { env } from 'node:process';
4
- import { anhedralPrint } from './print.js';
5
- import { appendGitignore, execFile, writeFile } from './util.js';
6
- import { MOBILE_NODE_ENGINE, NODE_ENGINE, PACKAGE_MANAGER, ROOT_DEPENDENCIES, TOOLCHAIN_DEPENDENCIES } from './dependencies.js';
7
- import { resolveToolchainChannel } from './toolchain.js';
8
- import { scaffoldApi } from './templates/api.js';
9
- import { r2BucketName, scaffoldAssetsPrivateProxy } from './templates/assets-private-proxy.js';
10
- import { scaffoldDesktop } from './templates/desktop.js';
11
- import { desktopUpdatesBucketName, scaffoldElectronUpdater, } from './templates/electron-updater.js';
12
- import { scaffoldExtension } from './templates/extension.js';
13
- import { scaffoldMobile } from './templates/mobile.js';
14
- import { scaffoldSharedPackages } from './templates/shared.js';
15
- import { scaffoldWeb } from './templates/web.js';
16
- import { assertPackageName, markdownHeading } from './render.js';
17
- import { runStagedTransaction } from './transaction.js';
18
- import { buildGenerationPlan, createManifest, hashContent, readManifest, resolveModules, serializeManifest, } from './architecture/index.js';
19
- import { GENERATOR_VERSION } from './version.js';
20
- import { collectModuleContributions } from './architecture/contributions.js';
21
- import { composeRootEnvironment, composeVercelCrons } from './composers/root.js';
22
- import { assertTemplateProvenance, materializeTemplates, } from './template-source.js';
23
- import { desiredWorkspacePolicy, mergeWorkspaceFile, } from './workspace-config.js';
24
- import { UI_TARGETS, installUiComponents, mergeUiInstalls, resolveUiInstalls, uiInstallKey, } from './ui.js';
25
- export function supportsMobileInstallNode(version) {
26
- const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version);
27
- if (!match)
28
- return false;
29
- const major = Number(match[1]);
30
- const minor = Number(match[2]);
31
- if (major === 22)
32
- return minor >= 13;
33
- if (major === 24)
34
- return minor >= 3;
35
- return major >= 25;
36
- }
37
- function assertInstallNodeCompatibility(options) {
38
- if (options.apps.mobile
39
- && !options.skipInstall
40
- && !options.dryRun
41
- && !supportsMobileInstallNode(process.versions.node)) {
42
- throw new Error(`Installing an Expo mobile workspace requires Node ${MOBILE_NODE_ENGINE}; current Node is ${process.versions.node}. `
43
- + 'Switch Node versions or rerun with --skip-install.');
44
- }
45
- }
46
- const ACTIONS = {
47
- checkout: 'actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10',
48
- pnpm: 'pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271',
49
- node: 'actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38',
50
- };
51
- const ROOT_MERGEABLE_FILES = new Set([
52
- '.env.example',
53
- '.gitignore',
54
- '.vercelignore',
55
- 'package.json',
56
- 'pnpm-workspace.yaml',
57
- 'turbo.json',
58
- 'vercel.json',
59
- ]);
60
- const GENERATED_CACHE_NAMES = new Set([
61
- '.git', '.next', '.output', '.turbo', '.wxt', 'dist', 'node_modules', 'release',
62
- ]);
63
- function lstatIfPresent(target) {
64
- try {
65
- return lstatSync(target);
66
- }
67
- catch (error) {
68
- if (error.code === 'ENOENT')
69
- return null;
70
- throw error;
71
- }
72
- }
73
- function pathEntryExists(target) {
74
- return lstatIfPresent(target) !== null;
75
- }
76
- function normalizedFileMode(mode) {
77
- // Windows exposes a synthetic subset of stat mode bits that cannot represent
78
- // Unix permissions reliably. Keep the manifest portable by treating those
79
- // permissions as unknown and disabling ownership checks on that platform.
80
- return process.platform === 'win32' ? null : Number(mode) & 0o777;
81
- }
82
- function displayFileMode(mode) {
83
- return `0o${mode.toString(8).padStart(3, '0')}`;
84
- }
85
- function assertManagedFileMode(relativePath, record, actualStat) {
86
- if (record.ownership !== 'managed' || record.mode === null)
87
- return;
88
- const actualMode = normalizedFileMode(actualStat.mode);
89
- if (actualMode === null || actualMode === record.mode)
90
- return;
91
- throw new Error(`Managed file mode has user modifications: ${relativePath} `
92
- + `(expected ${displayFileMode(record.mode)}, found ${displayFileMode(actualMode)}).`);
93
- }
94
- function assertManagedFileModes(root, manifest) {
95
- for (const [relativePath, record] of Object.entries(manifest.files)) {
96
- if (record.ownership !== 'managed' || record.mode === null)
97
- continue;
98
- const actualStat = lstatIfPresent(path.join(root, relativePath));
99
- if (!actualStat || !actualStat.isFile() || actualStat.isSymbolicLink())
100
- continue;
101
- assertManagedFileMode(relativePath, record, actualStat);
102
- }
103
- }
104
- function isTransactionMetadata(relativePath) {
105
- if (relativePath.includes('/'))
106
- return false;
107
- return relativePath === '.anhedral-txn'
108
- || relativePath === '.anhedral.lock'
109
- || relativePath === '.anhedral.lock.reclaim'
110
- || /^\.anhedral\.lock\..+\.tmp$/.test(relativePath)
111
- || relativePath === '.anhedral-journal.json'
112
- || /^\.anhedral-journal\.json\.tmp-.+$/.test(relativePath);
113
- }
114
- function projectOptions(options) {
115
- return {
116
- projectName: options.projectName,
117
- displayName: options.displayName,
118
- apps: options.apps,
119
- features: options.features,
120
- skipInstall: options.skipInstall || options.dryRun,
121
- nativeStyling: options.nativeStyling,
122
- };
123
- }
124
- function selectionsFromModules(modules) {
125
- const selected = new Set(modules);
126
- return {
127
- apps: {
128
- web: selected.has('web'),
129
- mobile: selected.has('mobile'),
130
- api: selected.has('api'),
131
- desktop: selected.has('desktop'),
132
- extension: selected.has('extension'),
133
- },
134
- features: {
135
- database: selected.has('db'),
136
- auth: selected.has('auth'),
137
- billing: selected.has('billing'),
138
- storage: selected.has('storage'),
139
- nativeSubscriptions: selected.has('native-subscriptions'),
140
- electronUpdater: selected.has('electron-updater'),
141
- },
142
- };
143
- }
144
- function canonicalInitOptions(options) {
145
- assertPackageName(options.projectName);
146
- const resolution = resolveModules(options.modules);
147
- return {
148
- ...options,
149
- uiComponents: options.uiComponents ?? [],
150
- nativeStyling: options.nativeStyling ?? 'nativewind',
151
- modules: [...resolution.requestedModules],
152
- ...selectionsFromModules(resolution.resolvedModules),
153
- };
154
- }
155
- function optionsFromManifest(manifest, addOptions, modules) {
156
- const resolution = resolveModules(modules);
157
- return {
158
- projectName: manifest.project.name,
159
- displayName: manifest.project.displayName,
160
- modules: [...resolution.requestedModules],
161
- ...selectionsFromModules(resolution.resolvedModules),
162
- skipInstall: addOptions.skipInstall,
163
- dryRun: addOptions.dryRun,
164
- json: addOptions.json,
165
- toolchainChannel: addOptions.toolchainChannel ?? toolchainChannelFromManifest(manifest),
166
- uiComponents: [],
167
- nativeStyling: manifest.ui.nativeStyling,
168
- };
169
- }
170
- function toolchainChannelFromManifest(manifest) {
171
- return resolveToolchainChannel(manifest.toolchain);
172
- }
173
- export function isSupportedProjectUpgrade(fromVersion, toVersion) {
174
- const parseStableVersion = (version) => {
175
- const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(version);
176
- return match
177
- ? [Number(match[1]), Number(match[2]), Number(match[3])]
178
- : undefined;
179
- };
180
- const from = parseStableVersion(fromVersion);
181
- const to = parseStableVersion(toVersion);
182
- if (!from || !to)
183
- return false;
184
- const supportedOwnershipMigration = fromVersion === '0.3.0' && to[0] === 0 && to[1] === 4;
185
- const compatiblePatchUpgrade = from[0] === to[0]
186
- && from[1] === to[1]
187
- && from[2] < to[2];
188
- return supportedOwnershipMigration || compatiblePatchUpgrade;
189
- }
190
- function ensureScaffoldRoot(root) {
191
- const rootStat = lstatIfPresent(root);
192
- if (!rootStat)
193
- throw new Error(`Scaffold destination is not a directory: ${root}`);
194
- if (rootStat.isSymbolicLink())
195
- throw new Error(`Refusing scaffold destination that is a symbolic link: ${root}`);
196
- if (!rootStat.isDirectory())
197
- throw new Error(`Scaffold destination is not a directory: ${root}`);
198
- const allowed = new Set(['.git', '.gitignore', '.DS_Store', '.anhedral.lock']);
199
- const unexpected = readdirSync(root).filter((entry) => !allowed.has(entry));
200
- if (unexpected.length > 0) {
201
- throw new Error(`Current directory is not empty. Found: ${unexpected.join(', ')}`);
202
- }
203
- }
204
- function selectedAppFilters(apps) {
205
- return Object.entries(apps)
206
- .filter(([, enabled]) => enabled)
207
- .map(([name]) => `./apps/${name}`);
208
- }
209
- function rootScripts(options) {
210
- const filters = selectedAppFilters(options.apps);
211
- const primaryClient = filters.find((entry) => entry !== './apps/api');
212
- const primaryFilters = primaryClient
213
- ? [primaryClient, ...(options.apps.api ? ['./apps/api'] : [])]
214
- : filters.slice(0, 1);
215
- const scripts = {
216
- dev: primaryFilters.length ? `turbo dev --parallel ${primaryFilters.map((entry) => `--filter=${entry}`).join(' ')}` : 'echo "No app surfaces selected."',
217
- ...(filters.length > primaryFilters.length
218
- ? { 'dev:all': `turbo dev --parallel ${filters.map((entry) => `--filter=${entry}`).join(' ')}` }
219
- : {}),
220
- build: 'turbo build',
221
- typecheck: 'turbo typecheck',
222
- };
223
- const verify = [];
224
- if (options.apps.web) {
225
- scripts['dev:web'] = 'pnpm --filter ./apps/web dev';
226
- scripts['verify:web'] = 'pnpm --filter ./apps/web typecheck && pnpm --filter ./apps/web build';
227
- verify.push('pnpm verify:web');
228
- }
229
- if (options.apps.web || options.apps.api) {
230
- scripts['deploy:vercel:link'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} link`;
231
- scripts['deploy:vercel:preview'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} deploy`;
232
- scripts['deploy:vercel:production'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} deploy --prod`;
233
- scripts['deploy:vercel:inspect'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} inspect`;
234
- scripts['deploy:vercel:domain:inspect'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} domains inspect`;
235
- }
236
- if (options.apps.mobile) {
237
- scripts['dev:mobile'] = 'pnpm --filter ./apps/mobile dev';
238
- scripts['verify:mobile'] = 'pnpm --filter ./apps/mobile typecheck && pnpm --filter ./apps/mobile build:web';
239
- verify.push('pnpm verify:mobile');
240
- const eas = `pnpm --dir apps/mobile dlx eas-cli@${TOOLCHAIN_DEPENDENCIES['eas-cli']}`;
241
- scripts['mobile:eas:login'] = `${eas} login`;
242
- scripts['mobile:eas:init'] = `${eas} init`;
243
- scripts['mobile:build:internal:ios'] = `${eas} build --platform ios --profile preview`;
244
- scripts['mobile:build:internal:android'] = `${eas} build --platform android --profile preview`;
245
- scripts['mobile:build:production:ios'] = `${eas} build --platform ios --profile production`;
246
- scripts['mobile:build:production:android'] = `${eas} build --platform android --profile production`;
247
- scripts['mobile:submit:ios'] = `${eas} submit --platform ios --profile production --latest`;
248
- scripts['mobile:submit:android'] = `${eas} submit --platform android --profile production --latest`;
249
- }
250
- if (options.apps.api) {
251
- scripts['dev:api'] = 'pnpm --filter ./apps/api dev';
252
- scripts['verify:api'] = 'pnpm --filter ./apps/api test:coverage && pnpm --filter ./apps/api build';
253
- verify.push('pnpm verify:api');
254
- }
255
- if (options.apps.desktop) {
256
- scripts['dev:desktop'] = 'pnpm --filter ./apps/desktop dev';
257
- scripts['desktop:build'] = 'pnpm --filter ./apps/desktop package';
258
- scripts['verify:desktop'] = 'pnpm --filter ./apps/desktop typecheck && pnpm --filter ./apps/desktop build';
259
- verify.push('pnpm verify:desktop');
260
- }
261
- if (options.features.electronUpdater) {
262
- const bucketName = desktopUpdatesBucketName(options.projectName);
263
- const wrangler = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler}`;
264
- scripts['desktop:updates:cloudflare:login'] = `${wrangler} login`;
265
- scripts['desktop:updates:bucket:create'] = `${wrangler} r2 bucket create ${bucketName}`;
266
- scripts['desktop:updates:worker:check'] = 'pnpm --filter ./apps/desktop-updater-worker check';
267
- scripts['desktop:updates:worker:dev'] = 'pnpm --filter ./apps/desktop-updater-worker dev';
268
- scripts['desktop:updates:worker:deploy'] = 'pnpm --filter ./apps/desktop-updater-worker deploy';
269
- scripts['desktop:updates:first-provision'] = 'pnpm desktop:updates:bucket:create && pnpm desktop:updates:worker:deploy';
270
- scripts['desktop:updates:worker:types'] = 'pnpm --filter ./apps/desktop-updater-worker types';
271
- scripts['desktop:updates:build:mac'] = 'pnpm --filter ./apps/desktop updates:build:mac';
272
- scripts['desktop:updates:build:win'] = 'pnpm --filter ./apps/desktop updates:build:win';
273
- scripts['desktop:updates:build:linux'] = 'pnpm --filter ./apps/desktop updates:build:linux';
274
- scripts['desktop:updates:publish'] = 'node apps/desktop/scripts/publish-updates.mjs';
275
- scripts['verify:desktop-updates'] = 'pnpm desktop:updates:worker:check && node --check apps/desktop/scripts/publish-updates.mjs';
276
- verify.push('pnpm verify:desktop-updates');
277
- }
278
- if (options.apps.extension) {
279
- scripts['dev:extension'] = 'pnpm --filter ./apps/extension dev';
280
- scripts['extension:zip'] = 'pnpm --filter ./apps/extension zip';
281
- scripts['verify:extension'] = 'pnpm --filter ./apps/extension typecheck && pnpm --filter ./apps/extension zip';
282
- verify.push('pnpm verify:extension');
283
- }
284
- if (options.features.database) {
285
- scripts['neon:login'] = `pnpm dlx neonctl@${TOOLCHAIN_DEPENDENCIES.neonctl} auth`;
286
- scripts['neon:project:create'] = `pnpm dlx neonctl@${TOOLCHAIN_DEPENDENCIES.neonctl} projects create`;
287
- scripts['db:generate'] = 'pnpm --filter @shared/db db:generate';
288
- scripts['db:migrate'] = 'pnpm --filter @shared/db db:migrate';
289
- scripts['db:check'] = 'pnpm --filter @shared/db db:check';
290
- scripts['db:studio'] = 'pnpm --filter @shared/db db:studio';
291
- scripts['verify:db'] = 'node scripts/verify-db-migrations.mjs && pnpm db:check';
292
- verify.push('pnpm verify:db');
293
- }
294
- if (options.features.storage) {
295
- const bucketName = r2BucketName(options.projectName);
296
- scripts['r2:login'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} login`;
297
- scripts['r2:bucket:create'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} r2 bucket create ${bucketName}`;
298
- scripts['r2:cors:list'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} r2 bucket cors list ${bucketName}`;
299
- scripts['r2:cors:set'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} r2 bucket cors set ${bucketName} --file cloudflare/r2-cors.template.json`;
300
- scripts['assets:proxy:check'] = 'pnpm --filter ./apps/assets-private-proxy check';
301
- scripts['assets:proxy:dev'] = 'pnpm --filter ./apps/assets-private-proxy dev';
302
- scripts['assets:proxy:deploy'] = 'pnpm --filter ./apps/assets-private-proxy deploy';
303
- scripts['verify:assets-proxy'] = 'pnpm assets:proxy:check';
304
- verify.push('pnpm verify:assets-proxy');
305
- }
306
- if (!Object.values(options.apps).some(Boolean))
307
- verify.unshift('pnpm typecheck');
308
- scripts.verify = verify.join(' && ');
309
- return scripts;
310
- }
311
- function desiredRootPackage(options) {
312
- const workspaces = [
313
- Object.values(options.apps).some(Boolean) ? 'apps/*' : null,
314
- options.apps.api || options.features.database ? 'packages/*' : null,
315
- ].filter((value) => value !== null);
316
- return {
317
- name: options.projectName,
318
- private: true,
319
- version: '0.1.0',
320
- packageManager: PACKAGE_MANAGER,
321
- engines: { node: options.apps.mobile ? MOBILE_NODE_ENGINE : NODE_ENGINE },
322
- scripts: rootScripts(options),
323
- workspaces,
324
- devDependencies: ROOT_DEPENDENCIES.devDependencies,
325
- };
326
- }
327
- function sameJson(left, right) {
328
- if (Object.is(left, right))
329
- return true;
330
- if (Array.isArray(left) || Array.isArray(right)) {
331
- return Array.isArray(left)
332
- && Array.isArray(right)
333
- && left.length === right.length
334
- && left.every((entry, index) => sameJson(entry, right[index]));
335
- }
336
- if (!isJsonRecord(left) || !isJsonRecord(right))
337
- return false;
338
- const leftKeys = Object.keys(left).sort();
339
- const rightKeys = Object.keys(right).sort();
340
- return leftKeys.length === rightKeys.length
341
- && leftKeys.every((key, index) => key === rightKeys[index] && sameJson(left[key], right[key]));
342
- }
343
- function isJsonRecord(value) {
344
- return typeof value === 'object' && value !== null && !Array.isArray(value);
345
- }
346
- const MISSING_JSON_VALUE = Symbol('missing-json-value');
347
- function includesJson(values, candidate) {
348
- return values.some((value) => sameJson(value, candidate));
349
- }
350
- function mergeChangedArrays(current, desired, previous) {
351
- const merged = [];
352
- for (const entry of desired) {
353
- if ((!includesJson(previous, entry) || includesJson(current, entry)) && !includesJson(merged, entry)) {
354
- merged.push(entry);
355
- }
356
- }
357
- for (const entry of current) {
358
- if (!includesJson(previous, entry) && !includesJson(merged, entry))
359
- merged.push(entry);
360
- }
361
- return merged;
362
- }
363
- function mergeGeneratedThreeWay(current, desired, previous, fieldPath) {
364
- if (current === MISSING_JSON_VALUE) {
365
- if (desired === MISSING_JSON_VALUE)
366
- return MISSING_JSON_VALUE;
367
- if (previous === MISSING_JSON_VALUE)
368
- return desired;
369
- if (sameJson(desired, previous))
370
- return MISSING_JSON_VALUE;
371
- throw new Error(`Conflict in ${fieldPath}: a generated value changed after the user removed it.`);
372
- }
373
- if (desired === MISSING_JSON_VALUE) {
374
- if (previous === MISSING_JSON_VALUE)
375
- return current;
376
- if (sameJson(current, previous))
377
- return MISSING_JSON_VALUE;
378
- return current;
379
- }
380
- if (previous === MISSING_JSON_VALUE) {
381
- if (sameJson(current, desired))
382
- return desired;
383
- if (isJsonRecord(current) && isJsonRecord(desired)) {
384
- return mergeGeneratedRecords(current, desired, {}, fieldPath, true);
385
- }
386
- if (Array.isArray(current) && Array.isArray(desired)) {
387
- return [...desired, ...current.filter((entry) => !includesJson(desired, entry))];
388
- }
389
- throw new Error(`Conflict in ${fieldPath}: a newly generated value collides with a user-defined value.`);
390
- }
391
- if (sameJson(current, desired))
392
- return current;
393
- if (sameJson(current, previous))
394
- return desired;
395
- if (sameJson(desired, previous))
396
- return current;
397
- if (isJsonRecord(current) && isJsonRecord(desired) && isJsonRecord(previous)) {
398
- return mergeGeneratedRecords(current, desired, previous, fieldPath, true);
399
- }
400
- if (Array.isArray(current) && Array.isArray(desired) && Array.isArray(previous)) {
401
- return mergeChangedArrays(current, desired, previous);
402
- }
403
- throw new Error(`Conflict in ${fieldPath}: both the generator and the user changed the value.`);
404
- }
405
- function mergeGeneratedOwned(current, desired, fieldPath) {
406
- if (desired === MISSING_JSON_VALUE)
407
- return current;
408
- if (current === MISSING_JSON_VALUE)
409
- return desired;
410
- if (isJsonRecord(current) && isJsonRecord(desired)) {
411
- return mergeGeneratedRecords(current, desired, {}, fieldPath, false);
412
- }
413
- if (Array.isArray(current) && Array.isArray(desired)) {
414
- return [...desired, ...current.filter((entry) => !includesJson(desired, entry))];
415
- }
416
- if (isJsonRecord(current)
417
- || isJsonRecord(desired)
418
- || Array.isArray(current)
419
- || Array.isArray(desired)) {
420
- throw new Error(`Conflict in ${fieldPath}: the generator version changed and the value shape is ambiguous.`);
421
- }
422
- // Without a trustworthy previous-generator snapshot, an existing scalar may
423
- // be user-authored. Preserve it instead of silently resetting it to today's
424
- // default. Newly introduced keys still take the desired value above.
425
- return current;
426
- }
427
- function mergeGeneratedRecords(current, desired, previous, fieldPath, trustPrevious) {
428
- const keys = [...new Set([...Object.keys(desired), ...Object.keys(current), ...Object.keys(previous)])];
429
- const entries = [];
430
- for (const key of keys) {
431
- const currentValue = Object.hasOwn(current, key) ? current[key] : MISSING_JSON_VALUE;
432
- const desiredValue = Object.hasOwn(desired, key) ? desired[key] : MISSING_JSON_VALUE;
433
- const previousValue = Object.hasOwn(previous, key) ? previous[key] : MISSING_JSON_VALUE;
434
- const value = trustPrevious
435
- ? mergeGeneratedThreeWay(currentValue, desiredValue, previousValue, `${fieldPath}.${key}`)
436
- : mergeGeneratedOwned(currentValue, desiredValue, `${fieldPath}.${key}`);
437
- if (value !== MISSING_JSON_VALUE)
438
- entries.push([key, value]);
439
- }
440
- return Object.fromEntries(entries);
441
- }
442
- function mergeGeneratedStructure(current, desired, previous, fieldPath, trustPrevious) {
443
- if (isJsonRecord(current) && isJsonRecord(desired)) {
444
- return mergeGeneratedRecords(current, desired, isJsonRecord(previous) ? previous : {}, fieldPath, trustPrevious);
445
- }
446
- return trustPrevious
447
- ? mergeGeneratedThreeWay(current, desired, previous, fieldPath)
448
- : mergeGeneratedOwned(current, desired, fieldPath);
449
- }
450
- function mergeStringMap(current, desired, previousGenerated, filePath, allowGeneratedUpdates) {
451
- const existing = current && typeof current === 'object' ? current : {};
452
- const generated = desired && typeof desired === 'object' ? desired : {};
453
- const previous = previousGenerated && typeof previousGenerated === 'object'
454
- ? previousGenerated
455
- : {};
456
- const merged = { ...existing };
457
- for (const [key, value] of Object.entries(generated)) {
458
- if (merged[key] === undefined || merged[key] === value || allowGeneratedUpdates || merged[key] === previous[key])
459
- merged[key] = value;
460
- else
461
- throw new Error(`Conflict in ${filePath}: key ${key} has a user-defined value.`);
462
- }
463
- return Object.fromEntries(Object.entries(merged).sort(([left], [right]) => left.localeCompare(right)));
464
- }
465
- function writeRootPackage(root, options, mode, allowGeneratedUpdates, previousGenerated) {
466
- const filePath = path.join(root, 'package.json');
467
- const desired = desiredRootPackage(options);
468
- if (mode === 'init' || !pathEntryExists(filePath)) {
469
- writeFile(filePath, JSON.stringify(desired, null, 2) + '\n');
470
- return;
471
- }
472
- const current = JSON.parse(readFileSync(filePath, 'utf8'));
473
- const desiredWorkspaces = desired.workspaces;
474
- const currentWorkspaces = Array.isArray(current.workspaces) ? current.workspaces.filter((value) => typeof value === 'string') : [];
475
- const mergeMetadataField = (field) => {
476
- const currentValue = current[field];
477
- const desiredValue = desired[field];
478
- const previousValue = previousGenerated?.[field];
479
- if (allowGeneratedUpdates
480
- || currentValue === undefined
481
- || (previousValue !== undefined && sameJson(currentValue, previousValue))) {
482
- return desiredValue;
483
- }
484
- if (previousValue !== undefined && !sameJson(previousValue, desiredValue)) {
485
- throw new Error(`Conflict in package.json: ${field} was user-modified and must satisfy the newly selected modules.`);
486
- }
487
- return currentValue;
488
- };
489
- const merged = {
490
- ...desired,
491
- ...current,
492
- private: true,
493
- packageManager: mergeMetadataField('packageManager'),
494
- engines: mergeMetadataField('engines'),
495
- workspaces: [...new Set([...currentWorkspaces, ...desiredWorkspaces])].sort(),
496
- scripts: mergeStringMap(current.scripts, desired.scripts, previousGenerated?.scripts, 'package.json scripts', allowGeneratedUpdates),
497
- devDependencies: mergeStringMap(current.devDependencies, desired.devDependencies, previousGenerated?.devDependencies, 'package.json devDependencies', allowGeneratedUpdates),
498
- };
499
- writeFile(filePath, JSON.stringify(merged, null, 2) + '\n');
500
- }
501
- function mergeJsonConfig(root, relativePath, desired, previousGenerated, trustPreviousGenerated) {
502
- const filePath = path.join(root, relativePath);
503
- if (!pathEntryExists(filePath)) {
504
- writeFile(filePath, JSON.stringify(desired, null, 2) + '\n');
505
- return;
506
- }
507
- const current = JSON.parse(readFileSync(filePath, 'utf8'));
508
- const merged = mergeGeneratedStructure(current, desired, previousGenerated, relativePath, trustPreviousGenerated);
509
- writeFile(filePath, JSON.stringify(merged, null, 2) + '\n');
510
- }
511
- function writeRootEnv(root, options) {
512
- const corsOrigins = [
513
- options.apps.web ? 'http://localhost:3000' : null,
514
- options.apps.mobile ? 'http://localhost:8081' : null,
515
- options.apps.desktop ? 'http://127.0.0.1:5173' : null,
516
- options.apps.desktop ? 'null' : null,
517
- ].filter((value) => value !== null);
518
- const lines = composeRootEnvironment(collectModuleContributions(options.modules), { corsOrigins });
519
- const filePath = path.join(root, '.env.example');
520
- const current = pathEntryExists(filePath) ? readFileSync(filePath, 'utf8') : '';
521
- const existingKeys = new Set([...current.matchAll(/^([A-Z][A-Z0-9_]*)=/gm)].map((match) => match[1]));
522
- const additions = lines.filter((line) => !existingKeys.has(line.slice(0, line.indexOf('='))));
523
- const separator = current && additions.length ? (current.endsWith('\n') ? '\n' : '\n\n') : '';
524
- writeFile(filePath, `${current}${separator}${additions.join('\n')}${additions.length ? '\n' : ''}`);
525
- }
526
- function desiredTurboConfig() {
527
- return {
528
- $schema: 'https://turborepo.dev/schema.json',
529
- tasks: {
530
- build: {
531
- dependsOn: ['^build'],
532
- outputs: ['.next/**', '!.next/cache/**', '.output/**', 'dist/**'],
533
- },
534
- typecheck: { dependsOn: ['^build'] },
535
- dev: { cache: false, persistent: true },
536
- },
537
- };
538
- }
539
- function desiredVercelConfig(options) {
540
- const services = {};
541
- if (options.apps.api) {
542
- services.api = { root: 'apps/api' };
543
- }
544
- if (options.apps.web) {
545
- services.web = { root: 'apps/web', framework: 'nextjs' };
546
- }
547
- const rewrites = [
548
- options.apps.api ? { source: '/api/(.*)', destination: { service: 'api' } } : null,
549
- options.apps.web ? { source: '/(.*)', destination: { service: 'web' } } : null,
550
- ].filter((rewrite) => rewrite !== null);
551
- const crons = composeVercelCrons(collectModuleContributions(options.modules));
552
- return {
553
- $schema: 'https://openapi.vercel.sh/vercel.json',
554
- ...(Object.keys(services).length > 0 ? { services } : {}),
555
- ...(rewrites.length > 0 ? { rewrites } : {}),
556
- ...(crons.length > 0 ? { crons } : {}),
557
- };
558
- }
559
- function generatedCi(options) {
560
- const nodeVersion = options.apps.mobile ? '22.13.0' : '20.19.0';
561
- const commands = [
562
- 'pnpm typecheck',
563
- options.apps.api ? 'pnpm --filter ./apps/api test:coverage' : null,
564
- 'pnpm build',
565
- ].filter((value) => value !== null).join('\n ');
566
- const databaseSteps = options.features.database ? `
567
- - name: Verify committed database migration history
568
- run: pnpm verify:db
569
- - name: Verify database schema and migration parity
570
- run: |
571
- pnpm db:generate
572
- git diff --exit-code -- packages/db/migrations
573
- if [[ -n "$(git status --porcelain --untracked-files=all -- packages/db/migrations)" ]]; then
574
- echo "drizzle-kit generated uncommitted migration artifacts:"
575
- git status --short --untracked-files=all -- packages/db/migrations
576
- exit 1
577
- fi
578
- ` : '';
579
- return `name: Anhedral CI
580
-
581
- on:
582
- pull_request:
583
- push:
584
- branches: [main]
585
-
586
- permissions:
587
- contents: read
588
-
589
- concurrency:
590
- group: anhedral-ci-\${{ github.ref }}
591
- cancel-in-progress: true
592
-
593
- jobs:
594
- verify:
595
- runs-on: ubuntu-latest
596
- timeout-minutes: 30
597
- steps:
598
- - uses: ${ACTIONS.checkout} # v6
599
- with:
600
- persist-credentials: false
601
- - uses: ${ACTIONS.pnpm} # v6
602
- with:
603
- version: ${PACKAGE_MANAGER.replace('pnpm@', '')}
604
- - uses: ${ACTIONS.node} # v6
605
- with:
606
- node-version: ${nodeVersion}
607
- cache: pnpm
608
- - run: pnpm install --frozen-lockfile
609
- ${databaseSteps} - name: Verify generated workspace
610
- run: |
611
- ${commands}
612
- `;
613
- }
614
- function writeDatabaseVerificationScript(root, options) {
615
- if (!options.features.database)
616
- return;
617
- writeFile(path.join(root, 'scripts/verify-db-migrations.mjs'), `import { readdirSync } from 'node:fs';
618
- import path from 'node:path';
619
- import { spawnSync } from 'node:child_process';
620
-
621
- const projectRoot = process.cwd();
622
- const migrationsRoot = path.join(projectRoot, 'packages/db/migrations');
623
-
624
- function collectSqlFiles(directory, relativeDirectory = '') {
625
- const files = [];
626
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
627
- const relativePath = path.posix.join(relativeDirectory, entry.name);
628
- if (entry.isDirectory()) files.push(...collectSqlFiles(path.join(directory, entry.name), relativePath));
629
- else if (entry.isFile() && entry.name.endsWith('.sql')) files.push(path.posix.join('packages/db/migrations', relativePath));
630
- }
631
- return files.sort();
632
- }
633
-
634
- const sqlFiles = collectSqlFiles(migrationsRoot);
635
- if (sqlFiles.length === 0) {
636
- throw new Error('No database migration SQL is committed. Run \`pnpm db:generate\`, review packages/db/migrations, and commit the generated migration before verification.');
637
- }
638
-
639
- const gitRoot = spawnSync('git', ['rev-parse', '--show-toplevel'], {
640
- cwd: projectRoot,
641
- encoding: 'utf8',
642
- stdio: ['ignore', 'pipe', 'ignore'],
643
- });
644
-
645
- if (gitRoot.status === 0) {
646
- const repositoryRoot = String(gitRoot.stdout).trim();
647
- const tracked = spawnSync('git', ['ls-files', '--full-name', '-z', '--', 'packages/db/migrations'], {
648
- cwd: projectRoot,
649
- encoding: 'utf8',
650
- stdio: ['ignore', 'pipe', 'pipe'],
651
- });
652
- if (tracked.status !== 0) {
653
- throw new Error('Unable to inspect committed database migrations: ' + String(tracked.stderr).trim());
654
- }
655
- const trackedFiles = new Set(String(tracked.stdout)
656
- .split('\\0')
657
- .filter(Boolean)
658
- .map((entry) => path.resolve(repositoryRoot, entry)));
659
- const untrackedSql = sqlFiles.filter((entry) => !trackedFiles.has(path.resolve(projectRoot, entry)));
660
- if (untrackedSql.length > 0) {
661
- throw new Error('Database migration SQL must be tracked by Git before verification: ' + untrackedSql.join(', '));
662
- }
663
- } else if (process.env.CI) {
664
- throw new Error('CI must run database migration verification inside a Git worktree.');
665
- }
666
-
667
- console.log('Database migration baseline is present' + (gitRoot.status === 0 ? ' and tracked by Git.' : '.'));
668
- `);
669
- }
670
- function isRecordedFileUnmodified(root, manifest, relativePath) {
671
- if (!manifest)
672
- return true;
673
- const record = manifest.files[relativePath];
674
- if (!record?.hash)
675
- return false;
676
- const filePath = path.join(root, relativePath);
677
- return pathEntryExists(filePath) && hashContent(readFileSync(filePath)) === record.hash;
678
- }
679
- function writeRootFiles(root, options, mode, currentRoot, manifest) {
680
- const packageUnmodified = isRecordedFileUnmodified(currentRoot, manifest, 'package.json');
681
- const workspaceUnmodified = manifest !== undefined
682
- && isRecordedFileUnmodified(currentRoot, manifest, 'pnpm-workspace.yaml');
683
- const previousOptions = manifest
684
- ? { ...options, ...selectionsFromModules(manifest.modules), modules: [...manifest.modules] }
685
- : undefined;
686
- const previousPackage = previousOptions ? desiredRootPackage(previousOptions) : undefined;
687
- writeRootPackage(root, options, mode, packageUnmodified, previousPackage);
688
- const workspacePackages = [
689
- Object.values(options.apps).some(Boolean) ? 'apps/*' : null,
690
- options.apps.api || options.features.database ? 'packages/*' : null,
691
- ].filter((value) => value !== null);
692
- mergeWorkspaceFile(root, workspacePackages, desiredWorkspacePolicy(), workspaceUnmodified);
693
- mergeJsonConfig(root, 'turbo.json', desiredTurboConfig(), desiredTurboConfig(), true);
694
- mergeJsonConfig(root, 'vercel.json', desiredVercelConfig(options), previousOptions ? desiredVercelConfig(previousOptions) : {}, true);
695
- appendGitignore(root, [
696
- 'node_modules',
697
- '.turbo',
698
- '.next',
699
- '.output',
700
- '.wxt',
701
- '.expo',
702
- 'coverage',
703
- 'dist',
704
- 'release',
705
- '.env',
706
- '.env.*',
707
- '!.env.example',
708
- '*.tsbuildinfo',
709
- options.features.electronUpdater ? 'electron-builder.env' : null,
710
- ].filter((value) => value !== null));
711
- writeRootEnv(root, options);
712
- writeDatabaseVerificationScript(root, options);
713
- const vercelIgnore = path.join(root, '.vercelignore');
714
- const currentIgnore = pathEntryExists(vercelIgnore) ? readFileSync(vercelIgnore, 'utf8') : '';
715
- const ignoreLines = [...new Set([
716
- ...currentIgnore.split('\n').filter(Boolean),
717
- 'apps/extension/.output',
718
- 'apps/mobile/dist',
719
- 'apps/desktop/release',
720
- 'apps/assets-private-proxy',
721
- 'apps/desktop-updater-worker',
722
- ])];
723
- writeFile(vercelIgnore, ignoreLines.join('\n') + '\n');
724
- writeFile(path.join(root, '.github/workflows/anhedral-ci.yml'), generatedCi(options));
725
- }
726
- function enabledModuleNames(options) {
727
- return resolveModules(options.modules).resolvedModules;
728
- }
729
- function writeProjectDocs(root, options, includeUserDocs) {
730
- const modules = enabledModuleNames(options);
731
- const storageBucketName = r2BucketName(options.projectName);
732
- const environmentSetupCommands = [
733
- 'pnpm install',
734
- options.apps.api ? 'cp apps/api/.env.example apps/api/.env' : null,
735
- options.features.database ? 'cp packages/db/.env.example packages/db/.env' : null,
736
- options.apps.web ? 'cp apps/web/.env.example apps/web/.env.local' : null,
737
- options.apps.mobile ? 'cp apps/mobile/.env.example apps/mobile/.env' : null,
738
- options.apps.desktop ? 'cp apps/desktop/.env.example apps/desktop/.env' : null,
739
- options.features.electronUpdater ? 'cp apps/desktop/electron-builder.env.example apps/desktop/electron-builder.env' : null,
740
- options.apps.extension ? 'cp apps/extension/.env.example apps/extension/.env' : null,
741
- ].filter((value) => value !== null).join('\n');
742
- const firstVerificationCommands = [
743
- options.features.database ? 'pnpm db:generate' : null,
744
- options.features.database ? 'git add packages/db/migrations' : null,
745
- 'pnpm verify',
746
- options.features.database ? 'pnpm db:migrate' : null,
747
- ].filter((value) => value !== null).join('\n');
748
- const deploymentRows = [
749
- options.apps.web || options.apps.api ? '| Web/API | Vercel Git integration | Import this repository once; branch pushes create previews and the production branch deploys automatically. |' : null,
750
- options.apps.mobile ? '| Mobile | EAS Build + App Store Connect + Google Play Console | EAS creates signed binaries; Apple TestFlight/App Review and Google testing tracks/store review control release. |' : null,
751
- options.features.database ? '| Database | Neon | Provision the project, set `DATABASE_URL`, review/apply Drizzle migrations, and use separate branches or projects for preview and production. |' : null,
752
- options.features.storage ? '| Object storage | Private Cloudflare R2 + `assets-private-proxy` Worker | Authenticated uploads use presigned R2 URLs; the Worker streams known-key GET/HEAD downloads through `assets.<domain>` while direct bucket access stays disabled. |' : null,
753
- options.features.electronUpdater ? '| Desktop updates | Private Cloudflare R2 + `desktop-updater` Worker | Signed native artifacts are uploaded to a private bucket; a custom-domain Worker supplies metadata, ranges, and downloads to `electron-updater`. |' : null,
754
- options.apps.extension ? '| Chrome extension | Chrome Web Store | Build the production ZIP, test it as an unpublished/trusted-tester item, complete privacy disclosures, and submit it for review. |' : null,
755
- options.apps.desktop ? `| Desktop | electron-builder artifacts${options.features.electronUpdater ? ' + automatic update channel' : ''} | Build and sign on each target OS, then publish through the release channel chosen for the product. |` : null,
756
- ].filter((value) => value !== null).join('\n');
757
- const deploymentCommands = [
758
- options.apps.web || options.apps.api ? 'pnpm deploy:vercel:link' : null,
759
- options.apps.web || options.apps.api ? 'pnpm deploy:vercel:preview' : null,
760
- options.apps.web || options.apps.api ? 'pnpm deploy:vercel:production' : null,
761
- options.apps.mobile ? 'pnpm mobile:eas:login' : null,
762
- options.apps.mobile ? 'pnpm mobile:build:internal:ios' : null,
763
- options.apps.mobile ? 'pnpm mobile:build:internal:android' : null,
764
- options.features.database ? `pnpm neon:project:create -- --name ${options.projectName}` : null,
765
- options.features.storage ? 'pnpm r2:bucket:create' : null,
766
- options.features.storage ? 'pnpm assets:proxy:check' : null,
767
- options.features.storage ? 'pnpm assets:proxy:deploy' : null,
768
- options.features.electronUpdater ? 'pnpm desktop:updates:cloudflare:login' : null,
769
- options.features.electronUpdater ? 'pnpm desktop:updates:first-provision' : null,
770
- options.features.electronUpdater ? 'pnpm desktop:updates:build:mac' : null,
771
- options.features.electronUpdater ? 'pnpm desktop:updates:publish -- --platform mac --arch arm64' : null,
772
- options.apps.extension ? 'pnpm extension:zip' : null,
773
- ].filter((value) => value !== null).join('\n');
774
- const sourceRows = [
775
- options.apps.web ? '| Web frontend | `apps/web/app/`, `apps/web/components/`, `apps/web/lib/` | Next.js App Router pages, layouts, components, and web utilities. |' : null,
776
- options.apps.mobile ? '| Mobile frontend | `apps/mobile/app/`, `apps/mobile/components/` | Expo Router screens, layouts, and native UI. |' : null,
777
- options.apps.api ? '| Backend API | `apps/api/src/routes/app.ts`, `apps/api/src/<feature>.ts` | User-owned Fastify routes and server-only product modules; Anhedral keeps provider routes in managed wiring. |' : null,
778
- options.apps.desktop ? '| Desktop app | `apps/desktop/src/renderer/`, `apps/desktop/src/main/` | React UI and privileged Electron main-process code. |' : null,
779
- options.features.electronUpdater ? '| Desktop update edge | `apps/desktop-updater-worker/`, `apps/desktop/scripts/publish-updates.mjs` | Private R2 delivery Worker, custom domain, and ordered release publisher. |' : null,
780
- options.apps.extension ? '| Browser extension | `apps/extension/src/entrypoints/`, `apps/extension/src/components/` | WXT entrypoints and extension UI. |' : null,
781
- options.apps.api ? '| Shared API contracts | `packages/contracts/src/app.ts` | User-owned Zod request and response schemas exported beside managed provider contracts. |' : null,
782
- options.apps.api ? '| Typed API client | `packages/api-client/src/app.ts` | User-owned client-safe methods exported beside the managed fetch client. |' : null,
783
- options.features.database ? '| Database | `packages/db/src/app-schema.ts`, `packages/db/migrations/` | User-owned Drizzle tables plus reviewed SQL migrations; provider tables remain generated. |' : null,
784
- ].filter((value) => value !== null).join('\n');
785
- const moduleCommands = [
786
- options.apps.web ? '- Web: `pnpm dev:web`' : null,
787
- options.apps.mobile ? '- Mobile: `pnpm dev:mobile`' : null,
788
- options.apps.api ? '- API: `pnpm dev:api`' : null,
789
- options.apps.desktop ? '- Desktop: `pnpm dev:desktop`' : null,
790
- options.apps.extension ? '- Extension: `pnpm dev:extension`' : null,
791
- ].filter((value) => value !== null).join('\n');
792
- const toolRows = [
793
- options.apps.web ? '| Next.js | Web routes and rendering | `apps/web` | https://nextjs.org/docs/app/getting-started |' : null,
794
- options.apps.mobile ? '| Expo Router | iOS and Android app | `apps/mobile` | https://docs.expo.dev/router/introduction/ |' : null,
795
- options.apps.api ? '| Fastify | HTTP API | `apps/api` | https://fastify.dev/docs/latest/ |' : null,
796
- options.features.database ? '| Neon | Managed Postgres; no local Postgres | `DATABASE_URL` | https://neon.com/docs/introduction |' : null,
797
- options.features.database ? '| Drizzle | SQL schema, queries, migrations | `packages/db` | https://orm.drizzle.team/docs/get-started |' : null,
798
- options.features.auth ? '| Clerk | Identity and sessions | generated auth files | https://clerk.com/docs/getting-started/quickstart/overview |' : null,
799
- options.features.storage ? '| Cloudflare R2 | Private object storage | upload API and `apps/assets-private-proxy` | https://developers.cloudflare.com/r2/ |' : null,
800
- options.features.billing ? '| RevenueCat | Subscription authority | API and native client | https://www.revenuecat.com/docs |' : null,
801
- options.features.billing ? '| Ably | Realtime invalidation | `packages/realtime` | https://ably.com/docs |' : null,
802
- options.apps.desktop ? '| Electron | Desktop runtime | `apps/desktop` | https://www.electronjs.org/docs/latest/ |' : null,
803
- options.features.electronUpdater ? '| electron-updater | Packaged-app update checks and installation | `apps/desktop/src/main/main.ts` | https://www.electron.build/auto-update.html |' : null,
804
- options.features.electronUpdater ? '| Cloudflare Workers + R2 | Private update storage and custom-domain delivery | `apps/desktop-updater-worker` | https://developers.cloudflare.com/r2/api/workers/workers-api-usage/ |' : null,
805
- options.apps.extension ? '| WXT | Browser extension tooling | `apps/extension` | https://wxt.dev/guide/installation.html |' : null,
806
- options.apps.web || options.apps.desktop || options.apps.extension ? '| shadcn/ui | Source-owned DOM UI | each DOM app\'s `components/ui` | https://ui.shadcn.com/docs |' : null,
807
- '| Turborepo | Workspace tasks | root `turbo.json` | https://turborepo.com/docs |',
808
- ].filter((value) => value !== null).join('\n');
809
- const developmentSteps = [
810
- options.apps.api ? 'Define shared Zod schemas in user-owned `packages/contracts/src/app.ts` so the network boundary has one definition.' : null,
811
- options.features.database ? 'Define persistent product state in user-owned `packages/db/src/app-schema.ts`. Run `pnpm db:generate`, review the SQL, and commit it. This project uses managed Neon—do not add a local Postgres container.' : null,
812
- options.apps.api ? 'Add server-only behavior in a focused `apps/api/src/<feature>.ts` module and register its validated HTTP boundary in user-owned `apps/api/src/routes/app.ts`.' : null,
813
- options.apps.api ? 'Expose client-safe methods from user-owned `packages/api-client/src/app.ts`; never import API implementation files into a frontend.' : null,
814
- options.apps.web ? 'Add web routes in `apps/web/app/<route>/page.tsx` and reusable UI in `apps/web/components/`. Use a client component only for browser state, events, or hooks.' : null,
815
- options.apps.mobile ? 'Add mobile routes in `apps/mobile/app/` and reusable native UI in `apps/mobile/components/`. Keep platform-only APIs in platform-specific modules.' : null,
816
- 'Test the smallest affected package first, then run `pnpm verify`.',
817
- ].filter((value) => value !== null).map((value, index) => `${index + 1}. ${value}`).join('\n');
818
- const commonTaskSections = [
819
- options.apps.web ? `### Add a web page
820
-
821
- Create \`apps/web/app/<route>/page.tsx\`. Follow Next.js App Router conventions directly. Put reusable components under \`apps/web/components/<feature>/\` and web-only helpers under \`apps/web/lib/\`.` : null,
822
- options.apps.api ? `### Add an API endpoint
823
-
824
- Define its Zod contract in \`packages/contracts/src/app.ts\`, implement server-only behavior in \`apps/api/src/<feature>.ts\`, and register the Fastify route in \`apps/api/src/routes/app.ts\`. Authenticate on the server and derive the user ID from the verified session.` : null,
825
- options.features.database ? `### Change the database
826
-
827
- Edit \`packages/db/src/app-schema.ts\`, then run:
828
-
829
- \`\`\`sh
830
- pnpm db:generate
831
- pnpm verify:db
832
- pnpm db:migrate
833
- \`\`\`
834
-
835
- Review generated SQL before applying it. \`DATABASE_URL\` points to a managed Neon branch or project; there is intentionally no local Postgres service.` : null,
836
- options.features.auth ? `### Use authentication
837
-
838
- Frontend applications use their generated Clerk provider and hooks. The API verifies Clerk sessions. Public keys may use a framework public environment prefix; \`CLERK_SECRET_KEY\` remains in the API environment only.` : null,
839
- options.features.storage ? `### Upload a file
840
-
841
- Use \`@shared/api-client\`. The API authorizes the user and creates a short-lived signed R2 upload; the client uploads directly and confirms through the API. Never put R2 credentials in a client or make the bucket public.` : null,
842
- ].filter((value) => value !== null).join('\n\n');
843
- const verticalSliceExample = options.apps.api && options.features.database ? `## Copy-paste example: a projects feature
844
-
845
- These files are user-owned extension seams. Anhedral preserves them during \`add\`, \`ui add\`, and \`upgrade\`.
846
-
847
- \`packages/contracts/src/app.ts\`:
848
-
849
- \`\`\`ts
850
- import { z } from 'zod';
851
-
852
- export const ProjectSchema = z.object({ id: z.string(), name: z.string() });
853
- export const ProjectListSchema = z.array(ProjectSchema);
854
- \`\`\`
855
-
856
- \`packages/db/src/app-schema.ts\`:
857
-
858
- \`\`\`ts
859
- import { pgTable, text } from 'drizzle-orm/pg-core';
860
-
861
- export const projects = pgTable('projects', {
862
- id: text('id').primaryKey(),
863
- name: text('name').notNull(),
864
- });
865
- \`\`\`
866
-
867
- \`apps/api/src/routes/app.ts\`:
868
-
869
- \`\`\`ts
870
- import type { FastifyPluginAsync } from 'fastify';
871
- import { ProjectListSchema } from '@shared/contracts';
872
- import { db } from '@shared/db';
873
- import { projects } from '@shared/db/schema';
874
-
875
- export const appRoutes: FastifyPluginAsync = async (app) => {
876
- app.get('/projects', async () => ProjectListSchema.parse(await db.select().from(projects)));
877
- };
878
- \`\`\`
879
-
880
- ${options.apps.web || options.apps.mobile || options.apps.desktop || options.apps.extension ? `\`packages/api-client/src/app.ts\`:
881
-
882
- \`\`\`ts
883
- import { ProjectListSchema } from '@shared/contracts';
884
- import { ApiClient } from './generated';
885
-
886
- export function listProjects(client: ApiClient) {
887
- return client.request('/projects', { method: 'GET' }, ProjectListSchema);
888
- }
889
- \`\`\`
890
-
891
- Import \`listProjects\` and the generated client factory in the frontend surface you are building.` : ''}
892
-
893
- Then run \`pnpm db:generate\`, review and commit the migration, run \`pnpm verify\`, apply it to the intended Neon branch with \`pnpm db:migrate\`, and start the relevant app surfaces.` : '';
894
- const dependencyLines = [
895
- options.apps.api ? 'frontend apps -> @shared/api-client -> HTTP -> apps/api' : null,
896
- options.apps.api ? 'frontend apps -> @shared/contracts <- apps/api' : null,
897
- options.apps.api && options.features.database ? 'apps/api -> @shared/db -> managed Neon Postgres' : null,
898
- options.features.electronUpdater ? 'apps/desktop -> updates.<domain> Worker -> private R2 bucket' : null,
899
- ].filter((value) => value !== null).join('\n');
900
- const uiTaskSection = Object.values(options.apps).some(Boolean) && (options.apps.web || options.apps.mobile || options.apps.desktop || options.apps.extension)
901
- ? `### Add UI primitives
902
-
903
- \`\`\`sh
904
- anhedral ui add dialog
905
- ${options.apps.web ? 'anhedral ui add data-table --target web\n' : ''}\`\`\`
906
-
907
- DOM apps receive source-owned shadcn/ui files. Mobile receives React Native Reusables files. Customize those files normally.`
908
- : '';
909
- if (includeUserDocs) {
910
- writeFile(path.join(root, 'README.md'), `# ${markdownHeading(options.displayName)}
911
-
912
- This is a complete, readable TypeScript product stack generated by Anhedral ${GENERATOR_VERSION}. Anhedral assembled and connected the tools; application code remains normal framework code.
913
-
914
- ## Start here
915
-
916
- Anhedral installs workspace dependencies during generation unless you used \`--skip-install\`. On a fresh clone, install them and copy the selected environment examples:
917
-
918
- \`\`\`sh
919
- ${environmentSetupCommands}
920
- \`\`\`
921
-
922
- Stop here and replace every required placeholder in those uncommitted files. In particular, \`DATABASE_URL\` must be the pooled connection string for the intended managed Neon branch when the database module is selected. Then generate the initial migration and verify the workspace:
923
-
924
- \`\`\`sh
925
- ${firstVerificationCommands}
926
- \`\`\`
927
-
928
- After verification succeeds, run \`pnpm dev\`. In a full stack this starts the primary web + API development loop, so opening the project does not also launch Expo, Electron, and WXT. Use \`pnpm dev:all\` when you intentionally want every selected surface, or run one surface:
929
-
930
- ${moduleCommands}
931
-
932
- There is no hidden Anhedral application runtime. Open the framework directory you want and write ordinary TypeScript there.
933
-
934
- ## Where to write code
935
-
936
- | Concern | Location | What belongs there |
937
- | --- | --- | --- |
938
- ${sourceRows}
939
-
940
- ${options.apps.api ? 'For an end-to-end feature, define shared contracts first, implement server and persistence behavior, expose it through the typed client, then build each frontend.' : 'Build product features directly inside each selected application using its native framework conventions.'} Read [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) for concrete recipes and [docs/STACK.md](docs/STACK.md) for every selected tool and its official documentation.
941
-
942
- ## Selected modules
943
-
944
- ${modules.map((moduleName) => `- \`${moduleName}\``).join('\n')}
945
-
946
- ## UI and customization
947
-
948
- DOM clients use source-owned shadcn/ui. Expo uses React Native Reusables with ${options.nativeStyling}. Add components with \`anhedral ui add <component>\`; use \`--target\` when a component belongs to one client. Customize the resulting source normally.
949
-
950
- ## Environment and first verification
951
-
952
- The setup blocks above are the first-run checklist. Provider secrets stay in their package-local environment files; none belong in client code. This project uses managed Neon and intentionally does not generate or start local Postgres.
953
-
954
- ## Deployment
955
-
956
- Only selected surfaces and providers contribute deployment scripts. Exact-version deployment CLIs run on demand instead of inflating the application lockfile.
957
-
958
- | Selection | Delivery target | Strategy |
959
- | --- | --- | --- |
960
- ${deploymentRows}
961
-
962
- \`\`\`sh
963
- ${deploymentCommands}
964
- \`\`\`
965
-
966
- Read \`PRODUCTION.md\` before creating accounts or production resources. Generated ownership and tool versions are recorded in \`anhedral.json\`. Run \`anhedral doctor\` before structural changes and preview them with \`--dry-run\`.
967
- `);
968
- }
969
- writeFile(path.join(root, 'docs/DEVELOPMENT.md'), `# Developing ${markdownHeading(options.displayName)}
970
-
971
- Anhedral generated this stack; it does not replace the frameworks inside it. Use official framework APIs and keep product logic in ordinary source files.
972
-
973
- ## End-to-end feature loop
974
-
975
- ${developmentSteps}
976
-
977
- ${verticalSliceExample}
978
-
979
- ## Common tasks
980
-
981
- ${commonTaskSections}
982
-
983
- ${uiTaskSection}
984
-
985
- ### Add another app surface
986
-
987
- \`\`\`sh
988
- anhedral add mobile --dry-run
989
- anhedral add mobile
990
- \`\`\`
991
-
992
- Anhedral refuses ownership conflicts instead of overwriting product changes. Run \`anhedral doctor\` when an add cannot proceed.
993
-
994
- ## Verification
995
-
996
- - While iterating, run the affected package's typecheck or tests.
997
- - Before handoff, run \`pnpm verify\`.
998
- - Before generation, run \`anhedral doctor\` and use \`--dry-run\`.
999
- - For schema changes, commit reviewed migration SQL and run \`pnpm verify:db\`.
1000
- `);
1001
- writeFile(path.join(root, 'docs/STACK.md'), `# Stack guide
1002
-
1003
- This maps generated source to upstream documentation. Anhedral owns initial integration and safe incremental generation. Each framework owns its runtime and programming model.
1004
-
1005
- | Tool | Responsibility | Generated location | Official documentation |
1006
- | --- | --- | --- | --- |
1007
- ${toolRows}
1008
-
1009
- ## Dependency direction
1010
-
1011
- \`\`\`text
1012
- ${dependencyLines || 'selected applications are independent framework projects'}
1013
- \`\`\`
1014
-
1015
- Clients may import contracts and the API client. They must not import API services, database connections, or server environment modules. Provider secrets terminate at the API or provider-specific Worker.
1016
-
1017
- \`anhedral add\` adds modules and integration files. \`anhedral ui add\` adds source-owned UI. \`anhedral doctor\` checks recorded ownership. Product features, models, pages, routes, and services remain developer-owned TypeScript.
1018
- `);
1019
- if (includeUserDocs) {
1020
- const productionItems = [
1021
- options.apps.api ? '- Keep `ANHEDRAL_DEMO=false` in production.' : null,
1022
- options.apps.api ? '- Set `TRUST_PROXY_HOPS` only to the number of trusted reverse-proxy hops.' : null,
1023
- options.apps.api ? '- Store server secrets only in the API deployment environment.' : null,
1024
- options.apps.api || options.apps.web ? '- Select the Vercel Services framework preset and deploy from the repository root.' : null,
1025
- options.apps.api && options.apps.web ? '- Keep the top-level `/api/(.*)` service rewrite before the web catch-all rewrite.' : null,
1026
- options.apps.api && options.apps.web ? '- The web client defaults to same-origin `/api` in production; override `NEXT_PUBLIC_API_URL` only when the API uses another origin.' : null,
1027
- options.features.storage ? '- Set a strong `CRON_SECRET` and verify Vercel invokes `/api/internal/storage/cleanup` on schedule.' : null,
1028
- options.features.billing ? '- Configure `ABLY_API_KEY`, set a strong `CRON_SECRET`, and verify Vercel invokes `/api/internal/realtime/flush` every five minutes to retry the transactional outbox.' : null,
1029
- options.features.billing ? '- Use a dedicated RevenueCat secret REST API key with customer-read access; keep it server-only and rotate it independently from the 32+ character webhook authorization secret.' : null,
1030
- options.features.storage ? '- List the live R2 CORS policy, merge every exact browser origin into `cloudflare/r2-cors.template.json`, then apply the complete replacement policy and verify preflight plus signed PUT.' : null,
1031
- options.features.storage ? '- Configure an R2 lifecycle rule for the `storage/staging/` prefix as a backstop, with an age longer than the application cleanup grace period.' : null,
1032
- options.features.database ? '- Commit every reviewed Drizzle SQL migration and its metadata with the schema change; `pnpm verify:db` rejects a missing or untracked SQL baseline and validates migration history.' : null,
1033
- options.features.database ? '- Generated CI runs `pnpm db:generate` and fails when `packages/db/migrations` changes, preventing schema changes without a matching migration.' : null,
1034
- '- Run `pnpm verify` before deployment.',
1035
- '- Run `anhedral doctor` before incremental generation.',
1036
- ].filter((item) => item !== null);
1037
- const productionSections = [
1038
- options.apps.web || options.apps.api || options.features.storage ? `## Domain registration and Cloudflare control plane
1039
-
1040
- Registration and DNS hosting are separate jobs. You can buy the domain at GoDaddy while Cloudflare becomes authoritative DNS immediately; transferring the registrar later is optional.
1041
-
1042
- 1. Buy the domain at GoDaddy under an organization-controlled account. Enable auto-renewal, MFA, accurate registrant contact details, and record renewal ownership.
1043
- 2. Add the domain as a website/zone in Cloudflare. Before changing nameservers, copy every existing DNS record—especially MX, TXT, DKIM, SPF, DMARC, verification, and subdomain records—and disable DNSSEC/DS records at GoDaddy if enabled.
1044
- 3. Cloudflare assigns two authoritative nameservers. Replace the GoDaddy nameservers with those exact values, then wait until Cloudflare marks the zone **Active**. Recreate and verify mail and other records before considering the migration complete. Re-enable DNSSEC in Cloudflare after activation.
1045
- 4. Optional registrar transfer: after the domain is eligible (commonly not within 60 days of registration, a prior transfer, or certain registrant changes), unlock it at GoDaddy, request its EPP/authorization code, and start **Transfer Domains** in Cloudflare. Approve the transfer and payment. DNS can remain live throughout because Cloudflare was already authoritative.
1046
- 5. Keep Cloudflare as the shared domain control plane: DNS and DNSSEC at the zone; Workers and R2 for the asset hostname; and optional Queues, Workflows, Durable Objects, WAF, Turnstile, or other compute/security products when the application actually needs them. Vercel remains the web/API runtime.
1047
-
1048
- Use organization-owned Cloudflare and GoDaddy accounts with MFA and least-privilege member roles. Do not confuse changing nameservers (DNS delegation) with transferring the registration (registrar/billing ownership). Follow the current [GoDaddy nameserver instructions](https://help.dc-aws.godaddy.com/help/edit-my-domain-nameservers-664), [GoDaddy transfer-away sequence](https://www.godaddy.com/en-ca/help/transfer-my-domain-away-from-godaddy-3560), [Cloudflare nameserver guidance](https://developers.cloudflare.com/dns/nameservers/update-nameservers/), and [Cloudflare registrar-transfer sequence](https://developers.cloudflare.com/registrar/get-started/transfer-domain-to-cloudflare/).` : null,
1049
- options.apps.web || options.apps.api ? `## Vercel: web and API
1050
-
1051
- 1. Push the repository to GitHub and import it in Vercel. Choose the **Services** framework preset and keep the repository root as the project root; \`vercel.json\` maps the selected \`apps/web\` and \`apps/api\` services.
1052
- 2. Add every required variable from the package-local \`.env.example\` files to Vercel's Development, Preview, and Production environments. Server secrets belong only to the API service. Never put a secret in a \`NEXT_PUBLIC_*\` variable.
1053
- 3. Run \`pnpm deploy:vercel:link\` for local CLI access. The normal release path is Git: every non-production branch/PR receives a preview deployment, and merging to the configured production branch creates production automatically. The explicit \`deploy:vercel:preview\` and \`deploy:vercel:production\` scripts are escape hatches for manual releases.
1054
- 4. Run \`pnpm deploy:vercel:inspect -- <deployment-url>\` when diagnosing a deployment. Verify health, authentication, scheduled jobs, and provider callbacks in Preview before merging.
1055
- 5. Add \`app.example.com\` in Vercel **Project → Settings → Domains** before changing DNS. Inspect it with \`pnpm deploy:vercel:domain:inspect -- app.example.com\`, then create the exact A/CNAME/TXT records Vercel reports in Cloudflare DNS. Leave the Vercel A/CNAME record **DNS only** (gray cloud), because placing Cloudflare's reverse proxy in front of Vercel hides traffic signals, adds another CDN hop, and can interfere with Vercel caching/firewall behavior. Ownership-verification TXT records are also DNS only. Vercel provisions TLS after validation.
1056
-
1057
- When web and API are both selected, keep the generated \`/api/(.*)\` route before the web catch-all. The browser uses same-origin \`/api\`; mobile, desktop, and extension builds need the absolute production API URL.` : null,
1058
- options.features.auth ? `## Clerk: production identity
1059
-
1060
- 1. Create the Clerk application for development, then create its separate **Production** instance. Copy \`pk_live_*\` and \`sk_live_*\` keys into the production environments; keep \`CLERK_SECRET_KEY\` server-only.
1061
- 2. Add the production root domain in Clerk and publish the DNS records shown on **Domains**. Configure a subdomain allowlist, production OAuth credentials, allowlisted redirect URLs, webhook URLs/signing secrets, and native application identifiers that apply to the selected clients.
1062
- 3. Use development keys locally and production keys only for production builds. Vercel Preview deployments should use a separate Clerk application/domain when stable preview auth is required; do not point previews at live user data.
1063
- 4. Redeploy every selected client after changing public Clerk keys. Test sign-in, sign-out, token refresh, deep links, and physical-device behavior before release.${options.apps.extension ? '\n5. For the extension, create a stable CRX ID, configure Clerk Chrome Extension deployment for that ID, and set `VITE_CLERK_FRONTEND_API_URL` plus `VITE_CLERK_SYNC_HOST` when using web-to-extension session sync. OAuth and email-link flows require Sync Host.' : ''}` : null,
1064
- options.features.database ? `## Neon and Drizzle: database
1065
-
1066
- 1. Create a Neon account, then run \`pnpm neon:login\` and \`pnpm neon:project:create -- --name ${options.projectName}\`, or create the project in the Neon console.
1067
- 2. Copy the pooled Postgres connection string to \`DATABASE_URL\` in \`packages/db/.env\` locally and the API's Vercel environment in production. Keep preview and production databases isolated with Neon branches or separate projects.
1068
- 3. Change the Drizzle schema, run \`pnpm db:generate\`, review and commit the SQL and metadata, then run \`pnpm verify:db\`.
1069
- 4. Apply \`pnpm db:migrate\` against the intended database as a controlled release step before sending production traffic to code that requires the new schema. Backward-compatible migrations make rollback safer; never run unreviewed migration generation during a Vercel build.
1070
- 5. Enable Neon backups/restore controls appropriate to the plan, restrict credentials, and rotate a leaked connection string immediately.` : null,
1071
- options.features.storage ? `## Cloudflare R2: private bucket and generated Worker
1072
-
1073
- 1. Run \`pnpm r2:login\` and \`pnpm r2:bucket:create\` to create \`${storageBucketName}\`, or create that bucket in **R2 → Overview**. Keep both the \`r2.dev\` development URL and R2 bucket custom-domain access disabled; the bucket itself remains private.
1074
- 2. Create an Object Read & Write S3 API token scoped to this bucket. Put \`BASE_URL\`, \`R2_ACCOUNT_ID\`, \`R2_ACCESS_KEY_ID\`, \`R2_SECRET_ACCESS_KEY\`, \`R2_BUCKET_NAME=${storageBucketName}\`, \`R2_PREFIX=storage\`, and \`R2_PROXY_READ_URL_TTL_SECONDS=600\` in the API deployment. The Worker uses the in-process \`ASSETS\` binding instead of these S3 credentials. Keep \`CLOUDFLARE_API_TOKEN\` operations/CI-only for Wrangler.
1075
- 3. Direct browser uploads continue to use short-lived presigned PUT URLs on \`<ACCOUNT_ID>.r2.cloudflarestorage.com\`. Presigned URLs do **not** work on custom domains. Run \`pnpm r2:cors:list\`, edit the user-owned \`cloudflare/r2-cors.template.json\`, then run \`pnpm r2:cors:set\`. The set command replaces the complete live policy, so retain every exact uploading origin.
1076
- 4. Open \`apps/assets-private-proxy/wrangler.jsonc\`. Replace both \`assets.example.com\` values with \`assets.yourdomain.com\`. The generated config names the Worker \`assets-private-proxy\`, disables \`workers.dev\` and preview URLs, binds \`${storageBucketName}\` as \`ASSETS\`, sets \`R2_PREFIX=storage\`, enables logs, and declares the hostname as a Worker Custom Domain.
1077
- 5. Run \`pnpm assets:proxy:check\`, then \`pnpm assets:proxy:deploy\`. Wrangler creates or updates the Worker, R2 binding, managed proxied DNS record, TLS certificate, and custom domain. The dashboard equivalent is **Workers & Pages → assets-private-proxy → Settings → Bindings** (R2, variable \`ASSETS\`, bucket \`${storageBucketName}\`) and **Domains & Routes → Add → Custom domain**.
1078
- 6. The Worker streams GET/HEAD bodies, preserves metadata/ranges/conditionals, caches complete public responses, rejects other methods and unexpected hosts, and never lists the bucket. It exposes only \`storage/confirmed/\` by unguessable key; \`storage/staging/\` and \`generation-inputs\` return 404. Authenticated private reads use \`GET /api/storage/uploads/:uploadId/read-url\`, which verifies ownership before returning a short-lived S3 URL.
1079
- 7. Add an R2 lifecycle rule for \`storage/staging/\` longer than the API cleanup grace period. Set a strong \`CRON_SECRET\` in Vercel and verify cleanup. Test missing keys, invalid encodings, GET, HEAD, range, conditional, cache HIT/MISS, forbidden methods, private-prefix rejection, authenticated read authorization, TTL bounds, and direct bucket inaccessibility.
1080
-
1081
- \`app.yourdomain.com\` is a Cloudflare DNS-only record targeting Vercel. \`assets.yourdomain.com\` is a Cloudflare-managed Worker Custom Domain and stays proxied. Never connect the asset hostname directly to R2, never CNAME it to \`r2.dev\`, and never expose S3 credentials in a client bundle.` : null,
1082
- options.apps.mobile ? `## Expo, TestFlight, and app stores
1083
-
1084
- Accounts required: an Expo/EAS account, an Apple Developer Program membership with App Store Connect access for iOS, and a Google Play Console developer account for Android. Create unique iOS bundle and Android package identifiers before the first store build.
1085
-
1086
- 1. Run \`pnpm mobile:eas:login\`, then \`pnpm mobile:eas:init\` from the repository root to create/link the EAS project. Review and commit the project ID/configuration that EAS adds.
1087
- 2. Put public build-time values in the matching EAS environment/profile; keep server secrets out of Expo. Configure Apple/Google credentials with EAS and test sign-in/deep links on physical devices.
1088
- 3. Internal EAS distribution: run \`pnpm mobile:build:internal:ios\` and/or \`pnpm mobile:build:internal:android\`. iOS ad hoc distribution requires registered device UDIDs; Android internal builds can be installed from the EAS share URL. These builds do not require a development server.
1089
- 4. TestFlight: run \`pnpm mobile:build:production:ios\`, then \`pnpm mobile:submit:ios\`. After App Store Connect processes the build, assign it to internal testers. External testers require TestFlight Beta App Review. TestFlight approval is not App Store production approval.
1090
- 5. Google Play: create the app/listing and required policy declarations in Play Console. Run \`pnpm mobile:build:production:android\`, then \`pnpm mobile:submit:android\`. Start with the internal testing track, promote through closed/open testing as appropriate, and only then roll out production. A brand-new Play app may require its first binary to be uploaded manually before API-based submissions work.
1091
- 6. Complete store metadata, screenshots, privacy/data-safety declarations, content ratings, export compliance, pricing/availability, review credentials, and release notes. Submit for store review and use staged/phased rollout where appropriate.` : null,
1092
- options.apps.extension ? `## Chrome Web Store
1093
-
1094
- 1. Register a Chrome Web Store developer account, verify its contact email, accept the agreement, and pay Google's one-time registration fee.
1095
- 2. Configure production extension environment values and a stable CRX public key/ID, then run \`pnpm verify:extension\` and \`pnpm extension:zip\`. Load the unpacked production build in Chrome first and test install, update, permissions, authentication, API calls, and sign-out.
1096
- 3. In the Developer Dashboard, create an item and upload the ZIP from \`apps/extension/.output\`. Complete the listing (description, icons, screenshots, category, regions) and keep the manifest version higher for every update.
1097
- 4. State one narrow purpose, justify every permission/host permission, disclose all handled data, certify limited use, and provide a public privacy-policy URL consistent with actual behavior. Clerk login counts as handling authentication data. Supply reviewer test instructions and credentials when features are gated.
1098
- 5. Publish first to trusted testers/unlisted visibility, verify the store-installed CRX ID matches Clerk and backend allowlists, then submit the production listing for review. Store review and rollout are separate from GitHub/Vercel deployment.` : null,
1099
- options.features.electronUpdater ? `## Electron desktop and automatic updates
1100
-
1101
- The generated update path is \`electron-updater -> updates.<domain> Worker -> private ${desktopUpdatesBucketName(options.projectName)} R2 bucket\`. The application never receives Cloudflare credentials, the Worker exposes reads only, and direct bucket access stays disabled.
1102
-
1103
- 1. In \`apps/desktop-updater-worker/wrangler.jsonc\`, replace both \`updates.example.com\` values with a hostname in an active Cloudflare zone. Run \`pnpm desktop:updates:cloudflare:login\`, then run \`pnpm desktop:updates:first-provision\` exactly once to create the private bucket and deploy the bound Worker, managed DNS record, TLS certificate, logs, and custom domain. For repeat deployments use \`pnpm desktop:updates:worker:deploy\`; bucket creation is intentionally not repeated. Keep the bucket's \`r2.dev\` URL and R2 bucket custom-domain access disabled.
1104
- 2. Copy \`apps/desktop/electron-builder.env.example\` to \`apps/desktop/electron-builder.env\` and set \`DESKTOP_UPDATE_BASE_URL\` to that exact HTTPS origin with no trailing slash. electron-builder writes the platform/architecture URL into the packaged app's update configuration; no update secret is embedded.
1105
- 3. Increase \`apps/desktop/package.json\`'s version for every release. Build on each target OS using \`pnpm desktop:updates:build:mac\`, \`pnpm desktop:updates:build:win\`, or \`pnpm desktop:updates:build:linux\`. Configure macOS signing/notarization and Windows code-signing credentials in CI, never in the repository.
1106
- 4. From the repository root, upload one architecture at a time, for example \`pnpm desktop:updates:publish -- --platform mac --arch arm64\`. The publisher accepts only known platform/architecture values, uploads immutable installers and blockmaps first, then uploads mutable \`latest*.yml\` metadata last. Run it only after signing succeeds.
1107
- 5. Install the previous signed version, publish a newer version, and verify update discovery, range downloads, signature validation, restart/install, rollback behavior, and logs on macOS, Windows, and the supported Linux package path. Test clean install, deep links, Clerk return flow, and OS security warnings too.
1108
-
1109
- The Worker accepts GET/HEAD only, validates the configured hostname and \`releases/\` prefix, supports conditionals and single-range downloads, serves metadata with \`no-store\`, and serves versioned artifacts as immutable. See \`cloudflare/desktop-updates.md\` for the generated resource contract.` : options.apps.desktop ? `## Electron desktop
1110
-
1111
- Builds are platform-specific: produce macOS, Windows, and Linux artifacts on their matching CI runners with the package's \`build:mac\`, \`build:win\`, and \`build:linux\` scripts. Configure signing/notarization credentials in CI, never in the repository. Test clean install, upgrade, deep links, Clerk return flow, auto-update strategy, and OS security warnings before publishing artifacts to the chosen release channel.` : null,
1112
- ].filter((section) => section !== null);
1113
- writeFile(path.join(root, 'PRODUCTION.md'), `# ${markdownHeading(options.displayName)} production guide
1114
-
1115
- This guide includes only the surfaces and providers selected when the project was generated. Provision separate Preview and Production resources, use least-privilege credentials, and keep account ownership with the organization rather than an individual developer.
1116
-
1117
- ## Release gate
1118
-
1119
- ${productionItems.join('\n')}
1120
-
1121
- ${productionSections.join('\n\n')}
1122
-
1123
- ## Final release order
1124
-
1125
- - Run \`pnpm verify\` and \`anhedral doctor\`; review the exact production diff.
1126
- ${options.features.database ? '- Apply reviewed, backward-compatible database migrations.' : ''}
1127
- ${options.apps.web || options.apps.api ? '- Deploy provider infrastructure and secrets, then deploy API/web.' : ''}
1128
- ${options.apps.mobile || options.apps.extension || options.apps.desktop ? '- Build immutable client artifacts only after production URLs and public keys are final.\n- Release to internal testers, verify telemetry and rollback, then promote through each store review/rollout.' : ''}
1129
- `);
1130
- }
1131
- writeFile(path.join(root, 'ANHEDRAL.md'), `# Anhedral-managed project information
1132
-
1133
- Generator: ${GENERATOR_VERSION}
1134
-
1135
- Resolved modules: ${modules.join(', ')}
1136
-
1137
- - \`anhedral add <module> --dry-run\` previews incremental changes.
1138
- - \`anhedral upgrade --dry-run\` previews a supported generator migration.
1139
- - \`anhedral ui add <component> --dry-run\` previews platform-routed component additions.
1140
- - \`anhedral doctor\` reports manifest and filesystem drift before incremental changes.
1141
- - README and existing user workflows are never rewritten by \`anhedral add\`.
1142
- `);
1143
- const surfaceGuidance = [
1144
- options.apps.web ? '- Web lives in `apps/web`: use Next.js App Router, server-first rendering, and shadcn/ui source components.' : null,
1145
- options.apps.mobile ? `- Mobile lives in \`apps/mobile\`: use Expo Router and React Native Reusables with ${options.nativeStyling}. Keep native-only APIs behind platform-safe modules.` : null,
1146
- options.apps.api ? '- HTTP and provider integration lives in `apps/api`: keep Fastify routes thin, validate boundaries, and put secrets only in server environment files.' : null,
1147
- options.apps.desktop ? '- Desktop lives in `apps/desktop`: keep Electron main/preload privileges minimal and application UI in the sandboxed React renderer.' : null,
1148
- options.features.electronUpdater ? '- Desktop update delivery lives in `apps/desktop-updater-worker`: keep the R2 bucket private, the Worker read-only, and the Worker Custom Domain aligned with `DESKTOP_UPDATE_BASE_URL`.' : null,
1149
- options.apps.extension ? '- Browser extension code lives in `apps/extension`: use WXT entrypoints and request only permissions required by the feature.' : null,
1150
- options.features.storage ? '- Private-bucket asset delivery lives in `apps/assets-private-proxy`: preserve the `ASSETS` R2 binding, streaming responses, method/host restrictions, and Cloudflare-managed custom domain.' : null,
1151
- ].filter((value) => value !== null).join('\n');
1152
- const featureGuidance = [
1153
- options.apps.api ? '- Reuse `@shared/contracts` at every network boundary and call the API through `@shared/api-client`; clients must not import server implementation modules.' : null,
1154
- options.features.database ? '- Neon/Drizzle state is authoritative. Change user-owned `packages/db/src/app-schema.ts`, generate SQL with `pnpm db:generate`, review it, and Git-track the migration.' : null,
1155
- options.features.auth ? '- Clerk owns identity and sessions. Never trust a client-supplied user ID; derive identity from verified server authentication.' : null,
1156
- options.features.billing ? '- RevenueCat events reconcile into Neon before Ably publishes an invalidation. Clients refetch entitlements instead of treating realtime payloads as authority.' : null,
1157
- options.features.storage ? '- R2 credentials and signed-upload policy stay in the API. The `assets-private-proxy` Worker uses its binding instead of S3 credentials and publicly serves GET/HEAD only by known unguessable key.' : null,
1158
- options.features.electronUpdater ? '- Electron releases use `electron-updater` through the generated private R2 + Worker channel. Build signed native artifacts first and publish mutable channel metadata last.' : null,
1159
- ].filter((value) => value !== null).join('\n');
1160
- const skillFeatureSteps = [
1161
- options.apps.api ? 'Define shared network schemas in user-owned `packages/contracts/src/app.ts`.' : null,
1162
- options.features.database ? 'Define persistent state in user-owned `packages/db/src/app-schema.ts`; generate, review, and commit Drizzle SQL. Use managed Neon, never a generated local Postgres service.' : null,
1163
- options.apps.api ? 'Put backend behavior in focused `apps/api/src/<feature>.ts` modules and register product routes in user-owned `apps/api/src/routes/app.ts`.' : null,
1164
- options.apps.api ? 'Add client-safe calls to user-owned `packages/api-client/src/app.ts`; frontends must not import server implementations.' : null,
1165
- options.apps.web ? 'Write web product code with normal Next.js App Router conventions in `apps/web`.' : null,
1166
- options.apps.mobile ? 'Write native product code with normal Expo Router conventions in `apps/mobile`.' : null,
1167
- 'Verify the affected package, then run the root verification before handoff.',
1168
- ].filter((value) => value !== null).map((value, index) => `${index + 1}. ${value}`).join('\n');
1169
- writeFile(path.join(root, 'SKILL.md'), `---
1170
- name: anhedral-project
1171
- description: Build and extend this Anhedral-generated ${modules.join(', ')} TypeScript application while preserving its framework, ownership, security, and verification conventions.
1172
- ---
1173
-
1174
- # Anhedral project
1175
-
1176
- Use this skill whenever you plan, implement, review, or diagnose work in this repository.
1177
-
1178
- ## Product model
1179
-
1180
- This is a standard TypeScript monorepo assembled by Anhedral, not an application running inside an Anhedral framework. Write normal Next.js, Expo Router, Fastify, Drizzle, Electron, or WXT code in the generated workspace. Use Anhedral only for structural operations such as adding a module, adding source-owned UI, and checking generated-file ownership.
1181
-
1182
- Before implementing a feature, read \`README.md\` for the source map, \`docs/DEVELOPMENT.md\` for task recipes, and \`docs/STACK.md\` when you need the selected tools' responsibility boundaries and official documentation.
1183
-
1184
- ## Start safely
1185
-
1186
- 1. Read \`anhedral.json\` for the selected modules, native styling provider, installed UI components, and file ownership.
1187
- 2. Run \`pnpm dlx anhedral@${GENERATOR_VERSION} doctor\` before generator operations. If it reports a supported older generator, preview and apply \`anhedral upgrade\` before continuing.
1188
- 3. Preview structural changes with \`anhedral upgrade --dry-run\`, \`anhedral add <module> --dry-run\`, or \`anhedral ui add <component> --dry-run\` as applicable.
1189
- 4. Never hand-edit \`anhedral.json\`, ownership hashes, or bundled-template provenance.
1190
-
1191
- Resolved modules: ${modules.map((moduleName) => `\`${moduleName}\``).join(', ')}.
1192
-
1193
- ## Repository boundaries
1194
-
1195
- ${surfaceGuidance}
1196
-
1197
- - Shared source belongs in focused packages under \`packages/\`; do not create a second workspace, lockfile, or nested dependency island.
1198
- ${featureGuidance}
1199
-
1200
- ## Feature workflow
1201
-
1202
- ${skillFeatureSteps}
1203
-
1204
- ## UI conventions
1205
-
1206
- - Add source-owned components with \`pnpm dlx anhedral@${GENERATOR_VERSION} ui add <component>\`; use \`--target\` only when the component should not exist in every selected client.
1207
- - Web, desktop, and extension components come from shadcn/ui. Mobile components come from React Native Reusables using ${options.nativeStyling}.
1208
- - Compose application-specific UI around installed primitives. Preserve accessibility, keyboard behavior, focus handling, and platform conventions.
1209
- - Use lowercase kebab-case filenames, PascalCase component exports, and \`use-\` prefixes for hooks.
1210
-
1211
- ## Ownership rules
1212
-
1213
- - \`README.md\`, \`PRODUCTION.md\`, product UI, and the backend \`app.ts\`/\`app-schema.ts\` extension seams are user-owned. Root JSON/YAML configuration is mergeable. Other recorded files are generator-managed unless \`anhedral.json\` says otherwise.
1214
- - Prefer new application files and narrow composition points over editing managed substrate files. If a managed file must change, understand that future \`anhedral add\` operations will stop until the project is reconciled.
1215
- - Never overwrite user changes, bypass a generator conflict, or replace a failed ownership check with fabricated hashes.
1216
-
1217
- ## Environment and security
1218
-
1219
- - The root \`.env.example\` is an inventory, not a runtime environment file. Copy package-local examples and keep real environment files uncommitted.
1220
- - Keep server secrets out of browser, Expo, Electron renderer, and extension bundles. Only variables with the framework's explicit public prefix may enter client code.
1221
- - Validate external input at the API boundary, use parameterized Drizzle queries, and keep privileged Electron functionality behind a narrow context-isolated preload bridge.
1222
-
1223
- ## Deployment conventions
1224
-
1225
- ### Agent-assisted provisioning
1226
-
1227
- When the user asks you to provision this project:
1228
-
1229
- 1. Ask for the exact environment and custom domain first. Record canonical resource names and selected provider teams without recording secrets.
1230
- 2. Inspect whether Computer Use/browser control and subagents are available. With Computer Use, navigate provider dashboards and complete approved non-secret setup. Stop for the user at sign-in, password, passkey, MFA, CAPTCHA, paid purchase, destructive replacement, secret generation/reveal/rotation, and final release/store submission.
1231
- 3. If subagents are available, keep one lead agent responsible for mutations. Delegate bounded independent tasks only: one subagent reads this project's docs and environment examples, one performs read-only DNS/hostname checks, and one performs final read-only verification. Never send credentials, cookies, or secret values to a subagent, and never let two agents mutate the same provider or DNS zone.
1232
- 4. At every secret-generation screen, stop before the final button. Tell the user the exact button, variable name, and uncommitted package-local environment file. The user clicks and pastes the value directly into that file or the provider's protected field, never into chat. Validate presence without printing populated environment files.
1233
- 5. Read \`PRODUCTION.md\` completely and follow its selection-specific order. Do not claim completion until cloud resources, environment names, DNS, TLS, application health, and the verification commands below pass.
1234
-
1235
- Domain topology: Cloudflare is authoritative DNS; Vercel hosts web/API; the Vercel A/CNAME/TXT records are created in Cloudflare DNS and normally remain DNS-only. Generated Worker hostnames such as \`assets.<domain>\` or \`updates.<domain>\` are Cloudflare Worker Custom Domains created by Wrangler, not CNAMEs to Vercel or public R2 endpoints.
1236
-
1237
- - Read \`PRODUCTION.md\` before provisioning or changing production resources. It is tailored to this project's selected surfaces and providers.
1238
- ${options.apps.web || options.apps.api ? '- Prefer GitHub-triggered Vercel Preview and Production deployments. Keep the generated Services routing intact; use manual `deploy:vercel:*` scripts only when explicitly required.' : ''}
1239
- ${options.features.database ? '- Treat reviewed, committed Drizzle SQL as the release artifact. Apply migrations as a controlled step against the intended Neon environment; never generate migrations during an application build.' : ''}
1240
- ${options.features.storage ? '- Keep the R2 bucket private and deploy `assets-private-proxy` at the Cloudflare Worker custom domain. Expose only `storage/confirmed/` publicly; use the owner-authorized read-URL endpoint for private objects and keep `CLOUDFLARE_API_TOKEN` operations-only.' : ''}
1241
- ${options.features.electronUpdater ? '- Provision the private desktop-update R2 bucket and deploy `desktop-updater` at `updates.<domain>`. Keep the update origin identical in Wrangler and `electron-builder.env`, then publish signed per-platform artifacts before channel metadata.' : ''}
1242
- ${options.apps.mobile ? '- Promote mobile artifacts through EAS internal distribution, TestFlight/Google Play testing, then store review. Build-time public variables are not secrets.' : ''}
1243
- ${options.apps.extension ? '- Publish the exact verified WXT ZIP through trusted/unlisted Chrome Web Store testing before production review; preserve a stable CRX ID and least-privilege permissions.' : ''}
1244
-
1245
- ## Verify changes
1246
-
1247
- Run the strongest applicable checks before handing work back:
1248
-
1249
- \`\`\`sh
1250
- pnpm typecheck
1251
- pnpm verify
1252
- pnpm build
1253
- pnpm dlx anhedral@${GENERATOR_VERSION} doctor
1254
- \`\`\`
1255
-
1256
- Use the package-specific \`verify:*\` scripts while iterating. A database schema change is incomplete until its reviewed migration is Git-tracked. Report exact failing packages and commands; do not weaken checks to make a change pass.
1257
- `);
1258
- }
1259
- function collectFiles(root, relativeRoot = '') {
1260
- const absoluteRoot = path.join(root, relativeRoot);
1261
- if (!pathEntryExists(absoluteRoot))
1262
- return [];
1263
- const files = [];
1264
- for (const entry of readdirSync(absoluteRoot, { withFileTypes: true })) {
1265
- if (GENERATED_CACHE_NAMES.has(entry.name))
1266
- continue;
1267
- const relativePath = relativeRoot ? `${relativeRoot}/${entry.name}` : entry.name;
1268
- if (relativePath === 'anhedral.json' || isTransactionMetadata(relativePath))
1269
- continue;
1270
- if (entry.isDirectory())
1271
- files.push(...collectFiles(root, relativePath));
1272
- else if (entry.isFile())
1273
- files.push(relativePath);
1274
- }
1275
- return files.sort();
1276
- }
1277
- function ownerForPath(relativePath) {
1278
- if (relativePath.startsWith('apps/desktop-updater-worker/'))
1279
- return 'electron-updater';
1280
- if (relativePath === 'apps/desktop/scripts/publish-updates.mjs')
1281
- return 'electron-updater';
1282
- if (relativePath === 'apps/desktop/electron-builder.env.example')
1283
- return 'electron-updater';
1284
- if (relativePath === 'cloudflare/desktop-updates.md')
1285
- return 'electron-updater';
1286
- if (relativePath.startsWith('apps/assets-private-proxy/'))
1287
- return 'storage';
1288
- if (relativePath.startsWith('cloudflare/'))
1289
- return 'storage';
1290
- const app = /^apps\/(web|mobile|api|desktop|extension)(?:\/|$)/.exec(relativePath);
1291
- if (app)
1292
- return app[1];
1293
- if (relativePath.startsWith('packages/db/'))
1294
- return 'db';
1295
- return 'root';
1296
- }
1297
- function defaultOwnership(relativePath) {
1298
- if (relativePath === 'README.md' || relativePath === 'PRODUCTION.md')
1299
- return 'user';
1300
- if (relativePath === 'apps/assets-private-proxy/wrangler.jsonc')
1301
- return 'user';
1302
- if (relativePath === 'apps/desktop-updater-worker/wrangler.jsonc')
1303
- return 'user';
1304
- if (relativePath === 'cloudflare/r2-cors.template.json')
1305
- return 'user';
1306
- if (relativePath === 'apps/web/app/page.tsx'
1307
- || /^apps\/web\/components\//.test(relativePath)
1308
- || relativePath === 'apps/mobile/app/index.tsx'
1309
- || /^apps\/mobile\/components\//.test(relativePath)
1310
- || relativePath === 'apps/desktop/src/main/app-window.ts'
1311
- || /^apps\/desktop\/src\/renderer\/components\//.test(relativePath)
1312
- || /^apps\/extension\/src\/components\//.test(relativePath)
1313
- || relativePath === 'apps/api/src/routes/app.ts'
1314
- || /^apps\/api\/src\/services\//.test(relativePath)
1315
- || relativePath === 'packages/contracts/src/app.ts'
1316
- || relativePath === 'packages/api-client/src/app.ts'
1317
- || relativePath === 'packages/db/src/app-schema.ts')
1318
- return 'user';
1319
- if (ROOT_MERGEABLE_FILES.has(relativePath))
1320
- return 'mergeable';
1321
- return 'managed';
1322
- }
1323
- function applyCurrentOwnership(manifest) {
1324
- const files = Object.freeze(Object.fromEntries(Object.entries(manifest.files).map(([relativePath, record]) => [
1325
- relativePath,
1326
- record.ownership === 'managed' && defaultOwnership(relativePath) === 'user'
1327
- ? Object.freeze({ ...record, ownership: 'user' })
1328
- : record,
1329
- ])));
1330
- return Object.freeze({ ...manifest, files });
1331
- }
1332
- function preserveUserOwnedFiles(root, stageRoot, manifest) {
1333
- for (const [relativePath, record] of Object.entries(manifest.files)) {
1334
- if (record.ownership !== 'user')
1335
- continue;
1336
- const current = path.join(root, relativePath);
1337
- const staged = path.join(stageRoot, relativePath);
1338
- const currentStat = lstatIfPresent(current);
1339
- const stagedStat = lstatIfPresent(staged);
1340
- if (!currentStat?.isFile())
1341
- continue;
1342
- if (stagedStat?.isSymbolicLink() || (stagedStat && !stagedStat.isFile())) {
1343
- throw new Error(`Refusing to replace user-owned path with a non-file: ${relativePath}`);
1344
- }
1345
- if (stagedStat?.isFile() && readFileSync(current).equals(readFileSync(staged)))
1346
- continue;
1347
- mkdirSync(path.dirname(staged), { recursive: true });
1348
- copyFileSync(current, staged);
1349
- chmodSync(staged, Number(currentStat.mode) & 0o777);
1350
- }
1351
- }
1352
- function createProjectManifest(root, options, operation, templates, previous, components = previous?.ui.components ?? []) {
1353
- const contributions = new Map();
1354
- for (const relativePath of collectFiles(root)) {
1355
- const previousRecord = previous?.files[relativePath];
1356
- const ownership = previousRecord?.ownership ?? defaultOwnership(relativePath);
1357
- const owner = previousRecord?.owner ?? ownerForPath(relativePath);
1358
- const files = contributions.get(owner) ?? [];
1359
- files.push({
1360
- path: relativePath,
1361
- ownership,
1362
- content: readFileSync(path.join(root, relativePath), 'utf8'),
1363
- });
1364
- contributions.set(owner, files);
1365
- }
1366
- const plan = buildGenerationPlan({
1367
- operation,
1368
- requestedModules: options.modules,
1369
- contributions: [...contributions].map(([module, files]) => ({ module, files })),
1370
- });
1371
- const manifest = createManifest({
1372
- generatorVersion: GENERATOR_VERSION,
1373
- project: { name: options.projectName, displayName: options.displayName },
1374
- plan,
1375
- toolchain: options.toolchainChannel,
1376
- templates,
1377
- nativeStyling: options.nativeStyling,
1378
- components,
1379
- });
1380
- const files = Object.freeze(Object.fromEntries(Object.entries(manifest.files).map(([relativePath, record]) => [
1381
- relativePath,
1382
- Object.freeze({
1383
- ...record,
1384
- hash: hashContent(readFileSync(path.join(root, relativePath))),
1385
- mode: normalizedFileMode(lstatSync(path.join(root, relativePath)).mode),
1386
- }),
1387
- ])));
1388
- return Object.freeze({ ...manifest, files });
1389
- }
1390
- function writeManifest(root, manifest) {
1391
- writeFile(path.join(root, 'anhedral.json'), serializeManifest(manifest));
1392
- }
1393
- function readProjectManifest(root, options = {}) {
1394
- const filePath = path.join(root, 'anhedral.json');
1395
- if (!pathEntryExists(filePath))
1396
- throw new Error('anhedral.json was not found. Run anhedral init first.');
1397
- const manifest = readManifest(readFileSync(filePath, 'utf8'));
1398
- if (manifest.generatorVersion !== GENERATOR_VERSION) {
1399
- if (options.allowSupportedUpgrade && isSupportedProjectUpgrade(manifest.generatorVersion, GENERATOR_VERSION)) {
1400
- return manifest;
1401
- }
1402
- const nextStep = isSupportedProjectUpgrade(manifest.generatorVersion, GENERATOR_VERSION)
1403
- ? 'Run anhedral upgrade before adding modules.'
1404
- : 'Regenerate the project with the current CLI before adding modules.';
1405
- throw new Error(`This project was generated by Anhedral ${manifest.generatorVersion}; current CLI ${GENERATOR_VERSION} only supports exact-current projects. `
1406
- + nextStep);
1407
- }
1408
- assertTemplateProvenance(manifest.modules, manifest.templates);
1409
- return manifest;
1410
- }
1411
- function cleanNestedArtifacts(root) {
1412
- rmSync(path.join(root, 'node_modules'), { recursive: true, force: true });
1413
- const appsRoot = path.join(root, 'apps');
1414
- if (!pathEntryExists(appsRoot))
1415
- return;
1416
- for (const app of readdirSync(appsRoot, { withFileTypes: true })) {
1417
- if (!app.isDirectory())
1418
- continue;
1419
- for (const artifact of ['.git', 'node_modules', 'package-lock.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'yarn.lock']) {
1420
- rmSync(path.join(appsRoot, app.name, artifact), { recursive: true, force: true });
1421
- }
1422
- }
1423
- }
1424
- function selectedUiTargets(options) {
1425
- return UI_TARGETS.filter((target) => options.apps[target]);
1426
- }
1427
- function installSelectedUiComponents(root, options) {
1428
- const installs = resolveUiInstalls(options.uiComponents, selectedUiTargets(options), options.nativeStyling);
1429
- if (installs.length > 0 && !options.dryRun)
1430
- installUiComponents(root, installs);
1431
- return installs;
1432
- }
1433
- function installWorkspaceDependencies(root) {
1434
- const executable = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
1435
- execFile(executable, ['install', '--no-frozen-lockfile'], root);
1436
- }
1437
- async function writeSelectedModules(root, options) {
1438
- const templates = materializeTemplates(root, resolveModules(options.modules).resolvedModules);
1439
- const shared = projectOptions(options);
1440
- scaffoldSharedPackages(root, shared);
1441
- if (options.apps.api)
1442
- await scaffoldApi(root, shared);
1443
- if (options.apps.mobile)
1444
- await scaffoldMobile(root, shared);
1445
- if (options.apps.web)
1446
- await scaffoldWeb(root, shared);
1447
- if (options.apps.desktop)
1448
- await scaffoldDesktop(root, shared);
1449
- if (options.apps.extension)
1450
- await scaffoldExtension(root, shared);
1451
- if (options.features.storage)
1452
- scaffoldAssetsPrivateProxy(root, shared);
1453
- if (options.features.electronUpdater)
1454
- scaffoldElectronUpdater(root, shared);
1455
- return templates;
1456
- }
1457
- function printPlan(operation, paths, json) {
1458
- if (json) {
1459
- console.log(JSON.stringify({ operation, paths }, null, 2));
1460
- return;
1461
- }
1462
- anhedralPrint.info(`${operation} plan: ${paths.length} path${paths.length === 1 ? '' : 's'}`);
1463
- for (const relativePath of paths)
1464
- console.log(` ${relativePath}`);
1465
- }
1466
- function assertSafeChangedPaths(root, stageRoot, manifest, paths, deleting = new Set()) {
1467
- for (const relativePath of paths) {
1468
- if (relativePath === 'anhedral.json')
1469
- continue;
1470
- const target = path.join(root, relativePath);
1471
- const record = manifest.files[relativePath];
1472
- const targetStat = lstatIfPresent(target);
1473
- if (targetStat?.isSymbolicLink())
1474
- throw new Error(`Refusing to modify symbolic-link path: ${relativePath}`);
1475
- if (targetStat && !record) {
1476
- throw new Error(`Refusing to overwrite unowned path: ${relativePath}`);
1477
- }
1478
- if (!record || !targetStat)
1479
- continue;
1480
- assertManagedFileMode(relativePath, record, targetStat);
1481
- const actualHash = hashContent(readFileSync(target));
1482
- if (record.ownership === 'user' && actualHash !== record.hash) {
1483
- throw new Error(`Refusing to modify user-owned path: ${relativePath}`);
1484
- }
1485
- if (record.ownership === 'managed' && actualHash !== record.hash) {
1486
- throw new Error(`Managed file has user modifications: ${relativePath}`);
1487
- }
1488
- if (!deleting.has(relativePath) && !pathEntryExists(path.join(stageRoot, relativePath))) {
1489
- throw new Error(`Internal plan error: staged path is missing: ${relativePath}`);
1490
- }
1491
- }
1492
- }
1493
- function stagedFileDiff(root, stageRoot, manifest) {
1494
- const changed = [...collectFiles(stageRoot), 'anhedral.json'].filter((relativePath) => {
1495
- const target = path.join(root, relativePath);
1496
- const targetStat = lstatIfPresent(target);
1497
- if (!targetStat)
1498
- return true;
1499
- if (targetStat.isSymbolicLink())
1500
- throw new Error(`Refusing to compare symbolic-link path: ${relativePath}`);
1501
- const stagedTarget = path.join(stageRoot, relativePath);
1502
- const stagedStat = lstatSync(stagedTarget);
1503
- const targetMode = normalizedFileMode(targetStat.mode);
1504
- const stagedMode = normalizedFileMode(stagedStat.mode);
1505
- return !readFileSync(target).equals(readFileSync(stagedTarget))
1506
- || (targetMode !== null && stagedMode !== null && targetMode !== stagedMode);
1507
- });
1508
- const deleted = Object.keys(manifest?.files ?? {}).filter((relativePath) => pathEntryExists(path.join(root, relativePath)) && !pathEntryExists(path.join(stageRoot, relativePath)));
1509
- return { changed, deleted };
1510
- }
1511
- export async function scaffoldProject(inputOptions) {
1512
- const options = canonicalInitOptions(inputOptions);
1513
- assertInstallNodeCompatibility(options);
1514
- const root = path.resolve(options.rootDirectory ?? process.cwd());
1515
- let createdRoot = false;
1516
- if (!pathEntryExists(root)) {
1517
- mkdirSync(root);
1518
- createdRoot = true;
1519
- }
1520
- const previousChannel = env.ANHEDRAL_TOOLCHAIN;
1521
- env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
1522
- const commitPaths = [];
1523
- const seedPaths = [];
1524
- try {
1525
- anhedralPrint.banner(`Initializing ${options.displayName}`);
1526
- const planned = await runStagedTransaction(root, {
1527
- commitPaths,
1528
- seedPaths,
1529
- dryRun: options.dryRun,
1530
- prepare: () => {
1531
- ensureScaffoldRoot(root);
1532
- if (pathEntryExists(path.join(root, '.gitignore')))
1533
- seedPaths.push('.gitignore');
1534
- },
1535
- build: async (stageRoot) => {
1536
- writeRootFiles(stageRoot, options, 'init', root);
1537
- const templates = await writeSelectedModules(stageRoot, options);
1538
- const components = installSelectedUiComponents(stageRoot, options);
1539
- writeProjectDocs(stageRoot, options, true);
1540
- cleanNestedArtifacts(stageRoot);
1541
- rmSync(path.join(stageRoot, 'pnpm-lock.yaml'), { force: true });
1542
- writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'init', templates, undefined, components));
1543
- commitPaths.push(...readdirSync(stageRoot));
1544
- },
1545
- afterCommit: () => {
1546
- if (!options.skipInstall) {
1547
- anhedralPrint.section('Workspace install');
1548
- installWorkspaceDependencies(root);
1549
- }
1550
- },
1551
- });
1552
- if (options.dryRun)
1553
- printPlan('init', planned, options.json);
1554
- if (!options.dryRun)
1555
- anhedralPrint.done(`Committed ${planned.length} paths`);
1556
- if (!options.dryRun && options.json)
1557
- printPlan('init', planned, true);
1558
- }
1559
- finally {
1560
- if (previousChannel == null)
1561
- delete env.ANHEDRAL_TOOLCHAIN;
1562
- else
1563
- env.ANHEDRAL_TOOLCHAIN = previousChannel;
1564
- if (createdRoot && pathEntryExists(root) && readdirSync(root).length === 0)
1565
- rmdirSync(root);
1566
- }
1567
- }
1568
- export async function scaffoldUiComponents(uiOptions) {
1569
- const root = path.resolve(process.cwd());
1570
- let manifest;
1571
- let options;
1572
- let additions = [];
1573
- let components = [];
1574
- let noOp = false;
1575
- const seedPaths = [];
1576
- const commitPaths = [];
1577
- const previousChannel = env.ANHEDRAL_TOOLCHAIN;
1578
- try {
1579
- const planned = await runStagedTransaction(root, {
1580
- seedPaths,
1581
- commitPaths,
1582
- dryRun: uiOptions.dryRun,
1583
- prepare: () => {
1584
- manifest = applyCurrentOwnership(readProjectManifest(root));
1585
- assertManagedFileModes(root, manifest);
1586
- const installedTargets = UI_TARGETS.filter((target) => manifest.modules.includes(target));
1587
- const targets = uiOptions.targets.length > 0 ? uiOptions.targets : installedTargets;
1588
- if (targets.length === 0)
1589
- throw new Error('This project has no UI client. Add web, mobile, desktop, or extension first.');
1590
- for (const target of targets) {
1591
- if (!manifest.modules.includes(target))
1592
- throw new Error(`UI target is not installed: ${target}`);
1593
- }
1594
- const requested = resolveUiInstalls(uiOptions.components, targets, manifest.ui.nativeStyling);
1595
- const installedKeys = new Set(manifest.ui.components.map(uiInstallKey));
1596
- additions = requested.filter((entry) => !installedKeys.has(uiInstallKey(entry)));
1597
- components = mergeUiInstalls(manifest.ui.components, additions);
1598
- if (additions.length === 0) {
1599
- noOp = true;
1600
- return false;
1601
- }
1602
- options = {
1603
- projectName: manifest.project.name,
1604
- displayName: manifest.project.displayName,
1605
- modules: [...manifest.modules],
1606
- ...selectionsFromModules(manifest.modules),
1607
- skipInstall: uiOptions.skipInstall,
1608
- dryRun: uiOptions.dryRun,
1609
- json: uiOptions.json,
1610
- toolchainChannel: toolchainChannelFromManifest(manifest),
1611
- uiComponents: [],
1612
- nativeStyling: manifest.ui.nativeStyling,
1613
- };
1614
- env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
1615
- seedPaths.push(...new Set([
1616
- ...Object.keys(manifest.files).filter((relativePath) => pathEntryExists(path.join(root, relativePath))),
1617
- 'anhedral.json',
1618
- ]));
1619
- anhedralPrint.banner(`Adding UI components`);
1620
- },
1621
- build: async (stageRoot) => {
1622
- if (!manifest || !options)
1623
- throw new Error('Internal UI plan was not prepared.');
1624
- if (!uiOptions.dryRun)
1625
- installUiComponents(stageRoot, additions);
1626
- cleanNestedArtifacts(stageRoot);
1627
- rmSync(path.join(stageRoot, 'pnpm-lock.yaml'), { force: true });
1628
- preserveUserOwnedFiles(root, stageRoot, manifest);
1629
- writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', manifest.templates, manifest, components));
1630
- const diff = stagedFileDiff(root, stageRoot, manifest);
1631
- assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
1632
- commitPaths.push(...diff.changed);
1633
- },
1634
- afterCommit: () => {
1635
- if (!uiOptions.skipInstall)
1636
- installWorkspaceDependencies(root);
1637
- },
1638
- });
1639
- if (noOp) {
1640
- if (uiOptions.json)
1641
- console.log(JSON.stringify({ operation: 'ui-add', paths: [], components: [] }, null, 2));
1642
- else
1643
- anhedralPrint.info('All requested UI components are already installed in the selected clients.');
1644
- return;
1645
- }
1646
- const componentPlan = additions.map((entry) => ({
1647
- component: entry.name,
1648
- target: entry.target,
1649
- provider: entry.provider,
1650
- source: entry.source,
1651
- }));
1652
- if (uiOptions.json) {
1653
- console.log(JSON.stringify({ operation: 'ui-add', paths: planned, components: componentPlan }, null, 2));
1654
- }
1655
- else {
1656
- anhedralPrint.info(`ui-add plan: ${componentPlan.length} installation${componentPlan.length === 1 ? '' : 's'}`);
1657
- for (const entry of componentPlan)
1658
- console.log(` ${entry.target}: ${entry.component} (${entry.provider})`);
1659
- for (const relativePath of planned)
1660
- console.log(` ${relativePath}`);
1661
- }
1662
- }
1663
- finally {
1664
- if (previousChannel == null)
1665
- delete env.ANHEDRAL_TOOLCHAIN;
1666
- else
1667
- env.ANHEDRAL_TOOLCHAIN = previousChannel;
1668
- }
1669
- }
1670
- export async function scaffoldUpgradeProject(upgradeOptions) {
1671
- const root = path.resolve(process.cwd());
1672
- let manifest;
1673
- let options;
1674
- let noOp = false;
1675
- const seedPaths = [];
1676
- const commitPaths = [];
1677
- const deletePaths = [];
1678
- const previousChannel = env.ANHEDRAL_TOOLCHAIN;
1679
- try {
1680
- const planned = await runStagedTransaction(root, {
1681
- commitPaths,
1682
- deletePaths,
1683
- seedPaths,
1684
- dryRun: upgradeOptions.dryRun,
1685
- prepare: () => {
1686
- manifest = applyCurrentOwnership(readProjectManifest(root, { allowSupportedUpgrade: true }));
1687
- if (manifest.generatorVersion === GENERATOR_VERSION) {
1688
- noOp = true;
1689
- return false;
1690
- }
1691
- assertManagedFileModes(root, manifest);
1692
- options = optionsFromManifest(manifest, {
1693
- modules: [],
1694
- skipInstall: upgradeOptions.skipInstall,
1695
- dryRun: upgradeOptions.dryRun,
1696
- json: upgradeOptions.json,
1697
- }, manifest.modules);
1698
- assertInstallNodeCompatibility(options);
1699
- env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
1700
- seedPaths.push(...new Set([
1701
- ...Object.keys(manifest.files).filter((relativePath) => pathEntryExists(path.join(root, relativePath))),
1702
- 'anhedral.json',
1703
- ]));
1704
- anhedralPrint.banner(`Upgrading ${manifest.generatorVersion} to ${GENERATOR_VERSION}`);
1705
- },
1706
- build: async (stageRoot) => {
1707
- if (!manifest || !options)
1708
- throw new Error('Internal upgrade plan was not prepared.');
1709
- writeRootFiles(stageRoot, options, 'add', root, manifest);
1710
- const templates = await writeSelectedModules(stageRoot, options);
1711
- writeProjectDocs(stageRoot, options, false);
1712
- cleanNestedArtifacts(stageRoot);
1713
- preserveUserOwnedFiles(root, stageRoot, manifest);
1714
- writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', templates, manifest, manifest.ui.components));
1715
- const diff = stagedFileDiff(root, stageRoot, manifest);
1716
- assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
1717
- commitPaths.push(...diff.changed);
1718
- deletePaths.push(...diff.deleted);
1719
- },
1720
- afterCommit: () => {
1721
- if (!upgradeOptions.skipInstall)
1722
- installWorkspaceDependencies(root);
1723
- },
1724
- });
1725
- if (noOp) {
1726
- if (upgradeOptions.json)
1727
- console.log(JSON.stringify({ operation: 'upgrade', paths: [] }, null, 2));
1728
- else
1729
- anhedralPrint.info(`Project is already on Anhedral ${GENERATOR_VERSION}.`);
1730
- return;
1731
- }
1732
- printPlan('upgrade', planned, upgradeOptions.json);
1733
- }
1734
- finally {
1735
- if (previousChannel == null)
1736
- delete env.ANHEDRAL_TOOLCHAIN;
1737
- else
1738
- env.ANHEDRAL_TOOLCHAIN = previousChannel;
1739
- }
1740
- }
1741
- export async function scaffoldAddModules(addOptions) {
1742
- const root = path.resolve(process.cwd());
1743
- let manifest;
1744
- let options;
1745
- let missing = [];
1746
- let noOp = false;
1747
- const seedPaths = [];
1748
- const commitPaths = [];
1749
- const deletePaths = [];
1750
- const previousChannel = env.ANHEDRAL_TOOLCHAIN;
1751
- try {
1752
- const planned = await runStagedTransaction(root, {
1753
- commitPaths,
1754
- deletePaths,
1755
- seedPaths,
1756
- dryRun: addOptions.dryRun,
1757
- prepare: () => {
1758
- manifest = applyCurrentOwnership(readProjectManifest(root));
1759
- assertManagedFileModes(root, manifest);
1760
- const desiredRequested = [...new Set([...manifest.modules, ...addOptions.modules])];
1761
- const resolution = resolveModules(desiredRequested);
1762
- const installed = new Set(manifest.modules);
1763
- missing = resolution.resolvedModules.filter((moduleId) => !installed.has(moduleId));
1764
- if (!missing.length) {
1765
- noOp = true;
1766
- return false;
1767
- }
1768
- options = optionsFromManifest(manifest, addOptions, resolution.requestedModules);
1769
- assertInstallNodeCompatibility(options);
1770
- env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
1771
- seedPaths.push(...new Set([
1772
- ...Object.keys(manifest.files).filter((relativePath) => pathEntryExists(path.join(root, relativePath))),
1773
- 'anhedral.json',
1774
- ]));
1775
- anhedralPrint.banner(`Adding ${missing.join(', ')}`);
1776
- },
1777
- build: async (stageRoot) => {
1778
- if (!manifest || !options)
1779
- throw new Error('Internal add plan was not prepared.');
1780
- writeRootFiles(stageRoot, options, 'add', root, manifest);
1781
- const templates = await writeSelectedModules(stageRoot, options);
1782
- writeProjectDocs(stageRoot, options, false);
1783
- cleanNestedArtifacts(stageRoot);
1784
- preserveUserOwnedFiles(root, stageRoot, manifest);
1785
- writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', templates, manifest));
1786
- const diff = stagedFileDiff(root, stageRoot, manifest);
1787
- assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
1788
- commitPaths.push(...diff.changed);
1789
- deletePaths.push(...diff.deleted);
1790
- },
1791
- afterCommit: () => {
1792
- if (!addOptions.skipInstall)
1793
- installWorkspaceDependencies(root);
1794
- },
1795
- });
1796
- if (noOp) {
1797
- if (addOptions.json)
1798
- console.log(JSON.stringify({ operation: 'add', paths: [] }, null, 2));
1799
- else
1800
- anhedralPrint.info('All requested modules are already installed.');
1801
- return;
1802
- }
1803
- if (addOptions.dryRun || !addOptions.json)
1804
- printPlan('add', planned, addOptions.json);
1805
- if (!addOptions.dryRun && addOptions.json)
1806
- printPlan('add', planned, true);
1807
- }
1808
- finally {
1809
- if (previousChannel == null)
1810
- delete env.ANHEDRAL_TOOLCHAIN;
1811
- else
1812
- env.ANHEDRAL_TOOLCHAIN = previousChannel;
1813
- }
1814
- }
1815
- export function doctorProject() {
1816
- const root = path.resolve(process.cwd());
1817
- const filePath = path.join(root, 'anhedral.json');
1818
- if (!pathEntryExists(filePath))
1819
- throw new Error('anhedral.json was not found. Run anhedral init first.');
1820
- const manifest = readManifest(readFileSync(filePath, 'utf8'));
1821
- const issues = [];
1822
- for (const entry of readdirSync(root, { withFileTypes: true })) {
1823
- if (!isTransactionMetadata(entry.name))
1824
- continue;
1825
- if (entry.name === '.anhedral-journal.json') {
1826
- issues.push({ path: entry.name, severity: 'error', message: 'An interrupted transaction requires recovery by init or add.' });
1827
- }
1828
- else if (entry.name.startsWith('.anhedral-journal.json.tmp-')) {
1829
- issues.push({ path: entry.name, severity: 'error', message: 'An incomplete transaction journal artifact requires manual inspection.' });
1830
- }
1831
- else {
1832
- issues.push({ path: entry.name, severity: 'error', message: 'An Anhedral operation is running or left a transaction-lock artifact.' });
1833
- }
1834
- }
1835
- if (manifest.generatorVersion !== GENERATOR_VERSION) {
1836
- issues.push({
1837
- path: 'anhedral.json',
1838
- severity: 'error',
1839
- message: isSupportedProjectUpgrade(manifest.generatorVersion, GENERATOR_VERSION)
1840
- ? `Project generator ${manifest.generatorVersion} differs from CLI ${GENERATOR_VERSION}; run anhedral upgrade.`
1841
- : `Project generator ${manifest.generatorVersion} differs from CLI ${GENERATOR_VERSION}; regenerate with the current CLI.`,
1842
- });
1843
- }
1844
- try {
1845
- assertTemplateProvenance(manifest.modules, manifest.templates);
1846
- }
1847
- catch (error) {
1848
- issues.push({
1849
- path: 'anhedral.json',
1850
- severity: 'error',
1851
- message: error instanceof Error ? error.message : 'Template provenance is invalid.',
1852
- });
1853
- }
1854
- for (const [relativePath, record] of Object.entries(manifest.files)) {
1855
- const target = path.join(root, relativePath);
1856
- const targetStat = lstatIfPresent(target);
1857
- if (!targetStat) {
1858
- issues.push({ path: relativePath, severity: 'error', message: 'Recorded file is missing.' });
1859
- continue;
1860
- }
1861
- if (targetStat.isSymbolicLink()) {
1862
- issues.push({ path: relativePath, severity: 'error', message: 'Recorded path is a symbolic link.' });
1863
- continue;
1864
- }
1865
- if (!targetStat.isFile()) {
1866
- issues.push({ path: relativePath, severity: 'error', message: 'Recorded path is not a regular file.' });
1867
- continue;
1868
- }
1869
- const actual = hashContent(readFileSync(target));
1870
- if (actual !== record.hash) {
1871
- issues.push({
1872
- path: relativePath,
1873
- severity: record.ownership === 'managed' ? 'error' : 'warning',
1874
- message: `${record.ownership} file differs from its recorded hash.`,
1875
- });
1876
- }
1877
- if (record.mode !== null) {
1878
- const actualMode = normalizedFileMode(targetStat.mode);
1879
- if (actualMode !== null && actualMode !== record.mode) {
1880
- issues.push({
1881
- path: relativePath,
1882
- severity: record.ownership === 'managed' ? 'error' : 'warning',
1883
- message: `${record.ownership} file mode differs from its recorded mode `
1884
- + `(${displayFileMode(record.mode)} expected, ${displayFileMode(actualMode)} found).`,
1885
- });
1886
- }
1887
- }
1888
- }
1889
- return {
1890
- ok: !issues.some((issue) => issue.severity === 'error'),
1891
- schemaVersion: manifest.schemaVersion,
1892
- generatorVersion: manifest.generatorVersion,
1893
- issues,
1894
- };
1895
- }