UNPKG

2.78 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const assert_1 = __importDefault(require("assert"));
7const url_1 = require("url");
8const utils_1 = require("./utils");
9function resolve(specifier, parsedImportMap, scriptURL) {
10 const asURL = utils_1.tryURLLikeSpecifierParse(specifier, scriptURL);
11 const normalizedSpecifier = asURL ? asURL.href : specifier;
12 const scriptURLString = scriptURL.href;
13 for (const [scopePrefix, scopeImports] of Object.entries(parsedImportMap.scopes)) {
14 if (scopePrefix === scriptURLString ||
15 (scopePrefix.endsWith("/") && scriptURLString.startsWith(scopePrefix))) {
16 const scopeImportsMatch = resolveImportsMatch(normalizedSpecifier, scopeImports);
17 if (scopeImportsMatch !== null) {
18 return scopeImportsMatch;
19 }
20 }
21 }
22 const topLevelImportsMatch = resolveImportsMatch(normalizedSpecifier, parsedImportMap.imports);
23 if (topLevelImportsMatch !== null) {
24 return topLevelImportsMatch;
25 }
26 // The specifier was able to be turned into a URL, but wasn't remapped into anything.
27 if (asURL) {
28 return asURL;
29 }
30 throw new TypeError(`Unmapped bare specifier "${specifier}"`);
31}
32exports.resolve = resolve;
33function resolveImportsMatch(normalizedSpecifier, specifierMap) {
34 for (const [specifierKey, resolutionResult] of Object.entries(specifierMap)) {
35 // Exact-match case
36 if (specifierKey === normalizedSpecifier) {
37 if (resolutionResult === null) {
38 throw new TypeError(`Blocked by a null entry for "${specifierKey}"`);
39 }
40 assert_1.default(resolutionResult instanceof url_1.URL);
41 return resolutionResult;
42 }
43 // Package prefix-match case
44 if (specifierKey.endsWith("/") && normalizedSpecifier.startsWith(specifierKey)) {
45 if (resolutionResult === null) {
46 throw new TypeError(`Blocked by a null entry for "${specifierKey}"`);
47 }
48 assert_1.default(resolutionResult instanceof url_1.URL);
49 const afterPrefix = normalizedSpecifier.substring(specifierKey.length);
50 // Enforced by parsing
51 assert_1.default(resolutionResult.href.endsWith("/"));
52 const url = utils_1.tryURLParse(afterPrefix, resolutionResult);
53 if (url === null) {
54 throw new TypeError(`Failed to resolve prefix-match relative URL for "${specifierKey}"`);
55 }
56 assert_1.default(url instanceof url_1.URL);
57 return url;
58 }
59 }
60 return null;
61}