delete Object.prototype.__proto__;
(( window) => {
const core = window.Deno.core;
const ops = core.ops;
let logDebug = false;
let logSource = "JS";
const normalizedToOriginalMap = new Map();
function isCreateSourceFileOptions(value) {
return value != null && typeof value === "object" &&
"languageVersion" in value;
}
function getCreateSourceFileOptions(versionOrOptions) {
return isCreateSourceFileOptions(versionOrOptions)
? versionOrOptions
: { languageVersion: versionOrOptions ?? ts.ScriptTarget.ESNext };
}
function setLogDebug(debug, source) {
logDebug = debug;
if (source) {
logSource = source;
}
}
function printStderr(msg) {
core.print(msg, true);
}
function debug(...args) {
if (logDebug) {
const stringifiedArgs = args.map((arg) =>
typeof arg === "string" ? arg : JSON.stringify(arg)
).join(" ");
printStderr(`DEBUG ${logSource} - ${stringifiedArgs}\n`);
}
}
function error(...args) {
const stringifiedArgs = args.map((arg) =>
typeof arg === "string" || arg instanceof Error
? String(arg)
: JSON.stringify(arg)
).join(" ");
printStderr(`ERROR ${logSource} = ${stringifiedArgs}\n`);
}
class AssertionError extends Error {
constructor(msg) {
super(msg);
this.name = "AssertionError";
}
}
function assert(cond, msg = "Assertion failed.") {
if (!cond) {
throw new AssertionError(msg);
}
}
class SpecifierIsCjsCache {
#cache = new Set();
add([specifier, ext]) {
if (ext === ".cjs" || ext === ".d.cts" || ext === ".cts") {
this.#cache.add(specifier);
}
}
has(specifier) {
return this.#cache.has(specifier);
}
}
const sourceFileCache = new Map();
let scriptFileNamesCache;
const scriptVersionCache = new Map();
const isNodeSourceFileCache = new Map();
const isCjsCache = new SpecifierIsCjsCache();
function getCompilationSettings(settingsOrHost) {
if (typeof settingsOrHost.getCompilationSettings === "function") {
return settingsOrHost.getCompilationSettings();
}
return (settingsOrHost);
}
const documentRegistrySourceFileCache = new Map();
const { getKeyForCompilationSettings } = ts.createDocumentRegistry();
const documentRegistry = {
acquireDocument(
fileName,
compilationSettingsOrHost,
scriptSnapshot,
version,
scriptKind,
sourceFileOptions,
) {
const key = getKeyForCompilationSettings(
getCompilationSettings(compilationSettingsOrHost),
);
return this.acquireDocumentWithKey(
fileName,
(fileName),
compilationSettingsOrHost,
key,
scriptSnapshot,
version,
scriptKind,
sourceFileOptions,
);
},
acquireDocumentWithKey(
fileName,
path,
_compilationSettingsOrHost,
key,
scriptSnapshot,
version,
scriptKind,
sourceFileOptions,
) {
const mapKey = path + key;
let sourceFile = documentRegistrySourceFileCache.get(mapKey);
if (!sourceFile || sourceFile.version !== version) {
sourceFile = ts.createLanguageServiceSourceFile(
fileName,
scriptSnapshot,
{
...getCreateSourceFileOptions(sourceFileOptions),
impliedNodeFormat: isCjsCache.has(fileName)
? ts.ModuleKind.CommonJS
: ts.ModuleKind.ESNext,
},
version,
true,
scriptKind,
);
documentRegistrySourceFileCache.set(mapKey, sourceFile);
}
return sourceFile;
},
updateDocument(
fileName,
compilationSettingsOrHost,
scriptSnapshot,
version,
scriptKind,
sourceFileOptions,
) {
const key = getKeyForCompilationSettings(
getCompilationSettings(compilationSettingsOrHost),
);
return this.updateDocumentWithKey(
fileName,
(fileName),
compilationSettingsOrHost,
key,
scriptSnapshot,
version,
scriptKind,
sourceFileOptions,
);
},
updateDocumentWithKey(
fileName,
path,
compilationSettingsOrHost,
key,
scriptSnapshot,
version,
scriptKind,
sourceFileOptions,
) {
const mapKey = path + key;
let sourceFile = documentRegistrySourceFileCache.get(mapKey) ??
this.acquireDocumentWithKey(
fileName,
path,
compilationSettingsOrHost,
key,
scriptSnapshot,
version,
scriptKind,
sourceFileOptions,
);
if (sourceFile.version !== version) {
sourceFile = ts.updateLanguageServiceSourceFile(
sourceFile,
scriptSnapshot,
version,
scriptSnapshot.getChangeRange(
(sourceFile.scriptSnapShot),
),
);
}
return sourceFile;
},
getKeyForCompilationSettings(settings) {
return getKeyForCompilationSettings(settings);
},
releaseDocument(
fileName,
compilationSettings,
scriptKind,
impliedNodeFormat,
) {
const key = getKeyForCompilationSettings(compilationSettings);
return this.releaseDocumentWithKey(
(fileName),
key,
scriptKind,
impliedNodeFormat,
);
},
releaseDocumentWithKey(path, key, _scriptKind, _impliedNodeFormat) {
const mapKey = path + key;
documentRegistrySourceFileCache.delete(mapKey);
},
reportStats() {
return "[]";
},
};
ts.deno.setIsNodeSourceFileCallback((sourceFile) => {
const fileName = sourceFile.fileName;
let isNodeSourceFile = isNodeSourceFileCache.get(fileName);
if (isNodeSourceFile == null) {
const result = ops.op_is_node_file(fileName);
isNodeSourceFile = (result);
isNodeSourceFileCache.set(fileName, isNodeSourceFile);
}
return isNodeSourceFile;
});
function fromRelatedInformation({
start,
length,
file,
messageText: msgText,
...ri
}) {
let messageText;
let messageChain;
if (typeof msgText === "object") {
messageChain = msgText;
} else {
messageText = msgText;
}
if (start !== undefined && length !== undefined && file) {
const startPos = file.getLineAndCharacterOfPosition(start);
const sourceLine = file.getFullText().split("\n")[startPos.line];
const fileName = file.fileName;
return {
start: startPos,
end: file.getLineAndCharacterOfPosition(start + length),
fileName,
messageChain,
messageText,
sourceLine,
...ri,
};
} else {
return {
messageChain,
messageText,
...ri,
};
}
}
function fromTypeScriptDiagnostic(diagnostics) {
return diagnostics.map(({ relatedInformation: ri, source, ...diag }) => {
const value = fromRelatedInformation(diag);
value.relatedInformation = ri
? ri.map(fromRelatedInformation)
: undefined;
value.source = source;
return value;
});
}
const ASSETS_URL_PREFIX = "asset:///";
const CACHE_URL_PREFIX = "cache:///";
const IGNORED_DIAGNOSTICS = [
1452,
2306,
2688,
2792,
5009,
5055,
5070,
7016,
];
const SNAPSHOT_COMPILE_OPTIONS = {
esModuleInterop: true,
jsx: ts.JsxEmit.React,
module: ts.ModuleKind.ESNext,
noEmit: true,
strict: true,
target: ts.ScriptTarget.ESNext,
lib: ["lib.deno.window.d.ts"],
};
class OperationCanceledError extends Error {
}
class ThrottledCancellationToken {
#lastCheckTimeMs = 0;
isCancellationRequested() {
const timeMs = Date.now();
if ((timeMs - this.#lastCheckTimeMs) < 20) {
return false;
}
this.#lastCheckTimeMs = timeMs;
return ops.op_is_cancelled();
}
throwIfCancellationRequested() {
if (this.isCancellationRequested()) {
throw new OperationCanceledError();
}
}
}
let compilationSettings = {};
let languageService;
const host = {
fileExists(specifier) {
if (logDebug) {
debug(`host.fileExists("${specifier}")`);
}
return false;
},
readFile(specifier) {
if (logDebug) {
debug(`host.readFile("${specifier}")`);
}
return ops.op_load({ specifier }).data;
},
getCancellationToken() {
return new ThrottledCancellationToken();
},
getSourceFile(
specifier,
languageVersion,
_onError,
_shouldCreateNewSourceFile,
) {
const createOptions = getCreateSourceFileOptions(languageVersion);
if (logDebug) {
debug(
`host.getSourceFile("${specifier}", ${
ts.ScriptTarget[createOptions.languageVersion]
})`,
);
}
specifier = normalizedToOriginalMap.get(specifier) ?? specifier;
let sourceFile = sourceFileCache.get(specifier);
if (sourceFile) {
return sourceFile;
}
const { data, scriptKind, version } = ops.op_load(
{ specifier },
);
assert(
data != null,
`"data" is unexpectedly null for "${specifier}".`,
);
sourceFile = ts.createSourceFile(
specifier,
data,
{
...createOptions,
impliedNodeFormat: isCjsCache.has(specifier)
? ts.ModuleKind.CommonJS
: ts.ModuleKind.ESNext,
},
false,
scriptKind,
);
sourceFile.moduleName = specifier;
sourceFile.version = version;
sourceFileCache.set(specifier, sourceFile);
scriptVersionCache.set(specifier, version);
return sourceFile;
},
getDefaultLibFileName() {
return `${ASSETS_URL_PREFIX}lib.esnext.d.ts`;
},
getDefaultLibLocation() {
return ASSETS_URL_PREFIX;
},
writeFile(fileName, data, _writeByteOrderMark, _onError, _sourceFiles) {
if (logDebug) {
debug(`host.writeFile("${fileName}")`);
}
return ops.op_emit(
{ fileName, data },
);
},
getCurrentDirectory() {
if (logDebug) {
debug(`host.getCurrentDirectory()`);
}
return CACHE_URL_PREFIX;
},
getCanonicalFileName(fileName) {
return fileName;
},
useCaseSensitiveFileNames() {
return true;
},
getNewLine() {
return "\n";
},
resolveTypeReferenceDirectives(
typeDirectiveNames,
containingFilePath,
redirectedReference,
options,
containingFileMode,
) {
return typeDirectiveNames.map((arg) => {
const fileReference = typeof arg === "string"
? {
pos: -1,
end: -1,
fileName: arg,
}
: arg;
if (fileReference.fileName.startsWith("npm:")) {
const resolved = ops.op_resolve({
specifiers: [fileReference.fileName],
base: containingFilePath,
})?.[0];
if (resolved) {
isCjsCache.add(resolved);
return {
primary: true,
resolvedFileName: resolved[0],
};
} else {
return undefined;
}
} else {
return ts.resolveTypeReferenceDirective(
fileReference.fileName,
containingFilePath,
options,
host,
redirectedReference,
undefined,
containingFileMode ?? fileReference.resolutionMode,
).resolvedTypeReferenceDirective;
}
});
},
resolveModuleNames(specifiers, base) {
if (logDebug) {
debug(`host.resolveModuleNames()`);
debug(` base: ${base}`);
debug(` specifiers: ${specifiers.join(", ")}`);
}
const resolved = ops.op_resolve({
specifiers,
base,
});
if (resolved) {
const result = resolved.map((item) => {
if (item) {
isCjsCache.add(item);
const [resolvedFileName, extension] = item;
if (resolvedFileName.startsWith("node:")) {
return undefined;
}
return {
resolvedFileName,
extension,
isExternalLibraryImport: false,
};
}
return undefined;
});
result.length = specifiers.length;
return result;
} else {
return new Array(specifiers.length);
}
},
createHash(data) {
return ops.op_create_hash({ data }).hash;
},
getCompilationSettings() {
if (logDebug) {
debug("host.getCompilationSettings()");
}
return compilationSettings;
},
getScriptFileNames() {
if (logDebug) {
debug("host.getScriptFileNames()");
}
if (scriptFileNamesCache) {
return scriptFileNamesCache;
}
return scriptFileNamesCache = ops.op_script_names();
},
getScriptVersion(specifier) {
if (logDebug) {
debug(`host.getScriptVersion("${specifier}")`);
}
const sourceFile = sourceFileCache.get(specifier);
if (sourceFile) {
return sourceFile.version ?? "1";
}
if (scriptVersionCache.has(specifier)) {
return scriptVersionCache.get(specifier);
}
const scriptVersion = ops.op_script_version({ specifier });
scriptVersionCache.set(specifier, scriptVersion);
return scriptVersion;
},
getScriptSnapshot(specifier) {
if (logDebug) {
debug(`host.getScriptSnapshot("${specifier}")`);
}
const sourceFile = sourceFileCache.get(specifier);
if (sourceFile) {
return {
getText(start, end) {
return sourceFile.text.substring(start, end);
},
getLength() {
return sourceFile.text.length;
},
getChangeRange() {
return undefined;
},
};
}
const fileInfo = ops.op_load(
{ specifier },
);
if (fileInfo) {
scriptVersionCache.set(specifier, fileInfo.version);
return ts.ScriptSnapshot.fromString(fileInfo.data);
} else {
return undefined;
}
},
};
ts.setLocalizedDiagnosticMessages((() => {
const nodeMessage = "Cannot find name '{0}'."; const jqueryMessage =
"Cannot find name '{0}'. Did you mean to import jQuery? Try adding `import $ from \"npm:jquery\";`.";
return {
"Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580":
nodeMessage,
"Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591":
nodeMessage,
"Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581":
jqueryMessage,
"Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592":
jqueryMessage,
};
})());
const stats = [];
let statsStart = 0;
function performanceStart() {
stats.length = 0;
statsStart = Date.now();
ts.performance.enable();
}
function performanceProgram({ program, fileCount }) {
if (program) {
if ("getProgram" in program) {
program = program.getProgram();
}
stats.push(["Files", program.getSourceFiles().length]);
stats.push(["Nodes", program.getNodeCount()]);
stats.push(["Identifiers", program.getIdentifierCount()]);
stats.push(["Symbols", program.getSymbolCount()]);
stats.push(["Types", program.getTypeCount()]);
stats.push(["Instantiations", program.getInstantiationCount()]);
} else if (fileCount != null) {
stats.push(["Files", fileCount]);
}
const programTime = ts.performance.getDuration("Program");
const bindTime = ts.performance.getDuration("Bind");
const checkTime = ts.performance.getDuration("Check");
const emitTime = ts.performance.getDuration("Emit");
stats.push(["Parse time", programTime]);
stats.push(["Bind time", bindTime]);
stats.push(["Check time", checkTime]);
stats.push(["Emit time", emitTime]);
stats.push(
["Total TS time", programTime + bindTime + checkTime + emitTime],
);
}
function performanceEnd() {
const duration = Date.now() - statsStart;
stats.push(["Compile time", duration]);
return stats;
}
function checkNormalizedPath(rootName) {
const normalized = ts.normalizePath(rootName);
const originalRootName = normalizedToOriginalMap.get(normalized);
if (typeof originalRootName === "undefined") {
normalizedToOriginalMap.set(normalized, rootName);
} else if (originalRootName !== rootName) {
throw new AssertionError(
`The different names for the same normalized specifier are specified: normalized=${normalized}, rootNames=${originalRootName},${rootName}`,
);
}
}
function exec({ config, debug: debugFlag, rootNames, localOnly }) {
setLogDebug(debugFlag, "TS");
performanceStart();
if (logDebug) {
debug(">>> exec start", { rootNames });
debug(config);
}
rootNames.forEach(checkNormalizedPath);
const { options, errors: configFileParsingDiagnostics } = ts
.convertCompilerOptionsFromJson(config, "");
Object.assign(options, { allowNonTsExtensions: true });
const program = ts.createIncrementalProgram({
rootNames,
options,
host,
configFileParsingDiagnostics,
});
const checkFiles = localOnly
? rootNames
.filter((n) => !n.startsWith("http"))
.map((checkName) => {
const sourceFile = program.getSourceFile(checkName);
if (sourceFile == null) {
throw new Error("Could not find source file for: " + checkName);
}
return sourceFile;
})
: undefined;
const diagnostics = [
...program.getConfigFileParsingDiagnostics(),
...(checkFiles == null
? program.getSyntacticDiagnostics()
: ts.sortAndDeduplicateDiagnostics(
checkFiles.map((s) => program.getSyntacticDiagnostics(s)).flat(),
)),
...program.getOptionsDiagnostics(),
...program.getGlobalDiagnostics(),
...(checkFiles == null
? program.getSemanticDiagnostics()
: ts.sortAndDeduplicateDiagnostics(
checkFiles.map((s) => program.getSemanticDiagnostics(s)).flat(),
)),
].filter((diagnostic) => !IGNORED_DIAGNOSTICS.includes(diagnostic.code));
program.emitBuildInfo(host.writeFile);
performanceProgram({ program });
ops.op_respond({
diagnostics: fromTypeScriptDiagnostic(diagnostics),
stats: performanceEnd(),
});
debug("<<< exec stop");
}
function getAssets() {
const assets = [];
for (const sourceFile of sourceFileCache.values()) {
if (sourceFile.fileName.startsWith(ASSETS_URL_PREFIX)) {
assets.push({
specifier: sourceFile.fileName,
text: sourceFile.text,
});
}
}
return assets;
}
function respond(id, data = null) {
ops.op_respond({ id, data });
}
function serverRequest({ id, ...request }) {
if (logDebug) {
debug(`serverRequest()`, { id, ...request });
}
scriptFileNamesCache = undefined;
scriptVersionCache.clear();
switch (request.method) {
case "restart": {
serverRestart();
return respond(id, true);
}
case "configure": {
const { options, errors } = ts
.convertCompilerOptionsFromJson(request.compilerOptions, "");
Object.assign(options, {
allowNonTsExtensions: true,
allowImportingTsExtensions: true,
});
if (errors.length > 0 && logDebug) {
debug(ts.formatDiagnostics(errors, host));
}
compilationSettings = options;
return respond(id, true);
}
case "findRenameLocations": {
return respond(
id,
languageService.findRenameLocations(
request.specifier,
request.position,
request.findInStrings,
request.findInComments,
request.providePrefixAndSuffixTextForRename,
),
);
}
case "getAssets": {
return respond(id, getAssets());
}
case "getApplicableRefactors": {
return respond(
id,
languageService.getApplicableRefactors(
request.specifier,
request.range,
{
quotePreference: "double",
allowTextChangesInNewFiles: true,
provideRefactorNotApplicableReason: true,
},
undefined,
request.kind,
),
);
}
case "getEditsForRefactor": {
return respond(
id,
languageService.getEditsForRefactor(
request.specifier,
{
indentSize: 2,
indentStyle: ts.IndentStyle.Smart,
semicolons: ts.SemicolonPreference.Insert,
convertTabsToSpaces: true,
insertSpaceBeforeAndAfterBinaryOperators: true,
insertSpaceAfterCommaDelimiter: true,
},
request.range,
request.refactorName,
request.actionName,
{
quotePreference: "double",
},
),
);
}
case "getCodeFixes": {
return respond(
id,
languageService.getCodeFixesAtPosition(
request.specifier,
request.startPosition,
request.endPosition,
request.errorCodes.map((v) => Number(v)),
{
indentSize: 2,
indentStyle: ts.IndentStyle.Block,
semicolons: ts.SemicolonPreference.Insert,
},
{
quotePreference: "double",
},
),
);
}
case "getCombinedCodeFix": {
return respond(
id,
languageService.getCombinedCodeFix(
{
type: "file",
fileName: request.specifier,
},
request.fixId,
{
indentSize: 2,
indentStyle: ts.IndentStyle.Block,
semicolons: ts.SemicolonPreference.Insert,
},
{
quotePreference: "double",
},
),
);
}
case "getCompletionDetails": {
if (logDebug) {
debug("request", request);
}
return respond(
id,
languageService.getCompletionEntryDetails(
request.args.specifier,
request.args.position,
request.args.name,
{},
request.args.source,
request.args.preferences,
request.args.data,
),
);
}
case "getCompletions": {
return respond(
id,
languageService.getCompletionsAtPosition(
request.specifier,
request.position,
request.preferences,
),
);
}
case "getDefinition": {
return respond(
id,
languageService.getDefinitionAndBoundSpan(
request.specifier,
request.position,
),
);
}
case "getDiagnostics": {
try {
const diagnosticMap = {};
for (const specifier of request.specifiers) {
diagnosticMap[specifier] = fromTypeScriptDiagnostic([
...languageService.getSemanticDiagnostics(specifier),
...languageService.getSuggestionDiagnostics(specifier),
...languageService.getSyntacticDiagnostics(specifier),
].filter(({ code }) => !IGNORED_DIAGNOSTICS.includes(code)));
}
return respond(id, diagnosticMap);
} catch (e) {
if (
!(e instanceof OperationCanceledError ||
e instanceof ts.OperationCanceledException)
) {
if ("stack" in e) {
error(e.stack);
} else {
error(e);
}
}
return respond(id, {});
}
}
case "getDocumentHighlights": {
return respond(
id,
languageService.getDocumentHighlights(
request.specifier,
request.position,
request.filesToSearch,
),
);
}
case "getEncodedSemanticClassifications": {
return respond(
id,
languageService.getEncodedSemanticClassifications(
request.specifier,
request.span,
ts.SemanticClassificationFormat.TwentyTwenty,
),
);
}
case "getImplementation": {
return respond(
id,
languageService.getImplementationAtPosition(
request.specifier,
request.position,
),
);
}
case "getNavigateToItems": {
return respond(
id,
languageService.getNavigateToItems(
request.search,
request.maxResultCount,
request.fileName,
),
);
}
case "getNavigationTree": {
return respond(
id,
languageService.getNavigationTree(request.specifier),
);
}
case "getOutliningSpans": {
return respond(
id,
languageService.getOutliningSpans(
request.specifier,
),
);
}
case "getQuickInfo": {
return respond(
id,
languageService.getQuickInfoAtPosition(
request.specifier,
request.position,
),
);
}
case "findReferences": {
return respond(
id,
languageService.findReferences(
request.specifier,
request.position,
),
);
}
case "getSignatureHelpItems": {
return respond(
id,
languageService.getSignatureHelpItems(
request.specifier,
request.position,
request.options,
),
);
}
case "getSmartSelectionRange": {
return respond(
id,
languageService.getSmartSelectionRange(
request.specifier,
request.position,
),
);
}
case "getSupportedCodeFixes": {
return respond(
id,
ts.getSupportedCodeFixes(),
);
}
case "getTypeDefinition": {
return respond(
id,
languageService.getTypeDefinitionAtPosition(
request.specifier,
request.position,
),
);
}
case "prepareCallHierarchy": {
return respond(
id,
languageService.prepareCallHierarchy(
request.specifier,
request.position,
),
);
}
case "provideCallHierarchyIncomingCalls": {
return respond(
id,
languageService.provideCallHierarchyIncomingCalls(
request.specifier,
request.position,
),
);
}
case "provideCallHierarchyOutgoingCalls": {
return respond(
id,
languageService.provideCallHierarchyOutgoingCalls(
request.specifier,
request.position,
),
);
}
case "provideInlayHints":
return respond(
id,
languageService.provideInlayHints(
request.specifier,
request.span,
request.preferences,
),
);
default:
throw new TypeError(
`Invalid request method for request: "${request.method}" (${id})`,
);
}
}
function serverInit({ debug: debugFlag }) {
if (hasStarted) {
throw new Error("The language server has already been initialized.");
}
hasStarted = true;
languageService = ts.createLanguageService(host, documentRegistry);
setLogDebug(debugFlag, "TSLS");
debug("serverInit()");
}
function serverRestart() {
languageService = ts.createLanguageService(host, documentRegistry);
isNodeSourceFileCache.clear();
debug("serverRestart()");
}
let hasStarted = false;
function startup({ debugFlag = false }) {
if (hasStarted) {
throw new Error("The compiler runtime already started.");
}
hasStarted = true;
setLogDebug(!!debugFlag, "TS");
}
const { buildSpecifier, libs, nodeBuiltInModuleNames } = ops.op_build_info();
ts.deno.setNodeBuiltInModuleNames(nodeBuiltInModuleNames);
ts.deno.setNodeOnlyGlobalNames([
"NodeRequire",
"RequireResolve",
"RequireResolve",
"process",
"console",
"__filename",
"__dirname",
"require",
"module",
"exports",
"gc",
"BufferEncoding",
"BufferConstructor",
"WithImplicitCoercion",
"Buffer",
"Console",
"ImportMeta",
"setTimeout",
"setInterval",
"setImmediate",
"Global",
"AbortController",
"AbortSignal",
"Blob",
"BroadcastChannel",
"MessageChannel",
"MessagePort",
"Event",
"EventTarget",
"performance",
"TextDecoder",
"TextEncoder",
"URL",
"URLSearchParams",
]);
for (const lib of libs) {
const specifier = `lib.${lib}.d.ts`;
if (!ts.libs.includes(lib)) {
ts.libs.push(lib);
ts.libMap.set(lib, `lib.${lib}.d.ts`);
}
assert(
!!host.getSourceFile(
`${ASSETS_URL_PREFIX}${specifier}`,
ts.ScriptTarget.ESNext,
),
);
}
const TS_SNAPSHOT_PROGRAM = ts.createProgram({
rootNames: [buildSpecifier],
options: SNAPSHOT_COMPILE_OPTIONS,
host,
});
assert(ts.getPreEmitDiagnostics(TS_SNAPSHOT_PROGRAM).length === 0);
sourceFileCache.delete(buildSpecifier);
const global = globalThis;
global.startup = startup;
global.exec = exec;
global.getAssets = getAssets;
global.serverInit = serverInit;
global.serverRequest = serverRequest;
})(this);