UNPKG

@lcap/nasl

Version:

NetEase Application Specific Language

72 lines (62 loc) 2.92 kB
import { knownLibFilesForCompilerOptions } from '@typescript/vfs'; /** * 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) */ const createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version, cache, ts, lzstring, fetcher, storer) { const fetchlike = fetcher || fetch; const fsMap = new Map(); let files = knownLibFilesForCompilerOptions(options, ts); files = files.filter((file) => file.startsWith('lib.es')); const prefix = 'https://typescript.azureedge.net/cdn/' + version + '/typescript/lib/'; function zip(str) { return lzstring ? lzstring.compressToUTF16(str) : str; } function unzip(str) { 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)); }); } // A localstorage and lzzip aware version of the lib files function cached() { const storelike = storer || localStorage; const keys = Object.keys(localStorage); 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; }); } else { return Promise.resolve(unzip(content)); } })).then((contents) => { contents.forEach((text, index) => { const name = '/' + files[index]; fsMap.set(name, text); }); }); } const func = cache ? cached : uncached; return func().then(() => fsMap); }; export { createDefaultMapFromCDN };