@nera-static/stan 0.0.0-stage → 1.0.1
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/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +308 -2
- package/bin/nera-stan.js +22 -0
- package/package.json +60 -5
- package/src/cli.js +143 -0
- package/src/eslint/config.js +159 -0
- package/src/helper-names.js +159 -0
- package/src/index.js +10 -0
- package/src/kind.js +102 -0
- package/src/repo-files.js +140 -0
- package/src/rules/hook-shape.js +168 -0
- package/src/rules/index.js +26 -0
- package/src/rules/no-copied-from.js +92 -0
- package/src/rules/no-local-helper.js +231 -0
- package/src/rules/scope.js +14 -0
- package/src/rules/shared-logger.js +57 -0
- package/src/rules/test-rules.js +291 -0
- package/src/test-helper-names.js +54 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { isRuntimeFile, repoFile } from '../repo-files.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `nera/hook-shape`: in a plugin, the entry module declares each hook as
|
|
5
|
+
* `export function <hook>({ app = {}, pagesData = [] } = {})` (or `async`), and
|
|
6
|
+
* no runtime file reads its config at module scope (D8). Only the keys a hook
|
|
7
|
+
* uses are destructured, since `no-unused-vars` refuses the others. `--fix` only
|
|
8
|
+
* adds the missing defaults to an argument that destructures nothing but `app`
|
|
9
|
+
* and `pagesData`, as in `({ app, pagesData })`; `(data)` is never rewritten (D9).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The hooks core calls, in the order it calls them. */
|
|
13
|
+
export const HOOKS = Object.freeze(['getAppData', 'getMetaData', 'getAssets'])
|
|
14
|
+
|
|
15
|
+
/** Each hook argument key and the default it gets. */
|
|
16
|
+
const DEFAULTS = Object.freeze({ app: '{}', pagesData: '[]' })
|
|
17
|
+
|
|
18
|
+
/** Calls that read a plugin's config file. */
|
|
19
|
+
const CONFIG_READERS = Object.freeze(['getConfig', 'loadPluginConfig', 'loadConfig'])
|
|
20
|
+
|
|
21
|
+
const FUNCTION = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'])
|
|
22
|
+
|
|
23
|
+
export default {
|
|
24
|
+
meta: {
|
|
25
|
+
type: 'problem',
|
|
26
|
+
fixable: 'code',
|
|
27
|
+
docs: {
|
|
28
|
+
description: 'Plugin hooks are exported functions that destructure their argument with defaults',
|
|
29
|
+
},
|
|
30
|
+
schema: [],
|
|
31
|
+
messages: {
|
|
32
|
+
notFunction: '`{{name}}` is exported through `{{how}}`: declare it as `export function {{name}}(…)`',
|
|
33
|
+
params: '`{{name}}({{params}})` must destructure its argument with defaults, listing only the keys ' +
|
|
34
|
+
'it uses: `{{name}}({{canonical}})`',
|
|
35
|
+
moduleConfig: '`{{callee}}(…)` reads the config at module scope, once per import: call it inside ' +
|
|
36
|
+
'the hook (or a helper the hook calls), so every build reads the current file',
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
create(context) {
|
|
41
|
+
const { kind, root = context.cwd, entry = 'index.js' } = context.settings.nera ?? {}
|
|
42
|
+
const file = repoFile(root, context.filename)
|
|
43
|
+
if (kind !== 'plugin' || !isRuntimeFile(file)) {
|
|
44
|
+
return {}
|
|
45
|
+
}
|
|
46
|
+
const code = context.sourceCode
|
|
47
|
+
|
|
48
|
+
function checkParams(name, fn) {
|
|
49
|
+
const shape = paramShape(fn.params, code)
|
|
50
|
+
if (shape.ok) {
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
context.report({
|
|
54
|
+
node: fn.params[0] ?? fn,
|
|
55
|
+
messageId: 'params',
|
|
56
|
+
data: {
|
|
57
|
+
name,
|
|
58
|
+
params: fn.params.map((param) => code.getText(param)).join(', '),
|
|
59
|
+
canonical: canonical(shape.keys ?? Object.keys(DEFAULTS)),
|
|
60
|
+
},
|
|
61
|
+
fix: shape.keys && code.getCommentsInside(fn.params[0]).length === 0
|
|
62
|
+
? (fixer) => fixer.replaceText(fn.params[0], canonical(shape.keys))
|
|
63
|
+
: null,
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const visitors = {
|
|
68
|
+
CallExpression(node) {
|
|
69
|
+
const callee = calleeName(node.callee)
|
|
70
|
+
if (CONFIG_READERS.includes(callee) && !insideFunction(code.getAncestors(node))) {
|
|
71
|
+
context.report({ node, messageId: 'moduleConfig', data: { callee } })
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
if (file !== entry) {
|
|
76
|
+
return visitors
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
...visitors,
|
|
81
|
+
ExportNamedDeclaration(node) {
|
|
82
|
+
for (const specifier of node.specifiers) {
|
|
83
|
+
const name = exportedName(specifier.exported)
|
|
84
|
+
if (HOOKS.includes(name)) {
|
|
85
|
+
context.report({ node: specifier, messageId: 'notFunction', data: { name, how: 'export { … }' } })
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const { declaration } = node
|
|
89
|
+
if (declaration?.type === 'FunctionDeclaration' && HOOKS.includes(declaration.id.name)) {
|
|
90
|
+
checkParams(declaration.id.name, declaration)
|
|
91
|
+
}
|
|
92
|
+
if (declaration?.type === 'VariableDeclaration') {
|
|
93
|
+
for (const declarator of declaration.declarations) {
|
|
94
|
+
const name = declarator.id.type === 'Identifier' ? declarator.id.name : null
|
|
95
|
+
if (HOOKS.includes(name)) {
|
|
96
|
+
context.report({
|
|
97
|
+
node: declarator,
|
|
98
|
+
messageId: 'notFunction',
|
|
99
|
+
data: { name, how: `export ${declaration.kind}` },
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Whether `params` has the hook shape: none at all, or one object pattern
|
|
111
|
+
* defaulting to `{}` whose keys are `app`/`pagesData` with their defaults.
|
|
112
|
+
* `keys` is set when the one obviously correct rewrite exists.
|
|
113
|
+
*/
|
|
114
|
+
function paramShape(params, code) {
|
|
115
|
+
if (params.length === 0) {
|
|
116
|
+
return { ok: true }
|
|
117
|
+
}
|
|
118
|
+
const [param] = params
|
|
119
|
+
const hasDefault = param.type === 'AssignmentPattern'
|
|
120
|
+
const pattern = hasDefault ? param.left : param
|
|
121
|
+
if (params.length > 1 || pattern.type !== 'ObjectPattern') {
|
|
122
|
+
return { ok: false }
|
|
123
|
+
}
|
|
124
|
+
const properties = pattern.properties.map((property) => hookKey(property, code))
|
|
125
|
+
if (properties.length === 0 || properties.some((property) => property === null) ||
|
|
126
|
+
(hasDefault && code.getText(param.right).replace(/\s/g, '') !== '{}')) {
|
|
127
|
+
return { ok: false }
|
|
128
|
+
}
|
|
129
|
+
const ok = hasDefault && properties.every(({ defaulted }) => defaulted)
|
|
130
|
+
return { ok, keys: properties.map(({ key }) => key) }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** `app`, `app = {}`, `pagesData` or `pagesData = []` as `{ key, defaulted }`; anything else is `null`. */
|
|
134
|
+
function hookKey(property, code) {
|
|
135
|
+
if (property.type !== 'Property' || property.computed || !property.shorthand ||
|
|
136
|
+
!Object.hasOwn(DEFAULTS, property.key.name)) {
|
|
137
|
+
return null
|
|
138
|
+
}
|
|
139
|
+
const { key: { name }, value } = property
|
|
140
|
+
if (value.type === 'Identifier') {
|
|
141
|
+
return { key: name, defaulted: false }
|
|
142
|
+
}
|
|
143
|
+
const isCanonical = value.type === 'AssignmentPattern' &&
|
|
144
|
+
code.getText(value.right).replace(/\s/g, '') === DEFAULTS[name]
|
|
145
|
+
return isCanonical ? { key: name, defaulted: true } : null
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function canonical(keys) {
|
|
149
|
+
return `{ ${keys.map((key) => `${key} = ${DEFAULTS[key]}`).join(', ')} } = {}`
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function calleeName(callee) {
|
|
153
|
+
if (callee.type === 'Identifier') {
|
|
154
|
+
return callee.name
|
|
155
|
+
}
|
|
156
|
+
return callee.type === 'MemberExpression' && !callee.computed && callee.property.type === 'Identifier'
|
|
157
|
+
? callee.property.name
|
|
158
|
+
: null
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Static blocks and static fields run once, when the module loads, so only an instance field counts. */
|
|
162
|
+
function insideFunction(ancestors) {
|
|
163
|
+
return ancestors.some((node) => FUNCTION.has(node.type) || (node.type === 'PropertyDefinition' && !node.static))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function exportedName(node) {
|
|
167
|
+
return node.type === 'Identifier' ? node.name : node.value
|
|
168
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url'
|
|
2
|
+
|
|
3
|
+
import { readPackage } from '../kind.js'
|
|
4
|
+
import hookShape from './hook-shape.js'
|
|
5
|
+
import noCopiedFrom from './no-copied-from.js'
|
|
6
|
+
import noLocalHelper from './no-local-helper.js'
|
|
7
|
+
import sharedLogger from './shared-logger.js'
|
|
8
|
+
import testRules from './test-rules.js'
|
|
9
|
+
|
|
10
|
+
const { name, version } = readPackage(fileURLToPath(new URL('../..', import.meta.url)))
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The Nera ESLint plugin, registered as `nera`, so its rules read `nera/<rule>`
|
|
14
|
+
* (D8). Rules take their repo context from `settings.nera`, which `createConfig`
|
|
15
|
+
* fills in.
|
|
16
|
+
*/
|
|
17
|
+
export default {
|
|
18
|
+
meta: { name, version },
|
|
19
|
+
rules: {
|
|
20
|
+
'hook-shape': hookShape,
|
|
21
|
+
'no-copied-from': noCopiedFrom,
|
|
22
|
+
'no-local-helper': noLocalHelper,
|
|
23
|
+
'shared-logger': sharedLogger,
|
|
24
|
+
...testRules,
|
|
25
|
+
},
|
|
26
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { isPublished, repoFile } from '../repo-files.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `nera/no-copied-from`: no comment that marks code as a copy of another repo's,
|
|
5
|
+
* in any kind and any file, and no reference to the local-only roadmap specs in a
|
|
6
|
+
* comment or string of a file `npm publish` ships (D8).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The note up to the end of its sentence or an opening parenthesis; a dot inside a path does not end it.
|
|
11
|
+
* Only a copy of code counts, so what follows "from" must name a source of code: a package, repo or
|
|
12
|
+
* Nera package name (`@nera-static/…`, `nera-…`, `plugin-…`, `theme-…`, `starter-…`, core, validate,
|
|
13
|
+
* generator), a path or a `.js` file, or "the <name> plugin|theme|starter|repo|package". Prose such as
|
|
14
|
+
* "values copied from language `from`" or "bytes copied from the source" describes what code does.
|
|
15
|
+
*/
|
|
16
|
+
const COPIED = new RegExp(
|
|
17
|
+
'\\bcopied\\s+(?:verbatim\\s+)?from[\\s*]+(?:the\\s+)?' +
|
|
18
|
+
'(?:`?(?:@nera-static\\/|\\.{1,2}\\/|nera\\b|nera-|plugin-|theme-|starter-|generator\\b|core\\b|validate\\b|' +
|
|
19
|
+
'[\\w-]+\\/|[\\w-]+\\.[cm]?js\\b)|[\\w-]+\\s+(?:plugin|theme|starter|repo|package)\\b)' +
|
|
20
|
+
'(?:[^\\n();.]|\\.(?=\\S))*',
|
|
21
|
+
'i',
|
|
22
|
+
)
|
|
23
|
+
const SPEC = /\bROADMAP[\w.-]*/
|
|
24
|
+
|
|
25
|
+
export default {
|
|
26
|
+
meta: {
|
|
27
|
+
type: 'suggestion',
|
|
28
|
+
docs: {
|
|
29
|
+
description: 'No "copied from" notes, and no references to the local-only roadmap specs in published files',
|
|
30
|
+
},
|
|
31
|
+
schema: [],
|
|
32
|
+
messages: {
|
|
33
|
+
copied: 'comment "{{text}}" marks a copy: import the shared code from @nera-static/plugin-utils ' +
|
|
34
|
+
'(or ask for a new export there), or delete the note if the code is this repo\'s own',
|
|
35
|
+
spec: '`{{reference}}` in a published file: the roadmap specs are local only and 404 on npm and GitHub, ' +
|
|
36
|
+
'so state the decision in place or drop the reference',
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
create(context) {
|
|
41
|
+
const { root = context.cwd, published = null } = context.settings.nera ?? {}
|
|
42
|
+
const checksSpec = isPublished(published, repoFile(root, context.filename))
|
|
43
|
+
const code = context.sourceCode
|
|
44
|
+
|
|
45
|
+
/** `where` is `{ node }` or `{ loc }`, as `context.report` takes it. */
|
|
46
|
+
function reportSpec(where, text) {
|
|
47
|
+
const match = checksSpec && SPEC.exec(text)
|
|
48
|
+
if (match) {
|
|
49
|
+
context.report({ ...where, messageId: 'spec', data: { reference: match[0] } })
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
Program() {
|
|
55
|
+
const comments = code.getAllComments()
|
|
56
|
+
comments.forEach((comment, index) => {
|
|
57
|
+
// A note wrapped over `//` lines ("(copied from" / "// plugin-code-blocks)") is read as one.
|
|
58
|
+
const text = [comment, ...continuation(comments, index)].map(({ value }) => value).join(' ')
|
|
59
|
+
const copied = COPIED.exec(text)
|
|
60
|
+
if (copied && copied.index < comment.value.length) {
|
|
61
|
+
const note = copied[0].replace(/\s+/g, ' ').trim()
|
|
62
|
+
context.report({ loc: comment.loc, messageId: 'copied', data: { text: note } })
|
|
63
|
+
}
|
|
64
|
+
reportSpec({ loc: comment.loc }, comment.value)
|
|
65
|
+
})
|
|
66
|
+
},
|
|
67
|
+
Literal(node) {
|
|
68
|
+
if (typeof node.value === 'string') {
|
|
69
|
+
reportSpec({ node }, node.value)
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
TemplateElement(node) {
|
|
73
|
+
reportSpec({ node }, node.value.cooked ?? node.value.raw)
|
|
74
|
+
},
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The `//` comments that directly follow a `//` comment, one per line. */
|
|
80
|
+
function continuation(comments, index) {
|
|
81
|
+
const following = []
|
|
82
|
+
let previous = comments[index]
|
|
83
|
+
while (previous.type === 'Line') {
|
|
84
|
+
const next = comments[index + following.length + 1]
|
|
85
|
+
if (next?.type !== 'Line' || next.loc.start.line !== previous.loc.end.line + 1) {
|
|
86
|
+
break
|
|
87
|
+
}
|
|
88
|
+
following.push(next)
|
|
89
|
+
previous = next
|
|
90
|
+
}
|
|
91
|
+
return following
|
|
92
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `nera/no-local-helper`: a function that copies a `@nera-static/plugin-utils`
|
|
3
|
+
* helper, by its name or by its shape, instead of importing it (D6). The names
|
|
4
|
+
* come from `settings.nera.helpers` (see `helperNames`); a shape fires only when
|
|
5
|
+
* the export it points to exists there.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Shapes of a local helper, checked in this order; the first match is reported. */
|
|
9
|
+
const SHAPES = Object.freeze([
|
|
10
|
+
{ helper: 'isPlainObject', what: 'a plain-object check', matches: (fn, code) => isPlainObjectCheck(result(fn), code) },
|
|
11
|
+
{ helper: 'pageLang', what: 'the page language `meta.lang || app.lang`', matches: (fn) => isLangFallback(result(fn)) },
|
|
12
|
+
{ helper: 'escapeXml', what: 'XML escaping', matches: (fn, code) => escapes(fn, code, { xml: true }) },
|
|
13
|
+
{ helper: 'escapeHtml', what: 'HTML escaping', matches: (fn, code) => escapes(fn, code, { xml: false }) },
|
|
14
|
+
{ helper: 'satisfiesFloor', what: 'semver parsing', matches: (fn, code) => parsesSemver(fn, code) },
|
|
15
|
+
])
|
|
16
|
+
|
|
17
|
+
const ENTITY = /^&(?:amp|lt|gt|quot|apos|#0*39|#x0*27);$/
|
|
18
|
+
const ESCAPED_CHARACTERS = /&[^\]]*<|<[^\]]*&/
|
|
19
|
+
const VERSION_PATTERN = /\\d[+*]\)?\\\.\(?\\d/
|
|
20
|
+
const TO_NUMBER = Object.freeze(['Number', 'parseInt'])
|
|
21
|
+
const FUNCTION = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'])
|
|
22
|
+
|
|
23
|
+
export default {
|
|
24
|
+
meta: {
|
|
25
|
+
type: 'suggestion',
|
|
26
|
+
docs: {
|
|
27
|
+
description: 'Import the helpers @nera-static/plugin-utils exports instead of declaring a local copy',
|
|
28
|
+
},
|
|
29
|
+
schema: [],
|
|
30
|
+
messages: {
|
|
31
|
+
localCopy: '`{{name}}` is a local copy of a @nera-static/plugin-utils helper: delete it and ' +
|
|
32
|
+
"`import { {{name}} } from '{{specifier}}'`",
|
|
33
|
+
handRolls: '`{{name}}` hand-rolls `{{helper}}` ({{what}}): ' +
|
|
34
|
+
"`import { {{helper}} } from '{{specifier}}'` and call it instead",
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
create(context) {
|
|
39
|
+
const helpers = context.settings.nera?.helpers ?? {}
|
|
40
|
+
const code = context.sourceCode
|
|
41
|
+
const shapes = SHAPES.filter(({ helper }) => Object.hasOwn(helpers, helper))
|
|
42
|
+
|
|
43
|
+
function check(id, fn) {
|
|
44
|
+
if (Object.hasOwn(helpers, id.name)) {
|
|
45
|
+
context.report({
|
|
46
|
+
node: id,
|
|
47
|
+
messageId: 'localCopy',
|
|
48
|
+
data: { name: id.name, specifier: helpers[id.name] },
|
|
49
|
+
})
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
const shape = shapes.find(({ matches }) => matches(fn, code))
|
|
53
|
+
if (shape) {
|
|
54
|
+
context.report({
|
|
55
|
+
node: id,
|
|
56
|
+
messageId: 'handRolls',
|
|
57
|
+
data: { name: id.name, helper: shape.helper, what: shape.what, specifier: helpers[shape.helper] },
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
FunctionDeclaration(node) {
|
|
64
|
+
if (node.id) {
|
|
65
|
+
check(node.id, node)
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
VariableDeclarator(node) {
|
|
69
|
+
if (node.id.type === 'Identifier' && isHelperFunction(node.init)) {
|
|
70
|
+
check(node.id, node.init)
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isHelperFunction(node) {
|
|
78
|
+
return Boolean(node) && (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** What a function returns when its whole body is one expression, else `null`. */
|
|
82
|
+
function result(fn) {
|
|
83
|
+
if (fn.body.type !== 'BlockStatement') {
|
|
84
|
+
return fn.body
|
|
85
|
+
}
|
|
86
|
+
const [only, ...rest] = fn.body.body
|
|
87
|
+
return rest.length === 0 && only?.type === 'ReturnStatement' ? only.argument : null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The operands of a chain of the same logical operator(s), flattened. */
|
|
91
|
+
function operands(node, operators) {
|
|
92
|
+
if (node?.type === 'LogicalExpression' && operators.includes(node.operator)) {
|
|
93
|
+
return [...operands(node.left, operators), ...operands(node.right, operators)]
|
|
94
|
+
}
|
|
95
|
+
return node ? [node] : []
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* `typeof x === 'object' && … && !Array.isArray(x)` on the same `x`, where every other
|
|
100
|
+
* term only narrows the type of `x` too: a check that also tests a property of `x`
|
|
101
|
+
* (`x['@context'] != null`) is a predicate of its own, not a copy of `isPlainObject`.
|
|
102
|
+
*/
|
|
103
|
+
function isPlainObjectCheck(expression, code) {
|
|
104
|
+
const terms = operands(expression, ['&&'])
|
|
105
|
+
const typed = terms.map(typeofObjectSubject).filter(Boolean).map((node) => code.getText(node))
|
|
106
|
+
const notArrays = terms.map(notArraySubject).filter(Boolean).map((node) => code.getText(node))
|
|
107
|
+
const subject = typed.find((text) => notArrays.includes(text))
|
|
108
|
+
return subject !== undefined && terms.every((term) => {
|
|
109
|
+
const narrowed = typeofObjectSubject(term) ?? notArraySubject(term) ?? typeGuardSubject(term)
|
|
110
|
+
return narrowed !== null && code.getText(narrowed) === subject
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The value a type-only guard tests: `x`, `!!x`, `x !== null`, `x != null`, `!(x instanceof Y)`. */
|
|
115
|
+
function typeGuardSubject(node) {
|
|
116
|
+
if (node.type === 'Identifier' || node.type === 'MemberExpression') {
|
|
117
|
+
return node
|
|
118
|
+
}
|
|
119
|
+
if (node.type === 'UnaryExpression' && node.operator === '!') {
|
|
120
|
+
const inner = node.argument
|
|
121
|
+
if (inner.type === 'UnaryExpression' && inner.operator === '!') {
|
|
122
|
+
return inner.argument
|
|
123
|
+
}
|
|
124
|
+
return inner.type === 'BinaryExpression' && inner.operator === 'instanceof' ? inner.left : null
|
|
125
|
+
}
|
|
126
|
+
if (node.type !== 'BinaryExpression' || !['!==', '!='].includes(node.operator)) {
|
|
127
|
+
return null
|
|
128
|
+
}
|
|
129
|
+
const isNullish = (side) => (side.type === 'Literal' && side.value === null) ||
|
|
130
|
+
(side.type === 'Identifier' && side.name === 'undefined')
|
|
131
|
+
if (isNullish(node.right)) {
|
|
132
|
+
return node.left
|
|
133
|
+
}
|
|
134
|
+
return isNullish(node.left) ? node.right : null
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function typeofObjectSubject(node) {
|
|
138
|
+
if (node.type !== 'BinaryExpression' || !['===', '=='].includes(node.operator)) {
|
|
139
|
+
return null
|
|
140
|
+
}
|
|
141
|
+
const sides = [[node.left, node.right], [node.right, node.left]]
|
|
142
|
+
const match = sides.find(([typed, literal]) => typed.type === 'UnaryExpression' && typed.operator === 'typeof' &&
|
|
143
|
+
literal.type === 'Literal' && literal.value === 'object')
|
|
144
|
+
return match ? match[0].argument : null
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function notArraySubject(node) {
|
|
148
|
+
if (node.type !== 'UnaryExpression' || node.operator !== '!' || node.argument.type !== 'CallExpression') {
|
|
149
|
+
return null
|
|
150
|
+
}
|
|
151
|
+
const { callee, arguments: args } = node.argument
|
|
152
|
+
return isMember(callee, 'isArray') && callee.object.type === 'Identifier' && callee.object.name === 'Array'
|
|
153
|
+
? args[0] ?? null
|
|
154
|
+
: null
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** `meta.lang || app.lang` (also with `??` and a further fallback). */
|
|
158
|
+
function isLangFallback(expression) {
|
|
159
|
+
return operands(expression, ['||', '??']).filter((node) => isMember(node, 'lang')).length >= 2
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** A `.replace()`/`.replaceAll()` that writes an HTML entity or matches `&` and `<` together. */
|
|
163
|
+
function escapes(fn, code, { xml }) {
|
|
164
|
+
const nodes = descendants(fn, code)
|
|
165
|
+
const escaping = nodes.some((node) => node.type === 'CallExpression' &&
|
|
166
|
+
(isMember(node.callee, 'replace') || isMember(node.callee, 'replaceAll')) &&
|
|
167
|
+
isEscapeCall(...node.arguments))
|
|
168
|
+
if (!escaping) {
|
|
169
|
+
return false
|
|
170
|
+
}
|
|
171
|
+
const writesApos = nodes.some((node) => node.type === 'Literal' && node.value === ''')
|
|
172
|
+
return writesApos === xml
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function isEscapeCall(pattern, replacement) {
|
|
176
|
+
return (replacement?.type === 'Literal' && ENTITY.test(String(replacement.value))) ||
|
|
177
|
+
Boolean(pattern?.regex && ESCAPED_CHARACTERS.test(pattern.regex.pattern))
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** `.split('.').map(Number)` (or `parseInt`, also in a callback) or a `\d+\.\d+` regular expression. */
|
|
181
|
+
function parsesSemver(fn, code) {
|
|
182
|
+
return descendants(fn, code).some((node) => (node.type === 'Literal' && node.regex &&
|
|
183
|
+
VERSION_PATTERN.test(node.regex.pattern)) || isSplitDotsToNumbers(node, code))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function isSplitDotsToNumbers(node, code) {
|
|
187
|
+
if (node.type !== 'CallExpression' || !isMember(node.callee, 'map')) {
|
|
188
|
+
return false
|
|
189
|
+
}
|
|
190
|
+
const split = node.callee.object
|
|
191
|
+
const splitsDots = split.type === 'CallExpression' && isMember(split.callee, 'split') &&
|
|
192
|
+
split.arguments[0]?.type === 'Literal' && split.arguments[0].value === '.'
|
|
193
|
+
const [mapper] = node.arguments
|
|
194
|
+
const toNumber = (mapper?.type === 'Identifier' && TO_NUMBER.includes(mapper.name)) ||
|
|
195
|
+
(FUNCTION.has(mapper?.type) && TO_NUMBER.some((name) => code.getText(mapper.body).includes(`${name}(`)))
|
|
196
|
+
return splitsDots && toNumber
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function isMember(node, property) {
|
|
200
|
+
if (node?.type !== 'MemberExpression') {
|
|
201
|
+
return false
|
|
202
|
+
}
|
|
203
|
+
return node.computed
|
|
204
|
+
? node.property.type === 'Literal' && node.property.value === property
|
|
205
|
+
: node.property.type === 'Identifier' && node.property.name === property
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Every node inside `fn`'s body, without descending into a nested function
|
|
210
|
+
* declaration or a function assigned to a variable: those are checked on their own.
|
|
211
|
+
*/
|
|
212
|
+
function descendants(fn, code) {
|
|
213
|
+
const found = []
|
|
214
|
+
const queue = [fn.body]
|
|
215
|
+
while (queue.length > 0) {
|
|
216
|
+
const node = queue.shift()
|
|
217
|
+
found.push(node)
|
|
218
|
+
for (const key of code.visitorKeys[node.type] ?? []) {
|
|
219
|
+
for (const child of [node[key]].flat()) {
|
|
220
|
+
if (child && typeof child.type === 'string' && !isOwnHelper(child, node)) {
|
|
221
|
+
queue.push(child)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return found
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function isOwnHelper(child, parent) {
|
|
230
|
+
return child.type === 'FunctionDeclaration' || (parent.type === 'VariableDeclarator' && isHelperFunction(child))
|
|
231
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* References to the global `name`, whether declared as a global or left
|
|
3
|
+
* unresolved; a local shadow is skipped.
|
|
4
|
+
*
|
|
5
|
+
* @param {object} scope - The program's global scope.
|
|
6
|
+
* @param {string} name - The global's name, e.g. `console` or `process`.
|
|
7
|
+
* @returns {object[]} ESLint scope references.
|
|
8
|
+
*/
|
|
9
|
+
export function globalReferences(scope, name) {
|
|
10
|
+
const declared = scope.set.get(name)
|
|
11
|
+
return declared
|
|
12
|
+
? declared.references
|
|
13
|
+
: scope.through.filter((reference) => reference.identifier.name === name)
|
|
14
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { isRuntimeFile, repoFile } from '../repo-files.js'
|
|
2
|
+
import { globalReferences } from './scope.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `nera/shared-logger`: plugin runtime code logs through the shared logger of
|
|
6
|
+
* `@nera-static/plugin-utils`, never through a bare `console.*` call (D8). Plugins
|
|
7
|
+
* only; tests, `bin/`, `scripts/`, `views/` and `assets/` are not runtime code.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const LOGGER = 'createLogger'
|
|
11
|
+
const LOGGER_SPECIFIER = '@nera-static/plugin-utils/log'
|
|
12
|
+
|
|
13
|
+
export default {
|
|
14
|
+
meta: {
|
|
15
|
+
type: 'suggestion',
|
|
16
|
+
docs: {
|
|
17
|
+
description: 'Log through createLogger from @nera-static/plugin-utils in plugin runtime code',
|
|
18
|
+
},
|
|
19
|
+
schema: [],
|
|
20
|
+
messages: {
|
|
21
|
+
bareConsole: '`console.{{method}}` in plugin runtime code: ' +
|
|
22
|
+
"`import { createLogger } from '{{specifier}}'`, create one logger with " +
|
|
23
|
+
"`createLogger('{{name}}')` and call its `warn`/`info` instead",
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
|
|
27
|
+
create(context) {
|
|
28
|
+
const { kind, root = context.cwd, name = 'plugin-<name>', helpers = {} } = context.settings.nera ?? {}
|
|
29
|
+
if (kind !== 'plugin' || !isRuntimeFile(repoFile(root, context.filename))) {
|
|
30
|
+
return {}
|
|
31
|
+
}
|
|
32
|
+
const specifier = helpers[LOGGER] ?? LOGGER_SPECIFIER
|
|
33
|
+
const loggerName = name.replace(/^@nera-static\//, '')
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
'Program:exit'(program) {
|
|
37
|
+
for (const reference of globalReferences(context.sourceCode.getScope(program), 'console')) {
|
|
38
|
+
const { parent } = reference.identifier
|
|
39
|
+
if (parent.type === 'MemberExpression' && parent.object === reference.identifier) {
|
|
40
|
+
context.report({
|
|
41
|
+
node: parent,
|
|
42
|
+
messageId: 'bareConsole',
|
|
43
|
+
data: { method: memberName(parent), specifier, name: loggerName },
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function memberName(member) {
|
|
53
|
+
if (!member.computed && member.property.type === 'Identifier') {
|
|
54
|
+
return member.property.name
|
|
55
|
+
}
|
|
56
|
+
return member.property.type === 'Literal' ? String(member.property.value) : '[…]'
|
|
57
|
+
}
|