// Test-time module resolution for `node --test`. // // Vite/SvelteKit resolve things at build time that plain Node does not: // 1. `.js` specifiers that name a `.ts` file on disk — how the project spells // every `#lib/...` import, per `rewriteRelativeImportExtensions`. // 2. extensionless imports, which the generated lexicons use (ts-lex is run // with `--import-ext ""`, so `./net/atchan` means `./net/atchan.ts`). // 3. the `$app` virtual modules, which have no on-disk backing at all; we // point them at small stubs so modules that merely `import` them (e.g. // the logger) can be exercised under `node --test` without a bundler. // 4. directory imports, which node's esm resolver refuses outright — the db // modules import their shared connection as `from '.'`. // This resolve hook fills those gaps. import { registerHooks } from 'node:module' import { pathToFileURL } from 'node:url' const stub = (name) => pathToFileURL(process.cwd() + '/scripts/test-stubs/' + name).href const virtualStubs = { '$app/env': stub('app-env.mjs'), '$app/env/private': stub('app-env-private.mjs'), '$app/env/public': stub('app-env-public.mjs'), '$app/paths': stub('app-paths.mjs') } // what to try when the specifier as written doesn't resolve: the `.ts` behind a // `.js` specifier, else an extensionless name as a file and then as a directory const retries = (spec) => spec.endsWith('.js') ? [spec.slice(0, -3) + '.ts'] : [spec + '.ts', spec + '/index.ts'] registerHooks({ resolve(specifier, context, nextResolve) { const spec = specifier in virtualStubs ? virtualStubs[specifier] : specifier try { return nextResolve(spec, context) } catch (err) { for (const candidate of retries(spec)) { try { return nextResolve(candidate, context) } catch { continue } } throw err } } })