import type { AbstractModule, Agent, Module } from "@isolated-vm/experimental"; import * as fs from "node:fs/promises"; import { fileURLToPath } from "node:url"; import { mappedComparator, selectKey, stringComparator } from "./comparator.js"; type LoaderAsync = (path: string, attributes?: Module.ImportAttributes) => Promise; type LoaderSync = (path: string, attributes?: Module.ImportAttributes) => Type; type AnyLoader = LoaderAsync | LoaderSync; type ResolverSync = (specifier: string, referrer?: string, attributes?: Module.ImportAttributes) => Type; type ResolverAsync = (specifier: string, referrer?: string, attributes?: Module.ImportAttributes) => Promise; type AnyResolver = ResolverAsync | ResolverSync; function cacheKeyFor(name: string, attributes: Module.ImportAttributes | undefined): string { const sortedAttributes = Object.entries(attributes ?? {}).sort(mappedComparator(stringComparator, selectKey)); return `${name}#${JSON.stringify(sortedAttributes)}`; } export function makeCompositeLinker(...linkers: Module.Linker[]): Module.Linker { return async (specifier, origin, attributes) => { for (const linker of linkers) { const module = await linker(specifier, origin, attributes); if (module) { return module; } } }; } export function makeLinker(resolver: AnyResolver, loader: AnyLoader): Module.Linker { return async (specifier, origin, attributes) => { const path = await resolver(specifier, origin, attributes); return loader(path, attributes); }; } export function makeNullLinker(): Module.Linker { return specifier => { throw new Error(`Module '${specifier}' not found`); }; } export function makeDirectResolver(): ResolverSync { return specifier => specifier; } export function makeLocalResolver(meta: ImportMeta): ResolverSync { return specifier => meta.resolve(specifier); } export function makeCachedLoader(loader: LoaderAsync): LoaderAsync { const modules = new Map>(); return (name, attributes) => { const cacheKey = cacheKeyFor(name, attributes); const cached = modules.get(cacheKey); if (cached) { return cached; } const module = function() { try { return loader(name, attributes); } catch (error) { // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors return Promise.reject(error); } }(); modules.set(cacheKey, module); return module; }; } export function makeFileSystemCompilationLoader(agent: Agent): LoaderAsync { return makeCachedLoader(async path => { const origin = { name: path }; const sourceText = await fs.readFile(fileURLToPath(path), "utf8"); const result = await agent.compileModule(sourceText, { origin }); if (result?.complete) { return result.result; } else { throw new SyntaxError(`Module compilation failed for '${path}'`, { cause: result?.error }); } }); } export function makeStaticLoader(pathsToModules: Record): LoaderSync { const modules = new Map(Object.entries(pathsToModules)); return specifier => modules.get(specifier); }