slicejs-cli 4.4.0 → 4.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 (51) hide show
  1. package/client.js +192 -82
  2. package/commands/Print.js +158 -164
  3. package/commands/build/build.js +27 -1
  4. package/commands/buildProduction/buildProduction.js +42 -71
  5. package/commands/bundle/bundle.js +65 -60
  6. package/commands/docs/agents.js +260 -0
  7. package/commands/docs/events.js +365 -0
  8. package/commands/docs/index.js +123 -0
  9. package/commands/doctor/doctor.js +99 -12
  10. package/commands/export/checkExport.js +163 -0
  11. package/commands/export/clientRedirects.js +72 -0
  12. package/commands/export/copyDist.js +180 -0
  13. package/commands/export/export.js +236 -0
  14. package/commands/export/files.js +33 -0
  15. package/commands/export/hosts/cloudflare.js +48 -0
  16. package/commands/export/hosts/github.js +31 -0
  17. package/commands/export/hosts/index.js +69 -0
  18. package/commands/export/hosts/netlify.js +42 -0
  19. package/commands/export/hosts/nginx.js +73 -0
  20. package/commands/export/hosts/none.js +23 -0
  21. package/commands/export/hosts/s3.js +24 -0
  22. package/commands/export/hosts/shared.js +62 -0
  23. package/commands/export/hosts/vercel.js +69 -0
  24. package/commands/export/outDir.js +91 -0
  25. package/commands/export/prerender.js +121 -0
  26. package/commands/getComponent/getComponent.js +44 -40
  27. package/commands/init/init.js +32 -22
  28. package/commands/lint/lint.js +2 -2
  29. package/commands/lint/types.js +1 -1
  30. package/commands/listComponents/listComponents.js +205 -172
  31. package/commands/seo/check.js +7 -4
  32. package/commands/seo/images.js +77 -22
  33. package/commands/seo/sitemap.js +6 -3
  34. package/commands/seo/support.js +62 -0
  35. package/commands/setup/lint.js +1 -1
  36. package/commands/skill/skill.js +2 -2
  37. package/commands/startServer/startServer.js +60 -21
  38. package/commands/startServer/watchServer.js +3 -3
  39. package/commands/translator/check.js +32 -0
  40. package/commands/translator/init.js +125 -0
  41. package/commands/translator/scan.js +444 -0
  42. package/commands/typecheck/typecheck.js +2 -2
  43. package/commands/types/types.js +22 -3
  44. package/commands/utils/VersionChecker.js +14 -14
  45. package/commands/utils/bundling/BundleGenerator.js +45 -27
  46. package/commands/utils/bundling/DependencyAnalyzer.js +1007 -976
  47. package/commands/utils/componentCatalog.js +120 -0
  48. package/commands/utils/publicEnv.js +74 -0
  49. package/commands/utils/sliceConfigSchema.js +34 -0
  50. package/commands/utils/updateManager.js +12 -12
  51. package/package.json +22 -23
@@ -0,0 +1,180 @@
1
+ // commands/export/copyDist.js
2
+ //
3
+ // The export is an allowlist, not a copy of `dist/` minus a denylist. `dist/`
4
+ // also holds source (Components/), helpers (utils/), AppConfig.js, generated
5
+ // declarations and env files; Express production only serves a subset of it.
6
+ import fs from 'fs-extra';
7
+ import path from 'path';
8
+ import { writeSliceEnv, writeSliceEnvPayload } from '../utils/publicEnv.js';
9
+
10
+ const EXPORT_ROOT_FILES = new Set([
11
+ 'routes.js',
12
+ 'sliceConfig.json',
13
+ 'slice-env.json',
14
+ 'slice-env.generated.js',
15
+ // The event debugger dynamically imports this catalog at runtime.
16
+ 'slice-events.generated.js',
17
+ 'robots.txt',
18
+ 'sitemap.xml',
19
+ 'manifest.json',
20
+ 'service-worker.js'
21
+ ]);
22
+
23
+ const EXPORT_DIRS = new Set(['App', 'bundles', 'locales']);
24
+
25
+ // Files the exporter writes itself. `dist/public` is flattened to the root, but
26
+ // Express answers these paths with explicit routes before its static middleware,
27
+ // so a file with the same name in public/ must not replace them.
28
+ // `manifest.json` and `service-worker.js` are intentionally not reserved:
29
+ // Express prefers `dist/public/<file>` over `dist/<file>` for those two.
30
+ const RESERVED_ROOT_FILES = new Set([
31
+ 'index.html',
32
+ '404.html',
33
+ 'routes.js',
34
+ 'sliceConfig.json',
35
+ 'slice-env.json',
36
+ 'slice-env.generated.js'
37
+ ]);
38
+
39
+ // Express has a narrow carve-out for two generated docs data modules:
40
+ // `/bundles/documentationRoutes.generated.js` and `/bundles/docsIndex.js` are
41
+ // read from ComponentsPage. The static export prunes Components/, so copy just
42
+ // those two files into the public bundles folder.
43
+ const COMPONENTS_PAGE_BUNDLE_FILES = [
44
+ 'documentationRoutes.generated.js',
45
+ 'docsIndex.js'
46
+ ];
47
+
48
+ function readDeployedConfig(distDir) {
49
+ try {
50
+ return JSON.parse(fs.readFileSync(path.join(distDir, 'sliceConfig.json'), 'utf8'));
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ function readTranslatorFolder(distDir) {
57
+ const translator = readDeployedConfig(distDir)?.translator;
58
+ if (!translator?.enabled) return null;
59
+ const value = typeof translator.path === 'string' && translator.path.trim()
60
+ ? translator.path
61
+ : '/locales';
62
+ const folder = value.replace(/^\/+|\/+$/g, '');
63
+ return folder && !folder.includes('..') ? folder : null;
64
+ }
65
+
66
+ function eventsUiEnabled(distDir) {
67
+ return readDeployedConfig(distDir)?.events?.ui?.enabled === true;
68
+ }
69
+
70
+ const BLOCKED_SEGMENTS = new Set(['node_modules', '.git']);
71
+ const BLOCKED_FILES = /(?:^|\/)(?:\.env(?:\.[^/]+)?|package(?:-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|npm-shrinkwrap\.json)$/i;
72
+ const BLOCKED_ARTIFACTS = /\.(?:map(?:\.(?:br|gz))?|d\.ts)$/i;
73
+
74
+ function isExportableFile(relativePath) {
75
+ const normalized = String(relativePath).replace(/\\/g, '/');
76
+ if (!normalized) return true;
77
+ const segments = normalized.toLowerCase().split('/');
78
+ if (segments.some((segment) => BLOCKED_SEGMENTS.has(segment))) return false;
79
+ if (BLOCKED_FILES.test(normalized)) return false;
80
+ if (BLOCKED_ARTIFACTS.test(normalized)) return false;
81
+ return true;
82
+ }
83
+
84
+ export async function copyDist(outDir, distDir, { keepComponents, skipped }) {
85
+ const filter = (src) => {
86
+ const relative = path.relative(distDir, src);
87
+ return isExportableFile(relative);
88
+ };
89
+
90
+ for (const entry of await fs.readdir(distDir, { withFileTypes: true })) {
91
+ const name = entry.name;
92
+ const from = path.join(distDir, name);
93
+
94
+ if (entry.isDirectory()) {
95
+ if (name === 'public') {
96
+ await fs.copy(from, path.join(outDir, 'public'), { filter });
97
+ continue;
98
+ }
99
+ if (name === 'Components' && !keepComponents) {
100
+ skipped.push('Components/');
101
+ continue;
102
+ }
103
+ // Express production only serves `/Slice/Slice.js`; copying the whole
104
+ // folder would publish framework internals that Express 404s.
105
+ if (name === 'Slice') {
106
+ const sliceEntry = path.join(from, 'Slice.js');
107
+ if (await fs.pathExists(sliceEntry)) {
108
+ await fs.ensureDir(path.join(outDir, 'Slice'));
109
+ await fs.copy(sliceEntry, path.join(outDir, 'Slice', 'Slice.js'), { overwrite: true });
110
+ }
111
+ continue;
112
+ }
113
+ if (!EXPORT_DIRS.has(name) && name !== 'Components') {
114
+ skipped.push(`${name}/`);
115
+ continue;
116
+ }
117
+ await fs.copy(from, path.join(outDir, name), { filter });
118
+ continue;
119
+ }
120
+
121
+ if (!entry.isFile()) continue;
122
+ if (!EXPORT_ROOT_FILES.has(name)) {
123
+ skipped.push(name);
124
+ continue;
125
+ }
126
+ // The static event graph only exists for the debugger UI.
127
+ if (name === 'slice-events.generated.js' && !eventsUiEnabled(distDir)) {
128
+ skipped.push(name);
129
+ continue;
130
+ }
131
+ if (!isExportableFile(name)) continue;
132
+ await fs.copy(from, path.join(outDir, name), { overwrite: true });
133
+ }
134
+
135
+ // `translator.path` is configurable (`/locales` by default). Express mounts
136
+ // that exact folder, so copy it even when it is not a top-level allowlist dir.
137
+ const translatorFolder = readTranslatorFolder(distDir);
138
+ if (translatorFolder && !EXPORT_DIRS.has(translatorFolder)) {
139
+ const translatorDir = path.join(distDir, translatorFolder);
140
+ if (await fs.pathExists(translatorDir)) {
141
+ await fs.copy(translatorDir, path.join(outDir, translatorFolder), { filter });
142
+ }
143
+ }
144
+
145
+ // Narrow parity for the docs app: the Express bundle handler serves these two
146
+ // generated modules from ComponentsPage. Copy only these, never Components/.
147
+ const componentsPage = path.join(distDir, 'Components', 'AppComponents', 'ComponentsPage');
148
+ for (const fileName of COMPONENTS_PAGE_BUNDLE_FILES) {
149
+ const source = path.join(componentsPage, fileName);
150
+ if (!await fs.pathExists(source)) continue;
151
+ await fs.ensureDir(path.join(outDir, 'bundles'));
152
+ await fs.copy(source, path.join(outDir, 'bundles', fileName), { overwrite: true });
153
+ }
154
+ }
155
+
156
+ export async function flattenPublic(outDir) {
157
+ const publicDir = path.join(outDir, 'public');
158
+ if (!await fs.pathExists(publicDir)) return 0;
159
+
160
+ let copied = 0;
161
+ for (const entry of await fs.readdir(publicDir, { withFileTypes: true })) {
162
+ if (RESERVED_ROOT_FILES.has(entry.name)) continue;
163
+ await fs.copy(path.join(publicDir, entry.name), path.join(outDir, entry.name), { overwrite: true });
164
+ copied += 1;
165
+ }
166
+ await fs.remove(publicDir);
167
+ return copied;
168
+ }
169
+
170
+ export async function ensureEnv(outDir, projectRoot) {
171
+ const envPath = path.join(outDir, 'slice-env.json');
172
+ if (await fs.pathExists(envPath)) {
173
+ const payload = JSON.parse(await fs.readFile(envPath, 'utf8'));
174
+ // Re-emit both artifacts so an older build gets the ESM shim too.
175
+ await writeSliceEnvPayload(outDir, payload);
176
+ return Object.keys(payload.env || {}).length;
177
+ }
178
+ // Older builds (before env moved into `slice build`) get the files here.
179
+ return writeSliceEnv(outDir, projectRoot);
180
+ }
@@ -0,0 +1,236 @@
1
+ // commands/export/export.js
2
+ //
3
+ // `slice export`: turn the production build into a folder a static host can serve
4
+ // without Express. This file is orchestration only; copy rules, prerender, the
5
+ // check and each host live in their own module.
6
+ import fs from 'fs-extra';
7
+ import path from 'path';
8
+ import Print from '../Print.js';
9
+ import { getProjectRoot, getDistPath } from '../utils/PathHelper.js';
10
+ import build from '../build/build.js';
11
+ import { resolveSafeOutDir } from './outDir.js';
12
+ import { copyDist, ensureEnv, flattenPublic } from './copyDist.js';
13
+ import { buildPrerender } from './prerender.js';
14
+ import { checkExport } from './checkExport.js';
15
+ import { listFiles, writePage } from './files.js';
16
+ import { writeClientRedirects, writeClientSpa404 } from './clientRedirects.js';
17
+ import { detectHost, getHost } from './hosts/index.js';
18
+
19
+ function spaLabel(preset, spa) {
20
+ if (!spa) return 'no (unknown routes -> 404.html)';
21
+ if (preset.spaMode === 'omit-404') return 'yes (Cloudflare auto-SPA; no 404.html)';
22
+ if (preset.spaMode === 'client-404') return 'via 404.html (soft 404; host-dependent)';
23
+ return 'yes (unknown routes -> index.html)';
24
+ }
25
+
26
+ export default async function exportStatic(options = {}) {
27
+ const projectRoot = getProjectRoot(import.meta.url);
28
+ const distDir = getDistPath(import.meta.url);
29
+ const checkOnly = Boolean(options.check);
30
+ const dryRun = Boolean(options.dryRun);
31
+ const keepComponents = Boolean(options.keepComponents);
32
+
33
+ try {
34
+ Print.warning('slice export is experimental; flags and output may change between releases.');
35
+
36
+ // `--check` only reads, so it can inspect any existing folder. Every write
37
+ // path validates the target before touching it (a typo must not delete the
38
+ // project).
39
+ if (checkOnly) {
40
+ const outDir = path.resolve(projectRoot, options.out || 'dist-static');
41
+ const preset = options.host ? getHost(options.host) : await detectHost(outDir);
42
+ const explicitHost = options.host ? preset.id : null;
43
+
44
+ Print.title('Static export check');
45
+ const { issues, warnings } = await checkExport(outDir, {
46
+ keepComponents: options.keepComponents,
47
+ preset,
48
+ explicitHost
49
+ });
50
+ for (const warning of warnings) Print.warning(warning);
51
+ if (issues.length > 0) {
52
+ for (const issue of issues) Print.error(issue);
53
+ return false;
54
+ }
55
+ Print.success(`Export looks valid: ${path.relative(projectRoot, outDir)}`);
56
+ return true;
57
+ }
58
+
59
+ const outDir = await resolveSafeOutDir(projectRoot, options.out);
60
+ const preset = getHost(options.host);
61
+
62
+ if (options.sourcemap) {
63
+ Print.warning('--sourcemap builds maps that the export filters out; they will not be published.');
64
+ }
65
+ if (options.minify === false) {
66
+ Print.warning('--no-minify ships readable bundles; use it only for debugging.');
67
+ }
68
+
69
+ if (!options.fromDist) {
70
+ const built = await build({
71
+ minify: options.minify,
72
+ obfuscate: options.obfuscate,
73
+ sourcemap: options.sourcemap,
74
+ hashFilenames: options.hashFilenames,
75
+ compress: options.compress
76
+ });
77
+ if (built === false) return false;
78
+ }
79
+
80
+ if (!await fs.pathExists(distDir)) {
81
+ throw new Error('No dist/ found. Run "slice build" first, or drop --from-dist.');
82
+ }
83
+ if (!await fs.pathExists(path.join(distDir, 'App', 'index.html'))) {
84
+ throw new Error('dist/App/index.html is missing. Run "slice build" again.');
85
+ }
86
+
87
+ // A custom host rule inside src/public would be flattened and then silently
88
+ // replaced by the generated preset. Fail instead of losing CSP/redirects.
89
+ const customRuleFiles = (preset.ruleFiles || [])
90
+ .filter((name) => fs.existsSync(path.join(distDir, 'public', name)));
91
+ if (customRuleFiles.length > 0) {
92
+ throw new Error(
93
+ `dist/public/${customRuleFiles.join(', ')} would be replaced by --host ${preset.id}. Move custom host rules out of public/ or merge them into the generated files.`
94
+ );
95
+ }
96
+ if (fs.existsSync(path.join(distDir, 'public', '404.html'))) {
97
+ Print.warning('dist/public/404.html will be replaced by the generated 404.html.');
98
+ }
99
+
100
+ const prerender = await buildPrerender(projectRoot, distDir, options);
101
+
102
+ if (dryRun) {
103
+ Print.title('Static export (dry run)');
104
+ Print.info(`Would write ${path.relative(projectRoot, outDir)} from ${path.relative(projectRoot, distDir)}.`);
105
+ Print.info(`Host rules: ${preset.id}`);
106
+ if (prerender) {
107
+ Print.info(`${prerender.pages.size} route(s) would be prerendered`);
108
+ if (prerender.seo.redirects.length) {
109
+ Print.info(`${prerender.seo.redirects.length} locale redirect(s)`);
110
+ }
111
+ } else {
112
+ Print.info('No SEO manifest; the SPA shell would be the only page.');
113
+ }
114
+ return true;
115
+ }
116
+
117
+ const skippedEntries = [];
118
+ await fs.remove(outDir);
119
+ await copyDist(outDir, distDir, { keepComponents, skipped: skippedEntries });
120
+ await flattenPublic(outDir);
121
+
122
+ // In Express production `/Components` answers 404. Match that in the static
123
+ // export: component source is minified but still source, and every component
124
+ // used at runtime is in a bundle. `--keep-components` is a debugging escape.
125
+ let componentsState = 'none';
126
+ if (keepComponents && await fs.pathExists(path.join(outDir, 'Components'))) {
127
+ componentsState = 'kept';
128
+ } else if (skippedEntries.includes('Components/')) {
129
+ componentsState = 'pruned';
130
+ }
131
+
132
+ const rootIndex = path.join(outDir, 'index.html');
133
+ let pagesWritten = 0;
134
+
135
+ if (prerender) {
136
+ for (const [url, page] of prerender.pages) {
137
+ await writePage(outDir, url, page);
138
+ pagesWritten += 1;
139
+ }
140
+ }
141
+
142
+ if (!await fs.pathExists(rootIndex)) {
143
+ await fs.copy(path.join(outDir, 'App', 'index.html'), rootIndex);
144
+ }
145
+
146
+ const redirects = prerender?.seo.redirects || [];
147
+ const spa = options.spa === true || !prerender;
148
+ const cloudflareSpa = preset.spaMode === 'omit-404' && spa;
149
+ const clientSpa = preset.spaMode === 'client-404' && spa;
150
+ const notFoundPage = prerender
151
+ ? (prerender.seo.notFound.get(null) || [...prerender.seo.notFound.values()][0])
152
+ : null;
153
+
154
+ if (cloudflareSpa) {
155
+ // Cloudflare Pages only enables its own SPA mode when there is no
156
+ // top-level 404.html. A `_redirects` catch-all is rejected as an infinite
157
+ // loop, and `/* / 200` would hijack every asset.
158
+ await fs.remove(path.join(outDir, '404.html'));
159
+ } else if (clientSpa) {
160
+ // GitHub/S3/none cannot return 200 for unknown routes. The portable
161
+ // fallback is a 404.html that renders the app shell (soft 404).
162
+ await writeClientSpa404(outDir);
163
+ } else if (notFoundPage) {
164
+ await fs.writeFile(path.join(outDir, '404.html'), notFoundPage.html);
165
+ } else {
166
+ await fs.copy(rootIndex, path.join(outDir, '404.html'));
167
+ }
168
+
169
+ const envKeys = await ensureEnv(outDir, projectRoot);
170
+ const hostFiles = await preset.write({ outDir, redirects, spa });
171
+
172
+ // Hosts without server-side redirect syntax get portable HTML redirect files.
173
+ let clientRedirects = { written: 0, skipped: [] };
174
+ if (preset.clientRedirectPages && redirects.length) {
175
+ clientRedirects = await writeClientRedirects(
176
+ outDir,
177
+ redirects,
178
+ prerender?.seo.origin || '',
179
+ { allowRoot: !prerender?.pages.has('/') }
180
+ );
181
+ }
182
+
183
+ const files = await listFiles(outDir);
184
+ const totalBytes = files.reduce((sum, file) => sum + file.size, 0);
185
+
186
+ Print.title('Static export');
187
+ Print.success(`Exported to ${path.relative(projectRoot, outDir) || '.'}`);
188
+ Print.info(`${files.length} files, ${(totalBytes / 1024 / 1024).toFixed(2)} MB`);
189
+
190
+ if (prerender) {
191
+ const localeLabel = prerender.localeCount ? ` (${prerender.localeCount} locales)` : '';
192
+ Print.info(`${pagesWritten} route(s) prerendered${localeLabel}`);
193
+ if (cloudflareSpa) {
194
+ Print.info('404.html: omitted (Cloudflare auto-SPA)');
195
+ } else {
196
+ Print.info(`404.html${notFoundPage && !clientSpa ? ' (noindex)' : ''}`);
197
+ }
198
+ if (redirects.length) Print.info(`${redirects.length} locale redirect(s)`);
199
+ if (prerender.patternsSkipped) {
200
+ Print.warning(`${prerender.patternsSkipped} dynamic route(s) not prerendered; add sitemap.paths or pass --spa.`);
201
+ }
202
+ } else if (options.prerender === false) {
203
+ Print.warning('Prerender disabled; using the SPA shell (soft 404).');
204
+ } else {
205
+ Print.warning('No seo.json found; using the SPA shell (soft 404).');
206
+ }
207
+
208
+ Print.info(`Public env: ${envKeys} key(s) (JSON + ESM)`);
209
+ Print.info(`Host rules: ${hostFiles.length ? hostFiles.join(', ') : 'none'}`);
210
+ Print.info(`SPA fallback: ${spaLabel(preset, spa)}`);
211
+ if (componentsState === 'pruned') {
212
+ Print.info('Components: pruned (source not shipped)');
213
+ } else if (componentsState === 'kept') {
214
+ Print.warning('Components: kept; component source is fetchable.');
215
+ }
216
+ if (skippedEntries.length > 0 && process.env.SLICE_DEBUG) {
217
+ Print.verbose(`Skipped from dist: ${skippedEntries.join(', ')}`);
218
+ }
219
+ if (clientRedirects.written) {
220
+ Print.info(`${clientRedirects.written} client redirect page(s)`);
221
+ }
222
+ for (const skipped of clientRedirects.skipped) {
223
+ Print.warning(`Redirect path already has a page; kept the page: ${skipped}`);
224
+ }
225
+
226
+ Print.newLine();
227
+ Print.subtitle('Next step');
228
+ Print.commandExample('Serve the export locally', `npx serve ${path.relative(projectRoot, outDir) || '.'}`);
229
+ Print.info('Use "npx serve -s" only to test the SPA fallback: it hides the real 404.html.');
230
+ return true;
231
+ } catch (error) {
232
+ Print.error(`Static export failed: ${error.message}`);
233
+ Print.stack(error);
234
+ return false;
235
+ }
236
+ }
@@ -0,0 +1,33 @@
1
+ // commands/export/files.js
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+
5
+ export async function listFiles(dir, base = dir) {
6
+ const files = [];
7
+ for (const entry of await fs.readdir(dir)) {
8
+ const full = path.join(dir, entry);
9
+ const stat = await fs.stat(full);
10
+ if (stat.isDirectory()) {
11
+ files.push(...await listFiles(full, base));
12
+ } else {
13
+ files.push({ path: path.relative(base, full).replace(/\\/g, '/'), size: stat.size });
14
+ }
15
+ }
16
+ return files;
17
+ }
18
+
19
+ export function pagePathForUrl(url) {
20
+ const clean = String(url).split(/[?#]/)[0].replace(/^\/+|\/+$/g, '');
21
+ if (!clean) return 'index.html';
22
+ const normalized = path.normalize(clean);
23
+ if (normalized.startsWith('..') || path.isAbsolute(normalized)) {
24
+ throw new Error(`Refusing to export an unsafe route: ${url}`);
25
+ }
26
+ return path.join(normalized, 'index.html');
27
+ }
28
+
29
+ export async function writePage(outDir, url, page) {
30
+ const file = path.join(outDir, pagePathForUrl(url));
31
+ await fs.ensureDir(path.dirname(file));
32
+ await fs.writeFile(file, page.html);
33
+ }
@@ -0,0 +1,48 @@
1
+ // commands/export/hosts/cloudflare.js
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { HEADER_RULES, redirectCatchAll, redirectLines } from './shared.js';
5
+
6
+ export default {
7
+ id: 'cloudflare',
8
+ // Cloudflare Pages only enables its automatic SPA mode when there is no
9
+ // top-level 404.html. A `_redirects` catch-all is rejected as an infinite
10
+ // loop, and `/* / 200` would intercept every asset.
11
+ spaMode: 'omit-404',
12
+ clientRedirectPages: false,
13
+ ruleFiles: ['_redirects', '_headers'],
14
+
15
+ async write({ outDir, redirects }) {
16
+ const redirectBlock = redirects.length ? `${redirectLines(redirects)}\n` : '';
17
+ await fs.writeFile(path.join(outDir, '_redirects'), redirectBlock, 'utf8');
18
+ await fs.writeFile(path.join(outDir, '_headers'), HEADER_RULES, 'utf8');
19
+ return ['_redirects', '_headers'];
20
+ },
21
+
22
+ async check({ outDir, explicitHost }) {
23
+ const issues = [];
24
+ const warnings = [];
25
+ const hasRedirects = await fs.pathExists(path.join(outDir, '_redirects'));
26
+ const hasHeaders = await fs.pathExists(path.join(outDir, '_headers'));
27
+
28
+ if (hasRedirects !== hasHeaders) {
29
+ issues.push('_redirects and _headers must be written together (Cloudflare/Netlify).');
30
+ }
31
+ if (explicitHost && !hasRedirects) {
32
+ issues.push('Cloudflare export is missing _redirects.');
33
+ }
34
+ return { issues, warnings };
35
+ },
36
+
37
+ async spaFallback({ outDir }) {
38
+ const has404 = await fs.pathExists(path.join(outDir, '404.html'));
39
+ if (!has404 && await fs.pathExists(path.join(outDir, '_redirects'))) {
40
+ return true;
41
+ }
42
+ const redirectsFile = path.join(outDir, '_redirects');
43
+ if (await fs.pathExists(redirectsFile)) {
44
+ return redirectCatchAll(await fs.readFile(redirectsFile, 'utf8'));
45
+ }
46
+ return false;
47
+ }
48
+ };
@@ -0,0 +1,31 @@
1
+ // commands/export/hosts/github.js
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { clientSpaFallback } from './shared.js';
5
+
6
+ export default {
7
+ id: 'github',
8
+ // GitHub Pages has no server redirects/headers. `--spa` writes the shell as
9
+ // 404.html; unknown routes render the app with a 404 status.
10
+ spaMode: 'client-404',
11
+ clientRedirectPages: true,
12
+ ruleFiles: [],
13
+
14
+ async write({ outDir }) {
15
+ await fs.writeFile(path.join(outDir, '.nojekyll'), '', 'utf8');
16
+ return ['.nojekyll'];
17
+ },
18
+
19
+ async check({ outDir, explicitHost }) {
20
+ const issues = [];
21
+ const warnings = [];
22
+ if (explicitHost && !await fs.pathExists(path.join(outDir, '.nojekyll'))) {
23
+ issues.push('GitHub Pages export is missing .nojekyll.');
24
+ }
25
+ return { issues, warnings };
26
+ },
27
+
28
+ spaFallback({ outDir }) {
29
+ return clientSpaFallback(outDir);
30
+ }
31
+ };
@@ -0,0 +1,69 @@
1
+ // commands/export/hosts/index.js
2
+ //
3
+ // Host preset registry. Every preset is a plain object with one job:
4
+ //
5
+ // id stable name used by --host
6
+ // spaMode how --spa is implemented on this host
7
+ // clientRedirectPages whether locale redirects become HTML pages
8
+ // write(ctx) write the host files, return their names
9
+ // check(ctx) validate the host files
10
+ // spaFallback(ctx) whether the export declares an SPA fallback
11
+ //
12
+ // `spaMode` values:
13
+ // omit-404 Cloudflare Pages: no top-level 404.html, automatic SPA
14
+ // redirects Netlify: `/* /index.html 200`
15
+ // rewrite Vercel: `/(.*)` rewrite
16
+ // try-files nginx: `try_files ... /index.html`
17
+ // client-404 GitHub/S3/none: shell as 404.html, status stays 404
18
+ import fs from 'fs-extra';
19
+ import path from 'path';
20
+ import cloudflare from './cloudflare.js';
21
+ import netlify from './netlify.js';
22
+ import vercel from './vercel.js';
23
+ import nginx from './nginx.js';
24
+ import github from './github.js';
25
+ import s3 from './s3.js';
26
+ import none from './none.js';
27
+ import { redirectCatchAll } from './shared.js';
28
+
29
+ const PRESETS = new Map([
30
+ [cloudflare.id, cloudflare],
31
+ [netlify.id, netlify],
32
+ [vercel.id, vercel],
33
+ [nginx.id, nginx],
34
+ [github.id, github],
35
+ [s3.id, s3],
36
+ [none.id, none]
37
+ ]);
38
+
39
+ export const HOST_IDS = [...PRESETS.keys()];
40
+
41
+ export function getHost(value) {
42
+ const id = String(value || 'cloudflare').toLowerCase();
43
+ const preset = PRESETS.get(id);
44
+ if (!preset) {
45
+ throw new Error(`Unknown host "${value}". Use one of: ${HOST_IDS.join(', ')}.`);
46
+ }
47
+ return preset;
48
+ }
49
+
50
+ /**
51
+ * Pick the preset for `--check` when the user did not pass `--host`.
52
+ * The files are the only evidence: Vercel/nginx/GitHub have unique files;
53
+ * Cloudflare and Netlify share `_redirects`/`_headers`, so the catch-all
54
+ * distinguishes them.
55
+ */
56
+ export async function detectHost(outDir) {
57
+ if (await fs.pathExists(path.join(outDir, 'vercel.json'))) return vercel;
58
+ if (await fs.pathExists(path.join(outDir, 'nginx.conf'))) return nginx;
59
+ if (await fs.pathExists(path.join(outDir, '.nojekyll'))) return github;
60
+
61
+ const redirectsFile = path.join(outDir, '_redirects');
62
+ if (await fs.pathExists(redirectsFile)) {
63
+ const text = await fs.readFile(redirectsFile, 'utf8');
64
+ return redirectCatchAll(text) ? netlify : cloudflare;
65
+ }
66
+ if (await fs.pathExists(path.join(outDir, '_headers'))) return cloudflare;
67
+
68
+ return none;
69
+ }
@@ -0,0 +1,42 @@
1
+ // commands/export/hosts/netlify.js
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { HEADER_RULES, redirectCatchAll, redirectLines } from './shared.js';
5
+
6
+ export default {
7
+ id: 'netlify',
8
+ // Netlify's shadowing rules keep existing files first, so the catch-all is
9
+ // safe for assets and gives unknown routes the shell with a 200.
10
+ spaMode: 'redirects',
11
+ clientRedirectPages: false,
12
+ ruleFiles: ['_redirects', '_headers'],
13
+
14
+ async write({ outDir, redirects, spa }) {
15
+ const redirectBlock = redirects.length ? `${redirectLines(redirects)}\n` : '';
16
+ const spaBlock = spa ? '/* /index.html 200\n' : '';
17
+ await fs.writeFile(path.join(outDir, '_redirects'), `${redirectBlock}${spaBlock}`, 'utf8');
18
+ await fs.writeFile(path.join(outDir, '_headers'), HEADER_RULES, 'utf8');
19
+ return ['_redirects', '_headers'];
20
+ },
21
+
22
+ async check({ outDir, explicitHost }) {
23
+ const issues = [];
24
+ const warnings = [];
25
+ const hasRedirects = await fs.pathExists(path.join(outDir, '_redirects'));
26
+ const hasHeaders = await fs.pathExists(path.join(outDir, '_headers'));
27
+
28
+ if (hasRedirects !== hasHeaders) {
29
+ issues.push('_redirects and _headers must be written together (Cloudflare/Netlify).');
30
+ }
31
+ if (explicitHost && !hasRedirects) {
32
+ issues.push('Netlify export is missing _redirects.');
33
+ }
34
+ return { issues, warnings };
35
+ },
36
+
37
+ async spaFallback({ outDir }) {
38
+ const redirectsFile = path.join(outDir, '_redirects');
39
+ if (!await fs.pathExists(redirectsFile)) return false;
40
+ return redirectCatchAll(await fs.readFile(redirectsFile, 'utf8'));
41
+ }
42
+ };