@emberbox/lint 0.0.0-stage → 0.1.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.
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env node
2
+ import {spawnSync} from 'node:child_process'
3
+ import {existsSync} from 'node:fs'
4
+ import {createRequire} from 'node:module'
5
+ import {dirname, join, resolve} from 'node:path'
6
+ import {pathToFileURL} from 'node:url'
7
+ import {checkBrowserStorage} from './browser-storage.mjs'
8
+ import {checkComments} from './comments.mjs'
9
+ import {checkEmDash} from './em-dash.mjs'
10
+
11
+ const require = createRequire(import.meta.url)
12
+ const CONFIG_FILE = 'emberbox-lint.config.mjs'
13
+
14
+ /**
15
+ * The project's lint configuration from `emberbox-lint.config.mjs` in the working directory, the
16
+ * frontend that ESLint also runs in.
17
+ *
18
+ * <p>It exports `root`, the repository root relative to the frontend (`.` by default); `sources`,
19
+ * the `{path, extensions}` targets the comment and the em dash linter read (`extensions` null for a
20
+ * single file); `text`, further targets only the em dash linter reads; `browserStorage`, a
21
+ * `{catalogue, sources}` pair when the project keeps a catalogue; and `duplication`, the jscpd
22
+ * config file when the project measures duplication. Paths of targets and of the catalogue are
23
+ * relative to the root.
24
+ *
25
+ * @returns the configuration, with `root` absolute
26
+ */
27
+ async function loadConfig() {
28
+ const file = resolve(CONFIG_FILE)
29
+ if (!existsSync(file)) {
30
+ console.error(`No ${CONFIG_FILE} in ${process.cwd()}.`)
31
+ process.exit(2)
32
+ }
33
+ const config = (await import(pathToFileURL(file).href)).default
34
+ return {...config, root: resolve(config.root ?? '.'), sources: config.sources ?? [], text: config.text ?? []}
35
+ }
36
+
37
+ /**
38
+ * Runs a package's command line tool in the working directory and answers its exit code.
39
+ *
40
+ * @param pkg the package that brings the tool
41
+ * @param bin the path of its entry point inside the package
42
+ * @param args the arguments
43
+ * @returns the exit code, 1 when it could not be started
44
+ */
45
+ function runTool(pkg, bin, args) {
46
+ const entry = join(dirname(require.resolve(`${pkg}/package.json`)), bin)
47
+ return spawnSync(process.execPath, [entry, ...args], {stdio: 'inherit'}).status ?? 1
48
+ }
49
+
50
+ /**
51
+ * The linters of a project, each with its name and how it runs. A linter the configuration does not
52
+ * ask for is left out.
53
+ *
54
+ * @param config the loaded configuration
55
+ * @returns the linters, in the order they run
56
+ */
57
+ function lintersOf(config) {
58
+ return [
59
+ {name: 'eslint', run: extra => runTool('eslint', 'bin/eslint.js', ['--max-warnings=0', ...extra]) === 0},
60
+ config.duplication && {name: 'duplication', run: extra => runTool('jscpd', 'run-jscpd.js', ['--config', config.duplication, ...extra]) === 0},
61
+ config.browserStorage && {name: 'browser-storage', run: () => checkBrowserStorage(config.root, config.browserStorage)},
62
+ {name: 'em-dash', run: () => checkEmDash(config.root, [...config.sources, ...config.text])},
63
+ {name: 'comments', run: () => checkComments(config.root, config.sources)},
64
+ ].filter(Boolean)
65
+ }
66
+
67
+ /**
68
+ * Runs one linter; one that crashes counts as failed, so the linters after it still run.
69
+ *
70
+ * @param linter the linter
71
+ * @param extra arguments for ESLint or jscpd
72
+ * @returns whether it passed
73
+ */
74
+ function passes(linter, extra) {
75
+ try {
76
+ return linter.run(extra)
77
+ } catch (error) {
78
+ console.error(`${linter.name} could not run: ${error instanceof Error ? error.message : error}`)
79
+ return false
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Runs the project's linters.
85
+ *
86
+ * <p>`emberbox-lint` runs all of them and fails when any of them fails, after every one has had its
87
+ * say, so one run shows the whole picture. `--audit` runs all of them and never fails.
88
+ * `emberbox-lint <name> [args]` runs one, handing the arguments on to ESLint or jscpd.
89
+ *
90
+ * @param args the command line arguments
91
+ */
92
+ async function main(args) {
93
+ const linters = lintersOf(await loadConfig())
94
+ if (args.length > 0 && args[0] !== '--audit') {
95
+ const [name, ...rest] = args
96
+ const linter = linters.find(candidate => candidate.name === name)
97
+ if (!linter) {
98
+ console.error(`No linter named '${name}'. Known: ${linters.map(candidate => candidate.name).join(', ')}`)
99
+ process.exit(2)
100
+ }
101
+ process.exit(passes(linter, rest) ? 0 : 1)
102
+ }
103
+ const failed = linters.filter(linter => !passes(linter, [])).map(linter => linter.name)
104
+ if (failed.length === 0) return
105
+ console.error(`\nLinters failed: ${failed.join(', ')}`)
106
+ if (args[0] !== '--audit') process.exit(1)
107
+ }
108
+
109
+ await main(process.argv.slice(2))
package/src/eslint.mjs ADDED
@@ -0,0 +1,205 @@
1
+ import js from '@eslint/js'
2
+ import vueI18n from '@intlify/eslint-plugin-vue-i18n'
3
+ import {createNodeResolver, importX} from 'eslint-plugin-import-x'
4
+ import vue from 'eslint-plugin-vue'
5
+ import vueA11y from 'eslint-plugin-vuejs-accessibility'
6
+ import globals from 'globals'
7
+ import tseslint from 'typescript-eslint'
8
+ import * as localeParser from './i18n/locale-parser.mjs'
9
+ import {localeSnapshots} from './i18n/locales.mjs'
10
+ import emberbox from './plugin.mjs'
11
+ import {INLINE_STATE_TYPE, restrictSyntax} from './restrictions.mjs'
12
+
13
+ /**
14
+ * Vue's rules as the Emberbox components are written: script, template, style; an element with
15
+ * nothing inside closes itself; no `v-html`. Layout is left to the author.
16
+ */
17
+ const VUE_RULES = {
18
+ 'vue/block-order': ['error', {order: ['script', 'template', 'style']}],
19
+ 'vue/html-self-closing': ['error', {html: {void: 'always', normal: 'always', component: 'always'}, svg: 'always', math: 'always'}],
20
+ 'vue/no-v-html': 'error',
21
+ 'vue/multi-word-component-names': 'off',
22
+ 'vue/html-indent': 'off',
23
+ 'vue/html-closing-bracket-spacing': 'off',
24
+ 'vue/html-closing-bracket-newline': 'off',
25
+ 'vue/singleline-html-element-content-newline': 'off',
26
+ 'vue/multiline-html-element-content-newline': 'off',
27
+ 'vue/max-attributes-per-line': 'off',
28
+ 'vue/first-attribute-linebreak': 'off',
29
+ }
30
+
31
+ /**
32
+ * Text that reads the same in every language and so needs no catalogue entry: a run without
33
+ * letters, a number with its unit, an upper-case code.
34
+ */
35
+ const LANGUAGE_NEUTRAL_TEXT = [
36
+ '[\\p{N}\\p{P}\\p{S}\\s]+',
37
+ '[<>≤≥]?\\s?\\d[\\d.,:]*\\s?(?:ms|s|min|h|m|km|%)?',
38
+ '[A-Z0-9]+(?:[-./][A-Z0-9]+)*\\.?',
39
+ ]
40
+
41
+ /** Files that run in Node rather than in the browser: configs, build and lint scripts. */
42
+ const NODE_FILES = ['*.config.{ts,mjs,js}', 'scripts/**/*.{mjs,js,ts}', 'tools/**/*.{mjs,js,ts}']
43
+
44
+ /**
45
+ * The `import-x/no-restricted-paths` zones of one layer.
46
+ *
47
+ * @param src the source directory
48
+ * @param layer the layer and the layers above it, which it may not import from
49
+ * @returns the zones its files are held to
50
+ */
51
+ function layerZones(src, {layer, above}) {
52
+ return above.map(from => ({
53
+ target: `./${src}/${layer}`,
54
+ from: `./${src}/${from}`,
55
+ message: `${layer}/ may not import from ${from}/.`,
56
+ }))
57
+ }
58
+
59
+ /**
60
+ * The rules about the catalogue: every key used exists, no text is written into a template
61
+ * instead, the catalogue has no plurals and no key nobody uses.
62
+ *
63
+ * @param src the source directory
64
+ * @param catalogue the catalogue module
65
+ * @param cwd the directory ESLint runs in
66
+ * @returns the config entries
67
+ */
68
+ async function i18nConfigs(src, catalogue, cwd) {
69
+ const snapshots = await localeSnapshots(catalogue, cwd)
70
+ const sourceRule = {
71
+ name: 'emberbox/vue-i18n',
72
+ files: [`${src}/**/*.{ts,vue}`],
73
+ ignores: [catalogue, `${src}/**/*.test.ts`],
74
+ plugins: {'@intlify/vue-i18n': vueI18n},
75
+ rules: {'@intlify/vue-i18n/no-missing-keys': 'error'},
76
+ }
77
+ const rawText = {
78
+ name: 'emberbox/raw-text',
79
+ files: [`${src}/**/*.vue`],
80
+ plugins: {'@intlify/vue-i18n': vueI18n},
81
+ rules: {
82
+ '@intlify/vue-i18n/no-raw-text': ['error', {
83
+ ignorePattern: `^(?:${LANGUAGE_NEUTRAL_TEXT.join('|')})$`,
84
+ ignoreNodes: ['code'],
85
+ attributes: {'/.+/': ['aria-label', 'title', 'placeholder', 'alt', 'label']},
86
+ }],
87
+ },
88
+ }
89
+ const locales = {
90
+ name: 'emberbox/locales',
91
+ files: [catalogue],
92
+ languageOptions: {parser: localeParser},
93
+ plugins: {'@intlify/vue-i18n': vueI18n},
94
+ settings: {'vue-i18n': {localeDir: [snapshots, catalogue], messageSyntaxVersion: '^11.0.0'}},
95
+ rules: {
96
+ '@intlify/vue-i18n/valid-message-syntax': 'error',
97
+ 'emberbox/i18n-no-plural-messages': 'error',
98
+ 'emberbox/i18n-unused-keys': ['error', {sources: src, german: [{file: catalogue}]}],
99
+ },
100
+ }
101
+ return {settings: {'vue-i18n': {localeDir: snapshots, messageSyntaxVersion: '^11.0.0'}}, configs: [sourceRule, rawText, locales]}
102
+ }
103
+
104
+ /**
105
+ * Leaves the catalogue module to the locale rules: the locale parser hands ESLint a JSON AST, which
106
+ * no rule written for a script can read.
107
+ *
108
+ * @param catalogue the catalogue module, if there is one
109
+ * @returns a function adjusting one config entry
110
+ */
111
+ function keepOffCatalogue(catalogue) {
112
+ return config => {
113
+ if (!catalogue || config.name === 'emberbox/locales') return config
114
+ if (!config.rules && !config.processor) return config
115
+ return {...config, ignores: [...(config.ignores ?? []), catalogue]}
116
+ }
117
+ }
118
+
119
+ /**
120
+ * The ESLint flat config of an Emberbox frontend.
121
+ *
122
+ * <p>Vue, TypeScript and accessibility as recommended, without `no-undef` for TypeScript and Vue
123
+ * files, whose names the type checker resolves, auto-imports included; the Emberbox Vue conventions, no leftover
124
+ * `console.log`, named state types, functions of at most `maxFunctionLines` lines, and for the
125
+ * templates outside `components/` no repeated class patterns and no oversized blocks. With a
126
+ * `catalogue`, every user-visible text goes through vue-i18n and the catalogue is checked; without
127
+ * one the project has no i18n. `layers` names which source directories may not import from which.
128
+ * Paths are relative to the working directory, where ESLint runs.
129
+ *
130
+ * @param {object} [options]
131
+ * @param {string} [options.cwd] the directory ESLint runs in, the working directory by default
132
+ * @param {string} [options.src] the source directory, `src` by default
133
+ * @param {string} [options.catalogue] the German catalogue module, such as `src/i18n/de.ts`
134
+ * @param {{layer: string, above: string[]}[]} [options.layers] import boundaries between source directories
135
+ * @param {number} [options.maxFunctionLines] the longest function allowed, 79 by default
136
+ * @param {string[]} [options.ignores] further files ESLint skips
137
+ * @param {string[]} [options.nodeFiles] further files that run in Node
138
+ * @returns {Promise<import('eslint').Linter.Config[]>} the config
139
+ */
140
+ export async function emberboxEslint(options = {}) {
141
+ const {cwd = process.cwd(), src = 'src', catalogue, layers = [], maxFunctionLines = 79, ignores = [], nodeFiles = []} = options
142
+ const i18n = catalogue ? await i18nConfigs(src, catalogue, cwd) : {settings: {}, configs: []}
143
+ return [
144
+ {name: 'emberbox/ignores', ignores: ['node_modules/**', 'dist/**', 'coverage/**', 'public/**', ...ignores]},
145
+ {
146
+ name: 'emberbox/settings',
147
+ settings: {
148
+ 'import-x/resolver-next': [createNodeResolver({extensions: ['.ts', '.vue', '.mjs', '.js']})],
149
+ ...i18n.settings,
150
+ },
151
+ },
152
+ {name: 'emberbox/plugin', plugins: {emberbox, 'import-x': importX}},
153
+ js.configs.recommended,
154
+ ...tseslint.configs.recommended,
155
+ ...vue.configs['flat/recommended'],
156
+ {
157
+ name: 'emberbox/vue-parser',
158
+ files: ['**/*.vue'],
159
+ languageOptions: {parserOptions: {parser: tseslint.parser, extraFileExtensions: ['.vue']}},
160
+ },
161
+ {name: 'emberbox/globals', languageOptions: {globals: globals.browser}},
162
+ {name: 'emberbox/typescript-names', files: ['**/*.ts', '**/*.vue'], rules: {'no-undef': 'off'}},
163
+ {name: 'emberbox/node', files: [...NODE_FILES, ...nodeFiles], languageOptions: {globals: {...globals.node}}},
164
+ ...vueA11y.configs['flat/recommended'],
165
+ {
166
+ name: 'emberbox/accessibility',
167
+ files: ['**/*.vue'],
168
+ rules: {'vuejs-accessibility/label-has-for': ['error', {required: {some: ['nesting', 'id']}, allowChildren: true}]},
169
+ },
170
+ {name: 'emberbox/vue', files: ['**/*.vue'], rules: VUE_RULES},
171
+ {
172
+ name: 'emberbox/console',
173
+ files: [`${src}/**/*.{ts,vue}`],
174
+ rules: {
175
+ 'no-restricted-properties': ['error',
176
+ {object: 'console', property: 'log', message: 'Leftover console.log: remove it.'},
177
+ {object: 'console', property: 'debug', message: 'Leftover console.debug: remove it.'},
178
+ ],
179
+ },
180
+ },
181
+ ...i18n.configs,
182
+ ...layers.map(layer => ({
183
+ name: `emberbox/layers/${layer.layer}`,
184
+ files: [`${src}/${layer.layer}/**/*.{ts,vue}`],
185
+ rules: {'import-x/no-restricted-paths': ['error', {zones: layerZones(src, layer), basePath: cwd}]},
186
+ })),
187
+ {
188
+ name: 'emberbox/source-size',
189
+ files: [`${src}/**/*.{ts,vue}`],
190
+ ignores: [`${src}/**/*.test.ts`, ...(catalogue ? [catalogue] : [])],
191
+ rules: {'emberbox/max-function-lines': ['error', {max: maxFunctionLines}]},
192
+ },
193
+ {name: 'emberbox/state-types', files: [`${src}/**/*.{ts,vue}`], rules: restrictSyntax(INLINE_STATE_TYPE)},
194
+ {
195
+ name: 'emberbox/view-templates',
196
+ files: [`${src}/**/*.vue`],
197
+ ignores: [`${src}/components/**`],
198
+ rules: {
199
+ 'emberbox/repeated-class-pattern': ['error', {src}],
200
+ 'emberbox/template-block-size': 'error',
201
+ },
202
+ },
203
+ {name: 'emberbox/views', files: [`${src}/views/**/*.vue`, `${src}/pages/**/*.vue`], rules: {'max-lines': ['error', {max: 500}]}},
204
+ ].map(keepOffCatalogue(catalogue))
205
+ }
@@ -0,0 +1,74 @@
1
+ import {resolve} from 'node:path'
2
+ import {leafKeys, localeMessagesOf, messagesOf} from './locale-parser.mjs'
3
+
4
+ /**
5
+ * The locale files a rule is told about, resolved against the directory ESLint runs in.
6
+ *
7
+ * <p>`german` lists the files the German messages are made of, each with the key it is merged in
8
+ * under; here that is the one catalogue at the top.
9
+ *
10
+ * @param context the rule context
11
+ * @param options the rule's options
12
+ * @returns the files, absolute
13
+ */
14
+ export function localeFiles(context, options) {
15
+ return {
16
+ german: (options.german ?? []).map(entry => ({file: resolve(context.cwd, entry.file), prefix: entry.prefix ?? ''})),
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Every leaf key of the file being linted, with the property that defines it.
22
+ *
23
+ * @param program the JSON AST the locale parser produced
24
+ * @param prefix the key the file is merged in under
25
+ * @returns the properties by dotted key, in source order
26
+ */
27
+ export function definedProperties(program, prefix) {
28
+ const found = new Map()
29
+ collect(program.body[0].expression, prefix, found)
30
+ return found
31
+ }
32
+
33
+ /**
34
+ * Every leaf key of the German messages, with the file being linted read from its AST rather than
35
+ * from disk, so a rule sees what the editor holds.
36
+ *
37
+ * @param german the German files
38
+ * @param current the absolute path of the file being linted
39
+ * @param program its JSON AST
40
+ * @returns the keys
41
+ */
42
+ export function germanKeys(german, current, program) {
43
+ const keys = new Set()
44
+ for (const {file, prefix} of german) {
45
+ const messages = file === current ? messagesOf(program) : localeMessagesOf(file)
46
+ for (const key of leafKeys(messages, prefix)) keys.add(key)
47
+ }
48
+ return keys
49
+ }
50
+
51
+ /**
52
+ * The name of a property's key.
53
+ *
54
+ * @param property the JSON AST property
55
+ * @returns the name
56
+ */
57
+ function nameOf(property) {
58
+ return property.key.type === 'JSONIdentifier' ? property.key.name : String(property.key.value)
59
+ }
60
+
61
+ /**
62
+ * Walks an object of the JSON AST, recording its leaves.
63
+ *
64
+ * @param object the object
65
+ * @param path the key it sits under
66
+ * @param found the leaves so far
67
+ */
68
+ function collect(object, path, found) {
69
+ for (const property of object.properties) {
70
+ const key = path ? `${path}.${nameOf(property)}` : nameOf(property)
71
+ if (property.value.type === 'JSONObjectExpression') collect(property.value, key, found)
72
+ else found.set(key, property)
73
+ }
74
+ }
@@ -0,0 +1,271 @@
1
+ import {existsSync, readFileSync, statSync} from 'node:fs'
2
+ import {dirname, resolve} from 'node:path'
3
+ import * as typescriptParser from '@typescript-eslint/parser'
4
+ import * as jsonc from 'jsonc-eslint-parser'
5
+
6
+ /**
7
+ * Reads a TypeScript locale module the way `@intlify/eslint-plugin-vue-i18n` reads a JSON one.
8
+ *
9
+ * <p>The plugin's rules for locale files walk the AST `jsonc-eslint-parser` defines and look for
10
+ * `parserServices.isJSON`, and they take no other shape. The locales here are modules exporting one
11
+ * object literal, so this parses the module as TypeScript and hands ESLint that object converted
12
+ * node by node into the JSON AST, every node keeping the range of the source it came from. Reports
13
+ * therefore land on the real line of the `.ts` file.
14
+ *
15
+ * <p>A value may be a string, a concatenation of strings, a template literal without substitutions,
16
+ * a number, a boolean or a nested object. An identifier naming a constant declared in the module
17
+ * stands for that constant's value, and so does a constant imported by name from a sibling module,
18
+ * as the plain string at the identifier's place. An identifier naming anything else, such as an
19
+ * imported block merged in under its key, becomes an empty object.
20
+ *
21
+ * <p>ESLint gets nothing but this AST for such a file, so a config must hand the locale files to
22
+ * this parser alone and run only rules written for the JSON AST on them.
23
+ *
24
+ * @param code the module's source
25
+ * @param options the parser options, whose `filePath` the imports are resolved against
26
+ * @returns what ESLint expects of a parser
27
+ */
28
+ export function parseForESLint(code, options = {}) {
29
+ const program = parseModule(code)
30
+ const exported = program.body.find(statement => statement.type === 'ExportDefaultDeclaration')
31
+ const constants = moduleConstants(program, options.filePath)
32
+ const expression = exported
33
+ ? convert(unwrap(exported.declaration), constants)
34
+ : {type: 'JSONObjectExpression', properties: [], range: program.range, loc: program.loc}
35
+ const statement = {type: 'JSONExpressionStatement', expression, range: expression.range, loc: expression.loc}
36
+ return {
37
+ ast: {
38
+ type: 'Program',
39
+ body: [statement],
40
+ comments: program.comments,
41
+ tokens: program.tokens,
42
+ range: [0, code.length],
43
+ loc: {start: {line: 1, column: 0}, end: program.loc.end},
44
+ },
45
+ visitorKeys: jsonc.VisitorKeys,
46
+ services: {isJSON: true},
47
+ }
48
+ }
49
+
50
+ /** Parser metadata ESLint prints and caches by. */
51
+ export const meta = {name: 'emberbox-locale-parser'}
52
+
53
+ const cache = new Map()
54
+
55
+ /**
56
+ * The messages a locale module defines, as a plain object, read from disk and kept until the file
57
+ * changes.
58
+ *
59
+ * @param file the absolute path of the module
60
+ * @returns its messages
61
+ */
62
+ export function localeMessagesOf(file) {
63
+ const modified = statSync(file).mtimeMs
64
+ const cached = cache.get(file)
65
+ if (cached && cached.modified === modified) return cached.messages
66
+ const messages = messagesOf(parseForESLint(readFileSync(file, 'utf-8'), {filePath: file}).ast)
67
+ cache.set(file, {modified, messages})
68
+ return messages
69
+ }
70
+
71
+ /**
72
+ * The messages the JSON AST of a locale module describes.
73
+ *
74
+ * @param ast the program this parser produced
75
+ * @returns the messages as a plain object
76
+ */
77
+ export function messagesOf(ast) {
78
+ return jsonc.getStaticJSONValue(ast.body[0].expression)
79
+ }
80
+
81
+ /**
82
+ * Every leaf key of a message tree as a dotted path.
83
+ *
84
+ * @param messages the tree
85
+ * @param prefix the path the tree sits under
86
+ * @returns the dotted paths of its messages
87
+ */
88
+ export function leafKeys(messages, prefix = '') {
89
+ const keys = []
90
+ for (const [name, value] of Object.entries(messages)) {
91
+ const key = prefix ? `${prefix}.${name}` : name
92
+ if (typeof value === 'object' && value !== null) keys.push(...leafKeys(value, key))
93
+ else keys.push(key)
94
+ }
95
+ return keys
96
+ }
97
+
98
+ /**
99
+ * A module's source as a TypeScript AST with ranges, locations, tokens and comments.
100
+ *
101
+ * @param code the source
102
+ * @returns the program
103
+ */
104
+ function parseModule(code) {
105
+ return typescriptParser.parse(code, {range: true, loc: true, tokens: true, comment: true, sourceType: 'module'})
106
+ }
107
+
108
+ /**
109
+ * The constants a module can name: those declared at its top, exported or not, with the expression
110
+ * each is set to, and those it imports by name from a relative module, with the string each holds.
111
+ *
112
+ * @param program the parsed module
113
+ * @param filePath the module's absolute path, without which imports are not followed
114
+ * @returns the constants by name, as `{node}` for a declaration and `{value}` for an import
115
+ */
116
+ function moduleConstants(program, filePath) {
117
+ const constants = new Map()
118
+ for (const statement of program.body) {
119
+ const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
120
+ if (declaration?.type === 'VariableDeclaration' && declaration.kind === 'const') {
121
+ for (const declarator of declaration.declarations) {
122
+ if (declarator.id.type === 'Identifier' && declarator.init) constants.set(declarator.id.name, {node: declarator.init})
123
+ }
124
+ }
125
+ if (statement.type === 'ImportDeclaration' && filePath) importConstants(statement, filePath, constants)
126
+ }
127
+ return constants
128
+ }
129
+
130
+ /**
131
+ * Adds the string constants one import names to a module's constants.
132
+ *
133
+ * <p>Only a relative module that exists as a `.ts` file is followed, and only a name it declares as
134
+ * a constant with a static string value is taken. Anything else stays unknown, as it was before.
135
+ *
136
+ * @param statement the import declaration
137
+ * @param filePath the importing module's absolute path
138
+ * @param constants the constants to add to
139
+ */
140
+ function importConstants(statement, filePath, constants) {
141
+ const source = statement.source.value
142
+ if (!source.startsWith('.')) return
143
+ const file = resolve(dirname(filePath), source.endsWith('.ts') ? source : `${source}.ts`)
144
+ if (!existsSync(file)) return
145
+ const imported = moduleConstants(parseModule(readFileSync(file, 'utf-8')), file)
146
+ for (const specifier of statement.specifiers) {
147
+ if (specifier.type !== 'ImportSpecifier') continue
148
+ const constant = imported.get(specifier.imported.name)
149
+ const value = constant && staticValue(constant, imported)
150
+ if (typeof value === 'string') constants.set(specifier.local.name, {value})
151
+ }
152
+ }
153
+
154
+ /**
155
+ * The value a constant holds, read without running anything.
156
+ *
157
+ * @param constant the constant, as `moduleConstants` records it
158
+ * @param constants the constants of the module declaring it
159
+ * @returns the value, or undefined where it is not static
160
+ */
161
+ function staticValue(constant, constants) {
162
+ if ('value' in constant) return constant.value
163
+ try {
164
+ return jsonc.getStaticJSONValue(convert(unwrap(constant.node), constants))
165
+ } catch {
166
+ return undefined
167
+ }
168
+ }
169
+
170
+ /**
171
+ * An expression without the type assertions around it, which carry no message.
172
+ *
173
+ * @param node the expression
174
+ * @returns the expression inside
175
+ */
176
+ function unwrap(node) {
177
+ let current = node
178
+ while (current.type === 'TSAsExpression' || current.type === 'TSSatisfiesExpression') current = current.expression
179
+ return current
180
+ }
181
+
182
+ /**
183
+ * One TypeScript expression as the JSON AST node that stands for it.
184
+ *
185
+ * @param node the expression
186
+ * @param constants the module's constants, for identifiers that name one
187
+ * @returns a new JSON AST node carrying the expression's range
188
+ */
189
+ function convert(node, constants) {
190
+ const at = {range: node.range, loc: node.loc}
191
+ switch (node.type) {
192
+ case 'ObjectExpression':
193
+ return {type: 'JSONObjectExpression', properties: node.properties.filter(isPlainProperty).map(property => convertProperty(property, constants)), ...at}
194
+ case 'ArrayExpression':
195
+ return {type: 'JSONArrayExpression', elements: node.elements.map(element => element && convert(element, constants)), ...at}
196
+ case 'Literal':
197
+ return {type: 'JSONLiteral', value: node.value, raw: node.raw, ...at}
198
+ case 'TemplateLiteral':
199
+ return node.expressions.length === 0
200
+ ? {type: 'JSONTemplateLiteral', quasis: node.quasis.map(quasi => ({type: 'JSONTemplateElement', value: quasi.value, tail: quasi.tail, range: quasi.range, loc: quasi.loc})), expressions: [], ...at}
201
+ : emptyObject(at)
202
+ case 'BinaryExpression':
203
+ return {type: 'JSONBinaryExpression', operator: node.operator, left: convert(node.left, constants), right: convert(node.right, constants), ...at}
204
+ case 'Identifier':
205
+ return constantNode(constants.get(node.name), constants, at)
206
+ case 'TSAsExpression':
207
+ case 'TSSatisfiesExpression':
208
+ return convert(unwrap(node), constants)
209
+ default:
210
+ return emptyObject(at)
211
+ }
212
+ }
213
+
214
+ /**
215
+ * The JSON AST node an identifier stands for: a declared constant's expression, an imported
216
+ * constant's string at the identifier's place, or an empty object for anything else.
217
+ *
218
+ * @param constant the constant the identifier names, if any
219
+ * @param constants the module's constants
220
+ * @param at the identifier's range and location
221
+ * @returns the node
222
+ */
223
+ function constantNode(constant, constants, at) {
224
+ if (!constant) return emptyObject(at)
225
+ if ('value' in constant) return {type: 'JSONLiteral', value: constant.value, raw: JSON.stringify(constant.value), ...at}
226
+ return convert(unwrap(constant.node), constants)
227
+ }
228
+
229
+ /**
230
+ * Whether an object member is a plain `key: value` pair, which is all a message tree holds.
231
+ *
232
+ * @param property the member
233
+ * @returns false for spreads, methods and computed keys
234
+ */
235
+ function isPlainProperty(property) {
236
+ return property.type === 'Property' && !property.computed && property.kind === 'init' && !property.method
237
+ }
238
+
239
+ /**
240
+ * One property as a JSON AST property.
241
+ *
242
+ * @param property the TypeScript property
243
+ * @param constants the module's constants
244
+ * @returns the JSON AST property
245
+ */
246
+ function convertProperty(property, constants) {
247
+ const key = property.key.type === 'Identifier'
248
+ ? {type: 'JSONIdentifier', name: property.key.name, range: property.key.range, loc: property.key.loc}
249
+ : {type: 'JSONLiteral', value: property.key.value, raw: property.key.raw, range: property.key.range, loc: property.key.loc}
250
+ return {
251
+ type: 'JSONProperty',
252
+ kind: 'init',
253
+ computed: false,
254
+ method: false,
255
+ shorthand: false,
256
+ key,
257
+ value: convert(property.value, constants),
258
+ range: property.range,
259
+ loc: property.loc,
260
+ }
261
+ }
262
+
263
+ /**
264
+ * An empty object standing where a value is not a message this file defines.
265
+ *
266
+ * @param at the range and location it takes
267
+ * @returns the node
268
+ */
269
+ function emptyObject(at) {
270
+ return {type: 'JSONObjectExpression', properties: [], ...at}
271
+ }
@@ -0,0 +1,27 @@
1
+ import {mkdirSync, writeFileSync} from 'node:fs'
2
+ import {join, resolve} from 'node:path'
3
+ import {createJiti} from 'jiti'
4
+
5
+ /** The one file the catalogue is written to, so a renamed catalogue leaves no stale keys behind. */
6
+ const SNAPSHOT = 'catalogue.json'
7
+
8
+ /**
9
+ * A catalogue module as `@intlify/eslint-plugin-vue-i18n` reads it.
10
+ *
11
+ * <p>The plugin loads messages from JSON, YAML or CommonJS files only, and the catalogues of the
12
+ * Emberbox projects are TypeScript modules. So the module is evaluated and written out as JSON
13
+ * below `node_modules/.cache/emberbox-lint/locales` of the directory ESLint runs in, for the plugin's
14
+ * `localeDir`.
15
+ *
16
+ * @param catalogue the catalogue module, relative to `cwd`
17
+ * @param cwd the directory ESLint runs in
18
+ * @returns the snapshot file, for the plugin's `localeDir` setting
19
+ */
20
+ export async function localeSnapshots(catalogue, cwd) {
21
+ const snapshots = resolve(cwd, 'node_modules/.cache/emberbox-lint/locales')
22
+ const jiti = createJiti(import.meta.url, {moduleCache: false})
23
+ const messages = await jiti.import(resolve(cwd, catalogue), {default: true})
24
+ mkdirSync(snapshots, {recursive: true})
25
+ writeFileSync(join(snapshots, SNAPSHOT), JSON.stringify(messages))
26
+ return join(snapshots, SNAPSHOT)
27
+ }