@esm.sh/import-map 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,563 @@
1
- export * from "./add.ts";
2
- export * from "./blank.ts";
3
- export * from "./parse.ts";
4
- export * from "./resolve.ts";
5
- export * from "./support.ts";
1
+ // src/add.ts
2
+ import { satisfies, valid } from "semver";
3
+ var KNOWN_TARGETS = /* @__PURE__ */ new Set([
4
+ "es2015",
5
+ "es2016",
6
+ "es2017",
7
+ "es2018",
8
+ "es2019",
9
+ "es2020",
10
+ "es2021",
11
+ "es2022",
12
+ "es2023",
13
+ "es2024",
14
+ "esnext"
15
+ ]);
16
+ var ESM_SEGMENTS = /* @__PURE__ */ new Set([
17
+ "es2015",
18
+ "es2016",
19
+ "es2017",
20
+ "es2018",
21
+ "es2019",
22
+ "es2020",
23
+ "es2021",
24
+ "es2022",
25
+ "es2023",
26
+ "es2024",
27
+ "esnext",
28
+ "denonext",
29
+ "deno",
30
+ "node"
31
+ ]);
32
+ var SPECIFIER_MARK_SEPARATOR = "\0";
33
+ var META_CACHE = /* @__PURE__ */ new Map();
34
+ async function addImport(importMap, specifier, noSRI) {
35
+ const imp = parseImportSpecifier(specifier);
36
+ const config = importMap.config ?? {};
37
+ const target = normalizeTarget(config.target);
38
+ const cdnOrigin = getCdnOrigin(config.cdn);
39
+ const meta = await fetchImportMeta(cdnOrigin, imp, target);
40
+ const mark = /* @__PURE__ */ new Set();
41
+ await addImportImpl(importMap, mark, meta, false, void 0, cdnOrigin, target, noSRI ?? false);
42
+ }
43
+ async function addImportImpl(importMap, mark, imp, indirect, targetImports, cdnOrigin, target, noSRI) {
44
+ const markedSpecifier = `${specifierOf(imp)}${SPECIFIER_MARK_SEPARATOR}${imp.version}`;
45
+ if (mark.has(markedSpecifier)) {
46
+ return;
47
+ }
48
+ mark.add(markedSpecifier);
49
+ const cdnScopeKey = `${cdnOrigin}/`;
50
+ const cdnScopeImports = importMap.scopes?.[cdnScopeKey];
51
+ const imports = indirect ? targetImports ?? ensureScope(importMap, cdnScopeKey) : importMap.imports;
52
+ const moduleUrl = moduleUrlOf(cdnOrigin, target, imp);
53
+ const currentSpecifier = specifierOf(imp);
54
+ imports[currentSpecifier] = moduleUrl;
55
+ await updateIntegrity(importMap, imp, moduleUrl, cdnOrigin, target, noSRI);
56
+ if (!indirect) {
57
+ if (cdnScopeImports) {
58
+ delete cdnScopeImports[currentSpecifier];
59
+ }
60
+ pruneEmptyScopes(importMap);
61
+ }
62
+ const allDeps = [
63
+ ...imp.peerImports.map((pathname) => ({ pathname, isPeer: true })),
64
+ ...imp.imports.map((pathname) => ({ pathname, isPeer: false }))
65
+ ];
66
+ await Promise.all(
67
+ allDeps.map(async ({ pathname, isPeer }) => {
68
+ if (pathname.startsWith("/node/")) {
69
+ return;
70
+ }
71
+ const depImport = parseEsmPath(pathname);
72
+ if (depImport.name === imp.name) {
73
+ depImport.version = imp.version;
74
+ }
75
+ const depSpecifier = specifierOf(depImport);
76
+ const existingUrl = importMap.imports[depSpecifier] ?? importMap.scopes?.[cdnScopeKey]?.[depSpecifier];
77
+ let scopedTargetImports = targetImports;
78
+ if (existingUrl?.startsWith(`${cdnOrigin}/`)) {
79
+ const existingImport = parseEsmPath(existingUrl);
80
+ const existingVersion = valid(existingImport.version);
81
+ if (existingVersion && depImport.version === existingImport.version) {
82
+ return;
83
+ }
84
+ if (existingVersion && depImport.version && !valid(depImport.version)) {
85
+ if (satisfies(existingVersion, depImport.version, { includePrerelease: true })) {
86
+ return;
87
+ }
88
+ if (isPeer) {
89
+ console.warn(
90
+ `incorrect peer dependency(unmeet ${depImport.version}): ${depImport.name}@${existingVersion}`
91
+ );
92
+ return;
93
+ }
94
+ const scope = `${cdnOrigin}/${esmSpecifierOf(imp)}/`;
95
+ scopedTargetImports = ensureScope(importMap, scope);
96
+ }
97
+ }
98
+ const depMeta = await fetchImportMeta(cdnOrigin, depImport, target);
99
+ await addImportImpl(importMap, mark, depMeta, !isPeer, scopedTargetImports, cdnOrigin, target, noSRI);
100
+ })
101
+ );
102
+ pruneEmptyScopes(importMap);
103
+ }
104
+ async function updateIntegrity(importMap, imp, moduleUrl, cdnOrigin, target, noSRI) {
105
+ if (noSRI) {
106
+ if (importMap.integrity) {
107
+ delete importMap.integrity[moduleUrl];
108
+ }
109
+ return;
110
+ }
111
+ if (!hasExternalImports(imp)) {
112
+ if (imp.integrity) {
113
+ importMap.integrity ??= {};
114
+ importMap.integrity[moduleUrl] = imp.integrity;
115
+ }
116
+ return;
117
+ }
118
+ const integrityMeta = await fetchImportMeta(
119
+ cdnOrigin,
120
+ {
121
+ name: imp.name,
122
+ version: imp.version,
123
+ subPath: imp.subPath,
124
+ github: imp.github,
125
+ jsr: imp.jsr,
126
+ external: true,
127
+ dev: imp.dev
128
+ },
129
+ target
130
+ );
131
+ if (integrityMeta.integrity) {
132
+ importMap.integrity ??= {};
133
+ importMap.integrity[moduleUrl] = integrityMeta.integrity;
134
+ }
135
+ }
136
+ function parseImportSpecifier(specifier) {
137
+ let source = specifier.trim();
138
+ const imp = {
139
+ name: "",
140
+ version: "",
141
+ subPath: "",
142
+ github: false,
143
+ jsr: false,
144
+ external: false,
145
+ dev: false
146
+ };
147
+ if (source.startsWith("gh:")) {
148
+ imp.github = true;
149
+ source = source.slice(3);
150
+ } else if (source.startsWith("jsr:")) {
151
+ imp.jsr = true;
152
+ source = source.slice(4);
153
+ }
154
+ let scopeName = "";
155
+ if ((source.startsWith("@") || imp.github) && source.includes("/")) {
156
+ [scopeName, source] = splitByFirst(source, "/");
157
+ }
158
+ let packageAndVersion = "";
159
+ [packageAndVersion, imp.subPath] = splitByFirst(source, "/");
160
+ [imp.name, imp.version] = splitByFirst(packageAndVersion, "@");
161
+ if (scopeName) {
162
+ imp.name = `${scopeName}/${imp.name}`;
163
+ }
164
+ if (!imp.name) {
165
+ throw new Error(`invalid package name or version: ${specifier}`);
166
+ }
167
+ return imp;
168
+ }
169
+ function normalizeTarget(target) {
170
+ if (target && KNOWN_TARGETS.has(target)) {
171
+ return target;
172
+ }
173
+ return "es2022";
174
+ }
175
+ function getCdnOrigin(cdn) {
176
+ if (cdn && (cdn.startsWith("https://") || cdn.startsWith("http://"))) {
177
+ return cdn.replace(/\/+$/, "");
178
+ }
179
+ return "https://esm.sh";
180
+ }
181
+ function specifierOf(imp) {
182
+ const prefix = imp.github ? "gh:" : imp.jsr ? "jsr:" : "";
183
+ return `${prefix}${imp.name}${imp.subPath ? `/${imp.subPath}` : ""}`;
184
+ }
185
+ function esmSpecifierOf(imp) {
186
+ const prefix = imp.github ? "gh/" : imp.jsr ? "jsr/" : "";
187
+ const external = hasExternalImports(imp) ? "*" : "";
188
+ return `${prefix}${external}${imp.name}@${imp.version}`;
189
+ }
190
+ function registryPrefix(imp) {
191
+ if (imp.github) {
192
+ return "gh/";
193
+ }
194
+ if (imp.jsr) {
195
+ return "jsr/";
196
+ }
197
+ return "";
198
+ }
199
+ function hasExternalImports(meta) {
200
+ if (meta.peerImports.length > 0) {
201
+ return true;
202
+ }
203
+ for (const dep of meta.imports) {
204
+ if (!dep.startsWith("/node/") && !dep.startsWith(`/${meta.name}@`)) {
205
+ return true;
206
+ }
207
+ }
208
+ return false;
209
+ }
210
+ function moduleUrlOf(cdnOrigin, target, imp) {
211
+ let url = `${cdnOrigin}/${esmSpecifierOf(imp)}/${target}/`;
212
+ if (imp.subPath) {
213
+ if (imp.dev || imp.subPath === "jsx-dev-runtime") {
214
+ url += `${imp.subPath}.development.mjs`;
215
+ } else {
216
+ url += `${imp.subPath}.mjs`;
217
+ }
218
+ return url;
219
+ }
220
+ const fileName = imp.name.includes("/") ? imp.name.split("/").at(-1) : imp.name;
221
+ return `${url}${fileName}.mjs`;
222
+ }
223
+ async function fetchImportMeta(cdnOrigin, imp, target) {
224
+ const star = imp.external ? "*" : "";
225
+ const version = imp.version ? `@${imp.version}` : "";
226
+ const subPath = imp.subPath ? `/${imp.subPath}` : "";
227
+ const targetQuery = target !== "es2022" ? `&target=${encodeURIComponent(target)}` : "";
228
+ const url = `${cdnOrigin}/${star}${registryPrefix(imp)}${imp.name}${version}${subPath}?meta${targetQuery}`;
229
+ const cached = META_CACHE.get(url);
230
+ if (cached) {
231
+ return cached;
232
+ }
233
+ const pending = (async () => {
234
+ const res = await fetch(url);
235
+ if (res.status === 404) {
236
+ throw new Error(`package not found: ${imp.name}${version}${subPath}`);
237
+ }
238
+ if (!res.ok) {
239
+ throw new Error(`unexpected http status ${res.status}: ${await res.text()}`);
240
+ }
241
+ const bodyText = await res.text();
242
+ let data;
243
+ try {
244
+ data = JSON.parse(bodyText);
245
+ } catch {
246
+ throw new Error(`invalid meta response from ${url}: ${bodyText.slice(0, 200)}`);
247
+ }
248
+ return {
249
+ name: data.name ?? imp.name,
250
+ version: data.version ?? imp.version,
251
+ subPath: imp.subPath,
252
+ github: imp.github,
253
+ jsr: imp.jsr,
254
+ external: imp.external,
255
+ dev: imp.dev,
256
+ module: data.module ?? "",
257
+ integrity: data.integrity ?? "",
258
+ exports: data.exports ?? [],
259
+ imports: data.imports ?? [],
260
+ peerImports: data.peerImports ?? []
261
+ };
262
+ })();
263
+ META_CACHE.set(url, pending);
264
+ try {
265
+ return await pending;
266
+ } catch (error) {
267
+ META_CACHE.delete(url);
268
+ throw error;
269
+ }
270
+ }
271
+ function ensureScope(importMap, scopeKey) {
272
+ importMap.scopes ??= {};
273
+ importMap.scopes[scopeKey] ??= {};
274
+ return importMap.scopes[scopeKey];
275
+ }
276
+ function pruneEmptyScopes(importMap) {
277
+ if (!importMap.scopes) {
278
+ return;
279
+ }
280
+ for (const [scope, imports] of Object.entries(importMap.scopes)) {
281
+ if (Object.keys(imports).length === 0) {
282
+ delete importMap.scopes[scope];
283
+ }
284
+ }
285
+ }
286
+ function parseEsmPath(pathnameOrUrl) {
287
+ let pathname;
288
+ if (pathnameOrUrl.startsWith("https://") || pathnameOrUrl.startsWith("http://")) {
289
+ pathname = new URL(pathnameOrUrl).pathname;
290
+ } else if (pathnameOrUrl.startsWith("/")) {
291
+ pathname = splitByFirst(splitByFirst(pathnameOrUrl, "#")[0], "?")[0];
292
+ } else {
293
+ throw new Error(`invalid pathname or url: ${pathnameOrUrl}`);
294
+ }
295
+ const imp = {
296
+ name: "",
297
+ version: "",
298
+ subPath: "",
299
+ github: false,
300
+ jsr: false,
301
+ external: false,
302
+ dev: false
303
+ };
304
+ if (pathname.startsWith("/gh/")) {
305
+ imp.github = true;
306
+ pathname = pathname.slice(3);
307
+ } else if (pathname.startsWith("/jsr/")) {
308
+ imp.jsr = true;
309
+ pathname = pathname.slice(4);
310
+ }
311
+ const segs = pathname.split("/").filter(Boolean);
312
+ if (segs.length === 0) {
313
+ throw new Error(`invalid pathname: ${pathnameOrUrl}`);
314
+ }
315
+ if (segs[0].startsWith("@")) {
316
+ if (!segs[1]) {
317
+ throw new Error(`invalid pathname: ${pathnameOrUrl}`);
318
+ }
319
+ const [name, version] = splitByLast(segs[1], "@");
320
+ imp.name = `${segs[0]}/${name}`.replace(/^\*/, "");
321
+ imp.version = version;
322
+ segs.splice(0, 2);
323
+ } else {
324
+ const [name, version] = splitByLast(segs[0], "@");
325
+ imp.name = name.replace(/^\*/, "");
326
+ imp.version = version;
327
+ segs.splice(0, 1);
328
+ }
329
+ let hasTargetSegment = false;
330
+ if (segs[0] && ESM_SEGMENTS.has(segs[0])) {
331
+ hasTargetSegment = true;
332
+ segs.shift();
333
+ }
334
+ if (segs.length > 0) {
335
+ if (hasTargetSegment && pathname.endsWith(".mjs")) {
336
+ let subPath = segs.join("/");
337
+ if (subPath.endsWith(".mjs")) {
338
+ subPath = subPath.slice(0, -4);
339
+ }
340
+ if (subPath.endsWith(".development")) {
341
+ subPath = subPath.slice(0, -12);
342
+ imp.dev = true;
343
+ }
344
+ if (subPath.includes("/") || subPath !== imp.name && !imp.name.endsWith(`/${subPath}`)) {
345
+ imp.subPath = subPath;
346
+ }
347
+ } else {
348
+ imp.subPath = segs.join("/");
349
+ }
350
+ }
351
+ return imp;
352
+ }
353
+ function splitByFirst(value, separator) {
354
+ const idx = value.indexOf(separator);
355
+ if (idx < 0) {
356
+ return [value, ""];
357
+ }
358
+ return [value.slice(0, idx), value.slice(idx + separator.length)];
359
+ }
360
+ function splitByLast(value, separator) {
361
+ const idx = value.lastIndexOf(separator);
362
+ if (idx < 0) {
363
+ return [value, ""];
364
+ }
365
+ return [value.slice(0, idx), value.slice(idx + separator.length)];
366
+ }
367
+
368
+ // src/resolve.ts
369
+ function resolve(importMap, specifier, containingFile) {
370
+ const baseURL = importMap.baseURL;
371
+ const referrer = new URL(containingFile, baseURL);
372
+ const [specifierWithoutHash, hashPart = ""] = specifier.split("#", 2);
373
+ const [specifierWithoutQuery, queryPart = ""] = specifierWithoutHash.split("?", 2);
374
+ const hash = hashPart ? `#${hashPart}` : "";
375
+ const query = queryPart ? `?${queryPart}` : "";
376
+ const cleanSpecifier = specifierWithoutQuery;
377
+ const scopes = importMap.scopes ?? {};
378
+ const scopeEntries = Object.entries(scopes).map(([scopeKey, scopeImports]) => {
379
+ try {
380
+ return [new URL(scopeKey, baseURL).toString(), scopeImports];
381
+ } catch {
382
+ return [scopeKey, scopeImports];
383
+ }
384
+ }).sort((a, b) => compareScopeKeys(a[0], b[0]));
385
+ for (const [scopeKey, scopeImports] of scopeEntries) {
386
+ if (!referrer.toString().startsWith(scopeKey)) {
387
+ continue;
388
+ }
389
+ const mapped2 = resolveWith(cleanSpecifier, scopeImports ?? {});
390
+ if (mapped2) {
391
+ return [normalizeUrl(baseURL, mapped2) + query + hash, true];
392
+ }
393
+ }
394
+ const mapped = resolveWith(cleanSpecifier, importMap.imports);
395
+ if (mapped) {
396
+ return [normalizeUrl(baseURL, mapped) + query + hash, true];
397
+ }
398
+ return [cleanSpecifier + query + hash, false];
399
+ }
400
+ function resolveWith(specifier, imports) {
401
+ if (imports[specifier]) {
402
+ return imports[specifier];
403
+ }
404
+ if (!specifier.includes("/")) {
405
+ return null;
406
+ }
407
+ const prefixKeys = Object.keys(imports).filter((k) => k.endsWith("/") && specifier.startsWith(k)).sort((a, b) => b.length - a.length || (a < b ? 1 : -1));
408
+ for (const key of prefixKeys) {
409
+ const value = imports[key];
410
+ if (value && value.endsWith("/")) {
411
+ return value + specifier.slice(key.length);
412
+ }
413
+ }
414
+ return null;
415
+ }
416
+ function compareScopeKeys(a, b) {
417
+ const aSlashCount = a.split("/").length;
418
+ const bSlashCount = b.split("/").length;
419
+ if (aSlashCount !== bSlashCount) {
420
+ return bSlashCount - aSlashCount;
421
+ }
422
+ return a < b ? 1 : -1;
423
+ }
424
+ function normalizeUrl(baseURL, path) {
425
+ if (path.startsWith("/") || path.startsWith("./") || path.startsWith("../")) {
426
+ return new URL(path, baseURL).toString();
427
+ }
428
+ return path;
429
+ }
430
+
431
+ // src/sanitize.ts
432
+ function sanitizeStringMap(map) {
433
+ if (!isObject(map)) {
434
+ return {};
435
+ }
436
+ const next = {};
437
+ for (const [key, value] of Object.entries(map)) {
438
+ if (typeof value === "string") {
439
+ next[key] = value;
440
+ }
441
+ }
442
+ return next;
443
+ }
444
+ function sanitizeScopes(scopes) {
445
+ if (!isObject(scopes)) {
446
+ return {};
447
+ }
448
+ const next = {};
449
+ for (const [scopeKey, scopeImports] of Object.entries(scopes)) {
450
+ if (isObject(scopeImports)) {
451
+ next[scopeKey] = sanitizeStringMap(scopeImports);
452
+ }
453
+ }
454
+ return next;
455
+ }
456
+ function isObject(v) {
457
+ return typeof v === "object" && v !== null && !Array.isArray(v);
458
+ }
459
+
460
+ // src/importmap.ts
461
+ var ImportMap = class {
462
+ #baseURL;
463
+ config = {};
464
+ imports = {};
465
+ scopes = {};
466
+ integrity = {};
467
+ constructor(baseURL, init) {
468
+ this.#baseURL = new URL(baseURL ?? globalThis.location?.href ?? "file:///");
469
+ if (init) {
470
+ this.config = sanitizeStringMap(init.config);
471
+ this.imports = sanitizeStringMap(init.imports);
472
+ this.scopes = sanitizeScopes(init.scopes);
473
+ this.integrity = sanitizeStringMap(init.integrity);
474
+ }
475
+ }
476
+ get baseURL() {
477
+ return this.#baseURL;
478
+ }
479
+ get isBlank() {
480
+ return Object.keys(this.imports).length === 0 && Object.keys(this.scopes).length === 0;
481
+ }
482
+ get raw() {
483
+ const json = {};
484
+ const config = sortStringMap(this.config);
485
+ if (Object.keys(config).length > 0) {
486
+ json.config = config;
487
+ }
488
+ const imports = sortStringMap(this.imports);
489
+ if (Object.keys(imports).length > 0) {
490
+ json.imports = imports;
491
+ }
492
+ const scopes = sortScopes(this.scopes);
493
+ if (Object.keys(scopes).length > 0) {
494
+ json.scopes = scopes;
495
+ }
496
+ const integrity = sortStringMap(this.integrity);
497
+ if (Object.keys(integrity).length > 0) {
498
+ json.integrity = integrity;
499
+ }
500
+ return json;
501
+ }
502
+ addImport(specifier, noSRI) {
503
+ return addImport(this, specifier, noSRI);
504
+ }
505
+ resolve(specifier, containingFile) {
506
+ return resolve(this, specifier, containingFile);
507
+ }
508
+ };
509
+ function sortStringMap(map) {
510
+ const source = map;
511
+ const next = {};
512
+ for (const key of Object.keys(source).sort()) {
513
+ const value = source[key];
514
+ if (typeof value === "string") {
515
+ next[key] = value;
516
+ }
517
+ }
518
+ return next;
519
+ }
520
+ function sortScopes(scopes) {
521
+ const next = {};
522
+ for (const scopeKey of Object.keys(scopes).sort()) {
523
+ const scopeImports = sortStringMap(scopes[scopeKey]);
524
+ if (Object.keys(scopeImports).length > 0) {
525
+ next[scopeKey] = scopeImports;
526
+ }
527
+ }
528
+ return next;
529
+ }
530
+
531
+ // src/parse.ts
532
+ function parseFromJson(json, baseURL) {
533
+ const im = new ImportMap(baseURL);
534
+ const v = JSON.parse(json);
535
+ if (isObject(v)) {
536
+ const { config, imports, scopes, integrity } = v;
537
+ im.config = sanitizeStringMap(config);
538
+ im.imports = sanitizeStringMap(imports);
539
+ im.scopes = sanitizeScopes(scopes);
540
+ im.integrity = sanitizeStringMap(integrity);
541
+ }
542
+ return im;
543
+ }
544
+ function parseFromHtml(html, baseURL) {
545
+ const tplEl = document.createElement("template");
546
+ tplEl.innerHTML = html;
547
+ const scriptEl = tplEl.content.querySelector("script[type='importmap']");
548
+ if (scriptEl) {
549
+ return parseFromJson(scriptEl.textContent, baseURL);
550
+ }
551
+ return new ImportMap(baseURL);
552
+ }
553
+
554
+ // src/support.ts
555
+ function isSupportImportMap() {
556
+ return !!globalThis.HTMLScriptElement?.supports?.("importmap");
557
+ }
558
+ export {
559
+ ImportMap,
560
+ isSupportImportMap,
561
+ parseFromHtml,
562
+ parseFromJson
563
+ };
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "@esm.sh/import-map",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "A import map parser and resolver.",
5
5
  "type": "module",
6
- "main": "dist/index.mjs",
7
- "module": "dist/index.mjs",
8
- "types": "types/index.d.ts",
6
+ "main": "./dist/index.mjs",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./types/index.d.ts",
9
9
  "files": [
10
- "dist",
11
- "types",
10
+ "dist/",
11
+ "types/",
12
12
  "README.md",
13
13
  "LICENSE"
14
14
  ],
15
15
  "scripts": {
16
16
  "prepublishOnly": "npm run build",
17
- "build": "rm -rf dist && esbuild --format=esm --outdir=dist --out-extension:.js=.mjs src/index.ts src/add.ts src/blank.ts src/parse.ts src/resolve.ts src/support.ts",
17
+ "build": "rm -rf dist && esbuild --bundle --format=esm --outdir=dist --out-extension:.js=.mjs --external:semver src/index.ts",
18
18
  "test": "bun test src/*.test.ts"
19
19
  },
20
20
  "dependencies": {
package/types/index.d.ts CHANGED
@@ -1,39 +1,71 @@
1
- /** The import maps follow the spec at https://wicg.github.io/import-maps/. */
2
- export interface ImportMap {
3
- baseURL?: URL;
4
- config?: Record<string, string>;
5
- imports: Record<string, string>;
1
+ /**
2
+ * The import map config.
3
+ *
4
+ * The config is not a standard part of the import map spec,
5
+ * it is used to create the new import url from CDN.
6
+ */
7
+ export interface ImportMapConfig {
8
+ /** The CDN origin to use for the import map. defaults to `https://esm.sh` */
9
+ cdn?: string;
10
+ /** The build target for the new import url from CDN. defaults to `es2022` */
11
+ target?: string;
12
+ }
13
+
14
+ /** The import map raw object. */
15
+ export interface ImportMapRaw {
16
+ /** The config for generating the new import url from CDN. */
17
+ config?: ImportMapConfig;
18
+ /** The imports of the import map. */
19
+ imports?: Record<string, string>;
20
+ /** The scopes of the import map. */
6
21
  scopes?: Record<string, Record<string, string>>;
22
+ /** The integrity of the import map. */
7
23
  integrity?: Record<string, string>;
8
24
  }
9
25
 
10
- /** Create a blank import map. */
11
- export function createBlankImportMap(baseURL?: string): ImportMap;
26
+ /** The import map class. */
27
+ export class ImportMap {
28
+ constructor(baseURL?: string | URL, init?: Record<string, any>);
12
29
 
13
- /** Create an import map from the given object. */
14
- export function importMapFrom(v: any, baseURL?: string): ImportMap;
30
+ /** The config for generating the new import url from CDN. */
31
+ config: ImportMapConfig;
15
32
 
16
- /** Parse the import map from a JSON string. */
17
- export function parseImportMapFromJson(json: string, baseURL?: string): ImportMap;
33
+ /** The imports of the import map. */
34
+ imports: Record<string, string>;
18
35
 
19
- /** Parse the import map from the given HTML. (Requires Browser environment) */
20
- export function parseImportMapFromHtml(html: string, baseURL?: string): ImportMap;
36
+ /** The scopes of the import map. */
37
+ scopes: Record<string, Record<string, string>>;
21
38
 
22
- /**
23
- * Add an import from esm.sh CDN to the import map.
24
- *
25
- * @param importMap - The import map to add the import to.
26
- * @param specifier - The specifier of the import to add.
27
- * @param noSRI - Whether to add the import without SRI.
28
- * @returns A promise that resolves when the import is added.
29
- */
30
- export function addImport(importMap: ImportMap, specifier: string, noSRI?: boolean): Promise<void>;
39
+ /** The integrity of the import map. */
40
+ integrity: Record<string, string>;
41
+
42
+ /** The base URL of the import map. */
43
+ get baseURL(): URL;
44
+
45
+ /** Check if the import map is blank. */
46
+ get isBlank(): boolean;
31
47
 
32
- /** Resolve the specifier with the import map. */
33
- export function resolve(importMap: ImportMap, specifier: string, containingFile: string): [url: string, ok: boolean];
48
+ /** Return a clean, key-ordered raw import map object. */
49
+ get raw(): ImportMapRaw;
50
+
51
+ /**
52
+ * Add an import from esm.sh CDN to the import map.
53
+ *
54
+ * @param specifier - The specifier of the import to add.
55
+ * @param noSRI - Whether to add the import without SRI.
56
+ * @returns A promise that resolves when the import is added.
57
+ */
58
+ addImport(specifier: string, noSRI?: boolean): Promise<void>;
59
+
60
+ /** Resolve the specifier with the import map. */
61
+ resolve(specifier: string, containingFile: string): [url: string, ok: boolean];
62
+ }
63
+
64
+ /** Parse the import map from a JSON string. */
65
+ export function parseFromJson(json: string, baseURL?: string): ImportMap;
66
+
67
+ /** Parse the import map from the given HTML. (Requires Browser environment) */
68
+ export function parseFromHtml(html: string, baseURL?: string): ImportMap;
34
69
 
35
70
  /** Check if current browser supports import maps. */
36
71
  export function isSupportImportMap(): boolean;
37
-
38
- /** Check if the import map is blank. */
39
- export function isBlankImportMap(importMap: ImportMap): boolean;