-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathutils.ts
1462 lines (1308 loc) · 40.5 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
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { exec } from 'node:child_process'
import { createHash } from 'node:crypto'
import { URL, fileURLToPath } from 'node:url'
import { builtinModules, createRequire } from 'node:module'
import { promises as dns } from 'node:dns'
import { performance } from 'node:perf_hooks'
import type { AddressInfo, Server } from 'node:net'
import fsp from 'node:fs/promises'
import type { FSWatcher } from 'dep-types/chokidar'
import remapping from '@ampproject/remapping'
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping'
import colors from 'picocolors'
import debug from 'debug'
import type { Alias, AliasOptions } from 'dep-types/alias'
import type MagicString from 'magic-string'
import type { TransformResult } from 'rollup'
import { createFilter as _createFilter } from '@rollup/pluginutils'
import { cleanUrl, isWindows, slash, withTrailingSlash } from '../shared/utils'
import { VALID_ID_PREFIX } from '../shared/constants'
import {
CLIENT_ENTRY,
CLIENT_PUBLIC_PATH,
ENV_PUBLIC_PATH,
FS_PREFIX,
OPTIMIZABLE_ENTRY_RE,
loopbackHosts,
wildcardHosts,
} from './constants'
import type { DepOptimizationOptions } from './optimizer'
import type { ResolvedConfig } from './config'
import type { ResolvedServerUrls, ViteDevServer } from './server'
import type { PreviewServer } from './preview'
import {
type PackageCache,
findNearestPackageData,
resolvePackageData,
} from './packages'
import type { CommonServerOptions } from '.'
/**
* Inlined to keep `@rollup/pluginutils` in devDependencies
*/
export type FilterPattern =
| ReadonlyArray<string | RegExp>
| string
| RegExp
| null
export const createFilter = _createFilter as (
include?: FilterPattern,
exclude?: FilterPattern,
options?: { resolve?: string | false | null },
) => (id: string | unknown) => boolean
const replaceSlashOrColonRE = /[/:]/g
const replaceDotRE = /\./g
const replaceNestedIdRE = /\s*>\s*/g
const replaceHashRE = /#/g
export const flattenId = (id: string): string => {
const flatId = limitFlattenIdLength(
id
.replace(replaceSlashOrColonRE, '_')
.replace(replaceDotRE, '__')
.replace(replaceNestedIdRE, '___')
.replace(replaceHashRE, '____'),
)
return flatId
}
const FLATTEN_ID_HASH_LENGTH = 8
const FLATTEN_ID_MAX_FILE_LENGTH = 170
const limitFlattenIdLength = (
id: string,
limit: number = FLATTEN_ID_MAX_FILE_LENGTH,
): string => {
if (id.length <= limit) {
return id
}
return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + '_' + getHash(id)
}
export const normalizeId = (id: string): string =>
id.replace(replaceNestedIdRE, ' > ')
// Supported by Node, Deno, Bun
const NODE_BUILTIN_NAMESPACE = 'node:'
// Supported by Deno
const NPM_BUILTIN_NAMESPACE = 'npm:'
// Supported by Bun
const BUN_BUILTIN_NAMESPACE = 'bun:'
// Some runtimes like Bun injects namespaced modules here, which is not a node builtin
const nodeBuiltins = builtinModules.filter((id) => !id.includes(':'))
// TODO: Use `isBuiltin` from `node:module`, but Deno doesn't support it
export function isBuiltin(id: string): boolean {
if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE)) return true
if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE)) return true
return isNodeBuiltin(id)
}
export function isNodeBuiltin(id: string): boolean {
if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true
return nodeBuiltins.includes(id)
}
export function isInNodeModules(id: string): boolean {
return id.includes('node_modules')
}
export function moduleListContains(
moduleList: string[] | undefined,
id: string,
): boolean | undefined {
return moduleList?.some(
(m) => m === id || id.startsWith(withTrailingSlash(m)),
)
}
export function isOptimizable(
id: string,
optimizeDeps: DepOptimizationOptions,
): boolean {
const { extensions } = optimizeDeps
return (
OPTIMIZABLE_ENTRY_RE.test(id) ||
(extensions?.some((ext) => id.endsWith(ext)) ?? false)
)
}
export const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/
export const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//
// TODO: use import()
const _require = createRequire(import.meta.url)
export function resolveDependencyVersion(
dep: string,
pkgRelativePath = '../../package.json',
): string {
const pkgPath = path.resolve(_require.resolve(dep), pkgRelativePath)
return JSON.parse(fs.readFileSync(pkgPath, 'utf-8')).version
}
export const rollupVersion = resolveDependencyVersion('rollup')
// 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'] | undefined {
const log = debug(namespace)
const { onlyWhenFocused } = options
let enabled = log.enabled
if (enabled && onlyWhenFocused) {
const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace
enabled = !!DEBUG?.includes(ns)
}
if (enabled) {
return (...args: [string, ...any[]]) => {
if (!filter || args.some((a) => a?.includes?.(filter))) {
log(...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 urlCanParse =
// eslint-disable-next-line n/no-unsupported-features/node-builtins
URL.canParse ??
// URL.canParse is supported from Node.js 18.17.0+, 20.0.0+
((path: string, base?: string | undefined): boolean => {
try {
new URL(path, base)
return true
} catch {
return false
}
})
export const isCaseInsensitiveFS = testCaseInsensitiveFS()
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[0] === '/' || VOLUME_RE.test(fsPath) ? 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 {
dir = withTrailingSlash(dir)
return (
file.startsWith(dir) ||
(isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))
)
}
/**
* Check if 2 file name are identical
*
* Warning: parameters are not validated, only works with normalized absolute paths
*
* @param file1 - normalized absolute path
* @param file2 - normalized absolute path
* @returns true if both files url are identical
*/
export function isSameFileUri(file1: string, file2: string): boolean {
return (
file1 === file2 ||
(isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase())
)
}
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 =
/\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/
export const isJSRequest = (url: string): boolean => {
url = cleanUrl(url)
if (knownJsSrcRE.test(url)) {
return true
}
if (!path.extname(url) && url[url.length - 1] !== '/') {
return true
}
return false
}
const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/
export const isTsRequest = (url: string): boolean => knownTsRE.test(url)
const importQueryRE = /(\?|&)import=?(?:&|$)/
const directRequestRE = /(\?|&)direct=?(?:&|$)/
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 removeDirectQuery(url: string): string {
return url.replace(directRequestRE, '$1').replace(trailingSeparatorRE, '')
}
export const urlRE = /(\?|&)url(?:&|$)/
export const rawRE = /(\?|&)raw(?:&|$)/
export function removeUrlQuery(url: string): string {
return url.replace(urlRE, '$1').replace(trailingSeparatorRE, '')
}
export function removeRawQuery(url: string): string {
return url.replace(rawRE, '$1').replace(trailingSeparatorRE, '')
}
const replacePercentageRE = /%/g
export function injectQuery(url: string, queryToInject: string): string {
// encode percents for consistent behavior with pathToFileURL
// see #2614 for details
const resolvedUrl = new URL(
url.replace(replacePercentageRE, '%25'),
'relative:///',
)
const { search, hash } = resolvedUrl
let pathname = cleanUrl(url)
pathname = isWindows ? slash(pathname) : 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)) {
const file = path.posix.relative(
root,
isAbsoluteFile ? url : fsPathFromId(url),
)
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
}
export function tryStatSync(file: string): fs.Stats | undefined {
try {
// The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
return fs.statSync(file, { throwIfNoEntry: false })
} catch {
// Ignore errors
}
}
export function lookupFile(
dir: string,
fileNames: string[],
): string | undefined {
while (dir) {
for (const fileName of fileNames) {
const fullPath = path.join(dir, fileName)
if (tryStatSync(fullPath)?.isFile()) return fullPath
}
const parentDir = path.dirname(dir)
if (parentDir === dir) return
dir = parentDir
}
}
export function isFilePathESM(
filePath: string,
packageCache?: PackageCache,
): boolean {
if (/\.m[jt]s$/.test(filePath)) {
return true
} else if (/\.c[jt]s$/.test(filePath)) {
return false
} else {
// check package.json for type: "module"
try {
const pkg = findNearestPackageData(path.dirname(filePath), packageCache)
return pkg?.data.type === 'module'
} catch {
return false
}
}
}
export const splitRE = /\r?\n/g
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`)
}
type Pos = {
/** 1-based */
line: number
/** 0-based */
column: number
}
export function posToNumber(source: string, pos: number | Pos): 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 < lines.length; i++) {
start += lines[i].length + 1
}
return start + column
}
export function numberToPos(source: string, offset: number | Pos): Pos {
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 | Pos = 0,
end?: number | Pos,
): string {
start = Math.max(posToNumber(source, start), 0)
end = Math.min(
end !== undefined ? posToNumber(source, end) : start,
source.length,
)
const lines = source.split(splitRE)
let count = 0
const res: string[] = []
for (let i = 0; i < lines.length; i++) {
count += lines[i].length
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 = Math.max(start - (count - lineLength), 0)
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
}
count++
}
return res.join('\n')
}
export function isFileReadable(filename: string): boolean {
if (!tryStatSync(filename)) {
return false
}
try {
// Check if current process has read permission to the file
fs.accessSync(filename, fs.constants.R_OK)
return true
} catch {
return false
}
}
const splitFirstDirRE = /(.+?)[\\/](.+)/
/**
* Delete every file and subdirectory. **The given directory must exist.**
* Pass an optional `skip` array to preserve files under the root directory.
*/
export function emptyDir(dir: string, skip?: string[]): void {
const skipInDir: string[] = []
let nested: Map<string, string[]> | null = null
if (skip?.length) {
for (const file of skip) {
if (path.dirname(file) !== '.') {
const matched = splitFirstDirRE.exec(file)
if (matched) {
nested ??= new Map()
const [, nestedDir, skipPath] = matched
let nestedSkip = nested.get(nestedDir)
if (!nestedSkip) {
nestedSkip = []
nested.set(nestedDir, nestedSkip)
}
if (!nestedSkip.includes(skipPath)) {
nestedSkip.push(skipPath)
}
}
} else {
skipInDir.push(file)
}
}
}
for (const file of fs.readdirSync(dir)) {
if (skipInDir.includes(file)) {
continue
}
if (nested?.has(file)) {
emptyDir(path.resolve(dir, file), nested.get(file))
} else {
fs.rmSync(path.resolve(dir, file), { recursive: true, force: true })
}
}
}
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 const ERR_SYMLINK_IN_RECURSIVE_READDIR =
'ERR_SYMLINK_IN_RECURSIVE_READDIR'
export async function recursiveReaddir(dir: string): Promise<string[]> {
if (!fs.existsSync(dir)) {
return []
}
let dirents: fs.Dirent[]
try {
dirents = await fsp.readdir(dir, { withFileTypes: true })
} catch (e) {
if (e.code === 'EACCES') {
// Ignore permission errors
return []
}
throw e
}
if (dirents.some((dirent) => dirent.isSymbolicLink())) {
const err: any = new Error(
'Symbolic links are not supported in recursiveReaddir',
)
err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR
throw err
}
const files = await Promise.all(
dirents.map((dirent) => {
const res = path.resolve(dir, dirent.name)
return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath(res)
}),
)
return files.flat(1)
}
// `fs.realpathSync.native` resolves differently in Windows network drive,
// causing file read errors. skip for now.
// https://github.com/nodejs/node/issues/37737
export let safeRealpathSync = isWindows
? windowsSafeRealPathSync
: fs.realpathSync.native
// Based on https://github.com/larrybahr/windows-network-drive
// MIT License, Copyright (c) 2017 Larry Bahr
const windowsNetworkMap = new Map()
function windowsMappedRealpathSync(path: string) {
const realPath = fs.realpathSync.native(path)
if (realPath.startsWith('\\\\')) {
for (const [network, volume] of windowsNetworkMap) {
if (realPath.startsWith(network)) return realPath.replace(network, volume)
}
}
return realPath
}
const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/
let firstSafeRealPathSyncRun = false
function windowsSafeRealPathSync(path: string): string {
if (!firstSafeRealPathSyncRun) {
optimizeSafeRealPathSync()
firstSafeRealPathSyncRun = true
}
return fs.realpathSync(path)
}
function optimizeSafeRealPathSync() {
// Skip if using Node <18.10 due to MAX_PATH issue: https://github.com/vitejs/vite/issues/12931
const nodeVersion = process.versions.node.split('.').map(Number)
if (nodeVersion[0] < 18 || (nodeVersion[0] === 18 && nodeVersion[1] < 10)) {
safeRealpathSync = fs.realpathSync
return
}
// Check the availability `fs.realpathSync.native`
// in Windows virtual and RAM disks that bypass the Volume Mount Manager, in programs such as imDisk
// get the error EISDIR: illegal operation on a directory
try {
fs.realpathSync.native(path.resolve('./'))
} catch (error) {
if (error.message.includes('EISDIR: illegal operation on a directory')) {
safeRealpathSync = fs.realpathSync
return
}
}
exec('net use', (error, stdout) => {
if (error) return
const lines = stdout.split('\n')
// OK Y: \\NETWORKA\Foo Microsoft Windows Network
// OK Z: \\NETWORKA\Bar Microsoft Windows Network
for (const line of lines) {
const m = parseNetUseRE.exec(line)
if (m) windowsNetworkMap.set(m[2], m[1])
}
if (windowsNetworkMap.size === 0) {
safeRealpathSync = fs.realpathSync.native
} else {
safeRealpathSync = windowsMappedRealpathSync
}
})
}
export function ensureWatchedFile(
watcher: FSWatcher,
file: string | null,
root: string,
): void {
if (
file &&
// only need to watch if out of root
!file.startsWith(withTrailingSlash(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*)/
function joinSrcset(ret: ImageCandidate[]) {
return ret
.map(({ url, descriptor }) => url + (descriptor ? ` ${descriptor}` : ''))
.join(', ')
}
// NOTE: The returned `url` should perhaps be decoded so all handled URLs within Vite are consistently decoded.
// However, this may also require a refactor for `cssReplacer` to accept decoded URLs instead.
function splitSrcSetDescriptor(srcs: string): ImageCandidate[] {
return splitSrcSet(srcs)
.map((s) => {
const src = s.replace(escapedSpaceCharacters, ' ').trim()
const url = imageSetUrlRE.exec(src)?.[0] ?? ''
return {
url,
descriptor: src.slice(url.length).trim(),
}
})
.filter(({ url }) => !!url)
}
export function processSrcSet(
srcs: string,
replacer: (arg: ImageCandidate) => Promise<string>,
): Promise<string> {
return Promise.all(
splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({
url: await replacer({ url, descriptor }),
descriptor,
})),
).then(joinSrcset)
}
export function processSrcSetSync(
srcs: string,
replacer: (arg: ImageCandidate) => string,
): string {
return joinSrcset(
splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({
url: replacer({ url, descriptor }),
descriptor,
})),
)
}
const cleanSrcSetRE =
/(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'|data:\w+\/[\w.+-]+;base64,[\w+/=]+|\?\S+,/g
function splitSrcSet(srcs: string) {
const parts: string[] = []
/**
* There could be a ',' inside of:
* - url(data:...)
* - linear-gradient(...)
* - "data:..."
* - data:...
* - query parameter ?...
*/
const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer)
let startIndex = 0
let splitIndex: number
do {
splitIndex = cleanedSrcs.indexOf(',', startIndex)
parts.push(
srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined),
)
startIndex = splitIndex + 1
} while (splitIndex !== -1)
return parts
}
const windowsDriveRE = /^[A-Z]:/
const replaceWindowsDriveRE = /^([A-Z]):\//
const linuxAbsolutePathRE = /^\/[^/]/
function escapeToLinuxLikePath(path: string) {
if (windowsDriveRE.test(path)) {
return path.replace(replaceWindowsDriveRE, '/windows/$1/')
}
if (linuxAbsolutePathRE.test(path)) {
return `/linux${path}`
}
return path
}
const revertWindowsDriveRE = /^\/windows\/([A-Z])\//
function unescapeToLinuxLikePath(path: string) {
if (path.startsWith('/linux/')) {
return path.slice('/linux'.length)
}
if (path.startsWith('/windows/')) {
return path.replace(revertWindowsDriveRE, '$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>,
): 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
})
// 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)
} else {
map = remapping(sourcemapList[0], function loader(sourcefile) {
const mapForSources = sourcemapList
.slice(mapIndex)
.find((s) => s.sources.includes(sourcefile))
if (mapForSources) {
mapIndex++
return mapForSources
}
return null
})
}
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))
}
/**
* Returns resolved localhost address when `dns.lookup` result differs from DNS
*
* `dns.lookup` result is same when defaultResultOrder is `verbatim`.
* Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
* For example, when IPv6 is not supported on that machine/network.
*/
export async function getLocalhostAddressIfDiffersFromDNS(): Promise<
string | undefined
> {
const [nodeResult, dnsResult] = await Promise.all([
dns.lookup('localhost'),
dns.lookup('localhost', { verbatim: true }),
])
const isSame =
nodeResult.family === dnsResult.family &&
nodeResult.address === dnsResult.address
return isSame ? undefined : nodeResult.address
}
export function diffDnsOrderChange(
oldUrls: ViteDevServer['resolvedUrls'],
newUrls: ViteDevServer['resolvedUrls'],
): boolean {
return !(
oldUrls === newUrls ||
(oldUrls &&
newUrls &&
arrayEqual(oldUrls.local, newUrls.local) &&
arrayEqual(oldUrls.network, newUrls.network))
)
}
export interface Hostname {
/** undefined sets the default behaviour of server.listen */
host: string | undefined
/** resolve to localhost when possible */
name: string
}
export async function resolveHostname(
optionsHost: string | boolean | undefined,
): Promise<Hostname> {
let host: string | undefined
if (optionsHost === undefined || optionsHost === false) {
// Use a secure default
host = 'localhost'
} 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
let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host
if (host === 'localhost') {
// See #8647 for more details.
const localhostAddr = await getLocalhostAddressIfDiffersFromDNS()
if (localhostAddr) {
name = localhostAddr
}
}
return { host, name }
}
export async function resolveServerUrls(
server: Server,
options: CommonServerOptions,
config: ResolvedConfig,
): Promise<ResolvedServerUrls> {
const address = server.address()
const isAddressInfo = (x: any): x is AddressInfo => x?.address
if (!isAddressInfo(address)) {
return { local: [], network: [] }
}
const local: string[] = []
const network: string[] = []
const hostname = await resolveHostname(options.host)
const protocol = options.https ? 'https' : 'http'
const port = address.port
const base =
config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase
if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) {
let hostnameName = hostname.name
// ipv6 host
if (hostnameName.includes(':')) {
hostnameName = `[${hostnameName}]`
}
const address = `${protocol}://${hostnameName}:${port}${base}`
if (loopbackHosts.has(hostname.host)) {
local.push(address)
} else {
network.push(address)
}
} else {
Object.values(os.networkInterfaces())
.flatMap((nInterface) => nInterface ?? [])
.filter(
(detail) =>
detail &&
detail.address &&
(detail.family === 'IPv4' ||