-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathno-raw-text.ts
844 lines (780 loc) · 21.7 KB
/
no-raw-text.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
/**
* @author kazuya kawaguchi (a.k.a. kazupon)
*/
import { parse, AST as VAST } from 'vue-eslint-parser'
import type { AST as JSONAST } from 'jsonc-eslint-parser'
import { parseJSON, getStaticJSONValue } from 'jsonc-eslint-parser'
import type { StaticLiteral } from '../utils/index'
import {
getStaticLiteralValue,
isStaticLiteral,
defineTemplateBodyVisitor,
getLocaleMessages,
getStaticAttributes,
getVueObjectType,
isI18nBlock,
isVElement
} from '../utils/index'
import type {
JSXText,
RuleContext,
RuleFixer,
Variable,
RuleListener,
SuggestionReportDescriptor,
Fix,
I18nLocaleMessageDictionary,
Range
} from '../types'
import { isKebabCase, pascalCase } from '../utils/casing'
import { createRule } from '../utils/rule'
import { toRegExp } from '../utils/regexp'
type LiteralValue = VAST.ESLintLiteral['value']
type TemplateOptionValueNode = StaticLiteral
type NodeScope = 'template' | 'template-option' | 'jsx'
type TargetAttrs = { name: RegExp; attrs: Set<string> }
type Config = {
attributes: TargetAttrs[]
ignorePattern: RegExp
ignoreNodes: string[]
ignoreText: string[]
}
type Quotes = Set<'"' | "'" | '`'>
function getFixQuote(quotes: Quotes, code: string) {
if (!code.includes('\n')) {
for (const q of ["'", '"'] as const) {
if (!quotes.has(q) && !code.includes(q)) {
return q
}
}
}
if (!quotes.has('`') && !code.includes('`')) {
return '`'
}
return null
}
const hasOnlyWhitespace = (value: string) => /^[\r\n\s\t\f\v]+$/.test(value)
const INNER_START_OFFSET = '<template>'.length
/**
* Get the attribute to be verified from the element name.
*/
function getTargetAttrs(tagName: string, config: Config): Set<string> {
const result = []
for (const { name, attrs } of config.attributes) {
name.lastIndex = 0
if (name.test(tagName)) {
result.push(...attrs)
}
}
if (isKebabCase(tagName)) {
result.push(...getTargetAttrs(pascalCase(tagName), config))
}
return new Set(result)
}
function calculateRange(
node: StaticLiteral | VAST.VText | JSXText | VAST.VLiteral | VAST.VIdentifier,
base: TemplateOptionValueNode | null
): Range {
const range = node.range
if (!base) {
return range
}
const offset = base.range[0] + 1 /* quote */ - INNER_START_OFFSET
return [offset + range[0], offset + range[1]]
}
function calculateLoc(
node: StaticLiteral | VAST.VText | JSXText | VAST.VLiteral,
base: TemplateOptionValueNode | null,
context: RuleContext
) {
if (!base) {
return node.loc
}
const range = calculateRange(node, base)
return {
start: context.getSourceCode().getLocFromIndex(range[0]),
end: context.getSourceCode().getLocFromIndex(range[1])
}
}
function testValue(value: LiteralValue, config: Config): boolean {
if (typeof value === 'string') {
return (
hasOnlyWhitespace(value) ||
config.ignorePattern.test(value.trim()) ||
config.ignoreText.includes(value.trim())
)
} else {
return false
}
}
// parent is directive (e.g <p v-xxx="..."></p>)
function checkVAttributeDirective(
context: RuleContext,
node: VAST.VExpressionContainer & {
parent: VAST.VDirective
},
config: Config,
baseNode: TemplateOptionValueNode | null,
scope: NodeScope
) {
const attrNode = node.parent
if (attrNode.key && attrNode.key.type === 'VDirectiveKey') {
if (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore -- for vue-eslint-parser v5
(attrNode.key.name === 'text' ||
// for vue-eslint-parser v6+
attrNode.key.name.name === 'text') &&
node.expression
) {
checkExpressionContainerText(
context,
node.expression,
config,
baseNode,
scope
)
}
}
}
function checkVExpressionContainer(
context: RuleContext,
node: VAST.VExpressionContainer,
config: Config,
baseNode: TemplateOptionValueNode | null,
scope: NodeScope
) {
if (!node.expression) {
return
}
if (node.parent && node.parent.type === 'VElement') {
// parent is element (e.g. <p>{{ ... }}</p>)
checkExpressionContainerText(
context,
node.expression,
config,
baseNode,
scope
)
} else if (
node.parent &&
node.parent.type === 'VAttribute' &&
node.parent.directive
) {
checkVAttributeDirective(
context,
node as VAST.VExpressionContainer & {
parent: VAST.VDirective
},
config,
baseNode,
scope
)
}
}
function checkExpressionContainerText(
context: RuleContext,
expression: Exclude<VAST.VExpressionContainer['expression'], null>,
config: Config,
baseNode: TemplateOptionValueNode | null,
scope: NodeScope
) {
if (isStaticLiteral(expression)) {
checkLiteral(context, expression, config, baseNode, scope)
} else if (expression.type === 'ConditionalExpression') {
const targets = [expression.consequent, expression.alternate]
targets.forEach(target => {
if (isStaticLiteral(target)) {
checkLiteral(context, target, config, baseNode, scope)
}
})
}
}
function checkLiteral(
context: RuleContext,
literal: StaticLiteral,
config: Config,
baseNode: TemplateOptionValueNode | null,
scope: NodeScope
) {
const value = getStaticLiteralValue(literal)
if (testValue(value, config)) {
return
}
const loc = calculateLoc(literal, baseNode, context)
context.report({
loc,
message: `raw text '${value}' is used`,
suggest: buildSuggest()
})
function buildSuggest(): SuggestionReportDescriptor[] | null {
if (scope === 'template-option') {
if (!withoutEscape(context, baseNode)) {
return null
}
} else if (scope !== 'template') {
return null
}
const replaceRange = calculateRange(literal, baseNode)
const suggest: SuggestionReportDescriptor[] = []
for (const key of extractMessageKeys(context, `${value}`)) {
suggest.push({
desc: `Replace to "$t('${key}')".`,
fix(fixer) {
return fixer.replaceTextRange(replaceRange, `$t('${key}')`)
}
})
}
const i18nBlocks = getFixableI18nBlocks(context, `${value}`)
if (i18nBlocks) {
suggest.push({
desc: "Add the resource to the '<i18n>' block.",
fix(fixer) {
return generateFixAddI18nBlock(
context,
fixer,
i18nBlocks,
`${value}`,
[
fixer.insertTextBeforeRange(replaceRange, '$t('),
fixer.insertTextAfterRange(replaceRange, ')')
]
)
}
})
}
return suggest
}
}
function checkVAttribute(
context: RuleContext,
attribute: VAST.VAttribute,
config: Config,
baseNode: TemplateOptionValueNode | null,
scope: NodeScope
) {
if (!attribute.value) {
return
}
const literal = attribute.value
const value = literal.value
if (testValue(value, config)) {
return
}
const loc = calculateLoc(literal, baseNode, context)
context.report({
loc,
message: `raw text '${value}' is used`,
suggest: buildSuggest()
})
function buildSuggest(): SuggestionReportDescriptor[] | null {
if (scope === 'template-option') {
if (!withoutEscape(context, baseNode)) {
return null
}
} else if (scope !== 'template') {
return null
}
const literalRange = calculateRange(literal, baseNode)
const replaceRange = [literalRange[0] + 1, literalRange[1] - 1] as Range
const keyRange = calculateRange(attribute.key, baseNode)
const sourceCode = context.getSourceCode()
const attrQuote = sourceCode.text[literalRange[0]]
const quotes: Quotes = new Set(attrQuote as never)
if (baseNode) {
const baseQuote = sourceCode.text[baseNode.range[0]]
quotes.add(baseQuote as never)
}
const suggest: SuggestionReportDescriptor[] = []
for (const key of extractMessageKeys(context, `${value}`)) {
const quote = getFixQuote(quotes, key)
if (quote) {
suggest.push({
desc: `Replace to "$t('${key}')".`,
fix(fixer) {
return [
fixer.insertTextBeforeRange(keyRange, ':'),
fixer.replaceTextRange(replaceRange, `$t(${quote}${key}${quote})`)
]
}
})
}
}
const i18nBlocks = getFixableI18nBlocks(context, `${value}`)
const quote = getFixQuote(quotes, sourceCode.text.slice(...replaceRange))
if (i18nBlocks && quote) {
suggest.push({
desc: "Add the resource to the '<i18n>' block.",
fix(fixer) {
return generateFixAddI18nBlock(
context,
fixer,
i18nBlocks,
`${value}`,
[
fixer.insertTextBeforeRange(keyRange, ':'),
fixer.insertTextBeforeRange(replaceRange, `$t(${quote}`),
fixer.insertTextAfterRange(replaceRange, `${quote})`)
]
)
}
})
}
return suggest
}
}
function checkText(
context: RuleContext,
textNode: VAST.VText | JSXText,
config: Config,
baseNode: TemplateOptionValueNode | null,
scope: NodeScope
) {
const value = textNode.value
if (testValue(value, config)) {
return
}
const loc = calculateLoc(textNode, baseNode, context)
context.report({
loc,
message: `raw text '${value}' is used`,
suggest: buildSuggest()
})
function buildSuggest(): SuggestionReportDescriptor[] | null {
if (scope === 'template-option') {
if (!withoutEscape(context, baseNode)) {
return null
}
}
const replaceRange = calculateRange(textNode, baseNode)
const sourceCode = context.getSourceCode()
const quotes: Quotes = new Set()
if (baseNode) {
const baseQuote = sourceCode.text[baseNode.range[0]]
quotes.add(baseQuote as never)
}
const suggest: SuggestionReportDescriptor[] = []
for (const key of extractMessageKeys(context, value)) {
const quote = getFixQuote(quotes, key)
if (quote) {
const before = `${scope === 'jsx' ? '{' : '{{'}$t(${quote}`
const after = `${quote})${scope === 'jsx' ? '}' : '}}'}`
suggest.push({
desc: `Replace to "${before}${key}${after}".`,
fix(fixer) {
return fixer.replaceTextRange(replaceRange, before + key + after)
}
})
}
}
const i18nBlocks = getFixableI18nBlocks(context, `${value}`)
const quote = getFixQuote(quotes, sourceCode.text.slice(...replaceRange))
if (i18nBlocks && quote) {
const before = `${scope === 'jsx' ? '{' : '{{'}$t(${quote}`
const after = `${quote})${scope === 'jsx' ? '}' : '}}'}`
suggest.push({
desc: "Add the resource to the '<i18n>' block.",
fix(fixer) {
return generateFixAddI18nBlock(
context,
fixer,
i18nBlocks,
`${value}`,
[
fixer.insertTextBeforeRange(replaceRange, before),
fixer.insertTextAfterRange(replaceRange, after)
]
)
}
})
}
return suggest
}
}
function findVariable(variables: Variable[], name: string) {
return variables.find(variable => variable.name === name)
}
function getComponentTemplateValueNode(
context: RuleContext,
node: VAST.ESLintObjectExpression
): TemplateOptionValueNode | null {
const templateNode = node.properties.find(
(p): p is VAST.ESLintProperty =>
p.type === 'Property' &&
p.key.type === 'Identifier' &&
p.key.name === 'template'
)
if (templateNode) {
if (isStaticLiteral(templateNode.value)) {
return templateNode.value
} else if (templateNode.value.type === 'Identifier') {
const templateVariable = findVariable(
context.getScope().variables,
templateNode.value.name
)
if (templateVariable) {
const varDeclNode = templateVariable.defs[0]
.node as VAST.ESLintVariableDeclarator
if (varDeclNode.init) {
if (isStaticLiteral(varDeclNode.init)) {
return varDeclNode.init
}
}
}
}
}
return null
}
function getComponentTemplateNode(node: TemplateOptionValueNode) {
return parse(`<template>${getStaticLiteralValue(node)}</template>`, {})
.templateBody!
}
function withoutEscape(
context: RuleContext,
baseNode: TemplateOptionValueNode | null
) {
if (!baseNode) {
return false
}
const sourceText = context.getSourceCode().getText(baseNode).slice(1, -1)
const templateText = `${getStaticLiteralValue(baseNode)}`
return sourceText === templateText
}
type I18nBlockInfo = {
attrs: { [name: string]: string | undefined }
i18n: VAST.VElement
offsets: {
getLoc: (index: number) => { line: number; column: number }
getIndex: (index: number) => number
}
objects: JSONAST.JSONObjectExpression[]
}
function getFixableI18nBlocks(
context: RuleContext,
newKey: string
): I18nBlockInfo[] | null {
const df = context.parserServices.getDocumentFragment?.()
if (!df) {
return null
}
const i18nBlocks: I18nBlockInfo[] = []
for (const i18n of df.children.filter(isI18nBlock)) {
const attrs = getStaticAttributes(i18n)
if (
attrs.src != null ||
(attrs.lang != null && attrs.lang !== 'json' && attrs.lang !== 'json5') // Do not support yaml
) {
return null
}
const textNode = i18n.children[0]
const sourceString =
textNode != null && textNode.type === 'VText' && textNode.value
if (!sourceString) {
return null
}
try {
const ast = parseJSON(sourceString)
const root = ast.body[0].expression
if (root.type !== 'JSONObjectExpression') {
// Maybe invalid messages
return null
}
const objects: JSONAST.JSONObjectExpression[] = []
if (attrs.locale) {
objects.push(root)
} else {
for (const prop of root.properties) {
if (prop.value.type !== 'JSONObjectExpression') {
// Maybe invalid messages
return null
}
objects.push(prop.value)
}
}
// check for new key
// If there are duplicate keys, the addition will be stopped.
for (const objNode of objects) {
if (
objNode.properties.some(prop => {
const keyValue = `${getStaticJSONValue(prop.key)}`
return keyValue === newKey
})
) {
return null
}
}
const offset = textNode.range[0]
const getIndex = (index: number): number => offset + index
i18nBlocks.push({
attrs,
i18n,
objects,
offsets: {
getLoc: (index: number) => {
return context.getSourceCode().getLocFromIndex(getIndex(index))
},
getIndex
}
})
} catch {
return null
}
}
return i18nBlocks
}
function* generateFixAddI18nBlock(
context: RuleContext,
fixer: RuleFixer,
i18nBlocks: I18nBlockInfo[],
resource: string,
replaceFixes: Fix[]
): IterableIterator<Fix> {
const text = JSON.stringify(resource)
const df = context.parserServices.getDocumentFragment!()!
const tokenStore = context.parserServices.getTemplateBodyTokenStore()
if (!i18nBlocks.length) {
let baseToken: VAST.VElement | VAST.Token = df.children.find(isVElement)!
let beforeToken = tokenStore.getTokenBefore(baseToken, {
includeComments: true
})
while (beforeToken && beforeToken.type === 'HTMLComment') {
baseToken = beforeToken
beforeToken = tokenStore.getTokenBefore(beforeToken, {
includeComments: true
})
}
yield fixer.insertTextBeforeRange(
baseToken.range,
`<i18n>\n{\n "en": {\n ${text}: ${text}\n }\n}\n</i18n>\n\n`
)
yield* replaceFixes
return
}
const replaceFix = replaceFixes[0]
const after = i18nBlocks.find(e => replaceFix.range[1] < e.i18n.range[0])
for (const { i18n, offsets, objects } of i18nBlocks) {
if (after && after.i18n === i18n) {
yield* replaceFixes
}
for (const objectNode of objects) {
const first = objectNode.properties[0]
let indent =
/^\s*/.exec(
context.getSourceCode().lines[
offsets.getLoc(objectNode.range[0]).line - 1
]
)![0] + ' '
let next = ''
if (first) {
if (objectNode.loc.start.line === first.loc.start.line) {
next = ',\n' + indent
} else {
indent = /^\s*/.exec(
context.getSourceCode().lines[
offsets.getLoc(first.range[0]).line - 1
]
)![0]
next = ','
}
}
yield fixer.insertTextAfterRange(
[
offsets.getIndex(objectNode.range[0]),
offsets.getIndex(objectNode.range[0] + 1)
],
`\n${indent}${text}: ${text}${next}`
)
}
}
if (after == null) {
yield* replaceFixes
}
}
function extractMessageKeys(
context: RuleContext,
targetValue: string
): string[] {
const keys = new Set<string>()
const localeMessages = getLocaleMessages(context, {
ignoreMissingSettingsError: true
})
for (const localeMessage of localeMessages.localeMessages) {
for (const locale of localeMessage.locales) {
const messages = localeMessage.getMessagesFromLocale(locale)
for (const key of extractMessageKeysFromObject(messages, [])) {
keys.add(key)
}
}
}
return [...keys].sort()
function* extractMessageKeysFromObject(
messages: I18nLocaleMessageDictionary,
paths: string[]
): Iterable<string> {
for (const key of Object.keys(messages)) {
const value = messages[key]
if (value == null) {
continue
}
if (typeof value !== 'object') {
if (targetValue === value) {
yield [...paths, key].join('.')
}
} else {
yield* extractMessageKeysFromObject(value, [...paths, key])
}
}
}
}
/**
* Parse attributes option
*/
function parseTargetAttrs(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options: any
) {
const regexps: TargetAttrs[] = []
for (const tagName of Object.keys(options)) {
const attrs: Set<string> = new Set(options[tagName])
regexps.push({
name: toRegExp(tagName),
attrs
})
}
return regexps
}
function create(context: RuleContext): RuleListener {
const options = context.options[0] || {}
const config: Config = {
attributes: [],
ignorePattern: /^$/,
ignoreNodes: [],
ignoreText: []
}
if (options.ignorePattern) {
config.ignorePattern = new RegExp(options.ignorePattern, 'u')
}
if (options.ignoreNodes) {
config.ignoreNodes = options.ignoreNodes
}
if (options.ignoreText) {
config.ignoreText = options.ignoreText
}
if (options.attributes) {
config.attributes = parseTargetAttrs(options.attributes)
}
const templateVisitor = {
// template block
VExpressionContainer(
node: VAST.VExpressionContainer,
baseNode: TemplateOptionValueNode | null = null,
scope: NodeScope = 'template'
) {
checkVExpressionContainer(context, node, config, baseNode, scope)
},
VAttribute(
node: VAST.VAttribute,
baseNode: TemplateOptionValueNode | null = null,
scope: NodeScope = 'template'
) {
if (node.directive) {
return
}
const tagName = node.parent.parent.rawName
const attrName = node.key.name
if (!getTargetAttrs(tagName, config).has(attrName)) {
return
}
checkVAttribute(context, node, config, baseNode, scope)
},
VText(
node: VAST.VText,
baseNode: TemplateOptionValueNode | null = null,
scope: NodeScope = 'template'
) {
if (config.ignoreNodes.includes((node.parent as VAST.VElement).name)) {
return
}
checkText(context, node, config, baseNode, scope)
}
}
return defineTemplateBodyVisitor(context, templateVisitor, {
// script block or scripts
ObjectExpression(node: VAST.ESLintObjectExpression) {
const valueNode = getComponentTemplateValueNode(context, node)
if (!valueNode) {
return
}
if (
getVueObjectType(context, node) == null ||
(valueNode.type === 'Literal' && valueNode.value == null)
) {
return
}
const templateNode = getComponentTemplateNode(valueNode)
VAST.traverseNodes(templateNode, {
enterNode(node) {
const visitor:
| ((
node: VAST.Node,
baseNode: TemplateOptionValueNode,
scope: NodeScope
) => void)
| undefined =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
templateVisitor[node.type as never] as any
if (visitor) {
visitor(node, valueNode, 'template-option')
}
},
leaveNode() {
// noop
}
})
},
JSXText(node: JSXText) {
checkText(context, node, config, null, 'jsx')
}
})
}
export = createRule({
meta: {
type: 'suggestion',
docs: {
description: 'disallow to string literal in template or JSX',
category: 'Recommended',
url: 'https://eslint-plugin-vue-i18n.intlify.dev/rules/no-raw-text.html',
recommended: true
},
fixable: null,
hasSuggestions: true,
schema: [
{
type: 'object',
properties: {
attributes: {
type: 'object',
patternProperties: {
'^(?:\\S+|/.*/[a-z]*)$': {
type: 'array',
items: { type: 'string' },
uniqueItems: true
}
},
additionalProperties: false
},
ignoreNodes: {
type: 'array'
},
ignorePattern: {
type: 'string'
},
ignoreText: {
type: 'array'
}
}
}
]
},
create
})