slicejs-cli 4.4.0 → 4.5.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.
- package/client.js +31 -0
- package/commands/doctor/doctor.js +56 -3
- package/commands/getComponent/getComponent.js +5 -6
- package/commands/seo/check.js +6 -3
- package/commands/seo/images.js +76 -21
- package/commands/seo/sitemap.js +5 -2
- package/commands/seo/support.js +62 -0
- package/commands/translator/check.js +32 -0
- package/commands/translator/init.js +125 -0
- package/commands/translator/scan.js +444 -0
- package/commands/utils/bundling/DependencyAnalyzer.js +986 -976
- package/commands/utils/sliceConfigSchema.js +34 -0
- package/package.json +1 -1
package/client.js
CHANGED
|
@@ -12,6 +12,8 @@ import runDiagnostics from "./commands/doctor/doctor.js";
|
|
|
12
12
|
import seoCheck from "./commands/seo/check.js";
|
|
13
13
|
import seoSitemap from "./commands/seo/sitemap.js";
|
|
14
14
|
import seoImages from "./commands/seo/images.js";
|
|
15
|
+
import translatorCheck from "./commands/translator/check.js";
|
|
16
|
+
import translatorInit from "./commands/translator/init.js";
|
|
15
17
|
import versionChecker from "./commands/utils/VersionChecker.js";
|
|
16
18
|
import updateManager from "./commands/utils/updateManager.js";
|
|
17
19
|
import fs from "fs";
|
|
@@ -819,6 +821,35 @@ seoCommand
|
|
|
819
821
|
});
|
|
820
822
|
});
|
|
821
823
|
|
|
824
|
+
// TRANSLATOR COMMANDS - dictionaries, data-t templates and key() props.
|
|
825
|
+
const translatorCommand = sliceClient
|
|
826
|
+
.command("translator")
|
|
827
|
+
.alias("i18n")
|
|
828
|
+
.description("Translator helpers: scaffold the locale files and check every key");
|
|
829
|
+
|
|
830
|
+
translatorCommand
|
|
831
|
+
.command("init")
|
|
832
|
+
.description("Add the translator block to sliceConfig.json and create src/locales/<locale>.json")
|
|
833
|
+
.option("--locales <list>", "comma-separated locales", "en")
|
|
834
|
+
.option("--default <locale>", "default locale (default: the first of --locales)")
|
|
835
|
+
.option("--path <path>", "dictionary folder served by the app", "/locales")
|
|
836
|
+
.option("--dry-run", "show what would change, write nothing")
|
|
837
|
+
.action(async (options) => {
|
|
838
|
+
await runWithVersionCheck(async () => {
|
|
839
|
+
await translatorInit(options, getProjectRoot(import.meta.url));
|
|
840
|
+
});
|
|
841
|
+
});
|
|
842
|
+
|
|
843
|
+
translatorCommand
|
|
844
|
+
.command("check")
|
|
845
|
+
.description("Verify every data-t / slice.t() key exists in every locale")
|
|
846
|
+
.option("--unused", "also report dictionary keys no template or call uses")
|
|
847
|
+
.action(async (options) => {
|
|
848
|
+
await runWithVersionCheck(async () => {
|
|
849
|
+
await translatorCheck(options, getProjectRoot(import.meta.url));
|
|
850
|
+
});
|
|
851
|
+
});
|
|
852
|
+
|
|
822
853
|
// POSTINSTALL COMMAND - Configure npm scripts in existing project
|
|
823
854
|
sliceClient
|
|
824
855
|
.command("postinstall")
|
|
@@ -14,8 +14,57 @@ import { rangeMismatch } from '../utils/semver.js';
|
|
|
14
14
|
import { parse as parseModule } from '@babel/parser';
|
|
15
15
|
import traverse from '@babel/traverse';
|
|
16
16
|
import ExternalModuleBundler from '../utils/bundling/ExternalModuleBundler.js';
|
|
17
|
-
import { loadFrameworkSeo, loadManifest } from '../seo/support.js';
|
|
17
|
+
import { loadFrameworkSeo, loadManifest, loadSeoTranslator } from '../seo/support.js';
|
|
18
18
|
import { loadRoutes } from '../seo/check.js';
|
|
19
|
+
import { checkProject as checkTranslatorProject } from '../translator/scan.js';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Translator: is it configured, and does every key on the page exist in every locale?
|
|
23
|
+
* Same scan as `slice translator check`, so the row and the command cannot disagree.
|
|
24
|
+
*/
|
|
25
|
+
async function checkTranslatorConfiguration() {
|
|
26
|
+
const projectRoot = getProjectRoot(import.meta.url);
|
|
27
|
+
|
|
28
|
+
let result;
|
|
29
|
+
try {
|
|
30
|
+
result = await checkTranslatorProject(projectRoot);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
return {
|
|
33
|
+
message: `Translator check could not run: ${error.message}`,
|
|
34
|
+
suggestion: 'Update slicejs-web-framework (the template rules live in Translator/dom.js)'
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!result.config?.enabled) {
|
|
39
|
+
return {
|
|
40
|
+
warn: true,
|
|
41
|
+
message: 'Not configured: data-t and slice.t() fall back to the key',
|
|
42
|
+
suggestion: 'Run `slice translator init`'
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (result.errors.length) {
|
|
47
|
+
return {
|
|
48
|
+
message: `${result.errors.length} problem(s): ${result.errors[0]}`,
|
|
49
|
+
suggestion: result.errors.length > 1 ? `${result.errors[1]} (run \`slice translator check\`)` : 'Run `slice translator check`'
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (result.warnings.length) {
|
|
54
|
+
return {
|
|
55
|
+
warn: true,
|
|
56
|
+
message: `${result.entries.length} key(s) x ${result.locales.length} locale(s)${contentSuffix(result)}, ${result.warnings.length} warning(s): ${result.warnings[0]}`,
|
|
57
|
+
suggestion: 'Run `slice translator check` for the full list'
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return { pass: true, message: `${result.entries.length} key(s) across ${result.locales.length} locale(s)${contentSuffix(result)}` };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `, 2 content document(s)` when the app has content documents. */
|
|
65
|
+
function contentSuffix(result) {
|
|
66
|
+
return result.contentCount ? `, ${result.contentCount} content document(s)` : '';
|
|
67
|
+
}
|
|
19
68
|
|
|
20
69
|
/**
|
|
21
70
|
* SEO: is it configured, and is it safe to deploy?
|
|
@@ -58,9 +107,11 @@ async function checkSeoConfiguration() {
|
|
|
58
107
|
}
|
|
59
108
|
|
|
60
109
|
const routes = await loadRoutes(projectRoot).catch(() => []);
|
|
110
|
+
const translator = await loadSeoTranslator(projectRoot, framework);
|
|
61
111
|
const { errors, warnings } = framework.validateSeoManifest(manifest, {
|
|
62
112
|
routes,
|
|
63
|
-
publicDir: path.join(projectRoot, 'src', 'public')
|
|
113
|
+
publicDir: path.join(projectRoot, 'src', 'public'),
|
|
114
|
+
translator
|
|
64
115
|
});
|
|
65
116
|
|
|
66
117
|
// The sitemap is a committed artifact, so a stale one is a deploy problem.
|
|
@@ -69,7 +120,7 @@ async function checkSeoConfiguration() {
|
|
|
69
120
|
const origin = framework.normalizeOrigin(manifest.origin);
|
|
70
121
|
if (!fs.existsSync(sitemapFile)) {
|
|
71
122
|
warnings.push('sitemap.xml is missing: run `slice seo sitemap`');
|
|
72
|
-
} else if (origin && fs.readFileSync(sitemapFile, 'utf8') !== framework.buildSitemap({ manifest, origin })) {
|
|
123
|
+
} else if (origin && fs.readFileSync(sitemapFile, 'utf8') !== framework.buildSitemap({ manifest, origin, translator })) {
|
|
73
124
|
warnings.push('sitemap.xml is out of date: run `slice seo sitemap`');
|
|
74
125
|
}
|
|
75
126
|
}
|
|
@@ -574,6 +625,7 @@ export {
|
|
|
574
625
|
checkDirectoryStructure,
|
|
575
626
|
checkConfig,
|
|
576
627
|
checkSeoConfiguration,
|
|
628
|
+
checkTranslatorConfiguration,
|
|
577
629
|
checkPort,
|
|
578
630
|
checkDependencies,
|
|
579
631
|
checkComponents,
|
|
@@ -591,6 +643,7 @@ export default async function runDiagnostics() {
|
|
|
591
643
|
{ name: 'Project Structure', fn: checkDirectoryStructure },
|
|
592
644
|
{ name: 'Configuration', fn: checkConfig },
|
|
593
645
|
{ name: 'SEO', fn: checkSeoConfiguration },
|
|
646
|
+
{ name: 'Translator', fn: checkTranslatorConfiguration },
|
|
594
647
|
{ name: 'Port Availability', fn: checkPort },
|
|
595
648
|
{ name: 'Package Manager', fn: checkPackageManagerSetup },
|
|
596
649
|
{ name: 'Dependencies', fn: checkDependencies },
|
|
@@ -186,11 +186,9 @@ filterOfficialComponents(allComponents) {
|
|
|
186
186
|
// Logical routing components only need JS
|
|
187
187
|
if (['Route', 'MultiRoute', 'Link'].includes(name)) {
|
|
188
188
|
files = [`${name}.js`];
|
|
189
|
-
} else if (name === 'Icon') {
|
|
190
|
-
// Icon component needs font files to render glyphs
|
|
191
|
-
files = [`${name}.js`, `${name}.html`, `${name}.css`, 'slc.eot', 'slc.woff2', 'slc.woff', 'slc.ttf', 'slc.svg'];
|
|
192
189
|
} else {
|
|
193
|
-
// Normal visual components need JS, HTML, CSS
|
|
190
|
+
// Normal visual components need JS, HTML, CSS (Icon draws inline SVG; its
|
|
191
|
+
// icons.generated.js arrives as a relative import, like any helper).
|
|
194
192
|
files = [`${name}.js`, `${name}.html`, `${name}.css`];
|
|
195
193
|
}
|
|
196
194
|
} else {
|
|
@@ -504,8 +502,9 @@ filterOfficialComponents(allComponents) {
|
|
|
504
502
|
try {
|
|
505
503
|
content = await fetchWithRetry(url, 3, 500, false);
|
|
506
504
|
} catch (error) {
|
|
507
|
-
|
|
508
|
-
|
|
505
|
+
// A component whose helper is missing installs as a broken import. Fail the install
|
|
506
|
+
// instead of printing "installed successfully".
|
|
507
|
+
throw new Error(`Could not download helper module '${repoRelPath}': ${error.message}`, { cause: error });
|
|
509
508
|
}
|
|
510
509
|
|
|
511
510
|
await fs.ensureDir(path.dirname(localPath));
|
package/commands/seo/check.js
CHANGED
|
@@ -14,7 +14,8 @@ import {
|
|
|
14
14
|
MANIFEST_FILE,
|
|
15
15
|
SITEMAP_FILE,
|
|
16
16
|
loadFrameworkSeo,
|
|
17
|
-
loadManifest
|
|
17
|
+
loadManifest,
|
|
18
|
+
loadSeoTranslator
|
|
18
19
|
} from './support.js';
|
|
19
20
|
|
|
20
21
|
export async function loadRoutes(projectRoot) {
|
|
@@ -42,9 +43,11 @@ export async function checkSeo(options = {}) {
|
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
const routes = options.routes || await loadRoutes(projectRoot);
|
|
46
|
+
const translator = options.translator ?? await loadSeoTranslator(projectRoot, framework);
|
|
45
47
|
const { errors, warnings } = framework.validateSeoManifest(manifest, {
|
|
46
48
|
routes,
|
|
47
|
-
publicDir: path.join(projectRoot, 'src', 'public')
|
|
49
|
+
publicDir: path.join(projectRoot, 'src', 'public'),
|
|
50
|
+
translator
|
|
48
51
|
});
|
|
49
52
|
|
|
50
53
|
let sitemap = 'ok';
|
|
@@ -57,7 +60,7 @@ export async function checkSeo(options = {}) {
|
|
|
57
60
|
errors.push(`${SITEMAP_FILE} is missing: run \`slice seo sitemap\``);
|
|
58
61
|
} else {
|
|
59
62
|
const origin = framework.normalizeOrigin(manifest.origin);
|
|
60
|
-
const expected = origin ? framework.buildSitemap({ manifest, origin }) : null;
|
|
63
|
+
const expected = origin ? framework.buildSitemap({ manifest, origin, translator }) : null;
|
|
61
64
|
if (expected !== null && fs.readFileSync(file, 'utf8') !== expected) {
|
|
62
65
|
sitemap = 'drifted';
|
|
63
66
|
errors.push(`${SITEMAP_FILE} is out of date: run \`slice seo sitemap\``);
|
package/commands/seo/images.js
CHANGED
|
@@ -15,7 +15,7 @@ import { createHash } from 'node:crypto';
|
|
|
15
15
|
import { createRequire } from 'node:module';
|
|
16
16
|
import { pathToFileURL } from 'node:url';
|
|
17
17
|
import Print from '../Print.js';
|
|
18
|
-
import { loadManifest, writeFileConfirmed } from './support.js';
|
|
18
|
+
import { loadFrameworkSeo, loadManifest, loadSeoTranslator, writeFileConfirmed } from './support.js';
|
|
19
19
|
|
|
20
20
|
const CARD = { width: 1200, height: 630 };
|
|
21
21
|
const DEVICE_SCALE = 2;
|
|
@@ -88,6 +88,29 @@ export function selectRoutes(manifest, only = null) {
|
|
|
88
88
|
.sort((a, b) => a.route.localeCompare(b.route));
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* One card target per route — or per route and locale when the translator puts the locale
|
|
93
|
+
* in the URL. `url` is both what the browser captures and the key in the cards manifest,
|
|
94
|
+
* so the server can pick the card for the exact page it is serving.
|
|
95
|
+
*/
|
|
96
|
+
export function cardTargets(manifest, translator = null, only = null) {
|
|
97
|
+
const wanted = only ? new Set(String(only).split(',').map((item) => item.trim())) : null;
|
|
98
|
+
const locales = translator?.enabled
|
|
99
|
+
? (translator.localePrefix ? translator.locales : [translator.defaultLocale])
|
|
100
|
+
: [null];
|
|
101
|
+
const targets = [];
|
|
102
|
+
|
|
103
|
+
for (const { route, meta } of selectRoutes(manifest, null)) {
|
|
104
|
+
for (const locale of locales) {
|
|
105
|
+
const url = translator?.enabled ? translator.localize(route, locale) : route;
|
|
106
|
+
if (wanted && !wanted.has(route) && !wanted.has(url)) continue;
|
|
107
|
+
targets.push({ route, url, locale, meta });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return targets;
|
|
112
|
+
}
|
|
113
|
+
|
|
91
114
|
/** Neutral 1200×630 card. `template` replaces it entirely. */
|
|
92
115
|
export function buildCardHtml({ title, route, host, imageData, dark = false, template = null }) {
|
|
93
116
|
if (template) {
|
|
@@ -358,8 +381,22 @@ export async function generateImages(options = {}) {
|
|
|
358
381
|
...(options.selector ? { selector: options.selector } : {}),
|
|
359
382
|
...(options.outDir || options.out ? { outDir: options.outDir || options.out } : {})
|
|
360
383
|
};
|
|
361
|
-
|
|
362
|
-
|
|
384
|
+
|
|
385
|
+
// The translator is optional: an older framework, or a project that has not enabled it,
|
|
386
|
+
// yields one single-language target per route and the old manifest keys.
|
|
387
|
+
let frameworkSeo = options.framework || null;
|
|
388
|
+
let translator = options.translator ?? null;
|
|
389
|
+
if (translator === null) {
|
|
390
|
+
try {
|
|
391
|
+
frameworkSeo = frameworkSeo || await loadFrameworkSeo(projectRoot);
|
|
392
|
+
translator = await loadSeoTranslator(projectRoot, frameworkSeo);
|
|
393
|
+
} catch {
|
|
394
|
+
translator = null;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const targets = cardTargets(manifest, translator, only);
|
|
399
|
+
if (!targets.length) {
|
|
363
400
|
return { errors: [`no indexable route matched${only ? ` --only=${only}` : ''}`], files: [], patched: null };
|
|
364
401
|
}
|
|
365
402
|
|
|
@@ -409,15 +446,24 @@ export async function generateImages(options = {}) {
|
|
|
409
446
|
locale: config.locale || 'en-US'
|
|
410
447
|
});
|
|
411
448
|
|
|
412
|
-
for (const
|
|
449
|
+
for (const target of targets) {
|
|
413
450
|
const page = await captureContext.newPage();
|
|
414
451
|
const cardPage = await cardContext.newPage();
|
|
415
452
|
try {
|
|
416
453
|
await page.clock?.setFixedTime?.(FIXED_TIME).catch?.(() => {});
|
|
417
|
-
const capture = await captureRoute(page, {
|
|
454
|
+
const capture = await captureRoute(page, {
|
|
455
|
+
baseUrl,
|
|
456
|
+
route: target.url,
|
|
457
|
+
selector: config.selector,
|
|
458
|
+
runner: runnerModule
|
|
459
|
+
});
|
|
460
|
+
const rawTitle = translator?.enabled
|
|
461
|
+
? frameworkSeo?.resolveSeoText?.(target.meta.title, (key, params) => translator.t(target.locale || translator.defaultLocale, key, params))
|
|
462
|
+
: target.meta.title;
|
|
463
|
+
const title = typeof rawTitle === 'string' && rawTitle ? rawTitle : target.route;
|
|
418
464
|
const card = await encodeCard(cardPage, {
|
|
419
|
-
title
|
|
420
|
-
route,
|
|
465
|
+
title,
|
|
466
|
+
route: target.url,
|
|
421
467
|
host,
|
|
422
468
|
shot: capture.shot,
|
|
423
469
|
kind: capture.kind,
|
|
@@ -426,7 +472,8 @@ export async function generateImages(options = {}) {
|
|
|
426
472
|
});
|
|
427
473
|
|
|
428
474
|
const hash = createHash('sha256').update(card.buffer).digest('hex').slice(0, 10);
|
|
429
|
-
const
|
|
475
|
+
const prefix = target.locale ? `${target.locale}-` : '';
|
|
476
|
+
const fileName = `${prefix}${routeSlug(target.route)}-${hash}${card.ext}`;
|
|
430
477
|
const file = path.join(outDir, fileName);
|
|
431
478
|
|
|
432
479
|
if (card.buffer.length > budgetBytes) {
|
|
@@ -438,7 +485,7 @@ export async function generateImages(options = {}) {
|
|
|
438
485
|
if (!fs.existsSync(file)) await fsp.writeFile(file, card.buffer);
|
|
439
486
|
}
|
|
440
487
|
|
|
441
|
-
images[
|
|
488
|
+
images[target.url] = {
|
|
442
489
|
path: `/og/${fileName}`,
|
|
443
490
|
width: CARD.width,
|
|
444
491
|
height: CARD.height,
|
|
@@ -446,10 +493,10 @@ export async function generateImages(options = {}) {
|
|
|
446
493
|
bytes: card.buffer.length,
|
|
447
494
|
kind: capture.kind
|
|
448
495
|
};
|
|
449
|
-
files.push({ route, file, status: dryRun ? 'would-write' : 'written', bytes: card.buffer.length });
|
|
496
|
+
files.push({ route: target.url, file, status: dryRun ? 'would-write' : 'written', bytes: card.buffer.length });
|
|
450
497
|
} catch (error) {
|
|
451
498
|
failed += 1;
|
|
452
|
-
files.push({ route, status: 'failed', error: error.message });
|
|
499
|
+
files.push({ route: target.url, status: 'failed', error: error.message });
|
|
453
500
|
} finally {
|
|
454
501
|
await page.close();
|
|
455
502
|
await cardPage.close();
|
|
@@ -506,7 +553,7 @@ const readExistingManifest = (outDir) => {
|
|
|
506
553
|
};
|
|
507
554
|
|
|
508
555
|
/** `--check`: no browser, no server. Every indexable route must have a card that fits. */
|
|
509
|
-
export function checkImages({ projectRoot, only = null }) {
|
|
556
|
+
export function checkImages({ projectRoot, only = null, translator = null }) {
|
|
510
557
|
const { manifest } = loadManifest(projectRoot);
|
|
511
558
|
if (!manifest) return { errors: ['seo.json not found'], checks: [] };
|
|
512
559
|
|
|
@@ -515,24 +562,24 @@ export function checkImages({ projectRoot, only = null }) {
|
|
|
515
562
|
const outDir = path.isAbsolute(configuredOut) ? configuredOut : path.join(projectRoot, configuredOut);
|
|
516
563
|
const budgetBytes = Math.round((config.budgetKB || DEFAULT_BUDGET_KB) * 1024);
|
|
517
564
|
const cards = readExistingManifest(outDir)?.images || {};
|
|
518
|
-
const
|
|
565
|
+
const targets = cardTargets(manifest, translator, only);
|
|
519
566
|
const errors = [];
|
|
520
567
|
const checks = [];
|
|
521
568
|
|
|
522
|
-
for (const {
|
|
523
|
-
const card = cards[
|
|
524
|
-
if (!card) { errors.push(`${
|
|
569
|
+
for (const { url } of targets) {
|
|
570
|
+
const card = cards[url];
|
|
571
|
+
if (!card) { errors.push(`${url} has no card: run \`slice seo images\``); continue; }
|
|
525
572
|
const file = path.join(projectRoot, config.outDir || DEFAULT_OUT_DIR, path.basename(card.path));
|
|
526
|
-
if (!fs.existsSync(file)) { errors.push(`${
|
|
573
|
+
if (!fs.existsSync(file)) { errors.push(`${url}: missing ${card.path}`); continue; }
|
|
527
574
|
const buffer = fs.readFileSync(file);
|
|
528
575
|
const size = imageSize(buffer);
|
|
529
576
|
if (size.width !== CARD.width || size.height !== CARD.height) {
|
|
530
|
-
errors.push(`${
|
|
577
|
+
errors.push(`${url}: ${size.width}×${size.height}, expected ${CARD.width}×${CARD.height}`);
|
|
531
578
|
}
|
|
532
579
|
if (buffer.length > budgetBytes) {
|
|
533
|
-
errors.push(`${
|
|
580
|
+
errors.push(`${url}: ${(buffer.length / 1024).toFixed(1)} KB over the budget`);
|
|
534
581
|
}
|
|
535
|
-
checks.push(
|
|
582
|
+
checks.push(url);
|
|
536
583
|
}
|
|
537
584
|
|
|
538
585
|
return { errors, checks };
|
|
@@ -551,7 +598,15 @@ const STATUS = {
|
|
|
551
598
|
export default async function imagesCommand(options = {}, projectRoot) {
|
|
552
599
|
try {
|
|
553
600
|
if (options.check) {
|
|
554
|
-
|
|
601
|
+
let translator = options.translator ?? null;
|
|
602
|
+
if (translator === null) {
|
|
603
|
+
try {
|
|
604
|
+
translator = await loadSeoTranslator(projectRoot, await loadFrameworkSeo(projectRoot));
|
|
605
|
+
} catch {
|
|
606
|
+
translator = null;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
const result = checkImages({ projectRoot, only: options.only, translator });
|
|
555
610
|
if (result.errors.length) {
|
|
556
611
|
for (const error of result.errors) Print.error(error);
|
|
557
612
|
Print.error(`SEO images check failed: ${result.errors.length} problem(s).`);
|
package/commands/seo/sitemap.js
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
buildRobotsTxt,
|
|
15
15
|
loadFrameworkSeo,
|
|
16
16
|
loadManifest,
|
|
17
|
+
loadSeoTranslator,
|
|
17
18
|
writeFileConfirmed
|
|
18
19
|
} from './support.js';
|
|
19
20
|
|
|
@@ -33,7 +34,8 @@ export async function generateSeoFiles(options = {}) {
|
|
|
33
34
|
}
|
|
34
35
|
|
|
35
36
|
const { errors, warnings } = framework.validateSeoManifest(manifest, {
|
|
36
|
-
publicDir: path.join(projectRoot, 'src', 'public')
|
|
37
|
+
publicDir: path.join(projectRoot, 'src', 'public'),
|
|
38
|
+
translator: await loadSeoTranslator(projectRoot, framework)
|
|
37
39
|
});
|
|
38
40
|
|
|
39
41
|
// A sitemap written with localhost URLs is a deploy bug, not a warning.
|
|
@@ -43,11 +45,12 @@ export async function generateSeoFiles(options = {}) {
|
|
|
43
45
|
if (errors.length) return { errors, warnings, files: [] };
|
|
44
46
|
|
|
45
47
|
const origin = framework.normalizeOrigin(manifest.origin);
|
|
48
|
+
const translator = await loadSeoTranslator(projectRoot, framework);
|
|
46
49
|
const files = [];
|
|
47
50
|
|
|
48
51
|
files.push(await writeFileConfirmed(
|
|
49
52
|
path.join(projectRoot, SITEMAP_FILE),
|
|
50
|
-
framework.buildSitemap({ manifest, origin }),
|
|
53
|
+
framework.buildSitemap({ manifest, origin, translator }),
|
|
51
54
|
{ yes, dryRun, confirm }
|
|
52
55
|
));
|
|
53
56
|
|
package/commands/seo/support.js
CHANGED
|
@@ -12,6 +12,68 @@ export const MANIFEST_FILE = 'seo.json';
|
|
|
12
12
|
export const SITEMAP_FILE = path.join('src', 'public', 'sitemap.xml');
|
|
13
13
|
export const ROBOTS_FILE = path.join('src', 'public', 'robots.txt');
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* The app's translator (config + dictionaries) as the framework's SEO context, or null
|
|
17
|
+
* for a single-language app / an older framework. `src` wins over `dist`: the CLI reads
|
|
18
|
+
* the authoring copy.
|
|
19
|
+
*/
|
|
20
|
+
export async function loadSeoTranslator(projectRoot, framework) {
|
|
21
|
+
let translator = null;
|
|
22
|
+
for (const folder of ['src', 'dist']) {
|
|
23
|
+
const file = path.join(projectRoot, folder, 'sliceConfig.json');
|
|
24
|
+
if (!fs.existsSync(file)) continue;
|
|
25
|
+
try {
|
|
26
|
+
translator = JSON.parse(fs.readFileSync(file, 'utf8')).translator || null;
|
|
27
|
+
} catch {
|
|
28
|
+
translator = null;
|
|
29
|
+
}
|
|
30
|
+
if (translator) break;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (translator?.enabled !== true || typeof framework?.buildTranslatorContext !== 'function') {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const folder = String(translator.path || '/locales').replace(/^\/+|\/+$/g, '') || 'locales';
|
|
38
|
+
const locales = [
|
|
39
|
+
translator.defaultLocale,
|
|
40
|
+
...(Array.isArray(translator.locales) ? translator.locales : []),
|
|
41
|
+
translator.fallbackLocale
|
|
42
|
+
].filter((value) => typeof value === 'string' && value);
|
|
43
|
+
|
|
44
|
+
const dictionaries = {};
|
|
45
|
+
for (const locale of [...new Set(locales)]) {
|
|
46
|
+
for (const base of ['src', 'dist']) {
|
|
47
|
+
const root = path.join(projectRoot, base, folder);
|
|
48
|
+
const file = path.join(root, `${locale}.json`);
|
|
49
|
+
const namespaceDir = path.join(root, locale);
|
|
50
|
+
if (!fs.existsSync(file) && !fs.existsSync(namespaceDir)) continue;
|
|
51
|
+
let messages = {};
|
|
52
|
+
if (fs.existsSync(file)) {
|
|
53
|
+
try {
|
|
54
|
+
messages = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new Error(`invalid translator dictionary ${path.join(base, folder, `${locale}.json`)}: ${error.message}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (fs.existsSync(namespaceDir) && fs.statSync(namespaceDir).isDirectory()) {
|
|
60
|
+
for (const name of fs.readdirSync(namespaceDir)) {
|
|
61
|
+
if (!name.endsWith('.json')) continue;
|
|
62
|
+
try {
|
|
63
|
+
messages[name.slice(0, -5)] = JSON.parse(fs.readFileSync(path.join(namespaceDir, name), 'utf8'));
|
|
64
|
+
} catch (error) {
|
|
65
|
+
throw new Error(`invalid translator dictionary ${path.join(base, folder, locale, name)}: ${error.message}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
dictionaries[locale] = messages;
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return framework.buildTranslatorContext(translator, dictionaries);
|
|
75
|
+
}
|
|
76
|
+
|
|
15
77
|
export const resolveRoot = (moduleUrl) => getProjectRoot(moduleUrl);
|
|
16
78
|
|
|
17
79
|
/**
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// `slice translator check` — the strict gate: every key a template or a `slice.t()` call
|
|
2
|
+
// needs must exist in every locale (a missing key ships as the key on screen).
|
|
3
|
+
//
|
|
4
|
+
// The scan reuses the framework's template rules and the dictionaries the app ships, so
|
|
5
|
+
// this command and the browser cannot disagree about what a `data-t` element needs.
|
|
6
|
+
|
|
7
|
+
import Print from '../Print.js';
|
|
8
|
+
import { checkProject } from './scan.js';
|
|
9
|
+
|
|
10
|
+
export default async function checkCommand(options = {}, projectRoot) {
|
|
11
|
+
try {
|
|
12
|
+
const result = await checkProject(projectRoot, options);
|
|
13
|
+
|
|
14
|
+
for (const warning of result.warnings) Print.warning(warning);
|
|
15
|
+
|
|
16
|
+
if (result.errors.length) {
|
|
17
|
+
for (const error of result.errors) Print.error(error);
|
|
18
|
+
Print.error(`Translator check failed: ${result.errors.length} problem(s).`);
|
|
19
|
+
process.exitCode = 1;
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
Print.success(
|
|
24
|
+
`Translator OK: ${result.entries.length} key reference(s) across ${result.locales.length} locale(s)` +
|
|
25
|
+
` (${result.dictionaryCount} dictionaries` +
|
|
26
|
+
`${result.contentCount ? `, ${result.contentCount} content document(s)` : ''}).`
|
|
27
|
+
);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
Print.error('slice translator check failed:', error.message);
|
|
30
|
+
process.exitCode = 1;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// `slice translator init` — add the translator block to sliceConfig and create the
|
|
2
|
+
// dictionaries folder. Idempotent: existing values and files are never overwritten.
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import Print from '../Print.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @returns {{ errors: string[], files: Array<{file: string, status: string}>, configFile: string }}
|
|
10
|
+
*/
|
|
11
|
+
export function initTranslatorFiles(options = {}) {
|
|
12
|
+
const { projectRoot, dryRun = false, localePath = '/locales' } = options;
|
|
13
|
+
const locales = (Array.isArray(options.locales) ? options.locales : [options.locales || 'en'])
|
|
14
|
+
.map((value) => String(value).trim())
|
|
15
|
+
.filter(Boolean);
|
|
16
|
+
const defaultLocale = options.defaultLocale || locales[0] || 'en';
|
|
17
|
+
const errors = [];
|
|
18
|
+
const files = [];
|
|
19
|
+
|
|
20
|
+
const configFile = path.join(projectRoot, 'src', 'sliceConfig.json');
|
|
21
|
+
if (!fs.existsSync(configFile)) {
|
|
22
|
+
return { errors: ['src/sliceConfig.json not found: run `slice init` first'], files, configFile };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let config;
|
|
26
|
+
try {
|
|
27
|
+
config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
|
|
28
|
+
} catch (error) {
|
|
29
|
+
return { errors: [`src/sliceConfig.json is not valid JSON: ${error.message}`], files, configFile };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const existing = config.translator && typeof config.translator === 'object' ? config.translator : null;
|
|
33
|
+
const declared = [...new Set([
|
|
34
|
+
existing?.defaultLocale || defaultLocale,
|
|
35
|
+
...(Array.isArray(existing?.locales) ? existing.locales : []),
|
|
36
|
+
...locales
|
|
37
|
+
])];
|
|
38
|
+
const translator = existing
|
|
39
|
+
? {
|
|
40
|
+
...existing,
|
|
41
|
+
// Re-running init must not turn a deliberately disabled translator back on.
|
|
42
|
+
enabled: existing.enabled !== undefined ? existing.enabled : true,
|
|
43
|
+
defaultLocale: existing.defaultLocale || defaultLocale,
|
|
44
|
+
locales: declared,
|
|
45
|
+
path: existing.path || localePath
|
|
46
|
+
}
|
|
47
|
+
: {
|
|
48
|
+
enabled: true,
|
|
49
|
+
defaultLocale,
|
|
50
|
+
locales: declared,
|
|
51
|
+
path: localePath,
|
|
52
|
+
saveLocally: true,
|
|
53
|
+
useBrowserLocale: true,
|
|
54
|
+
localePrefix: false
|
|
55
|
+
};
|
|
56
|
+
const next = { ...config, translator };
|
|
57
|
+
|
|
58
|
+
const before = fs.readFileSync(configFile, 'utf8');
|
|
59
|
+
const after = `${JSON.stringify(next, null, 2)}\n`;
|
|
60
|
+
const alreadyConfigured = existing?.enabled === true
|
|
61
|
+
&& existing.defaultLocale
|
|
62
|
+
&& existing.path
|
|
63
|
+
&& Array.isArray(existing.locales)
|
|
64
|
+
&& JSON.stringify(existing.locales) === JSON.stringify(declared);
|
|
65
|
+
if (alreadyConfigured) {
|
|
66
|
+
// Nothing to add: never reformat a config that is already set up.
|
|
67
|
+
files.push({ file: configFile, status: 'unchanged' });
|
|
68
|
+
} else if (before !== after) {
|
|
69
|
+
if (!dryRun) fs.writeFileSync(configFile, after);
|
|
70
|
+
files.push({ file: configFile, status: dryRun ? 'would-change' : 'updated' });
|
|
71
|
+
} else {
|
|
72
|
+
files.push({ file: configFile, status: 'unchanged' });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const folder = String(next.translator.path || '/locales').replace(/^\/+|\/+$/g, '') || 'locales';
|
|
76
|
+
for (const locale of new Set([next.translator.defaultLocale, ...(next.translator.locales || [])])) {
|
|
77
|
+
const file = path.join(projectRoot, 'src', folder, `${locale}.json`);
|
|
78
|
+
if (fs.existsSync(file)) {
|
|
79
|
+
files.push({ file, status: 'exists' });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (!dryRun) {
|
|
83
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
84
|
+
fs.writeFileSync(file, '{}\n');
|
|
85
|
+
}
|
|
86
|
+
files.push({ file, status: dryRun ? 'would-create' : 'created' });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return { errors, files, configFile };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export default async function initCommand(options = {}, projectRoot) {
|
|
93
|
+
try {
|
|
94
|
+
const locales = String(options.locales || options.locale || 'en')
|
|
95
|
+
.split(',')
|
|
96
|
+
.map((value) => value.trim())
|
|
97
|
+
.filter(Boolean);
|
|
98
|
+
const result = initTranslatorFiles({
|
|
99
|
+
projectRoot,
|
|
100
|
+
locales,
|
|
101
|
+
defaultLocale: options.default,
|
|
102
|
+
localePath: options.path,
|
|
103
|
+
dryRun: options.dryRun === true
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
if (result.errors.length) {
|
|
107
|
+
for (const error of result.errors) Print.error(error);
|
|
108
|
+
process.exitCode = 1;
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
for (const entry of result.files) {
|
|
113
|
+
const name = path.relative(projectRoot, entry.file);
|
|
114
|
+
if (entry.status === 'created' || entry.status === 'updated') Print.success(`${name}: ${entry.status}`);
|
|
115
|
+
else if (entry.status === 'would-create' || entry.status === 'would-change') Print.info(`${name}: ${entry.status}`);
|
|
116
|
+
else Print.info(`${name}: ${entry.status}`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
Print.info('Dictionaries live in that folder; templates use data-t="key" and code uses slice.t("key").');
|
|
120
|
+
Print.info('Next: `slice translator check`.');
|
|
121
|
+
} catch (error) {
|
|
122
|
+
Print.error('slice translator init failed:', error.message);
|
|
123
|
+
process.exitCode = 1;
|
|
124
|
+
}
|
|
125
|
+
}
|