Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

register-hash-imports.mjs

53 lines1.8 KB

1// Loaded with `node --import ./scripts/register-hash-imports.mjs` before a
2// repo script. Two resolution gaps between this TypeScript and Node:
3//
4// - `#/…` is the app alias (`package.json` imports + tsconfig paths). Node
5// rejects any specifier that starts with `#/`.
6// - Workspace packages use nodenext `.js` specifiers for files that exist
7// as `.ts` until `tsc` emits `dist/`. Node does not rewrite those.
8//
9// Also loads `.env` then `.env.local`, which Bun did for `bun scripts/…`.
10// A variable already in the environment wins. `.env.local` wins over `.env`.
11import { registerHooks } from 'node:module'
12import { join } from 'node:path'
13import { fileURLToPath, pathToFileURL } from 'node:url'
14import { config as loadEnv } from 'dotenv'
15​
16const root = join(fileURLToPath(new URL('.', import.meta.url)), '..')
17​
18const prior = { ...process.env }
19loadEnv({ path: join(root, '.env'), override: false, quiet: true })
20loadEnv({ path: join(root, '.env.local'), override: true, quiet: true })
21for (const [key, value] of Object.entries(prior)) {
22 if (value !== undefined) process.env[key] = value
24​
25registerHooks({
26 resolve(specifier, context, nextResolve) {
27 if (specifier.startsWith('#/')) {
28 return {
29 url: pathToFileURL(join(root, 'src', specifier.slice(2))).href,
30 shortCircuit: true,
31 }
32 }
33 if (specifier.endsWith('.js')) {
34 try {
35 return nextResolve(specifier, context)
36 } catch (error) {
37 if (!isNotFound(error)) throw error
38 return nextResolve(`${specifier.slice(0, -3)}.ts`, context)
39 }
40 }
41 return nextResolve(specifier, context)
42 },
43})
44​
45/** @param {unknown} error */
46function isNotFound(error) {
47 return (
48 typeof error === 'object' &&
49 error !== null &&
50 'code' in error &&
51 error.code === 'ERR_MODULE_NOT_FOUND'
52 )