@typescript/vfs 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,29 +3,24 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  function _extends() {
6
- _extends = Object.assign || function (target) {
6
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
7
7
  for (var i = 1; i < arguments.length; i++) {
8
8
  var source = arguments[i];
9
-
10
9
  for (var key in source) {
11
10
  if (Object.prototype.hasOwnProperty.call(source, key)) {
12
11
  target[key] = source[key];
13
12
  }
14
13
  }
15
14
  }
16
-
17
15
  return target;
18
16
  };
19
-
20
17
  return _extends.apply(this, arguments);
21
18
  }
22
19
 
23
20
  var hasLocalStorage = false;
24
-
25
21
  try {
26
22
  hasLocalStorage = typeof localStorage !== "undefined";
27
23
  } catch (error) {}
28
-
29
24
  var hasProcess = typeof process !== "undefined";
30
25
  var shouldDebug = hasLocalStorage && /*#__PURE__*/localStorage.getItem("DEBUG") || hasProcess && process.env.DEBUG;
31
26
  var debugLog = shouldDebug ? console.log : function (_message) {
@@ -41,26 +36,20 @@ var debugLog = shouldDebug ? console.log : function (_message) {
41
36
  * @param compilerOptions the options for this compiler run
42
37
  * @param customTransformers custom transformers for this compiler run
43
38
  */
44
-
45
39
  function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions, customTransformers) {
46
40
  if (compilerOptions === void 0) {
47
41
  compilerOptions = {};
48
42
  }
49
-
50
43
  var mergedCompilerOpts = _extends({}, defaultCompilerOptions(ts), compilerOptions);
51
-
52
44
  var _createVirtualLanguag = createVirtualLanguageServiceHost(sys, rootFiles, mergedCompilerOpts, ts, customTransformers),
53
- languageServiceHost = _createVirtualLanguag.languageServiceHost,
54
- _updateFile = _createVirtualLanguag.updateFile;
55
-
45
+ languageServiceHost = _createVirtualLanguag.languageServiceHost,
46
+ _updateFile = _createVirtualLanguag.updateFile;
56
47
  var languageService = ts.createLanguageService(languageServiceHost);
57
48
  var diagnostics = languageService.getCompilerOptionsDiagnostics();
58
-
59
49
  if (diagnostics.length) {
60
50
  var compilerHost = createVirtualCompilerHost(sys, compilerOptions, ts);
61
51
  throw new Error(ts.formatDiagnostics(diagnostics, compilerHost.compilerHost));
62
52
  }
63
-
64
53
  return {
65
54
  // @ts-ignore
66
55
  name: "vfs",
@@ -68,7 +57,6 @@ function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions,
68
57
  languageService: languageService,
69
58
  getSourceFile: function getSourceFile(fileName) {
70
59
  var _languageService$getP;
71
-
72
60
  return (_languageService$getP = languageService.getProgram()) == null ? void 0 : _languageService$getP.getSourceFile(fileName);
73
61
  },
74
62
  createFile: function createFile(fileName, content) {
@@ -76,26 +64,23 @@ function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions,
76
64
  },
77
65
  updateFile: function updateFile(fileName, content, optPrevTextSpan) {
78
66
  var prevSourceFile = languageService.getProgram().getSourceFile(fileName);
79
-
80
67
  if (!prevSourceFile) {
81
68
  throw new Error("Did not find a source file for " + fileName);
82
69
  }
83
-
84
- var prevFullContents = prevSourceFile.text; // TODO: Validate if the default text span has a fencepost error?
85
-
70
+ var prevFullContents = prevSourceFile.text;
71
+ // TODO: Validate if the default text span has a fencepost error?
86
72
  var prevTextSpan = optPrevTextSpan != null ? optPrevTextSpan : ts.createTextSpan(0, prevFullContents.length);
87
73
  var newText = prevFullContents.slice(0, prevTextSpan.start) + content + prevFullContents.slice(prevTextSpan.start + prevTextSpan.length);
88
74
  var newSourceFile = ts.updateSourceFile(prevSourceFile, newText, {
89
75
  span: prevTextSpan,
90
76
  newLength: content.length
91
77
  });
92
-
93
78
  _updateFile(newSourceFile);
94
79
  }
95
80
  };
96
- } // TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json
81
+ }
82
+ // TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json
97
83
  // and then using that to generate the list of files from the server, but it is not included in the npm package
98
-
99
84
  /**
100
85
  * Grab the list of lib files for a particular target, will return a bit more than necessary (by including
101
86
  * the dom) but that's OK, we're really working with the constraint that you can't get a list of files
@@ -104,27 +89,24 @@ function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions,
104
89
  * @param target The compiler settings target baseline
105
90
  * @param ts A copy of the TypeScript module
106
91
  */
107
-
108
92
  var knownLibFilesForCompilerOptions = function knownLibFilesForCompilerOptions(compilerOptions, ts) {
109
93
  var target = compilerOptions.target || ts.ScriptTarget.ES5;
110
- var lib = compilerOptions.lib || []; // Note that this will include files which can't be found for particular versions of TS
94
+ var lib = compilerOptions.lib || [];
95
+ // Note that this will include files which can't be found for particular versions of TS
111
96
  // TODO: Replace this with some sort of API call if https://github.com/microsoft/TypeScript/pull/54011
112
97
  // or similar is merged.
113
-
114
98
  var files = ["lib.d.ts", "lib.decorators.d.ts", "lib.decorators.legacy.d.ts", "lib.dom.d.ts", "lib.dom.iterable.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.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.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.esnext.array.d.ts", "lib.esnext.asynciterable.d.ts", "lib.esnext.bigint.d.ts", "lib.esnext.d.ts", "lib.esnext.decorators.d.ts", "lib.esnext.disposable.d.ts", "lib.esnext.full.d.ts", "lib.esnext.intl.d.ts", "lib.esnext.promise.d.ts", "lib.esnext.string.d.ts", "lib.esnext.symbol.d.ts", "lib.esnext.weakref.d.ts"];
115
99
  var targetToCut = ts.ScriptTarget[target];
116
100
  var matches = files.filter(function (f) {
117
101
  return f.startsWith("lib." + targetToCut.toLowerCase());
118
102
  });
119
103
  var targetCutIndex = files.indexOf(matches.pop());
120
-
121
104
  var getMax = function getMax(array) {
122
105
  return array && array.length ? array.reduce(function (max, current) {
123
106
  return current > max ? current : max;
124
107
  }) : undefined;
125
- }; // Find the index for everything in
126
-
127
-
108
+ };
109
+ // Find the index for everything in
128
110
  var indexesForCutting = lib.map(function (lib) {
129
111
  var matches = files.filter(function (f) {
130
112
  return f.startsWith("lib." + lib.toLowerCase());
@@ -144,16 +126,13 @@ var knownLibFilesForCompilerOptions = function knownLibFilesForCompilerOptions(c
144
126
  * The first two args are un-used, but kept around so as to not cause a
145
127
  * semver major bump for no gain to module users.
146
128
  */
147
-
148
129
  var createDefaultMapFromNodeModules = function createDefaultMapFromNodeModules(_compilerOptions, _ts, tsLibDirectory) {
149
130
  var path = requirePath();
150
131
  var fs = requireFS();
151
-
152
132
  var getLib = function getLib(name) {
153
133
  var lib = tsLibDirectory || path.dirname(require.resolve("typescript"));
154
134
  return fs.readFileSync(path.join(lib, name), "utf8");
155
135
  };
156
-
157
136
  var libFiles = fs.readdirSync(tsLibDirectory || path.dirname(require.resolve("typescript")));
158
137
  var knownLibFiles = libFiles.filter(function (f) {
159
138
  return f.startsWith("lib.") && f.endsWith(".d.ts");
@@ -167,18 +146,15 @@ var createDefaultMapFromNodeModules = function createDefaultMapFromNodeModules(_
167
146
  /**
168
147
  * Adds recursively files from the FS into the map based on the folder
169
148
  */
170
-
171
149
  var addAllFilesFromFolder = function addAllFilesFromFolder(map, workingDir) {
172
150
  var path = requirePath();
173
151
  var fs = requireFS();
174
-
175
152
  var walk = function walk(dir) {
176
153
  var results = [];
177
154
  var list = fs.readdirSync(dir);
178
155
  list.forEach(function (file) {
179
156
  file = path.join(dir, file);
180
157
  var stat = fs.statSync(file);
181
-
182
158
  if (stat && stat.isDirectory()) {
183
159
  /* Recurse into a subdirectory */
184
160
  results = results.concat(walk(file));
@@ -189,20 +165,17 @@ var addAllFilesFromFolder = function addAllFilesFromFolder(map, workingDir) {
189
165
  });
190
166
  return results;
191
167
  };
192
-
193
168
  var allFiles = walk(workingDir);
194
169
  allFiles.forEach(function (lib) {
195
170
  var fsPath = "/node_modules/@types" + lib.replace(workingDir, "");
196
171
  var content = fs.readFileSync(lib, "utf8");
197
172
  var validExtensions = [".ts", ".tsx"];
198
-
199
173
  if (validExtensions.includes(path.extname(fsPath))) {
200
174
  map.set(fsPath, content);
201
175
  }
202
176
  });
203
177
  };
204
178
  /** Adds all files from node_modules/@types into the FS Map */
205
-
206
179
  var addFilesForTypesIntoFolder = function addFilesForTypesIntoFolder(map) {
207
180
  return addAllFilesFromFolder(map, "node_modules/@types");
208
181
  };
@@ -218,22 +191,18 @@ var addFilesForTypesIntoFolder = function addFilesForTypesIntoFolder(map) {
218
191
  * @param fetcher an optional replacement for the global fetch function (tests mainly)
219
192
  * @param storer an optional replacement for the localStorage global (tests mainly)
220
193
  */
221
-
222
194
  var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version, cache, ts, lzstring, fetcher, storer) {
223
195
  var fetchlike = fetcher || fetch;
224
196
  var fsMap = new Map();
225
197
  var files = knownLibFilesForCompilerOptions(options, ts);
226
- var prefix = "https://typescript.azureedge.net/cdn/" + version + "/typescript/lib/";
227
-
198
+ var prefix = "https://playgroundcdn.typescriptlang.org/cdn/" + version + "/typescript/lib/";
228
199
  function zip(str) {
229
200
  return lzstring ? lzstring.compressToUTF16(str) : str;
230
201
  }
231
-
232
202
  function unzip(str) {
233
203
  return lzstring ? lzstring.decompressFromUTF16(str) : str;
234
- } // Map the known libs to a node fetch promise, then return the contents
235
-
236
-
204
+ }
205
+ // Map the known libs to a node fetch promise, then return the contents
237
206
  function uncached() {
238
207
  return Promise.all(files.map(function (lib) {
239
208
  return fetchlike(prefix + lib).then(function (resp) {
@@ -243,11 +212,11 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
243
212
  contents.forEach(function (text, index) {
244
213
  return fsMap.set("/" + files[index], text);
245
214
  });
246
- }) // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
215
+ })
216
+ // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
247
217
  ["catch"](function () {});
248
- } // A localstorage and lzzip aware version of the lib files
249
-
250
-
218
+ }
219
+ // A localstorage and lzzip aware version of the lib files
251
220
  function cached() {
252
221
  var storelike = storer || localStorage;
253
222
  var keys = Object.keys(storelike);
@@ -260,7 +229,6 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
260
229
  return Promise.all(files.map(function (lib) {
261
230
  var cacheKey = "ts-lib-" + version + "-" + lib;
262
231
  var content = storelike.getItem(cacheKey);
263
-
264
232
  if (!content) {
265
233
  // Make the API call and store the text concent in the cache
266
234
  return fetchlike(prefix + lib).then(function (resp) {
@@ -268,7 +236,8 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
268
236
  }).then(function (t) {
269
237
  storelike.setItem(cacheKey, zip(t));
270
238
  return t;
271
- }) // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
239
+ })
240
+ // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
272
241
  ["catch"](function () {});
273
242
  } else {
274
243
  return Promise.resolve(unzip(content));
@@ -282,23 +251,19 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
282
251
  });
283
252
  });
284
253
  }
285
-
286
254
  var func = cache ? cached : uncached;
287
255
  return func().then(function () {
288
256
  return fsMap;
289
257
  });
290
258
  };
291
-
292
259
  function notImplemented(methodName) {
293
260
  throw new Error("Method '" + methodName + "' is not implemented.");
294
261
  }
295
-
296
262
  function audit(name, fn) {
297
263
  return function () {
298
264
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
299
265
  args[_key] = arguments[_key];
300
266
  }
301
-
302
267
  var res = fn.apply(void 0, args);
303
268
  var smallres = typeof res === "string" ? res.slice(0, 80) + "..." : res;
304
269
  debugLog.apply(void 0, ["> " + name].concat(args));
@@ -307,8 +272,6 @@ function audit(name, fn) {
307
272
  };
308
273
  }
309
274
  /** The default compiler options if TypeScript could ever change the compiler options */
310
-
311
-
312
275
  var defaultCompilerOptions = function defaultCompilerOptions(ts) {
313
276
  return _extends({}, ts.getDefaultCompilerOptions(), {
314
277
  jsx: ts.JsxEmit.React,
@@ -320,9 +283,8 @@ var defaultCompilerOptions = function defaultCompilerOptions(ts) {
320
283
  skipDefaultLibCheck: true,
321
284
  moduleResolution: ts.ModuleResolutionKind.NodeJs
322
285
  });
323
- }; // "/DOM.d.ts" => "/lib.dom.d.ts"
324
-
325
-
286
+ };
287
+ // "/DOM.d.ts" => "/lib.dom.d.ts"
326
288
  var libize = function libize(path) {
327
289
  return path.replace("/", "/lib.").toLowerCase();
328
290
  };
@@ -330,8 +292,6 @@ var libize = function libize(path) {
330
292
  * Creates an in-memory System object which can be used in a TypeScript program, this
331
293
  * is what provides read/write aspects of the virtual fs
332
294
  */
333
-
334
-
335
295
  function createSystem(files) {
336
296
  return {
337
297
  args: [],
@@ -383,13 +343,12 @@ function createSystem(files) {
383
343
  * a set of virtual files which are prioritised over the FS versions, then a path to the root of your
384
344
  * project (basically the folder your node_modules lives)
385
345
  */
386
-
387
346
  function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
388
347
  // We need to make an isolated folder for the tsconfig, but also need to be able to resolve the
389
348
  // existing node_modules structures going back through the history
390
349
  var root = _projectRoot + "/vfs";
391
- var path = requirePath(); // The default System in TypeScript
392
-
350
+ var path = requirePath();
351
+ // The default System in TypeScript
393
352
  var nodeSys = ts.sys;
394
353
  var tsLib = tsLibDirectory != null ? tsLibDirectory : path.dirname(require.resolve("typescript"));
395
354
  return {
@@ -408,15 +367,13 @@ function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
408
367
  }),
409
368
  exit: nodeSys.exit,
410
369
  fileExists: audit("fileExists", function (fileName) {
411
- if (files.has(fileName)) return true; // Don't let other tsconfigs end up touching the vfs
412
-
370
+ if (files.has(fileName)) return true;
371
+ // Don't let other tsconfigs end up touching the vfs
413
372
  if (fileName.includes("tsconfig.json") || fileName.includes("tsconfig.json")) return false;
414
-
415
373
  if (fileName.startsWith("/lib")) {
416
374
  var tsLibName = tsLib + "/" + fileName.replace("/", "");
417
375
  return nodeSys.fileExists(tsLibName);
418
376
  }
419
-
420
377
  return nodeSys.fileExists(fileName);
421
378
  }),
422
379
  getCurrentDirectory: function getCurrentDirectory() {
@@ -435,19 +392,15 @@ function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
435
392
  }),
436
393
  readFile: audit("readFile", function (fileName) {
437
394
  if (files.has(fileName)) return files.get(fileName);
438
-
439
395
  if (fileName.startsWith("/lib")) {
440
396
  var tsLibName = tsLib + "/" + fileName.replace("/", "");
441
397
  var result = nodeSys.readFile(tsLibName);
442
-
443
398
  if (!result) {
444
399
  var libs = nodeSys.readDirectory(tsLib);
445
400
  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 + ".");
446
401
  }
447
-
448
402
  return result;
449
403
  }
450
-
451
404
  return nodeSys.readFile(fileName);
452
405
  }),
453
406
  resolvePath: function resolvePath(path) {
@@ -469,15 +422,12 @@ function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
469
422
  * which works with TypeScript objects - returns both a compiler host, and a way to add new SourceFile
470
423
  * instances to the in-memory file system.
471
424
  */
472
-
473
425
  function createVirtualCompilerHost(sys, compilerOptions, ts) {
474
426
  var sourceFiles = new Map();
475
-
476
427
  var save = function save(sourceFile) {
477
428
  sourceFiles.set(sourceFile.fileName, sourceFile);
478
429
  return sourceFile;
479
430
  };
480
-
481
431
  var vHost = {
482
432
  compilerHost: _extends({}, sys, {
483
433
  getCanonicalFileName: function getCanonicalFileName(fileName) {
@@ -486,6 +436,7 @@ function createVirtualCompilerHost(sys, compilerOptions, ts) {
486
436
  getDefaultLibFileName: function getDefaultLibFileName() {
487
437
  return "/" + ts.getDefaultLibFileName(compilerOptions);
488
438
  },
439
+ // '/lib.d.ts',
489
440
  // getDefaultLibLocation: () => '/',
490
441
  getDirectories: function getDirectories() {
491
442
  return [];
@@ -512,17 +463,13 @@ function createVirtualCompilerHost(sys, compilerOptions, ts) {
512
463
  /**
513
464
  * Creates an object which can host a language service against the virtual file-system
514
465
  */
515
-
516
466
  function createVirtualLanguageServiceHost(sys, rootFiles, compilerOptions, ts, customTransformers) {
517
467
  var fileNames = [].concat(rootFiles);
518
-
519
468
  var _createVirtualCompile = createVirtualCompilerHost(sys, compilerOptions, ts),
520
- compilerHost = _createVirtualCompile.compilerHost,
521
- _updateFile2 = _createVirtualCompile.updateFile;
522
-
469
+ compilerHost = _createVirtualCompile.compilerHost,
470
+ _updateFile2 = _createVirtualCompile.updateFile;
523
471
  var fileVersions = new Map();
524
472
  var projectVersion = 0;
525
-
526
473
  var languageServiceHost = _extends({}, compilerHost, {
527
474
  getProjectVersion: function getProjectVersion() {
528
475
  return projectVersion.toString();
@@ -546,11 +493,9 @@ function createVirtualLanguageServiceHost(sys, rootFiles, compilerOptions, ts, c
546
493
  },
547
494
  getScriptSnapshot: function getScriptSnapshot(fileName) {
548
495
  var contents = sys.readFile(fileName);
549
-
550
- if (contents) {
496
+ if (contents && typeof contents === "string") {
551
497
  return ts.ScriptSnapshot.fromString(contents);
552
498
  }
553
-
554
499
  return;
555
500
  },
556
501
  getScriptVersion: function getScriptVersion(fileName) {
@@ -558,27 +503,22 @@ function createVirtualLanguageServiceHost(sys, rootFiles, compilerOptions, ts, c
558
503
  },
559
504
  writeFile: sys.writeFile
560
505
  });
561
-
562
506
  var lsHost = {
563
507
  languageServiceHost: languageServiceHost,
564
508
  updateFile: function updateFile(sourceFile) {
565
509
  projectVersion++;
566
510
  fileVersions.set(sourceFile.fileName, projectVersion.toString());
567
-
568
511
  if (!fileNames.includes(sourceFile.fileName)) {
569
512
  fileNames.push(sourceFile.fileName);
570
513
  }
571
-
572
514
  _updateFile2(sourceFile);
573
515
  }
574
516
  };
575
517
  return lsHost;
576
518
  }
577
-
578
519
  var requirePath = function requirePath() {
579
520
  return require(String.fromCharCode(112, 97, 116, 104));
580
521
  };
581
-
582
522
  var requireFS = function requireFS() {
583
523
  return require(String.fromCharCode(102, 115));
584
524
  };