-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnode-import-map-loader.js
More file actions
64 lines (52 loc) · 1.56 KB
/
node-import-map-loader.js
File metadata and controls
64 lines (52 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { promises as fs } from "node:fs";
import { URL } from "node:url";
import {
resolveAndComposeImportMap,
resolveSpecifier,
} from "./import-map-utils.js";
let importMapPromise;
export async function initialize(registerData) {
importMapPromise = processRegisterData(registerData);
if (registerData.port) {
registerData.port.on("message", (data) => {
importMapPromise = processRegisterData(data);
});
}
}
async function processRegisterData(registerData) {
let importMap;
if (registerData.importMap) {
importMap = resolveAndComposeImportMap(registerData.importMap);
} else if (registerData.importMapUrl) {
let str;
try {
str = await fs.readFile(new URL(registerData.importMapUrl), "utf-8");
} catch (err) {
console.error(
`node-loader-import-maps: error reading import map from path '${registerData.importMapUrl}'`,
);
console.error(err);
throw err;
}
let json;
try {
json = await JSON.parse(str);
} catch (err) {
console.error(err);
throw Error(
`Import map at ${registerData.importMapUrl} contains invalid json: ${err.message}`,
);
}
importMap = resolveAndComposeImportMap(json);
}
return importMap;
}
export async function resolve(specifier, context, defaultResolve) {
const importMap = await importMapPromise;
let importMapUrl;
if (importMap) {
const { parentURL = null } = context;
importMapUrl = resolveSpecifier(importMap, specifier, parentURL);
}
return defaultResolve(importMapUrl ?? specifier, context);
}