slicejs-cli 4.3.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/LICENSE +21 -21
- package/README.md +260 -257
- package/client.js +958 -823
- package/commands/Print.js +163 -163
- package/commands/Validations.js +92 -92
- package/commands/build/build.js +97 -107
- package/commands/buildProduction/buildProduction.js +613 -613
- package/commands/bundle/bundle.js +251 -239
- package/commands/createComponent/VisualComponentTemplate.js +55 -55
- package/commands/createComponent/createComponent.js +128 -128
- package/commands/deleteComponent/deleteComponent.js +81 -81
- package/commands/docs/docs.js +365 -365
- package/commands/doctor/doctor.js +730 -563
- package/commands/getComponent/getComponent.js +841 -842
- package/commands/init/init.js +526 -475
- package/commands/lint/lint.js +75 -0
- package/commands/lint/types.js +85 -0
- package/commands/listComponents/listComponents.js +172 -172
- package/commands/seo/check.js +94 -0
- package/commands/seo/images.js +641 -0
- package/commands/seo/sitemap.js +109 -0
- package/commands/seo/support.js +192 -0
- package/commands/setup/lint.js +151 -0
- package/commands/skill/skill.js +236 -236
- package/commands/startServer/startServer.js +240 -240
- package/commands/startServer/watchServer.js +66 -66
- package/commands/translator/check.js +32 -0
- package/commands/translator/init.js +125 -0
- package/commands/translator/scan.js +444 -0
- package/commands/typecheck/typecheck.js +83 -0
- package/commands/types/types.js +1378 -1097
- package/commands/utils/JsMinifier.js +230 -230
- package/commands/utils/LocalCliDelegation.js +78 -53
- package/commands/utils/PackageManager.js +148 -148
- package/commands/utils/PathHelper.js +87 -75
- package/commands/utils/ProjectValidation.js +274 -0
- package/commands/utils/SourceDiagnostics.js +201 -201
- package/commands/utils/VersionChecker.js +169 -169
- package/commands/utils/analyzeSource.js +77 -77
- package/commands/utils/bundling/BundleGenerator.js +3748 -3776
- package/commands/utils/bundling/DependencyAnalyzer.js +12 -2
- package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
- package/commands/utils/componentAudit.js +74 -0
- package/commands/utils/compressAssets.js +103 -103
- package/commands/utils/cssScope.js +83 -0
- package/commands/utils/loadConfig.js +31 -31
- package/commands/utils/semver.js +66 -0
- package/commands/utils/sliceConfigSchema.js +106 -0
- package/commands/utils/sliceScripts.js +48 -48
- package/commands/utils/updateManager.js +471 -471
- package/eslint-config.js +128 -0
- package/package.json +19 -13
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// `slice translator check` — find the failures that only show up as a key on screen.
|
|
2
|
+
//
|
|
3
|
+
// The template rules are the framework's own (`Translator/dom.js`), so the CLI and the
|
|
4
|
+
// browser cannot disagree about which keys a `data-t` element needs.
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { createRequire } from 'node:module';
|
|
9
|
+
import { pathToFileURL } from 'node:url';
|
|
10
|
+
|
|
11
|
+
const SKIP_DIRS = new Set(['node_modules', 'dist', '.git', 'locales', 'public']);
|
|
12
|
+
const SKIP_FILES = /(\.spec|\.test|\.generated)\.js$/i;
|
|
13
|
+
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Resolve the framework's `dom.js` from the project (the version the app runs) or from
|
|
18
|
+
* the CLI's own dependency. Returns null when neither has it (older framework).
|
|
19
|
+
*/
|
|
20
|
+
export async function loadTemplateRules(projectRoot) {
|
|
21
|
+
const candidates = [
|
|
22
|
+
path.join(projectRoot, 'node_modules', 'slicejs-web-framework', 'Slice', 'Components', 'Structural', 'Translator', 'dom.js')
|
|
23
|
+
];
|
|
24
|
+
try {
|
|
25
|
+
const entry = require.resolve('slicejs-web-framework');
|
|
26
|
+
candidates.push(path.resolve(path.dirname(entry), '..', 'Slice', 'Components', 'Structural', 'Translator', 'dom.js'));
|
|
27
|
+
} catch {
|
|
28
|
+
// not installed next to the CLI either
|
|
29
|
+
}
|
|
30
|
+
const file = candidates.find((candidate) => fs.existsSync(candidate));
|
|
31
|
+
if (!file) return null;
|
|
32
|
+
return import(pathToFileURL(file).href);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Resolve the framework's `content.js` (copy resolver + validator). Returns null when the
|
|
37
|
+
* installed framework is older and does not ship it, so content validation degrades to the
|
|
38
|
+
* file-existence check instead of failing the whole command.
|
|
39
|
+
*/
|
|
40
|
+
export async function loadContentRules(projectRoot) {
|
|
41
|
+
const candidates = [
|
|
42
|
+
path.join(projectRoot, 'node_modules', 'slicejs-web-framework', 'Slice', 'Components', 'Structural', 'Translator', 'content.js')
|
|
43
|
+
];
|
|
44
|
+
try {
|
|
45
|
+
const entry = require.resolve('slicejs-web-framework');
|
|
46
|
+
candidates.push(path.resolve(path.dirname(entry), '..', 'Slice', 'Components', 'Structural', 'Translator', 'content.js'));
|
|
47
|
+
} catch {
|
|
48
|
+
// not installed next to the CLI either
|
|
49
|
+
}
|
|
50
|
+
const file = candidates.find((candidate) => fs.existsSync(candidate));
|
|
51
|
+
if (!file) return null;
|
|
52
|
+
return import(pathToFileURL(file).href);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const ATTRIBUTE = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
56
|
+
function parseAttributes(source) {
|
|
57
|
+
const attributes = {};
|
|
58
|
+
for (const match of String(source ?? '').matchAll(ATTRIBUTE)) {
|
|
59
|
+
const name = match[1].toLowerCase();
|
|
60
|
+
attributes[name] = match[2] ?? match[3] ?? match[4] ?? '';
|
|
61
|
+
}
|
|
62
|
+
return attributes;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Every `data-t` key an HTML string needs: the element's text, the attribute keys
|
|
67
|
+
* (`key.ariaLabel`) and the `data-t-*` params used to resolve plurals.
|
|
68
|
+
* `rules` is the framework's dom.js module.
|
|
69
|
+
*/
|
|
70
|
+
export function scanHtml(html, rules, where = '') {
|
|
71
|
+
const entries = [];
|
|
72
|
+
for (const match of String(html).matchAll(/<([a-zA-Z][\w-]*)((?:\s+[^<>]*?)?)\/?>/g)) {
|
|
73
|
+
const tagName = match[1].toUpperCase();
|
|
74
|
+
const attributes = parseAttributes(match[2]);
|
|
75
|
+
if (!attributes['data-t']) continue;
|
|
76
|
+
|
|
77
|
+
const element = {
|
|
78
|
+
tagName,
|
|
79
|
+
hasAttribute: (name) => Object.prototype.hasOwnProperty.call(attributes, name),
|
|
80
|
+
getAttribute: (name) => (Object.prototype.hasOwnProperty.call(attributes, name) ? attributes[name] : null)
|
|
81
|
+
};
|
|
82
|
+
const keys = rules.templateKeys(element);
|
|
83
|
+
if (!keys) continue;
|
|
84
|
+
|
|
85
|
+
const params = Object.keys(attributes)
|
|
86
|
+
.filter((name) => name.startsWith('data-t-'))
|
|
87
|
+
.map((name) => name.slice(7))
|
|
88
|
+
.filter((name) => name && !rules.RESERVED_PARAMS.includes(name))
|
|
89
|
+
.map((name) => rules.camelCase(name));
|
|
90
|
+
|
|
91
|
+
if (keys.text) entries.push({ key: keys.text, where, kind: 'text', params });
|
|
92
|
+
for (const [attribute, key] of Object.entries(keys.attributes)) {
|
|
93
|
+
entries.push({ key, where, kind: 'attribute', attribute, params });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return entries;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** `slice.t('key')`, `slice.t.ref('key')`, `slice.t.list('key')`, `slice.t.ref.list('key')`,
|
|
100
|
+
* `slice.translator.t('key')`, and local helpers named `tr()`/`translate()`. */
|
|
101
|
+
export function scanJs(source, where = '') {
|
|
102
|
+
const entries = [];
|
|
103
|
+
const pattern = /(?:slice\.t\.ref\.list|slice\.t\.list|slice\.t\.ref|(?:slice(?:\.translator)?|translator)\.(?:refList|t|ref|list)|(?<![.\w$])(?:\$t|tr|translate))\(\s*(['"])([^'"]+)\1/g;
|
|
104
|
+
for (const match of String(source).matchAll(pattern)) {
|
|
105
|
+
const call = match[0];
|
|
106
|
+
entries.push({
|
|
107
|
+
key: match[2],
|
|
108
|
+
where,
|
|
109
|
+
kind: /\.list\s*\(/.test(call) || /\.refList\s*\(/.test(call) ? 'list' : 'code'
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return entries;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** `slice.t.content('name')`: a content document, not a dictionary key. */
|
|
116
|
+
export function scanContentCalls(source, where = '') {
|
|
117
|
+
const calls = [];
|
|
118
|
+
const pattern = /(?:slice\.t|slice\.translator|translator)\.content\(\s*(['"])([^'"]+)\1/g;
|
|
119
|
+
for (const match of String(source).matchAll(pattern)) {
|
|
120
|
+
calls.push({ name: match[2], where });
|
|
121
|
+
}
|
|
122
|
+
return calls;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Raw `href="/path"` inside an anchor (they lose the locale with routing on). */
|
|
126
|
+
export function scanRawHrefs(html) {
|
|
127
|
+
const hrefs = [];
|
|
128
|
+
for (const tag of String(html).matchAll(/<a\b[^>]*>/gi)) {
|
|
129
|
+
const match = /\bhref\s*=\s*(['"])(\/[^'"]*)\1/i.exec(tag[0]);
|
|
130
|
+
if (!match) continue;
|
|
131
|
+
const href = match[2];
|
|
132
|
+
if (href.startsWith('//') || href.startsWith('{{')) continue;
|
|
133
|
+
hrefs.push(href);
|
|
134
|
+
}
|
|
135
|
+
return hrefs;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function walk(directory, files = []) {
|
|
139
|
+
if (!fs.existsSync(directory)) return files;
|
|
140
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
141
|
+
if (entry.isDirectory()) {
|
|
142
|
+
if (SKIP_DIRS.has(entry.name)) continue;
|
|
143
|
+
walk(path.join(directory, entry.name), files);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (SKIP_FILES.test(entry.name)) continue;
|
|
147
|
+
if (/\.(html|js)$/i.test(entry.name)) files.push(path.join(directory, entry.name));
|
|
148
|
+
}
|
|
149
|
+
return files;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Every `.html`/`.js` the app ships (never `locales/`, `public/` or `node_modules/`). */
|
|
153
|
+
export function sourceFiles(projectRoot) {
|
|
154
|
+
const src = path.join(projectRoot, 'src');
|
|
155
|
+
const files = new Set(walk(path.join(src, 'Components')));
|
|
156
|
+
for (const extra of [path.join(src, 'App', 'index.html'), path.join(src, 'App', 'index.js'), path.join(src, 'routes.js')]) {
|
|
157
|
+
if (fs.existsSync(extra)) files.add(extra);
|
|
158
|
+
}
|
|
159
|
+
return [...files].sort();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Read every source file and collect the keys, the raw hrefs and the dictionaries. */
|
|
163
|
+
export async function collectProject(projectRoot, options = {}) {
|
|
164
|
+
const rules = options.rules || await loadTemplateRules(projectRoot);
|
|
165
|
+
if (!rules) {
|
|
166
|
+
throw new Error('The installed slicejs-web-framework has no Translator/template rules: update the framework.');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const entries = [];
|
|
170
|
+
const rawHrefs = [];
|
|
171
|
+
const templates = [];
|
|
172
|
+
const contentCalls = [];
|
|
173
|
+
for (const file of sourceFiles(projectRoot)) {
|
|
174
|
+
const where = path.relative(projectRoot, file);
|
|
175
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
176
|
+
if (file.endsWith('.html')) {
|
|
177
|
+
templates.push({ file, where, content });
|
|
178
|
+
entries.push(...scanHtml(content, rules, where));
|
|
179
|
+
for (const href of scanRawHrefs(content)) rawHrefs.push({ where, href });
|
|
180
|
+
} else {
|
|
181
|
+
entries.push(...scanJs(content, where));
|
|
182
|
+
contentCalls.push(...scanContentCalls(content, where));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const config = readTranslatorConfig(projectRoot);
|
|
187
|
+
const dictionaries = config?.enabled ? readDictionaries(projectRoot, config) : {};
|
|
188
|
+
const content = config?.enabled ? readContentDocuments(projectRoot, config) : { documents: {}, errors: [] };
|
|
189
|
+
const contentRules = options.contentRules || await loadContentRules(projectRoot);
|
|
190
|
+
|
|
191
|
+
return { rules, config, dictionaries, entries, rawHrefs, templates, contentCalls, content, contentRules };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function readTranslatorConfig(projectRoot) {
|
|
195
|
+
for (const folder of ['src', 'dist']) {
|
|
196
|
+
const file = path.join(projectRoot, folder, 'sliceConfig.json');
|
|
197
|
+
if (!fs.existsSync(file)) continue;
|
|
198
|
+
try {
|
|
199
|
+
return JSON.parse(fs.readFileSync(file, 'utf8')).translator || null;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
throw new Error(`invalid ${folder}/sliceConfig.json: ${error.message}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function readDictionaries(projectRoot, config) {
|
|
208
|
+
const folder = String(config.path || '/locales').replace(/^\/+|\/+$/g, '') || 'locales';
|
|
209
|
+
const locales = [
|
|
210
|
+
config.defaultLocale,
|
|
211
|
+
...(Array.isArray(config.locales) ? config.locales : []),
|
|
212
|
+
config.fallbackLocale
|
|
213
|
+
].filter((value) => typeof value === 'string' && value);
|
|
214
|
+
|
|
215
|
+
const dictionaries = {};
|
|
216
|
+
for (const locale of [...new Set(locales)]) {
|
|
217
|
+
for (const base of ['src', 'dist']) {
|
|
218
|
+
const root = path.join(projectRoot, base, folder);
|
|
219
|
+
const file = path.join(root, `${locale}.json`);
|
|
220
|
+
const namespaceDir = path.join(root, locale);
|
|
221
|
+
if (!fs.existsSync(file) && !fs.existsSync(namespaceDir)) continue;
|
|
222
|
+
let messages = {};
|
|
223
|
+
if (fs.existsSync(file)) {
|
|
224
|
+
try {
|
|
225
|
+
messages = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
226
|
+
} catch (error) {
|
|
227
|
+
throw new Error(`invalid translator dictionary ${path.join(base, folder, `${locale}.json`)}: ${error.message}`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (fs.existsSync(namespaceDir) && fs.statSync(namespaceDir).isDirectory()) {
|
|
231
|
+
for (const name of fs.readdirSync(namespaceDir)) {
|
|
232
|
+
if (!name.endsWith('.json')) continue;
|
|
233
|
+
try {
|
|
234
|
+
messages[name.slice(0, -5)] = JSON.parse(fs.readFileSync(path.join(namespaceDir, name), 'utf8'));
|
|
235
|
+
} catch (error) {
|
|
236
|
+
throw new Error(`invalid translator dictionary ${path.join(base, folder, locale, name)}: ${error.message}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
dictionaries[locale] = messages;
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return dictionaries;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Every content document under `<path>/content/` (`src` wins over `dist`). Names are the
|
|
249
|
+
* file paths without `.json`, using `/` (`teaching`, `teaching/pr2`).
|
|
250
|
+
* @param {string} projectRoot
|
|
251
|
+
* @param {{ path?: string }} config
|
|
252
|
+
* @returns {{ documents: Record<string, any>, errors: string[] }}
|
|
253
|
+
*/
|
|
254
|
+
export function readContentDocuments(projectRoot, config) {
|
|
255
|
+
const folder = String(config.path || '/locales').replace(/^\/+|\/+$/g, '') || 'locales';
|
|
256
|
+
const documents = {};
|
|
257
|
+
const errors = [];
|
|
258
|
+
|
|
259
|
+
for (const base of ['src', 'dist']) {
|
|
260
|
+
const root = path.join(projectRoot, base, folder, 'content');
|
|
261
|
+
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) continue;
|
|
262
|
+
|
|
263
|
+
const walk = (directory) => {
|
|
264
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
265
|
+
const full = path.join(directory, entry.name);
|
|
266
|
+
if (entry.isDirectory()) {
|
|
267
|
+
walk(full);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (!entry.name.endsWith('.json')) continue;
|
|
271
|
+
const name = path.relative(root, full).split(path.sep).join('/').slice(0, -5);
|
|
272
|
+
try {
|
|
273
|
+
documents[name] = JSON.parse(fs.readFileSync(full, 'utf8'));
|
|
274
|
+
} catch (error) {
|
|
275
|
+
errors.push(`invalid content document ${path.relative(projectRoot, full)}: ${error.message}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
walk(root);
|
|
280
|
+
if (Object.keys(documents).length > 0 || errors.length > 0) break;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return { documents, errors };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function lookup(dictionary, key) { let node = dictionary;
|
|
287
|
+
for (const part of String(key).split('.')) {
|
|
288
|
+
if (!node || typeof node !== 'object' || !Object.prototype.hasOwnProperty.call(node, part)) return undefined;
|
|
289
|
+
node = node[part];
|
|
290
|
+
}
|
|
291
|
+
return node;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function flatten(dictionary, prefix = '', out = []) {
|
|
295
|
+
for (const [key, value] of Object.entries(dictionary || {})) {
|
|
296
|
+
const full = prefix ? `${prefix}.${key}` : key;
|
|
297
|
+
if (value && typeof value === 'object' && !Array.isArray(value) && typeof value.other !== 'string') {
|
|
298
|
+
flatten(value, full, out);
|
|
299
|
+
} else {
|
|
300
|
+
out.push(full);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return out;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const paramsOf = (text) => new Set([...String(text).matchAll(/\{([A-Za-z_$][\w$]*)\}/g)].map((match) => match[1]));
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The rules of the feature: missing key per locale, plural without `other`, params that
|
|
310
|
+
* differ between locales, dead keys and raw links that lose the locale.
|
|
311
|
+
*/
|
|
312
|
+
export function checkTranslations({ entries, dictionaries, config, rawHrefs = [], reportUnused = false, content = { documents: {}, errors: [] }, contentCalls = [], contentRules = null }) {
|
|
313
|
+
const errors = [];
|
|
314
|
+
const warnings = [];
|
|
315
|
+
const locales = config?.enabled
|
|
316
|
+
? [...new Set([config.defaultLocale, ...(config.locales || [])].filter(Boolean))]
|
|
317
|
+
: [];
|
|
318
|
+
|
|
319
|
+
if (!config?.enabled) {
|
|
320
|
+
return { errors: ['translator is not enabled in sliceConfig.json: run `slice translator init`'], warnings };
|
|
321
|
+
}
|
|
322
|
+
if (typeof config.defaultLocale !== 'string' || !config.defaultLocale.trim()) {
|
|
323
|
+
return {
|
|
324
|
+
errors: ['translator.enabled is true but defaultLocale is missing: the runtime stays disabled (set "defaultLocale" or "enabled": false)'],
|
|
325
|
+
warnings
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
if (locales.length === 0) {
|
|
329
|
+
return { errors: ['translator has no locales configured'], warnings };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const seen = new Set();
|
|
333
|
+
for (const entry of entries) {
|
|
334
|
+
// Library defaults (`slice.*`) are registered by the component itself in the
|
|
335
|
+
// translator's defaults layer; the app is not required to copy them.
|
|
336
|
+
if (entry.key.startsWith('slice.')) continue;
|
|
337
|
+
const id = `${entry.kind || 'code'}|${entry.key}|${entry.attribute || ''}`;
|
|
338
|
+
if (seen.has(id)) continue;
|
|
339
|
+
seen.add(id);
|
|
340
|
+
|
|
341
|
+
const where = `${entry.where}${entry.attribute ? ` (${entry.attribute})` : ''}`;
|
|
342
|
+
if (entry.kind === 'list') {
|
|
343
|
+
for (const locale of locales) {
|
|
344
|
+
const value = lookup(dictionaries[locale], entry.key)
|
|
345
|
+
?? lookup(dictionaries[config.fallbackLocale], entry.key);
|
|
346
|
+
if (value === undefined) errors.push(`missing list "${entry.key}" in "${locale}" (${where})`);
|
|
347
|
+
else if (!Array.isArray(value)) errors.push(`"${entry.key}" in "${locale}" is not a list (${where})`);
|
|
348
|
+
}
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const texts = {};
|
|
353
|
+
for (const locale of locales) {
|
|
354
|
+
const value = lookup(dictionaries[locale], entry.key)
|
|
355
|
+
?? lookup(dictionaries[config.fallbackLocale], entry.key);
|
|
356
|
+
if (value === undefined) {
|
|
357
|
+
errors.push(`missing "${entry.key}" in "${locale}" (${where})`);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
if (value && typeof value === 'object' && typeof value.other !== 'string') {
|
|
361
|
+
errors.push(`"${entry.key}" in "${locale}" is a group or a plural without "other" (${where})`);
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
texts[locale] = typeof value === 'string' ? value : value.other;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const withText = Object.entries(texts);
|
|
368
|
+
if (withText.length > 1) {
|
|
369
|
+
const expected = paramsOf(withText[0][1]);
|
|
370
|
+
for (const [locale, text] of withText.slice(1)) {
|
|
371
|
+
const actual = paramsOf(text);
|
|
372
|
+
for (const param of expected) {
|
|
373
|
+
if (!actual.has(param)) warnings.push(`"${entry.key}" (${locale}) is missing {${param}} used by ${withText[0][0]} (${where})`);
|
|
374
|
+
}
|
|
375
|
+
for (const param of actual) {
|
|
376
|
+
if (!expected.has(param)) warnings.push(`"${entry.key}" (${locale}) uses {${param}} which ${withText[0][0]} does not (${where})`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Content documents: a `slice.t.content('name')` needs `locales/content/name.json`,
|
|
383
|
+
// and every `copy` needs a branch for each locale with the same shape.
|
|
384
|
+
const contentLocales = [...new Set([...locales, config.fallbackLocale].filter(Boolean))];
|
|
385
|
+
const missingDocuments = new Set();
|
|
386
|
+
for (const { name, where } of contentCalls) {
|
|
387
|
+
if (content.documents[name] === undefined && !missingDocuments.has(name)) {
|
|
388
|
+
missingDocuments.add(name);
|
|
389
|
+
errors.push(`missing content document "${name}" (${where})`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
for (const error of content.errors || []) errors.push(error);
|
|
393
|
+
if (contentRules && typeof contentRules.validateContentDocument === 'function') {
|
|
394
|
+
for (const [name, document] of Object.entries(content.documents || {})) {
|
|
395
|
+
for (const issue of contentRules.validateContentDocument(document, contentLocales)) {
|
|
396
|
+
errors.push(`content/${name}.json${issue.path ? `: ${issue.path}` : ''}: ${issue.message}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// Keys nobody reads: cheap to spot, expensive to keep forever. Opt-in: keys reached
|
|
402
|
+
// through an app helper (`tr(key)`, a table of labels) are invisible to the scan, so
|
|
403
|
+
// this would otherwise report false positives.
|
|
404
|
+
if (reportUnused) {
|
|
405
|
+
const used = new Set(entries.map((entry) => entry.key));
|
|
406
|
+
const unused = [];
|
|
407
|
+
for (const locale of locales) {
|
|
408
|
+
for (const key of flatten(dictionaries[locale])) {
|
|
409
|
+
if (used.has(key) || key.startsWith('slice.')) continue;
|
|
410
|
+
if (!unused.includes(key)) unused.push(key);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
for (const key of unused.slice(0, 20)) warnings.push(`unused key "${key}"`);
|
|
414
|
+
if (unused.length > 20) warnings.push(`…and ${unused.length - 20} more unused keys`);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
if (config.localePrefix) {
|
|
418
|
+
for (const { where, href } of rawHrefs) {
|
|
419
|
+
warnings.push(`raw href="${href}" in ${where} loses the locale: use slice.router.href()`);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return { errors, warnings };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** Everything `slice translator check` and the doctor row need. */
|
|
427
|
+
export async function checkProject(projectRoot, options = {}) {
|
|
428
|
+
const collected = await collectProject(projectRoot, options);
|
|
429
|
+
const result = checkTranslations({
|
|
430
|
+
...collected,
|
|
431
|
+
reportUnused: options.unused === true
|
|
432
|
+
});
|
|
433
|
+
const locales = collected.config?.enabled
|
|
434
|
+
? [...new Set([collected.config.defaultLocale, ...(collected.config.locales || [])].filter(Boolean))]
|
|
435
|
+
: [];
|
|
436
|
+
return {
|
|
437
|
+
...result,
|
|
438
|
+
config: collected.config,
|
|
439
|
+
entries: collected.entries,
|
|
440
|
+
locales,
|
|
441
|
+
dictionaryCount: Object.keys(collected.dictionaries).length,
|
|
442
|
+
contentCount: Object.keys(collected.content?.documents || {}).length
|
|
443
|
+
};
|
|
444
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// slice typecheck — run the project's TypeScript over the JS, using the jsconfig
|
|
2
|
+
// that `slice types generate` maintains (`allowJs` + `checkJs`).
|
|
3
|
+
//
|
|
4
|
+
// ESLint does not type-check (no tsconfig, no type information). This is the
|
|
5
|
+
// compiler step: it compares the code against the generated prop and event
|
|
6
|
+
// declarations. TypeScript is the project's devDependency, like ESLint.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { spawnSync } from 'node:child_process';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
import Print from '../Print.js';
|
|
13
|
+
import { runTypeRefresh } from '../lint/lint.js';
|
|
14
|
+
import { reportTypesRefresh } from '../lint/types.js';
|
|
15
|
+
|
|
16
|
+
/** The project's own tsc, or null when TypeScript is not installed. */
|
|
17
|
+
export function resolveTypeScript(projectRoot) {
|
|
18
|
+
try {
|
|
19
|
+
const require = createRequire(path.join(projectRoot, 'package.json'));
|
|
20
|
+
const pkgPath = require.resolve('typescript/package.json');
|
|
21
|
+
return path.join(path.dirname(pkgPath), 'bin', 'tsc');
|
|
22
|
+
} catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The config to type-check with: explicit, jsconfig.json, or tsconfig.json. */
|
|
28
|
+
export function resolveProjectConfig(projectRoot, explicit = null) {
|
|
29
|
+
const candidates = explicit ? [explicit] : ['jsconfig.json', 'tsconfig.json'];
|
|
30
|
+
for (const candidate of candidates) {
|
|
31
|
+
const file = path.isAbsolute(candidate) ? candidate : path.join(projectRoot, candidate);
|
|
32
|
+
if (fs.existsSync(file)) return file;
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export default async function typecheckCommand(options = {}, projectRoot) {
|
|
38
|
+
// Check the declarations that exist now, not the ones from before the last
|
|
39
|
+
// `slice get`: the registry changed, so the .d.ts has to follow.
|
|
40
|
+
if (options.types !== false) {
|
|
41
|
+
try {
|
|
42
|
+
const types = await runTypeRefresh(projectRoot, options);
|
|
43
|
+
if (types) reportTypesRefresh(types, projectRoot);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
Print.warning('Could not refresh the generated types:', error.message);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const tsc = resolveTypeScript(projectRoot);
|
|
50
|
+
if (!tsc) {
|
|
51
|
+
Print.error('TypeScript is not installed in this project.');
|
|
52
|
+
Print.info('Install it: npm i -D typescript (or "pnpm add -D typescript")');
|
|
53
|
+
process.exitCode = 1;
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const config = resolveProjectConfig(projectRoot, options.project);
|
|
58
|
+
if (!config) {
|
|
59
|
+
Print.error('No jsconfig.json or tsconfig.json here: nothing to type-check with.');
|
|
60
|
+
Print.info('Run "slice types generate" to create the jsconfig that includes the generated declarations.');
|
|
61
|
+
process.exitCode = 1;
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const result = spawnSync(process.execPath, [tsc, '--noEmit', '-p', config], {
|
|
66
|
+
cwd: projectRoot,
|
|
67
|
+
stdio: 'inherit',
|
|
68
|
+
env: process.env
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
if (result.error) {
|
|
72
|
+
Print.error('Could not run tsc:', result.error.message);
|
|
73
|
+
process.exitCode = 1;
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (result.status !== 0) {
|
|
78
|
+
process.exitCode = result.status || 1;
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return true;
|
|
83
|
+
}
|