-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathindex.ts
executable file
·720 lines (658 loc) · 24.2 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
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
type System = import("typescript").System
type CompilerOptions = import("typescript").CompilerOptions
type CustomTransformers = import("typescript").CustomTransformers
type LanguageServiceHost = import("typescript").LanguageServiceHost
type CompilerHost = import("typescript").CompilerHost
type SourceFile = import("typescript").SourceFile
type TS = typeof import("typescript")
type FetchLike = (url: string) => Promise<{ json(): Promise<any>; text(): Promise<string> }>
interface LocalStorageLike {
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem(key: string): void
}
declare var localStorage: LocalStorageLike | undefined;
declare var fetch: FetchLike | undefined;
let hasLocalStorage = false
try {
hasLocalStorage = typeof localStorage !== `undefined`
} catch (error) { }
const hasProcess = typeof process !== `undefined`
const shouldDebug = (hasLocalStorage && localStorage!.getItem("DEBUG")) || (hasProcess && process.env.DEBUG)
const debugLog = shouldDebug ? console.log : (_message?: any, ..._optionalParams: any[]) => ""
export interface VirtualTypeScriptEnvironment {
sys: System
languageService: import("typescript").LanguageService
getSourceFile: (fileName: string) => import("typescript").SourceFile | undefined
createFile: (fileName: string, content: string) => void
updateFile: (fileName: string, content: string, replaceTextSpan?: import("typescript").TextSpan) => void
deleteFile: (fileName: string) => void
}
/**
* Makes a virtual copy of the TypeScript environment. This is the main API you want to be using with
* @typescript/vfs. A lot of the other exposed functions are used by this function to get set up.
*
* @param sys an object which conforms to the TS Sys (a shim over read/write access to the fs)
* @param rootFiles a list of files which are considered inside the project
* @param ts a copy pf the TypeScript module
* @param compilerOptions the options for this compiler run
* @param customTransformers custom transformers for this compiler run
*/
export function createVirtualTypeScriptEnvironment(
sys: System,
rootFiles: string[],
ts: TS,
compilerOptions: CompilerOptions = {},
customTransformers?: CustomTransformers
): VirtualTypeScriptEnvironment {
const mergedCompilerOpts = { ...defaultCompilerOptions(ts), ...compilerOptions }
const { languageServiceHost, updateFile, deleteFile } = createVirtualLanguageServiceHost(
sys,
rootFiles,
mergedCompilerOpts,
ts,
customTransformers
)
const languageService = ts.createLanguageService(languageServiceHost)
const diagnostics = languageService.getCompilerOptionsDiagnostics()
if (diagnostics.length) {
const compilerHost = createVirtualCompilerHost(sys, compilerOptions, ts)
throw new Error(ts.formatDiagnostics(diagnostics, compilerHost.compilerHost))
}
return {
// @ts-ignore
name: "vfs",
sys,
languageService,
getSourceFile: fileName => languageService.getProgram()?.getSourceFile(fileName),
createFile: (fileName, content) => {
updateFile(ts.createSourceFile(fileName, content, mergedCompilerOpts.target!, false))
},
updateFile: (fileName, content, optPrevTextSpan) => {
const prevSourceFile = languageService.getProgram()!.getSourceFile(fileName)
if (!prevSourceFile) {
throw new Error("Did not find a source file for " + fileName)
}
const prevFullContents = prevSourceFile.text
// TODO: Validate if the default text span has a fencepost error?
const prevTextSpan = optPrevTextSpan ?? ts.createTextSpan(0, prevFullContents.length)
const newText =
prevFullContents.slice(0, prevTextSpan.start) +
content +
prevFullContents.slice(prevTextSpan.start + prevTextSpan.length)
const newSourceFile = ts.updateSourceFile(prevSourceFile, newText, {
span: prevTextSpan,
newLength: content.length,
})
updateFile(newSourceFile)
},
deleteFile(fileName) {
const sourceFile = languageService.getProgram()!.getSourceFile(fileName)
if (sourceFile) {
deleteFile(sourceFile)
}
}
}
}
// TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json
// and then using that to generate the list of files from the server, but it is not included in the npm package
/**
* Grab the list of lib files for a particular target, will return a bit more than necessary (by including
* the dom) but that's OK, we're really working with the constraint that you can't get a list of files
* when running in a browser.
*
* @param target The compiler settings target baseline
* @param ts A copy of the TypeScript module
*/
export const knownLibFilesForCompilerOptions = (compilerOptions: CompilerOptions, ts: TS) => {
const target = compilerOptions.target || ts.ScriptTarget.ES5
const lib = compilerOptions.lib || []
// Note that this will include files which can't be found for particular versions of TS
// TODO: Replace this with some sort of API call if https://github.com/microsoft/TypeScript/pull/54011
// or similar is merged.
const files = [
"lib.d.ts",
"lib.core.d.ts",
"lib.decorators.d.ts",
"lib.decorators.legacy.d.ts",
"lib.dom.asynciterable.d.ts",
"lib.dom.d.ts",
"lib.dom.iterable.d.ts",
"lib.webworker.asynciterable.d.ts",
"lib.webworker.d.ts",
"lib.webworker.importscripts.d.ts",
"lib.webworker.iterable.d.ts",
"lib.scripthost.d.ts",
"lib.es5.d.ts",
"lib.es6.d.ts",
"lib.es7.d.ts",
"lib.core.es6.d.ts",
"lib.core.es7.d.ts",
"lib.es2015.collection.d.ts",
"lib.es2015.core.d.ts",
"lib.es2015.d.ts",
"lib.es2015.generator.d.ts",
"lib.es2015.iterable.d.ts",
"lib.es2015.promise.d.ts",
"lib.es2015.proxy.d.ts",
"lib.es2015.reflect.d.ts",
"lib.es2015.symbol.d.ts",
"lib.es2015.symbol.wellknown.d.ts",
"lib.es2016.array.include.d.ts",
"lib.es2016.d.ts",
"lib.es2016.full.d.ts",
"lib.es2016.intl.d.ts",
"lib.es2017.arraybuffer.d.ts",
"lib.es2017.d.ts",
"lib.es2017.date.d.ts",
"lib.es2017.full.d.ts",
"lib.es2017.intl.d.ts",
"lib.es2017.object.d.ts",
"lib.es2017.sharedmemory.d.ts",
"lib.es2017.string.d.ts",
"lib.es2017.typedarrays.d.ts",
"lib.es2018.asyncgenerator.d.ts",
"lib.es2018.asynciterable.d.ts",
"lib.es2018.d.ts",
"lib.es2018.full.d.ts",
"lib.es2018.intl.d.ts",
"lib.es2018.promise.d.ts",
"lib.es2018.regexp.d.ts",
"lib.es2019.array.d.ts",
"lib.es2019.d.ts",
"lib.es2019.full.d.ts",
"lib.es2019.intl.d.ts",
"lib.es2019.object.d.ts",
"lib.es2019.string.d.ts",
"lib.es2019.symbol.d.ts",
"lib.es2020.bigint.d.ts",
"lib.es2020.d.ts",
"lib.es2020.date.d.ts",
"lib.es2020.full.d.ts",
"lib.es2020.intl.d.ts",
"lib.es2020.number.d.ts",
"lib.es2020.promise.d.ts",
"lib.es2020.sharedmemory.d.ts",
"lib.es2020.string.d.ts",
"lib.es2020.symbol.wellknown.d.ts",
"lib.es2021.d.ts",
"lib.es2021.full.d.ts",
"lib.es2021.intl.d.ts",
"lib.es2021.promise.d.ts",
"lib.es2021.string.d.ts",
"lib.es2021.weakref.d.ts",
"lib.es2022.array.d.ts",
"lib.es2022.d.ts",
"lib.es2022.error.d.ts",
"lib.es2022.full.d.ts",
"lib.es2022.intl.d.ts",
"lib.es2022.object.d.ts",
"lib.es2022.regexp.d.ts",
"lib.es2022.sharedmemory.d.ts",
"lib.es2022.string.d.ts",
"lib.es2023.array.d.ts",
"lib.es2023.collection.d.ts",
"lib.es2023.d.ts",
"lib.es2023.full.d.ts",
"lib.es2023.intl.d.ts",
"lib.es2024.arraybuffer.d.ts",
"lib.es2024.collection.d.ts",
"lib.es2024.d.ts",
"lib.es2024.full.d.ts",
"lib.es2024.object.d.ts",
"lib.es2024.promise.d.ts",
"lib.es2024.regexp.d.ts",
"lib.es2024.sharedmemory.d.ts",
"lib.es2024.string.d.ts",
"lib.esnext.array.d.ts",
"lib.esnext.asynciterable.d.ts",
"lib.esnext.bigint.d.ts",
"lib.esnext.collection.d.ts",
"lib.esnext.d.ts",
"lib.esnext.decorators.d.ts",
"lib.esnext.disposable.d.ts",
"lib.esnext.float16.d.ts",
"lib.esnext.full.d.ts",
"lib.esnext.intl.d.ts",
"lib.esnext.iterator.d.ts",
"lib.esnext.object.d.ts",
"lib.esnext.promise.d.ts",
"lib.esnext.regexp.d.ts",
"lib.esnext.string.d.ts",
"lib.esnext.symbol.d.ts",
"lib.esnext.weakref.d.ts"
]
const targetToCut = ts.ScriptTarget[target]
const matches = files.filter(f => f.startsWith(`lib.${targetToCut.toLowerCase()}`))
const targetCutIndex = files.indexOf(matches.pop()!)
const getMax = (array: number[]) =>
array && array.length ? array.reduce((max, current) => (current > max ? current : max)) : undefined
// Find the index for everything in
const indexesForCutting = lib.map(lib => {
const matches = files.filter(f => f.startsWith(`lib.${lib.toLowerCase()}`))
if (matches.length === 0) return 0
const cutIndex = files.indexOf(matches.pop()!)
return cutIndex
})
const libCutIndex = getMax(indexesForCutting) || 0
const finalCutIndex = Math.max(targetCutIndex, libCutIndex)
return files.slice(0, finalCutIndex + 1)
}
/**
* Sets up a Map with lib contents by grabbing the necessary files from
* the local copy of typescript via the file system.
*
* The first two args are un-used, but kept around so as to not cause a
* semver major bump for no gain to module users.
*/
export const createDefaultMapFromNodeModules = (
_compilerOptions: CompilerOptions,
_ts?: typeof import("typescript"),
tsLibDirectory?: string
) => {
const path = requirePath()
const fs = requireFS()
const getLib = (name: string) => {
const lib = tsLibDirectory || path.dirname(require.resolve("typescript"))
return fs.readFileSync(path.join(lib, name), "utf8")
}
const isDtsFile = (file: string) => /\.d\.([^\.]+\.)?[cm]?ts$/i.test(file)
const libFiles = fs.readdirSync(tsLibDirectory || path.dirname(require.resolve("typescript")))
const knownLibFiles = libFiles.filter(f => f.startsWith("lib.") && isDtsFile(f))
const fsMap = new Map<string, string>()
knownLibFiles.forEach(lib => {
fsMap.set("/" + lib, getLib(lib))
})
return fsMap
}
/**
* Adds recursively files from the FS into the map based on the folder
*/
export const addAllFilesFromFolder = (map: Map<string, string>, workingDir: string): void => {
const path = requirePath()
const fs = requireFS()
const walk = function (dir: string) {
let results: string[] = []
const list = fs.readdirSync(dir)
list.forEach(function (file: string) {
file = path.join(dir, file)
const stat = fs.statSync(file)
if (stat && stat.isDirectory()) {
/* Recurse into a subdirectory */
results = results.concat(walk(file))
} else {
/* Is a file */
results.push(file)
}
})
return results
}
const allFiles = walk(workingDir)
allFiles.forEach(lib => {
const fsPath = "/node_modules/@types" + lib.replace(workingDir, "")
const content = fs.readFileSync(lib, "utf8")
const validExtensions = [".ts", ".tsx"]
if (validExtensions.includes(path.extname(fsPath))) {
map.set(fsPath, content)
}
})
}
/** Adds all files from node_modules/@types into the FS Map */
export const addFilesForTypesIntoFolder = (map: Map<string, string>) =>
addAllFilesFromFolder(map, "node_modules/@types")
export interface LZString {
compressToUTF16(input: string): string
decompressFromUTF16(compressed: string): string
}
/**
* Create a virtual FS Map with the lib files from a particular TypeScript
* version based on the target, Always includes dom ATM.
*
* @param options The compiler target, which dictates the libs to set up
* @param version the versions of TypeScript which are supported
* @param cache should the values be stored in local storage
* @param ts a copy of the typescript import
* @param lzstring an optional copy of the lz-string import
* @param fetcher an optional replacement for the global fetch function (tests mainly)
* @param storer an optional replacement for the localStorage global (tests mainly)
*/
export const createDefaultMapFromCDN = (
options: CompilerOptions,
version: string,
cache: boolean,
ts: TS,
lzstring?: LZString,
fetcher?: FetchLike,
storer?: LocalStorageLike
) => {
const fetchlike = fetcher || fetch!
const fsMap = new Map<string, string>()
const files = knownLibFilesForCompilerOptions(options, ts)
const prefix = `https://playgroundcdn.typescriptlang.org/cdn/${version}/typescript/lib/`
function zip(str: string) {
return lzstring ? lzstring.compressToUTF16(str) : str
}
function unzip(str: string) {
return lzstring ? lzstring.decompressFromUTF16(str) : str
}
// Map the known libs to a node fetch promise, then return the contents
function uncached() {
return (
Promise.all(files.map(lib => fetchlike(prefix + lib).then(resp => resp.text())))
.then(contents => {
contents.forEach((text, index) => fsMap.set("/" + files[index], text))
})
// Return a NOOP for .d.ts files which aren't in the current build of TypeScript
.catch(() => { })
)
}
// A localstorage and lzzip aware version of the lib files
function cached() {
const storelike = storer || localStorage!
const keys = Object.keys(storelike)
keys.forEach(key => {
// Remove anything which isn't from this version
if (key.startsWith("ts-lib-") && !key.startsWith("ts-lib-" + version)) {
storelike.removeItem(key)
}
})
return Promise.all(
files.map(lib => {
const cacheKey = `ts-lib-${version}-${lib}`
const content = storelike.getItem(cacheKey)
if (!content) {
// Make the API call and store the text concent in the cache
return (
fetchlike(prefix + lib)
.then(resp => resp.text())
.then(t => {
storelike.setItem(cacheKey, zip(t))
return t
})
// Return a NOOP for .d.ts files which aren't in the current build of TypeScript
.catch(() => { })
)
} else {
return Promise.resolve(unzip(content))
}
})
).then(contents => {
contents.forEach((text, index) => {
if (text) {
const name = "/" + files[index]
fsMap.set(name, text)
}
})
})
}
const func = cache ? cached : uncached
return func().then(() => fsMap)
}
function notImplemented(methodName: string): any {
throw new Error(`Method '${methodName}' is not implemented.`)
}
function audit<ArgsT extends any[], ReturnT>(
name: string,
fn: (...args: ArgsT) => ReturnT
): (...args: ArgsT) => ReturnT {
return (...args) => {
const res = fn(...args)
const smallres = typeof res === "string" ? res.slice(0, 80) + "..." : res
debugLog("> " + name, ...args)
debugLog("< " + smallres)
return res
}
}
/** The default compiler options if TypeScript could ever change the compiler options */
const defaultCompilerOptions = (ts: typeof import("typescript")): CompilerOptions => {
return {
...ts.getDefaultCompilerOptions(),
jsx: ts.JsxEmit.React,
strict: true,
esModuleInterop: true,
module: ts.ModuleKind.ESNext,
suppressOutputPathCheck: true,
skipLibCheck: true,
skipDefaultLibCheck: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
}
}
// "/DOM.d.ts" => "/lib.dom.d.ts"
const libize = (path: string) => path.replace("/", "/lib.").toLowerCase()
/**
* Creates an in-memory System object which can be used in a TypeScript program, this
* is what provides read/write aspects of the virtual fs
*/
export function createSystem(files: Map<string, string>): System {
return {
args: [],
createDirectory: () => notImplemented("createDirectory"),
// TODO: could make a real file tree
directoryExists: audit("directoryExists", directory => {
return Array.from(files.keys()).some(path => path.startsWith(directory))
}),
exit: () => notImplemented("exit"),
fileExists: audit("fileExists", fileName => files.has(fileName) || files.has(libize(fileName))),
getCurrentDirectory: () => "/",
getDirectories: () => [],
getExecutingFilePath: () => notImplemented("getExecutingFilePath"),
readDirectory: audit("readDirectory", directory => (directory === "/" ? Array.from(files.keys()) : [])),
readFile: audit("readFile", fileName => files.get(fileName) ?? files.get(libize(fileName))),
resolvePath: path => path,
newLine: "\n",
useCaseSensitiveFileNames: true,
write: () => notImplemented("write"),
writeFile: (fileName, contents) => {
files.set(fileName, contents)
},
deleteFile: (fileName) => {
files.delete(fileName)
},
}
}
/**
* Creates a file-system backed System object which can be used in a TypeScript program, you provide
* a set of virtual files which are prioritised over the FS versions, then a path to the root of your
* project (basically the folder your node_modules lives)
*/
export function createFSBackedSystem(
files: Map<string, string>,
_projectRoot: string,
ts: TS,
tsLibDirectory?: string
): System {
// We need to make an isolated folder for the tsconfig, but also need to be able to resolve the
// existing node_modules structures going back through the history
const root = _projectRoot + "/vfs"
const path = requirePath()
// The default System in TypeScript
const nodeSys = ts.sys
const tsLib = tsLibDirectory ?? path.dirname(require.resolve("typescript"))
return {
// @ts-ignore
name: "fs-vfs",
root,
args: [],
createDirectory: () => notImplemented("createDirectory"),
// TODO: could make a real file tree
directoryExists: audit("directoryExists", directory => {
return Array.from(files.keys()).some(path => path.startsWith(directory)) || nodeSys.directoryExists(directory)
}),
exit: nodeSys.exit,
fileExists: audit("fileExists", fileName => {
if (files.has(fileName)) return true
// Don't let other tsconfigs end up touching the vfs
if (fileName.includes("tsconfig.json") || fileName.includes("tsconfig.json")) return false
if (fileName.startsWith("/lib")) {
const tsLibName = `${tsLib}/${fileName.replace("/", "")}`
return nodeSys.fileExists(tsLibName)
}
return nodeSys.fileExists(fileName)
}),
getCurrentDirectory: () => root,
getDirectories: nodeSys.getDirectories,
getExecutingFilePath: () => notImplemented("getExecutingFilePath"),
readDirectory: audit("readDirectory", (...args) => {
if (args[0] === "/") {
return Array.from(files.keys())
} else {
return nodeSys.readDirectory(...args)
}
}),
readFile: audit("readFile", fileName => {
if (files.has(fileName)) return files.get(fileName)
if (fileName.startsWith("/lib")) {
const tsLibName = `${tsLib}/${fileName.replace("/", "")}`
const result = nodeSys.readFile(tsLibName)
if (!result) {
const libs = nodeSys.readDirectory(tsLib)
throw new Error(
`TSVFS: A request was made for ${tsLibName} but there wasn't a file found in the file map. You likely have a mismatch in the compiler options for the CDN download vs the compiler program. Existing Libs: ${libs}.`
)
}
return result
}
return nodeSys.readFile(fileName)
}),
resolvePath: path => {
if (files.has(path)) return path
return nodeSys.resolvePath(path)
},
newLine: "\n",
useCaseSensitiveFileNames: true,
write: () => notImplemented("write"),
writeFile: (fileName, contents) => {
files.set(fileName, contents)
},
deleteFile: (fileName) => {
files.delete(fileName)
},
realpath: nodeSys.realpath,
}
}
/**
* Creates an in-memory CompilerHost -which is essentially an extra wrapper to System
* which works with TypeScript objects - returns both a compiler host, and a way to add new SourceFile
* instances to the in-memory file system.
*/
export function createVirtualCompilerHost(sys: System, compilerOptions: CompilerOptions, ts: TS) {
const sourceFiles = new Map<string, SourceFile>()
const save = (sourceFile: SourceFile) => {
sourceFiles.set(sourceFile.fileName, sourceFile)
return sourceFile
}
type Return = {
compilerHost: CompilerHost
updateFile: (sourceFile: SourceFile) => boolean
deleteFile: (sourceFile: SourceFile) => boolean
}
const vHost: Return = {
compilerHost: {
...sys,
getCanonicalFileName: fileName => fileName,
getDefaultLibFileName: () => "/" + ts.getDefaultLibFileName(compilerOptions), // '/lib.d.ts',
// getDefaultLibLocation: () => '/',
getNewLine: () => sys.newLine,
getSourceFile: (fileName, languageVersionOrOptions) => {
return (
sourceFiles.get(fileName) ||
save(
ts.createSourceFile(
fileName,
sys.readFile(fileName)!,
languageVersionOrOptions ?? compilerOptions.target ?? defaultCompilerOptions(ts).target!,
false
)
)
)
},
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
},
updateFile: sourceFile => {
const alreadyExists = sourceFiles.has(sourceFile.fileName)
sys.writeFile(sourceFile.fileName, sourceFile.text)
sourceFiles.set(sourceFile.fileName, sourceFile)
return alreadyExists
},
deleteFile: sourceFile => {
const alreadyExists = sourceFiles.has(sourceFile.fileName)
sourceFiles.delete(sourceFile.fileName)
sys.deleteFile!(sourceFile.fileName)
return alreadyExists
}
}
return vHost
}
/**
* Creates an object which can host a language service against the virtual file-system
*/
export function createVirtualLanguageServiceHost(
sys: System,
rootFiles: string[],
compilerOptions: CompilerOptions,
ts: TS,
customTransformers?: CustomTransformers
) {
const fileNames = [...rootFiles]
const { compilerHost, updateFile, deleteFile } = createVirtualCompilerHost(sys, compilerOptions, ts)
const fileVersions = new Map<string, string>()
let projectVersion = 0
const languageServiceHost: LanguageServiceHost = {
...compilerHost,
getProjectVersion: () => projectVersion.toString(),
getCompilationSettings: () => compilerOptions,
getCustomTransformers: () => customTransformers,
// A couple weeks of 4.8 TypeScript nightlies had a bug where the Program's
// list of files was just a reference to the array returned by this host method,
// which means mutations by the host that ought to result in a new Program being
// created were not detected, since the old list of files and the new list of files
// were in fact a reference to the same underlying array. That was fixed in
// https://github.com/microsoft/TypeScript/pull/49813, but since the twoslash runner
// is used in bisecting for changes, it needs to guard against being busted in that
// couple-week period, so we defensively make a slice here.
getScriptFileNames: () => fileNames.slice(),
getScriptSnapshot: fileName => {
const contents = sys.readFile(fileName)
if (contents && typeof contents === "string") {
return ts.ScriptSnapshot.fromString(contents)
}
return
},
getScriptVersion: fileName => {
return fileVersions.get(fileName) || "0"
},
writeFile: sys.writeFile,
}
type Return = {
languageServiceHost: LanguageServiceHost
updateFile: (sourceFile: import("typescript").SourceFile) => void
deleteFile: (sourceFile: import("typescript").SourceFile) => void
}
const lsHost: Return = {
languageServiceHost,
updateFile: sourceFile => {
projectVersion++
fileVersions.set(sourceFile.fileName, projectVersion.toString())
if (!fileNames.includes(sourceFile.fileName)) {
fileNames.push(sourceFile.fileName)
}
updateFile(sourceFile)
},
deleteFile: sourceFile => {
projectVersion++
fileVersions.set(sourceFile.fileName, projectVersion.toString())
const index = fileNames.indexOf(sourceFile.fileName)
if (index !== -1) {
fileNames.splice(index, 1)
}
deleteFile(sourceFile)
}
}
return lsHost
}
const requirePath = () => {
return require(String.fromCharCode(112, 97, 116, 104)) as typeof import("path")
}
const requireFS = () => {
return require(String.fromCharCode(102, 115)) as typeof import("fs")
}