create-fs-app 2.0.3 → 3.0.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 (60) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +255 -151
  3. package/dist/cli/output.js +223 -0
  4. package/dist/cli/program.js +403 -0
  5. package/dist/cli/resolve-config.js +264 -0
  6. package/dist/cli/ui/errors.js +27 -0
  7. package/dist/cli/ui/help.js +43 -0
  8. package/dist/cli/ui/hints.js +22 -0
  9. package/dist/cli/ui/layer-log.js +109 -0
  10. package/dist/cli/ui/list.js +115 -0
  11. package/dist/cli/ui/text.js +56 -0
  12. package/dist/cli/wizard.js +275 -0
  13. package/dist/core/auth/jwt.js +478 -0
  14. package/dist/core/download.js +109 -0
  15. package/dist/core/health-check.js +42 -44
  16. package/dist/core/presets.js +75 -117
  17. package/dist/core/registry-fetch.js +101 -81
  18. package/dist/core/registry.fallback.json +892 -0
  19. package/dist/core/scaffold.js +121 -75
  20. package/dist/core/stack.js +109 -0
  21. package/dist/core/template-cache.js +95 -154
  22. package/dist/core/template-clone.js +351 -655
  23. package/dist/core/template-list.js +19 -141
  24. package/dist/core/template-registry.js +116 -216
  25. package/dist/index.js +13 -963
  26. package/dist/types/index.js +30 -82
  27. package/dist/utils/cli-error.js +15 -0
  28. package/dist/utils/exec.js +62 -0
  29. package/dist/utils/logger.js +10 -9
  30. package/dist/utils/theme.js +87 -0
  31. package/dist/utils/validation.js +24 -13
  32. package/package.json +22 -25
  33. package/dist/core/health-check.d.ts +0 -15
  34. package/dist/core/health-check.js.map +0 -1
  35. package/dist/core/presets.d.ts +0 -48
  36. package/dist/core/presets.js.map +0 -1
  37. package/dist/core/registry-fetch.d.ts +0 -20
  38. package/dist/core/registry-fetch.js.map +0 -1
  39. package/dist/core/scaffold.d.ts +0 -40
  40. package/dist/core/scaffold.js.map +0 -1
  41. package/dist/core/template-cache.d.ts +0 -38
  42. package/dist/core/template-cache.js.map +0 -1
  43. package/dist/core/template-clone.d.ts +0 -27
  44. package/dist/core/template-clone.js.map +0 -1
  45. package/dist/core/template-list.d.ts +0 -45
  46. package/dist/core/template-list.js.map +0 -1
  47. package/dist/core/template-registry.d.ts +0 -78
  48. package/dist/core/template-registry.js.map +0 -1
  49. package/dist/index.d.ts +0 -2
  50. package/dist/index.js.bak +0 -872
  51. package/dist/index.js.map +0 -1
  52. package/dist/types/index.d.ts +0 -102
  53. package/dist/types/index.js.map +0 -1
  54. package/dist/utils/errors.d.ts +0 -15
  55. package/dist/utils/errors.js +0 -50
  56. package/dist/utils/errors.js.map +0 -1
  57. package/dist/utils/logger.d.ts +0 -37
  58. package/dist/utils/logger.js.map +0 -1
  59. package/dist/utils/validation.d.ts +0 -48
  60. package/dist/utils/validation.js.map +0 -1
@@ -2,90 +2,87 @@
2
2
  * Environment Health Check
3
3
  * Verifies that the required tools are installed and at the right version.
4
4
  */
5
- import { execa } from 'execa';
6
- import chalk from 'chalk';
5
+ import { detectTheme } from '../utils/theme.js';
6
+ import { run } from '../utils/exec.js';
7
7
  export async function runHealthCheck() {
8
8
  const checks = [];
9
- console.log(chalk.cyan.bold('\nšŸ„ Environment Health Check\n'));
9
+ console.log(`\n${detectTheme(process.stdout).bold('Environment health check')}\n`);
10
10
  checks.push(await checkNode());
11
11
  checks.push(await checkGit());
12
12
  checks.push(await checkDocker());
13
13
  checks.push(await checkNpm());
14
14
  checks.push(await checkPnpm());
15
15
  checks.push(await checkYarn());
16
- const passed = checks.every(c => c.passed);
16
+ const passed = checks.every(c => c.passed || c.optional);
17
17
  return { passed, checks };
18
18
  }
19
19
  export function displayHealthCheckResults(result) {
20
+ const theme = detectTheme(process.stdout);
21
+ const { glyphs } = theme;
20
22
  console.log();
21
23
  result.checks.forEach(check => {
22
- const icon = check.passed ? chalk.green('āœ“') : chalk.red('āœ—');
23
- console.log(`${icon} ${chalk.bold(check.name)}`);
24
- console.log(chalk.gray(` ${check.message}`));
24
+ const icon = check.passed
25
+ ? theme.success(glyphs.check)
26
+ : check.optional ? theme.warn(glyphs.optional) : theme.error(glyphs.cross);
27
+ console.log(`${icon} ${theme.bold(check.name)}${check.optional ? theme.dim(' (optional)') : ''}`);
28
+ console.log(theme.dim(` ${check.message}`));
25
29
  if (!check.passed && check.suggestion) {
26
- console.log(chalk.yellow(` šŸ’” ${check.suggestion}`));
30
+ console.log(` ${theme.dim('Try:')} ${theme.accent(check.suggestion)}`);
27
31
  }
28
32
  console.log();
29
33
  });
30
34
  const passedCount = result.checks.filter(c => c.passed).length;
31
35
  const totalCount = result.checks.length;
32
- console.log(chalk.bold(`Results: ${passedCount}/${totalCount} checks passed\n`));
36
+ console.log(theme.bold(`Results: ${passedCount}/${totalCount} checks passed\n`));
33
37
  if (result.passed) {
34
- console.log(chalk.green.bold('✨ Environment is ready!\n'));
38
+ console.log(theme.success(theme.bold('Environment is ready.\n')));
35
39
  }
36
40
  else {
37
- console.log(chalk.yellow.bold('āš ļø Some tools are missing. See suggestions above.\n'));
41
+ console.log(theme.error(theme.bold('Required tools are missing. See suggestions above.\n')));
38
42
  }
39
43
  }
40
44
  // ── Individual checks ─────────────────────────────────────────────────────────
45
+ /** The Node.js running the CLI is the one that matters. */
41
46
  async function checkNode() {
42
- try {
43
- const result = await execa('node', ['--version']);
44
- const raw = result.stdout.trim(); // e.g. "v20.11.0"
45
- const [major] = raw.replace('v', '').split('.').map(Number);
46
- const ok = major >= 18;
47
- return {
48
- name: 'Node.js',
49
- passed: ok,
50
- message: `${raw} detected${ok ? '' : ' (v18+ required)'}`,
51
- suggestion: ok ? undefined : 'Download from https://nodejs.org (LTS recommended)',
52
- };
53
- }
54
- catch {
55
- return {
56
- name: 'Node.js',
57
- passed: false,
58
- message: 'Not found in PATH',
59
- suggestion: 'Download from https://nodejs.org',
60
- };
61
- }
47
+ const raw = process.version; // e.g. "v20.19.0"
48
+ const [major = 0, minor = 0] = raw.slice(1).split('.').map(Number);
49
+ const ok = major > 20 || (major === 20 && minor >= 19);
50
+ return {
51
+ name: 'Node.js',
52
+ passed: ok,
53
+ message: `${raw} detected${ok ? '' : ' (v20.19+ required)'}`,
54
+ suggestion: ok ? undefined : 'Download from https://nodejs.org (LTS recommended)',
55
+ };
62
56
  }
63
57
  async function checkGit() {
64
58
  try {
65
- const result = await execa('git', ['--version']);
59
+ const result = await run('git', ['--version']);
66
60
  return {
67
61
  name: 'Git',
68
62
  passed: true,
69
- message: result.stdout.trim(),
63
+ optional: true,
64
+ message: `${result.stdout.trim()} (only needed for git init)`,
70
65
  };
71
66
  }
72
67
  catch {
73
68
  return {
74
69
  name: 'Git',
75
70
  passed: false,
76
- message: 'Not found in PATH',
71
+ optional: true,
72
+ message: 'Not found in PATH (only needed for git init; use --no-git without it)',
77
73
  suggestion: 'Install from https://git-scm.com/downloads',
78
74
  };
79
75
  }
80
76
  }
81
77
  async function checkDocker() {
82
78
  try {
83
- const result = await execa('docker', ['--version']);
79
+ const result = await run('docker', ['--version']);
84
80
  // Check if daemon is running
85
81
  try {
86
- await execa('docker', ['info'], { timeout: 4000 });
82
+ await run('docker', ['info'], { timeout: 4000 });
87
83
  return {
88
84
  name: 'Docker',
85
+ optional: true,
89
86
  passed: true,
90
87
  message: result.stdout.trim() + ' — daemon running',
91
88
  };
@@ -93,6 +90,7 @@ async function checkDocker() {
93
90
  catch {
94
91
  return {
95
92
  name: 'Docker',
93
+ optional: true,
96
94
  passed: false,
97
95
  message: result.stdout.trim() + ' — daemon not running',
98
96
  suggestion: 'Start Docker Desktop or run: sudo systemctl start docker',
@@ -102,6 +100,7 @@ async function checkDocker() {
102
100
  catch {
103
101
  return {
104
102
  name: 'Docker',
103
+ optional: true,
105
104
  passed: false,
106
105
  message: 'Not found in PATH',
107
106
  suggestion: 'Install from https://docs.docker.com/get-docker/',
@@ -110,7 +109,7 @@ async function checkDocker() {
110
109
  }
111
110
  async function checkNpm() {
112
111
  try {
113
- const result = await execa('npm', ['--version']);
112
+ const result = await run('npm', ['--version']);
114
113
  return { name: 'npm', passed: true, message: `v${result.stdout.trim()}` };
115
114
  }
116
115
  catch {
@@ -119,20 +118,19 @@ async function checkNpm() {
119
118
  }
120
119
  async function checkPnpm() {
121
120
  try {
122
- const result = await execa('pnpm', ['--version']);
123
- return { name: 'pnpm', passed: true, message: `v${result.stdout.trim()}` };
121
+ const result = await run('pnpm', ['--version']);
122
+ return { name: 'pnpm', optional: true, passed: true, message: `v${result.stdout.trim()}` };
124
123
  }
125
124
  catch {
126
- return { name: 'pnpm', passed: false, message: 'Not installed', suggestion: 'npm install -g pnpm' };
125
+ return { name: 'pnpm', optional: true, passed: false, message: 'Not installed', suggestion: 'npm install -g pnpm' };
127
126
  }
128
127
  }
129
128
  async function checkYarn() {
130
129
  try {
131
- const result = await execa('yarn', ['--version']);
132
- return { name: 'Yarn', passed: true, message: `v${result.stdout.trim()}` };
130
+ const result = await run('yarn', ['--version']);
131
+ return { name: 'Yarn', optional: true, passed: true, message: `v${result.stdout.trim()}` };
133
132
  }
134
133
  catch {
135
- return { name: 'Yarn', passed: false, message: 'Not installed', suggestion: 'npm install -g yarn' };
134
+ return { name: 'Yarn', optional: true, passed: false, message: 'Not installed', suggestion: 'npm install -g yarn' };
136
135
  }
137
136
  }
138
- //# sourceMappingURL=health-check.js.map
@@ -5,46 +5,75 @@
5
5
  import fs from 'fs/promises';
6
6
  import path from 'path';
7
7
  import os from 'os';
8
+ import { z } from 'zod';
9
+ import { ProjectOptionsSchema } from '../types/index.js';
8
10
  import { Logger } from '../utils/logger.js';
9
- const PRESETS_DIR = path.join(os.homedir(), '.create-fs-app', 'presets');
10
- const PRESETS_FILE = path.join(PRESETS_DIR, 'presets.json');
11
+ /** Resolved lazily so HOME can change (tests). */
12
+ function presetsFile() {
13
+ return path.join(os.homedir(), '.create-fs-app', 'presets', 'presets.json');
14
+ }
11
15
  /**
12
- * Ensure presets directory exists
16
+ * v2 presets stored `{ monorepo, apps: { frontend: {...}, backend: {...} } }`.
17
+ * Map them to the v3 shape; v2-only keys (styling, apiStyle, turbopack) are dropped.
13
18
  */
14
- async function ensurePresetsDir() {
15
- try {
16
- await fs.mkdir(PRESETS_DIR, { recursive: true });
17
- }
18
- catch (error) {
19
- Logger.warn('Failed to create presets directory');
20
- }
19
+ function migrateV2Config(raw) {
20
+ if (typeof raw !== 'object' || raw === null || !('apps' in raw))
21
+ return raw;
22
+ const v2 = raw;
23
+ const fe = v2.apps?.frontend ?? {};
24
+ const be = v2.apps?.backend ?? {};
25
+ const complete = v2.monorepo && fe.framework && be.framework && be.database && be.orm;
26
+ return {
27
+ stack: complete
28
+ ? { monorepo: v2.monorepo, frontend: fe.framework, backend: be.framework, database: be.database, orm: be.orm }
29
+ : undefined,
30
+ packageManager: v2.packageManager,
31
+ ci: v2.ci,
32
+ eslint: fe.eslint,
33
+ prettier: fe.prettier,
34
+ docker: be.docker,
35
+ auth: be.auth,
36
+ };
21
37
  }
38
+ export const PresetConfigSchema = z.preprocess(migrateV2Config, ProjectOptionsSchema);
39
+ const StoredPresetSchema = z.object({
40
+ name: z.string(),
41
+ description: z.string().optional(),
42
+ config: PresetConfigSchema,
43
+ createdAt: z.string(),
44
+ lastUsed: z.string().optional(),
45
+ });
22
46
  /**
23
- * Load all presets
47
+ * Load all presets. Presets that no longer parse are skipped with a warning.
24
48
  */
25
49
  async function loadPresets() {
26
- await ensurePresetsDir();
50
+ let raw;
27
51
  try {
28
- const content = await fs.readFile(PRESETS_FILE, 'utf-8');
29
- return JSON.parse(content);
52
+ raw = JSON.parse(await fs.readFile(presetsFile(), 'utf-8'));
30
53
  }
31
54
  catch {
32
- return {
33
- version: '1',
34
- presets: {}
35
- };
55
+ return { version: '2', presets: {}, invalid: {} };
36
56
  }
57
+ const presets = {};
58
+ const invalid = {};
59
+ for (const [name, value] of Object.entries(raw.presets ?? {})) {
60
+ const parsed = StoredPresetSchema.safeParse(value);
61
+ if (parsed.success) {
62
+ presets[name] = parsed.data;
63
+ }
64
+ else {
65
+ invalid[name] = value;
66
+ Logger.warn(`Ignoring preset "${name}": it does not match the current format`);
67
+ }
68
+ }
69
+ return { version: '2', presets, invalid };
37
70
  }
38
- /**
39
- * Save presets
40
- */
41
71
  async function savePresets(data) {
42
- await ensurePresetsDir();
43
- await fs.writeFile(PRESETS_FILE, JSON.stringify(data, null, 2));
72
+ const file = presetsFile();
73
+ await fs.mkdir(path.dirname(file), { recursive: true });
74
+ const out = { version: data.version, presets: { ...data.invalid, ...data.presets } };
75
+ await fs.writeFile(file, JSON.stringify(out, null, 2));
44
76
  }
45
- /**
46
- * Save a preset
47
- */
48
77
  /** Returns true if the name collides with a built-in preset (case-insensitive). */
49
78
  export function isBuiltinPresetName(name) {
50
79
  return Object.keys(BUILTIN_PRESETS).some(k => k.toLowerCase() === name.toLowerCase());
@@ -56,14 +85,14 @@ export async function userPresetExists(name) {
56
85
  }
57
86
  export async function savePreset(name, config, description) {
58
87
  const data = await loadPresets();
59
- // Remove project name from config
60
- const { name: _, ...configWithoutName } = config;
88
+ // Strip the project name (and anything else not part of a preset)
89
+ const options = ProjectOptionsSchema.parse(config);
61
90
  // Preserve original createdAt when overwriting an existing preset
62
91
  const existingCreatedAt = data.presets[name]?.createdAt;
63
92
  data.presets[name] = {
64
93
  name,
65
94
  description,
66
- config: configWithoutName,
95
+ config: options,
67
96
  createdAt: existingCreatedAt ?? new Date().toISOString(),
68
97
  };
69
98
  await savePresets(data);
@@ -78,10 +107,9 @@ export async function loadPreset(name) {
78
107
  if (preset) {
79
108
  // Update last used time
80
109
  preset.lastUsed = new Date().toISOString();
81
- data.presets[name] = preset;
82
110
  await savePresets(data);
83
111
  }
84
- return preset || null;
112
+ return preset ?? null;
85
113
  }
86
114
  /**
87
115
  * List all presets
@@ -95,34 +123,15 @@ export async function listPresets() {
95
123
  */
96
124
  export async function deletePreset(name) {
97
125
  const data = await loadPresets();
98
- if (data.presets[name]) {
126
+ if (data.presets[name] || name in data.invalid) {
99
127
  delete data.presets[name];
128
+ delete data.invalid[name];
100
129
  await savePresets(data);
101
130
  Logger.success(`Preset "${name}" deleted successfully`);
102
131
  return true;
103
132
  }
104
133
  return false;
105
134
  }
106
- /**
107
- * Check if preset exists
108
- */
109
- export async function hasPreset(name) {
110
- const data = await loadPresets();
111
- return name in data.presets;
112
- }
113
- /**
114
- * Get preset configuration merged with project name
115
- */
116
- export async function getPresetConfig(presetName, projectName) {
117
- const preset = await loadPreset(presetName);
118
- if (!preset) {
119
- return null;
120
- }
121
- return {
122
- name: projectName,
123
- ...preset.config
124
- };
125
- }
126
135
  /**
127
136
  * Built-in presets
128
137
  */
@@ -130,80 +139,30 @@ export const BUILTIN_PRESETS = {
130
139
  'saas-starter': {
131
140
  name: 'saas-starter',
132
141
  description: 'Modern SaaS application with Next.js, NestJS, PostgreSQL, and Prisma',
133
- config: {
134
- monorepo: 'turborepo',
142
+ config: ProjectOptionsSchema.parse({
143
+ stack: { monorepo: 'turborepo', frontend: 'next.js', backend: 'nest.js', database: 'postgresql', orm: 'prisma' },
135
144
  packageManager: 'pnpm',
136
- ci: false,
137
- apps: {
138
- frontend: {
139
- framework: 'next.js',
140
- styling: 'tailwind',
141
- eslint: true,
142
- prettier: true,
143
- turbopack: false,
144
- },
145
- backend: {
146
- framework: 'nest.js',
147
- database: 'postgresql',
148
- orm: 'prisma',
149
- apiStyle: 'rest',
150
- auth: 'none',
151
- docker: true,
152
- }
153
- }
154
- }
145
+ }),
155
146
  },
156
147
  'ecommerce': {
157
148
  name: 'ecommerce',
158
149
  description: 'E-commerce platform with React, Express, and MongoDB',
159
- config: {
160
- monorepo: 'turborepo',
150
+ config: ProjectOptionsSchema.parse({
151
+ stack: { monorepo: 'turborepo', frontend: 'react', backend: 'express', database: 'mongodb', orm: 'mongoose' },
161
152
  packageManager: 'npm',
162
- ci: false,
163
- apps: {
164
- frontend: {
165
- framework: 'react',
166
- styling: 'tailwind',
167
- eslint: true,
168
- prettier: true,
169
- turbopack: false,
170
- },
171
- backend: {
172
- framework: 'express',
173
- database: 'mongodb',
174
- orm: 'mongoose',
175
- apiStyle: 'rest',
176
- auth: 'none',
177
- docker: true,
178
- }
179
- }
180
- }
153
+ }),
181
154
  },
182
155
  'minimal': {
183
156
  name: 'minimal',
184
- description: 'Minimal setup with React, Express, and PostgreSQL',
185
- config: {
186
- monorepo: 'turborepo',
157
+ description: 'Minimal setup with React, Express, PostgreSQL, and Prisma',
158
+ config: ProjectOptionsSchema.parse({
159
+ stack: { monorepo: 'turborepo', frontend: 'react', backend: 'express', database: 'postgresql', orm: 'prisma' },
187
160
  packageManager: 'npm',
188
- ci: false,
189
- apps: {
190
- frontend: {
191
- framework: 'react',
192
- styling: 'css',
193
- eslint: false,
194
- prettier: false,
195
- turbopack: false,
196
- },
197
- backend: {
198
- framework: 'express',
199
- database: 'postgresql',
200
- apiStyle: 'rest',
201
- auth: 'none',
202
- docker: false,
203
- }
204
- }
205
- }
206
- }
161
+ eslint: false,
162
+ prettier: false,
163
+ docker: false,
164
+ }),
165
+ },
207
166
  };
208
167
  /**
209
168
  * Get built-in preset
@@ -217,4 +176,3 @@ export function getBuiltinPreset(name) {
217
176
  createdAt: new Date().toISOString()
218
177
  };
219
178
  }
220
- //# sourceMappingURL=presets.js.map
@@ -1,121 +1,141 @@
1
1
  /**
2
- * Remote Registry Fetcher
2
+ * Registry loading (format v3).
3
3
  *
4
- * Downloads the template registry (v2) from the templates GitHub repo and
5
- * caches it locally for 1 hour. Falls back through a layered strategy:
4
+ * With --local-templates <dir>: read <dir>/registry.json (or
5
+ * <dir>/templates/registry.json); no network.
6
6
  *
7
- * 1. Fresh cache (< 1 h) → return immediately
8
- * 2. Network fetch succeeds → write fresh cache, return
9
- * 3. Network fails + stale cache → return stale (offline resilience)
10
- * 4. Nothing available → return null → hardcoded fallback
7
+ * Otherwise, in order:
8
+ * 1. Fresh cache (< 1 h) → use it
9
+ * 2. Network fetch succeeds → write the cache, use it
10
+ * 3. Network fails + stale cache → use the stale cache (offline)
11
+ * 4. Nothing available → bundled fallback (registry.fallback.json)
11
12
  *
12
- * registry.json v2 shape:
13
- * { version: 2, repoUrl, branch, official: {}, contributed: {} }
14
- *
15
- * Cache: ~/.cache/create-fs-app/registry.json
16
- * TTL: 1 hour
13
+ * Cache: ~/.create-fs-app/registry-v3.json (v2 CLIs use registry.json).
14
+ * Every source is validated with RegistrySchema.
17
15
  */
18
16
  import fs from 'fs/promises';
19
17
  import path from 'path';
20
18
  import os from 'os';
19
+ import { FALLBACK_REGISTRY, RegistrySchema, templatesRefOverride, } from './template-registry.js';
20
+ import { Logger } from '../utils/logger.js';
21
+ import { CliError } from '../utils/cli-error.js';
21
22
  // ── Constants ─────────────────────────────────────────────────────────────────
22
- const REGISTRY_RAW_URL = 'https://raw.githubusercontent.com/Om-jannu/create-fs-app-templates/master/registry.json';
23
- const CACHE_DIR = path.join(os.homedir(), '.create-fs-app');
24
- const CACHE_FILE = path.join(CACHE_DIR, 'registry.json');
23
+ const REGISTRY_REPO = 'Om-jannu/create-fs-app';
24
+ const DEFAULT_REF = 'master';
25
25
  const CACHE_TTL = 60 * 60 * 1000; // 1 hour
26
26
  const FETCH_TIMEOUT = 5_000;
27
- function buildMetadata(entry, repoUrl, branch, contributor) {
28
- return {
29
- id: entry.id,
30
- contributor,
31
- url: repoUrl,
32
- branch,
33
- subfolder: entry.subfolder,
34
- description: entry.description,
35
- features: entry.features,
36
- supports: entry.supports,
37
- };
27
+ export function registryRef() {
28
+ return templatesRefOverride() ?? DEFAULT_REF;
29
+ }
30
+ export function registryUrl(ref = registryRef()) {
31
+ return `https://raw.githubusercontent.com/${REGISTRY_REPO}/${ref}/templates/registry.json`;
32
+ }
33
+ /** Resolved lazily so HOME can change (tests). */
34
+ export function registryCacheFile() {
35
+ return path.join(os.homedir(), '.create-fs-app', 'registry-v3.json');
38
36
  }
39
- async function readCache(requireFresh = true) {
37
+ async function readCache(ref, requireFresh) {
40
38
  try {
41
- const raw = await fs.readFile(CACHE_FILE, 'utf-8');
42
- const cache = JSON.parse(raw);
43
- if (cache.version !== 2)
44
- return null; // stale format — force re-fetch
45
- if (!requireFresh || Date.now() - (cache.fetchedAt ?? 0) < CACHE_TTL) {
46
- return { official: cache.official ?? {}, contributed: cache.contributed ?? {} };
47
- }
48
- return null;
39
+ const cache = JSON.parse(await fs.readFile(registryCacheFile(), 'utf-8'));
40
+ if (cache.ref !== ref)
41
+ return null;
42
+ if (requireFresh && Date.now() - (cache.fetchedAt ?? 0) >= CACHE_TTL)
43
+ return null;
44
+ const parsed = RegistrySchema.safeParse(cache.registry);
45
+ return parsed.success ? parsed.data : null;
49
46
  }
50
47
  catch {
51
48
  return null;
52
49
  }
53
50
  }
54
- async function writeCache(payload) {
51
+ async function writeCache(ref, registry) {
55
52
  try {
56
- await fs.mkdir(CACHE_DIR, { recursive: true });
57
- const cache = {
58
- version: 2,
59
- fetchedAt: Date.now(),
60
- official: payload.official,
61
- contributed: payload.contributed,
62
- };
63
- await fs.writeFile(CACHE_FILE, JSON.stringify(cache, null, 2));
53
+ const file = registryCacheFile();
54
+ await fs.mkdir(path.dirname(file), { recursive: true });
55
+ const cache = { fetchedAt: Date.now(), ref, registry };
56
+ await fs.writeFile(file, JSON.stringify(cache, null, 2));
64
57
  }
65
- catch {
66
- // non-fatal
58
+ catch (error) {
59
+ Logger.debug(`Could not write registry cache: ${error instanceof Error ? error.message : String(error)}`);
67
60
  }
68
61
  }
69
- // ── Network fetch ─────────────────────────────────────────────────────────────
70
- async function fetchFromGitHub() {
62
+ // ── Sources ───────────────────────────────────────────────────────────────────
63
+ async function fetchRegistry(ref) {
71
64
  try {
72
- const res = await fetch(REGISTRY_RAW_URL, {
65
+ const res = await fetch(registryUrl(ref), {
73
66
  signal: AbortSignal.timeout(FETCH_TIMEOUT),
74
- headers: { 'User-Agent': 'create-fs-app-cli' },
67
+ headers: { 'User-Agent': 'create-fs-app' },
75
68
  });
76
- if (!res.ok)
69
+ if (!res.ok) {
70
+ Logger.debug(`Registry fetch: HTTP ${res.status}`);
77
71
  return null;
78
- const remote = await res.json();
79
- if (remote.version !== 2)
80
- return null; // unsupported format
81
- const { repoUrl, branch } = remote;
82
- const official = {};
83
- const contributed = {};
84
- for (const [key, entry] of Object.entries(remote.official ?? {})) {
85
- official[key] = buildMetadata(entry, repoUrl, branch);
86
- if (!official[key].subfolder)
87
- official[key].subfolder = `templates/${key}`;
88
72
  }
89
- for (const [key, entry] of Object.entries(remote.contributed ?? {})) {
90
- contributed[key] = buildMetadata(entry, repoUrl, branch, entry.contributor);
91
- if (!contributed[key].subfolder)
92
- contributed[key].subfolder = `templates/${key}`;
73
+ const parsed = RegistrySchema.safeParse(await res.json());
74
+ if (!parsed.success) {
75
+ Logger.debug(`Remote registry is not a valid v3 registry: ${parsed.error.message}`);
76
+ return null;
93
77
  }
94
- return { official, contributed };
78
+ return parsed.data;
95
79
  }
96
- catch {
80
+ catch (error) {
81
+ Logger.debug(`Registry fetch failed: ${error instanceof Error ? error.message : String(error)}`);
97
82
  return null;
98
83
  }
99
84
  }
85
+ async function fileExists(file) {
86
+ try {
87
+ await fs.access(file);
88
+ return true;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ /** Load registry.json from a --local-templates directory. Throws with a clear message. */
95
+ export async function loadLocalRegistry(dir) {
96
+ const root = path.resolve(dir);
97
+ const candidates = [root, path.join(root, 'templates')];
98
+ for (const candidate of candidates) {
99
+ const file = path.join(candidate, 'registry.json');
100
+ if (!(await fileExists(file)))
101
+ continue;
102
+ let data;
103
+ try {
104
+ data = JSON.parse(await fs.readFile(file, 'utf-8'));
105
+ }
106
+ catch (error) {
107
+ throw new Error(`Could not read ${file}: ${error instanceof Error ? error.message : String(error)}`);
108
+ }
109
+ const parsed = RegistrySchema.safeParse(data);
110
+ if (!parsed.success) {
111
+ throw new Error(`${file} is not a valid v3 registry:\n${parsed.error.message}`);
112
+ }
113
+ return { registry: parsed.data, source: 'local', localDir: candidate };
114
+ }
115
+ throw new CliError(`No registry.json in ${root}`, {
116
+ reason: `Looked in ${root} and ${path.join(root, 'templates')}.`,
117
+ fix: '--local-templates <dir that contains registry.json>',
118
+ });
119
+ }
100
120
  // ── Public API ────────────────────────────────────────────────────────────────
101
- export async function getRemoteRegistry() {
102
- const fresh = await readCache(true);
121
+ export async function loadRegistry(options = {}) {
122
+ if (options.localDir)
123
+ return loadLocalRegistry(options.localDir);
124
+ const ref = registryRef();
125
+ const fresh = await readCache(ref, true);
103
126
  if (fresh)
104
- return fresh;
105
- const fetched = await fetchFromGitHub();
127
+ return { registry: fresh, source: 'cache' };
128
+ const fetched = await fetchRegistry(ref);
106
129
  if (fetched) {
107
- await writeCache(fetched);
108
- return fetched;
130
+ if (!options.noCacheWrite)
131
+ await writeCache(ref, fetched);
132
+ return { registry: fetched, source: 'network' };
109
133
  }
110
- const stale = await readCache(false);
134
+ const stale = await readCache(ref, false);
111
135
  if (stale)
112
- return stale;
113
- return null;
136
+ return { registry: stale, source: 'stale-cache' };
137
+ return { registry: FALLBACK_REGISTRY, source: 'fallback' };
114
138
  }
115
139
  export async function clearRegistryCache() {
116
- try {
117
- await fs.unlink(CACHE_FILE);
118
- }
119
- catch { /* fine */ }
140
+ await fs.rm(registryCacheFile(), { force: true });
120
141
  }
121
- //# sourceMappingURL=registry-fetch.js.map