-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathindex.ts
636 lines (583 loc) · 16.3 KB
/
index.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
import type { AST } from "svelte-eslint-parser"
import * as compiler from "svelte/compiler"
import type { SourceMapMappings } from "sourcemap-codec"
import { decode } from "sourcemap-codec"
import type { RuleContext } from "../../types"
import { LinesAndColumns } from "../../utils/lines-and-columns"
import type { TransformResult } from "./transform/types"
import {
hasTypeScript,
transform as transformWithTypescript,
} from "./transform/typescript"
import { transform as transformWithBabel } from "./transform/babel"
import { transform as transformWithPostCSS } from "./transform/postcss"
import { transform as transformWithSass } from "./transform/sass"
import { transform as transformWithLess } from "./transform/less"
import { transform as transformWithStylus } from "./transform/stylus"
import type { IgnoreItem } from "./ignore-comment"
import { getSvelteIgnoreItems } from "./ignore-comment"
import { extractLeadingComments } from "./extract-leading-comments"
import { getLangValue } from "../../utils/ast-utils"
import path from "path"
import fs from "fs"
const STYLE_TRANSFORMS: Record<
string,
typeof transformWithPostCSS | undefined
> = {
postcss: transformWithPostCSS,
pcss: transformWithPostCSS,
scss: (node, context) => transformWithSass(node, context, "scss"),
sass: (node, context) => transformWithSass(node, context, "sass"),
less: transformWithLess,
stylus: transformWithStylus,
styl: transformWithStylus,
}
const CSS_WARN_CODES = new Set([
"css-unused-selector",
"css-invalid-global",
"css-invalid-global-selector",
])
const cacheAll = new WeakMap<AST.SvelteProgram, SvelteCompileWarnings>()
export type SvelteCompileWarnings = {
warnings: Warning[]
unusedIgnores: IgnoreItem[]
kind: "warn" | "error"
stripStyleElements: AST.SvelteStyleElement[]
}
export type Loc = {
start?: {
line: number
column: number
}
end?: {
line: number
column: number
}
}
export type Warning = {
code?: string
message: string
} & Loc
/**
* Get svelte compile warnings
*/
export function getSvelteCompileWarnings(
context: RuleContext,
): SvelteCompileWarnings {
const sourceCode = context.getSourceCode()
const cache = cacheAll.get(sourceCode.ast)
if (cache) {
return cache
}
const result = getSvelteCompileWarningsWithoutCache(context)
cacheAll.set(sourceCode.ast, result)
return result
}
/**
* Get svelte compile warnings
*/
function getSvelteCompileWarningsWithoutCache(
context: RuleContext,
): SvelteCompileWarnings {
const sourceCode = context.getSourceCode()
// Process for styles
const styleElementsWithNotCSS = [
...extractStyleElementsWithLangOtherThanCSS(context),
]
const stripStyleElements: AST.SvelteStyleElement[] = []
const transformResults: TransformResult[] = []
for (const style of styleElementsWithNotCSS) {
const transform = STYLE_TRANSFORMS[style.lang]
if (transform) {
const result = transform(style.node, context)
if (result) {
transformResults.push(result)
continue
}
}
stripStyleElements.push(style.node)
}
const stripStyleTokens = stripStyleElements.flatMap((e) => e.children)
const ignoreComments = getSvelteIgnoreItems(context).filter(
(item): item is IgnoreItem => item.code != null,
)
const text = buildStrippedText(context, ignoreComments, stripStyleTokens)
transformResults.push(...transformScripts(context))
if (!transformResults.length) {
const warnings = getWarningsFromCode(text)
return {
...processIgnore(
warnings.warnings,
warnings.kind,
stripStyleElements,
ignoreComments,
context,
),
kind: warnings.kind,
stripStyleElements,
}
}
class RemapContext {
private originalStart = 0
private code = ""
private locs: LinesAndColumns | null = null
private readonly mapIndexes: {
range: [number, number]
remap: (index: number) => number
}[] = []
public appendOriginal(endIndex: number) {
const codeStart = this.code.length
const start = this.originalStart
this.code += text.slice(start, endIndex)
this.originalStart = endIndex
const offset = start - codeStart
this.mapIndexes.push({
range: [codeStart, this.code.length],
remap(index) {
return index + offset
},
})
}
public postprocess(): string {
this.appendOriginal(text.length)
return this.code
}
public appendTranspile(output: TransformResult) {
const endIndex: number = output.inputRange[1]
const codeStart = this.code.length
const start = this.originalStart
const inputText = text.slice(start, endIndex)
const outputText = `${output.output}\n`
this.code += outputText
this.originalStart = endIndex
let outputLocs: LinesAndColumns | null = null
let inputLocs: LinesAndColumns | null = null
let decoded: SourceMapMappings | null = null
this.mapIndexes.push({
range: [codeStart, this.code.length],
remap: (index) => {
outputLocs = outputLocs ?? new LinesAndColumns(outputText)
inputLocs = inputLocs ?? new LinesAndColumns(inputText)
const outputCodePos = outputLocs.getLocFromIndex(index - codeStart)
const inputCodePos = remapPosition(outputCodePos)
return inputLocs.getIndexFromLoc(inputCodePos) + start
},
})
/** Remapping source position */
function remapPosition(pos: { line: number; column: number }): {
line: number
column: number
} {
decoded = decoded ?? decode(output.mappings)
const lineMaps = decoded[pos.line - 1]
if (!lineMaps?.length) {
for (let line = pos.line - 1; line >= 0; line--) {
const prevLineMaps = decoded[line]
if (prevLineMaps?.length) {
const [, , sourceCodeLine, sourceCodeColumn] =
prevLineMaps[prevLineMaps.length - 1]
return {
line: sourceCodeLine! + 1,
column: sourceCodeColumn!,
}
}
}
return { line: -1, column: -1 }
}
for (let index = 0; index < lineMaps.length - 1; index++) {
const [generateCodeColumn, , sourceCodeLine, sourceCodeColumn] =
lineMaps[index]
if (
generateCodeColumn <= pos.column &&
pos.column < lineMaps[index + 1][0]
) {
return {
line: sourceCodeLine! + 1,
column: sourceCodeColumn! + (pos.column - generateCodeColumn),
}
}
}
const [generateCodeColumn, , sourceCodeLine, sourceCodeColumn] =
lineMaps[lineMaps.length - 1]
return {
line: sourceCodeLine! + 1,
column: sourceCodeColumn! + (pos.column - generateCodeColumn),
}
}
}
public remapLocs(points: {
start?: {
line: number
column: number
}
end?: {
line: number
column: number
}
}): {
start?: {
line: number
column: number
}
end?: {
line: number
column: number
}
} {
const mapIndexes = this.mapIndexes
const locs = (this.locs = this.locs ?? new LinesAndColumns(this.code))
let start:
| {
line: number
column: number
}
| undefined = undefined
let end:
| {
line: number
column: number
}
| undefined = undefined
if (points.start) {
const index = locs.getIndexFromLoc(points.start)
const remapped = remapIndex(index)
if (remapped) {
start = sourceCode.getLocFromIndex(remapped)
}
}
if (points.end) {
const index = locs.getIndexFromLoc(points.end)
const remapped = remapIndex(index - 1 /* include index */)
if (remapped) {
end = sourceCode.getLocFromIndex(remapped + 1 /* restore */)
}
}
return { start, end }
/** remap index */
function remapIndex(index: number) {
for (const mapIndex of mapIndexes) {
if (mapIndex.range[0] <= index && index < mapIndex.range[1]) {
return mapIndex.remap(index)
}
}
return null
}
}
}
const remapContext = new RemapContext()
for (const result of transformResults.sort(
(a, b) => a.inputRange[0] - b.inputRange[0],
)) {
remapContext.appendOriginal(result.inputRange[0])
remapContext.appendTranspile(result)
}
const code = remapContext.postprocess()
const baseWarnings = getWarningsFromCode(code)
const warnings: Warning[] = []
for (const warn of baseWarnings.warnings) {
let loc: Loc | null = null
/** Get re-mapped location */
// eslint-disable-next-line func-style -- ignore
const getLoc = function getLoc() {
if (loc) {
return loc
}
return (loc = remapContext.remapLocs(warn))
}
warnings.push({
code: warn.code,
message: warn.message,
get start() {
return getLoc().start
},
get end() {
return getLoc().end
},
})
}
return {
...processIgnore(
warnings,
baseWarnings.kind,
stripStyleElements,
ignoreComments,
context,
),
kind: baseWarnings.kind,
stripStyleElements,
}
}
/**
* Extracts the style with the lang attribute other than CSS.
*/
function* extractStyleElementsWithLangOtherThanCSS(
context: RuleContext,
): Iterable<{
node: AST.SvelteStyleElement
readonly lang: string
}> {
const sourceCode = context.getSourceCode()
const root = sourceCode.ast
for (const node of root.body) {
if (node.type === "SvelteStyleElement") {
const lang = getLangValue(node)
if (lang != null && lang.toLowerCase() !== "css") {
yield { node, lang: lang.toLowerCase() }
}
}
}
}
/**
* Build the text stripped of tokens that are not needed for compilation.
*/
function buildStrippedText(
context: RuleContext,
ignoreComments: IgnoreItem[],
stripStyleTokens: AST.SvelteText[],
) {
const sourceCode = context.getSourceCode()
const baseText = sourceCode.text
const stripTokens = new Set([
...ignoreComments.map((item) => item.token),
...stripStyleTokens,
])
if (!stripTokens.size) {
return baseText
}
let code = ""
let start = 0
for (const token of [...stripTokens].sort(
(a, b) => a.range[0] - b.range[0],
)) {
code +=
baseText.slice(start, token.range[0]) +
baseText.slice(...token.range).replace(/[^\t\n\r ]/g, " ")
start = token.range[1]
}
code += baseText.slice(start)
return code
}
/** Returns the result of transforming the required script for the transform. */
function* transformScripts(context: RuleContext) {
const transform = isUseTypeScript(context)
? hasTypeScript(context)
? transformWithTypescript
: transformWithBabel
: isUseBabel(context)
? transformWithBabel
: null
const sourceCode = context.getSourceCode()
if (transform) {
const root = sourceCode.ast
for (const node of root.body) {
if (node.type === "SvelteScriptElement") {
const result = transform(node, context)
if (result) {
yield result
}
}
}
}
}
/**
* Get compile warnings
*/
function getWarningsFromCode(code: string): {
warnings: Warning[]
kind: "warn" | "error"
} {
try {
const result = compiler.compile(code, {
generate: false,
})
return { warnings: result.warnings as Warning[], kind: "warn" }
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
} catch (e: any) {
return {
warnings: [
{
code: e.code,
message: e.message,
start: e.start,
end: e.end,
},
],
kind: "error",
}
}
}
/** Ignore process */
function processIgnore(
warnings: Warning[],
kind: "warn" | "error",
stripStyleElements: AST.SvelteStyleElement[],
ignoreComments: IgnoreItem[],
context: RuleContext,
): {
warnings: Warning[]
unusedIgnores: IgnoreItem[]
} {
if (kind === "error") {
return {
warnings,
unusedIgnores: ignoreComments,
}
}
const sourceCode = context.getSourceCode()
const unusedIgnores = new Set(ignoreComments)
const remainingWarning = new Set(warnings)
for (const warning of warnings) {
if (!warning.code) {
continue
}
const node = getWarningNode(warning)
if (!node) {
continue
}
for (const comment of extractLeadingComments(context, node).reverse()) {
const ignoreItem = ignoreComments.find(
(item) => item.token === comment && item.code === warning.code,
)
if (ignoreItem) {
unusedIgnores.delete(ignoreItem)
remainingWarning.delete(warning)
break
}
}
}
// Stripped styles are ignored from compilation and cannot determine css errors.
for (const node of stripStyleElements) {
for (const comment of extractLeadingComments(context, node).reverse()) {
const ignoreItem = ignoreComments.find(
(item) => item.token === comment && CSS_WARN_CODES.has(item.code),
)
if (ignoreItem) {
unusedIgnores.delete(ignoreItem)
break
}
}
}
return {
warnings: [...remainingWarning],
unusedIgnores: [...unusedIgnores],
}
/** Get warning node */
function getWarningNode(warning: Warning) {
const index = getWarningIndex(warning)
if (index == null) {
return null
}
let targetNode = sourceCode.getNodeByRangeIndex(index)
while (targetNode) {
if (
targetNode.type === "SvelteElement" ||
targetNode.type === "SvelteStyleElement"
) {
return targetNode
}
if (targetNode.parent) {
if (
targetNode.parent.type === "Program" ||
targetNode.parent.type === "SvelteScriptElement"
) {
return targetNode
}
} else {
return null
}
targetNode = targetNode.parent || null
}
return null
}
/** Get warning index */
function getWarningIndex(warning: Warning) {
const start = warning.start && sourceCode.getIndexFromLoc(warning.start)
const end = warning.end && sourceCode.getIndexFromLoc(warning.end)
if (start != null && end != null) {
return Math.floor(start + (end - start) / 2)
}
return start ?? end
}
}
/**
* Check if using TypeScript.
*/
function isUseTypeScript(context: RuleContext) {
if (context.parserServices.esTreeNodeToTSNodeMap) return true
const sourceCode = context.getSourceCode()
const root = sourceCode.ast
for (const node of root.body) {
if (node.type === "SvelteScriptElement") {
const lang = getLangValue(node)?.toLowerCase()
if (lang === "ts" || lang === "typescript") {
return true
}
}
}
return false
}
/**
* Check if using Babel.
*/
function isUseBabel(context: RuleContext) {
const parser = context.parserOptions?.parser
if (!parser) {
return false
}
const sourceCode = context.getSourceCode()
const root = sourceCode.ast
let scriptLang = "js"
for (const node of root.body) {
if (node.type === "SvelteScriptElement") {
const lang = getLangValue(node)?.toLowerCase()
if (lang === "ts" || lang === "typescript") {
scriptLang = lang
break
}
}
}
const parserName = getParserName(scriptLang, parser)
if (!parserName) {
return false
}
if (parserName === "@babel/eslint-parser") {
return true
}
if (parserName.includes("@babel/eslint-parser")) {
let targetPath = parserName
while (targetPath) {
const pkgPath = path.join(targetPath, "package.json")
if (fs.existsSync(pkgPath)) {
try {
return (
JSON.parse(fs.readFileSync(pkgPath, "utf-8"))?.name ===
"@babel/eslint-parser"
)
} catch {
return false
}
}
const parent = path.dirname(targetPath)
if (targetPath === parent) {
break
}
targetPath = parent
}
}
return false
/** Get script parser name */
function getParserName(
lang: string,
parser: string | Record<string, string>,
): string | null {
if (typeof parser === "string") {
return parser
} else if (typeof parser === "object") {
const name = parser[lang]
if (typeof name === "string") {
return name
}
}
return null
}
}