forked from vitejs/vite
/
utils.ts
739 lines (662 loc) · 20.2 KB
/
utils.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
import debug from 'debug'
import colors from 'picocolors'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { pathToFileURL, URL } from 'url'
import {
FS_PREFIX,
DEFAULT_EXTENSIONS,
VALID_ID_PREFIX,
CLIENT_PUBLIC_PATH,
ENV_PUBLIC_PATH,
CLIENT_ENTRY
} from './constants'
import resolve from 'resolve'
import { builtinModules } from 'module'
import type { FSWatcher } from 'chokidar'
import remapping from '@ampproject/remapping'
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping'
import { performance } from 'perf_hooks'
import { parse as parseUrl, URLSearchParams } from 'url'
export function slash(p: string): string {
return p.replace(/\\/g, '/')
}
// Strip valid id prefix. This is prepended to resolved Ids that are
// not valid browser import specifiers by the importAnalysis plugin.
export function unwrapId(id: string): string {
return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id
}
export const flattenId = (id: string): string =>
id.replace(/(\s*>\s*)/g, '__').replace(/[\/\.:]/g, '_')
export const normalizeId = (id: string): string =>
id.replace(/(\s*>\s*)/g, ' > ')
//TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
const builtins = new Set([
...builtinModules,
'assert/strict',
'diagnostics_channel',
'dns/promises',
'fs/promises',
'path/posix',
'path/win32',
'readline/promises',
'stream/consumers',
'stream/promises',
'stream/web',
'timers/promises',
'util/types',
'wasi'
])
export function isBuiltin(id: string): boolean {
return builtins.has(id.replace(/^node:/, ''))
}
export function moduleListContains(
moduleList: string[] | undefined,
id: string
): boolean | undefined {
return moduleList?.some((m) => m === id || id.startsWith(m + '/'))
}
export const bareImportRE = /^[\w@](?!.*:\/\/)/
export const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//
export let isRunningWithYarnPnp: boolean
try {
isRunningWithYarnPnp = Boolean(require('pnpapi'))
} catch {}
const ssrExtensions = ['.js', '.cjs', '.json', '.node']
export function resolveFrom(
id: string,
basedir: string,
preserveSymlinks = false,
ssr = false
): string {
return resolve.sync(id, {
basedir,
paths: [],
extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS,
// necessary to work with pnpm
preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false
})
}
/**
* like `resolveFrom` but supports resolving `>` path in `id`,
* for example: `foo > bar > baz`
*/
export function nestedResolveFrom(
id: string,
basedir: string,
preserveSymlinks = false
): string {
const pkgs = id.split('>').map((pkg) => pkg.trim())
try {
for (const pkg of pkgs) {
basedir = resolveFrom(pkg, basedir, preserveSymlinks)
}
} catch {}
return basedir
}
// set in bin/vite.js
const filter = process.env.VITE_DEBUG_FILTER
const DEBUG = process.env.DEBUG
interface DebuggerOptions {
onlyWhenFocused?: boolean | string
}
export type ViteDebugScope = `vite:${string}`
export function createDebugger(
namespace: ViteDebugScope,
options: DebuggerOptions = {}
): debug.Debugger['log'] {
const log = debug(namespace)
const { onlyWhenFocused } = options
const focus =
typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace
return (msg: string, ...args: any[]) => {
if (filter && !msg.includes(filter)) {
return
}
if (onlyWhenFocused && !DEBUG?.includes(focus)) {
return
}
log(msg, ...args)
}
}
function testCaseInsensitiveFS() {
if (!CLIENT_ENTRY.endsWith('client.mjs')) {
throw new Error(
`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`
)
}
if (!fs.existsSync(CLIENT_ENTRY)) {
throw new Error(
'cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' +
CLIENT_ENTRY
)
}
return fs.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'))
}
export const isCaseInsensitiveFS = testCaseInsensitiveFS()
export const isWindows = os.platform() === 'win32'
const VOLUME_RE = /^[A-Z]:/i
export function normalizePath(id: string): string {
return path.posix.normalize(isWindows ? slash(id) : id)
}
export function fsPathFromId(id: string): string {
const fsPath = normalizePath(
id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id
)
return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
? fsPath
: `/${fsPath}`
}
export function fsPathFromUrl(url: string): string {
return fsPathFromId(cleanUrl(url))
}
/**
* Check if dir is a parent of file
*
* Warning: parameters are not validated, only works with normalized absolute paths
*
* @param dir - normalized absolute path
* @param file - normalized absolute path
* @returns true if dir is a parent of file
*/
export function isParentDirectory(dir: string, file: string): boolean {
if (!dir.endsWith('/')) {
dir = `${dir}/`
}
return (
file.startsWith(dir) ||
(isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))
)
}
export function ensureVolumeInPath(file: string): string {
return isWindows ? path.resolve(file) : file
}
export const queryRE = /\?.*$/s
export const hashRE = /#.*$/s
export const cleanUrl = (url: string): string =>
url.replace(hashRE, '').replace(queryRE, '')
export const externalRE = /^(https?:)?\/\//
export const isExternalUrl = (url: string): boolean => externalRE.test(url)
export const dataUrlRE = /^\s*data:/i
export const isDataUrl = (url: string): boolean => dataUrlRE.test(url)
export const virtualModuleRE = /^virtual-module:.*/
export const virtualModulePrefix = 'virtual-module:'
const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte|astro)($|\?)/
export const isJSRequest = (url: string): boolean => {
url = cleanUrl(url)
if (knownJsSrcRE.test(url)) {
return true
}
if (!path.extname(url) && !url.endsWith('/')) {
return true
}
return false
}
const knownTsRE = /\.(ts|mts|cts|tsx)$/
const knownTsOutputRE = /\.(js|mjs|cjs|jsx)$/
export const isTsRequest = (url: string) => knownTsRE.test(cleanUrl(url))
export const isPossibleTsOutput = (url: string) =>
knownTsOutputRE.test(cleanUrl(url))
export function getPotentialTsSrcPaths(filePath: string) {
const [name, type, query = ''] = filePath.split(/(\.(?:[cm]?js|jsx))(\?.*)?$/)
const paths = [name + type.replace('js', 'ts') + query]
if (!type.endsWith('x')) {
paths.push(name + type.replace('js', 'tsx') + query)
}
return paths
}
const importQueryRE = /(\?|&)import=?(?:&|$)/
const internalPrefixes = [
FS_PREFIX,
VALID_ID_PREFIX,
CLIENT_PUBLIC_PATH,
ENV_PUBLIC_PATH
]
const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`)
const trailingSeparatorRE = /[\?&]$/
export const isImportRequest = (url: string): boolean => importQueryRE.test(url)
export const isInternalRequest = (url: string): boolean =>
InternalPrefixRE.test(url)
export function removeImportQuery(url: string): string {
return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '')
}
export function injectQuery(url: string, queryToInject: string): string {
// encode percents for consistent behavior with pathToFileURL
// see #2614 for details
let resolvedUrl = new URL(url.replace(/%/g, '%25'), 'relative:///')
if (resolvedUrl.protocol !== 'relative:') {
resolvedUrl = pathToFileURL(url)
}
let { protocol, pathname, search, hash } = resolvedUrl
if (protocol === 'file:') {
pathname = pathname.slice(1)
}
pathname = decodeURIComponent(pathname)
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${
hash ?? ''
}`
}
const timestampRE = /\bt=\d{13}&?\b/
export function removeTimestampQuery(url: string): string {
return url.replace(timestampRE, '').replace(trailingSeparatorRE, '')
}
export async function asyncReplace(
input: string,
re: RegExp,
replacer: (match: RegExpExecArray) => string | Promise<string>
): Promise<string> {
let match: RegExpExecArray | null
let remaining = input
let rewritten = ''
while ((match = re.exec(remaining))) {
rewritten += remaining.slice(0, match.index)
rewritten += await replacer(match)
remaining = remaining.slice(match.index + match[0].length)
}
rewritten += remaining
return rewritten
}
export function timeFrom(start: number, subtract = 0): string {
const time: number | string = performance.now() - start - subtract
const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' ')
if (time < 10) {
return colors.green(timeString)
} else if (time < 50) {
return colors.yellow(timeString)
} else {
return colors.red(timeString)
}
}
/**
* pretty url for logging.
*/
export function prettifyUrl(url: string, root: string): string {
url = removeTimestampQuery(url)
const isAbsoluteFile = url.startsWith(root)
if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
let file = path.relative(root, isAbsoluteFile ? url : fsPathFromId(url))
const seg = file.split('/')
const npmIndex = seg.indexOf(`node_modules`)
const isSourceMap = file.endsWith('.map')
if (npmIndex > 0) {
file = seg[npmIndex + 1]
if (file.startsWith('@')) {
file = `${file}/${seg[npmIndex + 2]}`
}
file = `npm: ${colors.dim(file)}${isSourceMap ? ` (source map)` : ``}`
}
return colors.dim(file)
} else {
return colors.dim(url)
}
}
export function isObject(value: unknown): value is Record<string, any> {
return Object.prototype.toString.call(value) === '[object Object]'
}
export function isDefined<T>(value: T | undefined | null): value is T {
return value != null
}
interface LookupFileOptions {
pathOnly?: boolean
rootDir?: string
}
export function lookupFile(
dir: string,
formats: string[],
options?: LookupFileOptions
): string | undefined {
for (const format of formats) {
const fullPath = path.join(dir, format)
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
return options?.pathOnly ? fullPath : fs.readFileSync(fullPath, 'utf-8')
}
}
const parentDir = path.dirname(dir)
if (
parentDir !== dir &&
(!options?.rootDir || parentDir.startsWith(options?.rootDir))
) {
return lookupFile(parentDir, formats, options)
}
}
const splitRE = /\r?\n/
const range: number = 2
export function pad(source: string, n = 2): string {
const lines = source.split(splitRE)
return lines.map((l) => ` `.repeat(n) + l).join(`\n`)
}
export function posToNumber(
source: string,
pos: number | { line: number; column: number }
): number {
if (typeof pos === 'number') return pos
const lines = source.split(splitRE)
const { line, column } = pos
let start = 0
for (let i = 0; i < line - 1; i++) {
if (lines[i]) {
start += lines[i].length + 1
}
}
return start + column
}
export function numberToPos(
source: string,
offset: number | { line: number; column: number }
): { line: number; column: number } {
if (typeof offset !== 'number') return offset
if (offset > source.length) {
throw new Error(
`offset is longer than source length! offset ${offset} > length ${source.length}`
)
}
const lines = source.split(splitRE)
let counted = 0
let line = 0
let column = 0
for (; line < lines.length; line++) {
const lineLength = lines[line].length + 1
if (counted + lineLength >= offset) {
column = offset - counted + 1
break
}
counted += lineLength
}
return { line: line + 1, column }
}
export function generateCodeFrame(
source: string,
start: number | { line: number; column: number } = 0,
end?: number
): string {
start = posToNumber(source, start)
end = end || start
const lines = source.split(splitRE)
let count = 0
const res: string[] = []
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1
if (count >= start) {
for (let j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length) continue
const line = j + 1
res.push(
`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${
lines[j]
}`
)
const lineLength = lines[j].length
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1
const length = Math.max(
1,
end > count ? lineLength - pad : end - start
)
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length))
} else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1)
res.push(` | ` + '^'.repeat(length))
}
count += lineLength + 1
}
}
break
}
}
return res.join('\n')
}
export function writeFile(
filename: string,
content: string | Uint8Array
): void {
const dir = path.dirname(filename)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
fs.writeFileSync(filename, content)
}
/**
* Use instead of fs.existsSync(filename)
* #2051 if we don't have read permission on a directory, existsSync() still
* works and will result in massively slow subsequent checks (which are
* unnecessary in the first place)
*/
export function isFileReadable(filename: string): boolean {
try {
const stat = fs.statSync(filename, { throwIfNoEntry: false })
return !!stat
} catch {
return false
}
}
/**
* Delete every file and subdirectory. **The given directory must exist.**
* Pass an optional `skip` array to preserve files in the root directory.
*/
export function emptyDir(dir: string, skip?: string[]): void {
for (const file of fs.readdirSync(dir)) {
if (skip?.includes(file)) {
continue
}
const abs = path.resolve(dir, file)
// baseline is Node 12 so can't use rmSync :(
if (fs.lstatSync(abs).isDirectory()) {
emptyDir(abs)
fs.rmdirSync(abs)
} else {
fs.unlinkSync(abs)
}
}
}
export function copyDir(srcDir: string, destDir: string): void {
fs.mkdirSync(destDir, { recursive: true })
for (const file of fs.readdirSync(srcDir)) {
const srcFile = path.resolve(srcDir, file)
if (srcFile === destDir) {
continue
}
const destFile = path.resolve(destDir, file)
const stat = fs.statSync(srcFile)
if (stat.isDirectory()) {
copyDir(srcFile, destFile)
} else {
fs.copyFileSync(srcFile, destFile)
}
}
}
export function ensureWatchedFile(
watcher: FSWatcher,
file: string | null,
root: string
): void {
if (
file &&
// only need to watch if out of root
!file.startsWith(root + '/') &&
// some rollup plugins use null bytes for private resolved Ids
!file.includes('\0') &&
fs.existsSync(file)
) {
// resolve file to normalized system path
watcher.add(path.resolve(file))
}
}
interface ImageCandidate {
url: string
descriptor: string
}
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g
const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/
export async function processSrcSet(
srcs: string,
replacer: (arg: ImageCandidate) => Promise<string>
): Promise<string> {
const imageCandidates: ImageCandidate[] = srcs
.split(',')
.map((s) => {
const src = s.replace(escapedSpaceCharacters, ' ').trim()
const [url] = imageSetUrlRE.exec(src) || []
return {
url,
descriptor: src?.slice(url.length).trim()
}
})
.filter(({ url }) => !!url)
const ret = await Promise.all(
imageCandidates.map(async ({ url, descriptor }) => {
return {
url: await replacer({ url, descriptor }),
descriptor
}
})
)
return ret.reduce((prev, { url, descriptor }, index) => {
descriptor ??= ''
return (prev +=
url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`)
}, '')
}
function escapeToLinuxLikePath(path: string) {
if (/^[A-Z]:/.test(path)) {
return path.replace(/^([A-Z]):\//, '/windows/$1/')
}
if (/^\/[^/]/.test(path)) {
return `/linux${path}`
}
return path
}
function unescapeToLinuxLikePath(path: string) {
if (path.startsWith('/linux/')) {
return path.slice('/linux'.length)
}
if (path.startsWith('/windows/')) {
return path.replace(/^\/windows\/([A-Z])\//, '$1:/')
}
return path
}
// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
const nullSourceMap: RawSourceMap = {
names: [],
sources: [],
mappings: '',
version: 3
}
export function combineSourcemaps(
filename: string,
sourcemapList: Array<DecodedSourceMap | RawSourceMap>,
excludeContent = true
): RawSourceMap {
if (
sourcemapList.length === 0 ||
sourcemapList.every((m) => m.sources.length === 0)
) {
return { ...nullSourceMap }
}
// hack for parse broken with normalized absolute paths on windows (C:/path/to/something).
// escape them to linux like paths
// also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442)
sourcemapList = sourcemapList.map((sourcemap) => {
const newSourcemaps = { ...sourcemap }
newSourcemaps.sources = sourcemap.sources.map((source) =>
source ? escapeToLinuxLikePath(source) : null
)
if (sourcemap.sourceRoot) {
newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot)
}
return newSourcemaps
})
const escapedFilename = escapeToLinuxLikePath(filename)
// We don't declare type here so we can convert/fake/map as RawSourceMap
let map //: SourceMap
let mapIndex = 1
const useArrayInterface =
sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined
if (useArrayInterface) {
map = remapping(sourcemapList, () => null, excludeContent)
} else {
map = remapping(
sourcemapList[0],
function loader(sourcefile) {
if (sourcefile === escapedFilename && sourcemapList[mapIndex]) {
return sourcemapList[mapIndex++]
} else {
return null
}
},
excludeContent
)
}
if (!map.file) {
delete map.file
}
// unescape the previous hack
map.sources = map.sources.map((source) =>
source ? unescapeToLinuxLikePath(source) : source
)
map.file = filename
return map as RawSourceMap
}
export function unique<T>(arr: T[]): T[] {
return Array.from(new Set(arr))
}
export interface Hostname {
// undefined sets the default behaviour of server.listen
host: string | undefined
// resolve to localhost when possible
name: string
}
export function resolveHostname(
optionsHost: string | boolean | undefined
): Hostname {
let host: string | undefined
if (optionsHost === undefined || optionsHost === false) {
// Use a secure default
host = '127.0.0.1'
} else if (optionsHost === true) {
// If passed --host in the CLI without arguments
host = undefined // undefined typically means 0.0.0.0 or :: (listen on all IPs)
} else {
host = optionsHost
}
// Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1'
const name =
(optionsHost !== '127.0.0.1' && host === '127.0.0.1') ||
host === '0.0.0.0' ||
host === '::' ||
host === undefined
? 'localhost'
: host
return { host, name }
}
export function arraify<T>(target: T | T[]): T[] {
return Array.isArray(target) ? target : [target]
}
export function toUpperCaseDriveLetter(pathName: string): string {
return pathName.replace(/^\w:/, (letter) => letter.toUpperCase())
}
export const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm
export const singlelineCommentsRE = /\/\/.*/g
export const usingDynamicImport = typeof jest === 'undefined'
/**
* Dynamically import files. It will make sure it's not being compiled away by TS/Rollup.
*
* As a temporary workaround for Jest's lack of stable ESM support, we fallback to require
* if we're in a Jest environment.
* See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077
*
* @param file File path to import.
*/
export const dynamicImport = usingDynamicImport
? new Function('file', 'return import(file)')
: require
export function parseRequest(id: string): Record<string, string> | null {
const { search } = parseUrl(id)
if (!search) {
return null
}
return Object.fromEntries(new URLSearchParams(search.slice(1)))
}
export const blankReplacer = (match: string) => ' '.repeat(match.length)