Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read current import map #213

Merged
merged 19 commits into from
Oct 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Shim mode is an alternative to polyfill mode and doesn't rely on native modules

In shim mode, normal module scripts and import maps are entirely ignored and only the above shim tags will be parsed and executed by ES Module Shims instead.

Shim mode also provides some additional features that aren't yet natively supported such as supporting multiple import maps, [external import maps](#external-import-maps) with a `"src"` attribute or [dynamicallly injecting import maps](#dynamic-import-maps), which can be useful in certain applications.
Shim mode also provides some additional features that aren't yet natively supported such as supporting multiple import maps, [external import maps](#external-import-maps) with a `"src"` attribute, [dynamically injecting import maps](#dynamic-import-maps), and [reading current import map state](#reading-current-import-map-state), which can be useful in certain applications.

## Features

Expand Down Expand Up @@ -195,6 +195,16 @@ Both modes in ES Module Shims support dynamic injection using DOM Mutation Obser

While in polyfill mode the same restrictions apply that multiple import maps, import maps with a `src` attribute, and import maps loaded after the first module load are not supported, in shim mode all of these behaviours are fully enabled for `"importmap-shim"`.

#### Reading current import map state

To make it easy to keep track of import map state, es-module-shims provides a `importShim.getImportMap` utility function, available only in shim mode.

```js
const importMap = importShim.getImportMap()

// importMap will be an object in the same shape as the json in a importmap script
```

### Dynamic Import

> Stability: Stable browser standard
Expand Down
3 changes: 3 additions & 0 deletions src/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ export function resolveUrl (relUrl, parentUrl) {
function resolveAndComposePackages (packages, outPackages, baseUrl, parentMap) {
for (let p in packages) {
const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;
if (outPackages[resolvedLhs]) {
throw new Error(`Dynamic import map rejected: Overrides entry "${resolvedLhs}" from ${outPackages[resolvedLhs]} to ${packages[resolvedLhs]}.`);
}
let target = packages[p];
if (typeof target !== 'string')
continue;
Expand Down
12 changes: 9 additions & 3 deletions src/es-module-shims.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ async function importShim (id, parentUrl = pageBaseUrl, _assertion) {

self.importShim = importShim;

if (shimMode) {
importShim.getImportMap = () => JSON.parse(JSON.stringify(importMap));
}

const meta = {};

async function importMetaResolve (id, parentUrl = this.url) {
Expand Down Expand Up @@ -460,9 +464,11 @@ function processImportMap (script) {
importMapSrcOrLazy = true;
}
if (acceptingImportMaps) {
importMapPromise = importMapPromise.then(async () => {
importMap = resolveAndComposeImportMap(script.src ? await (await fetchHook(script.src)).json() : JSON.parse(script.innerHTML), script.src || pageBaseUrl, importMap);
});
importMapPromise = importMapPromise
.then(async () => {
importMap = resolveAndComposeImportMap(script.src ? await (await fetchHook(script.src)).json() : JSON.parse(script.innerHTML), script.src || pageBaseUrl, importMap);
})
.catch(error => setTimeout(() => { throw error }));
if (!shimMode)
acceptingImportMaps = false;
}
Expand Down
61 changes: 59 additions & 2 deletions test/shim.js
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,41 @@ suite('Export variations', function () {
});
});

// These tests are order dependent, as importMap state will change when dynamic import maps are injected in the suite.
suite('Get import map', () => {
test("should get correct import map state", async () => {
const importMap = await importShim.getImportMap();

const sortEntriesByKey = (entries) => [...entries].sort(([key1], [key2]) => key1.localeCompare(key2));

assert.equal(JSON.stringify(Object.keys(importMap)), JSON.stringify(["imports", "scopes"]));
assert.equal(
JSON.stringify(sortEntriesByKey(Object.entries(importMap.imports))),
JSON.stringify(sortEntriesByKey(Object.entries({
"test": "http://localhost:8080/test/fixtures/es-modules/es6-file.js",
"test/": "http://localhost:8080/test/fixtures/",
"global1": "http://localhost:8080/test/fixtures/es-modules/global1.js",
"bare-dynamic-import": "http://localhost:8080/test/fixtures/es-modules/bare-dynamic-import.js",
"react": "https://ga.jspm.io/npm:react@17.0.2/dev.index.js"
})))
);
assert.equal(
JSON.stringify(sortEntriesByKey(Object.entries(importMap.scopes))),
JSON.stringify(sortEntriesByKey(Object.entries({
"http://localhost:8080/": {
"test-dep": "http://localhost:8080/test/fixtures/test-dep.js",
},
"http://localhost:8080/test/fixtures/es-modules/import-relative-path.js": {
"http://localhost:8080/test/fixtures/es-modules/relative-path": "http://localhost:8080/test/fixtures/es-modules/es6-dep.js",
},
"https://ga.jspm.io/": {
"object-assign": "https://ga.jspm.io/npm:object-assign@4.1.1/index.js",
}
})))
);
});
});

suite('Errors', function () {
async function getImportError(module) {
try {
Expand Down Expand Up @@ -331,11 +366,33 @@ suite('Errors', function () {
assert.ok(lodash);
})

test('Dynamic import map shim with override attempt', async function () {
const listeningForError = new Promise((resolve, reject) => {
window.addEventListener('error', (event) => resolve(event.error))
// ensure we don't wait forever in the test if the error never comes
setTimeout(reject, 5000)
})

const removeImportMap = insertDynamicImportMap({
"imports": {
"global1": "data:text/javascript,throw new Error('Shim should not allow dynamic import map to override existing entries');"
}
});

const error = await listeningForError;

removeImportMap();

assert(error.message === 'Dynamic import map rejected: Overrides entry "global1" from http://localhost:8080/test/fixtures/es-modules/global1.js to data:text/javascript,throw new Error(\'Shim should not allow dynamic import map to override existing entries\');.');
})

function insertDynamicImportMap(importMap) {
document.body.appendChild(Object.assign(document.createElement('script'), {
const script = Object.assign(document.createElement('script'), {
type: 'importmap-shim',
innerHTML: JSON.stringify(importMap),
}));
});
document.body.appendChild(script);
return () => document.body.removeChild(script);
}
});

Expand Down
16 changes: 12 additions & 4 deletions test/test-shim.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,25 @@
"imports": {
"test": "/test/fixtures/es-modules/es6-file.js",
"test/": "/test/fixtures/",
"global1": "/test/fixtures/es-modules/global1.js",
"bare-dynamic-import": "/test/fixtures/es-modules/bare-dynamic-import.js",
"react": "https://ga.jspm.io/npm:react@17.0.2/dev.index.js"
"global1": "/test/fixtures/es-modules/global1.js"
},
"scopes": {
"/": {
"test-dep": "/test/fixtures/test-dep.js"
},
"/test/fixtures/es-modules/import-relative-path.js": {
"./fixtures/es-modules/relative-path": "./fixtures/es-modules/es6-dep.js"
},
}
}
}
</script>
<script type="importmap-shim">
{
"imports": {
"bare-dynamic-import": "/test/fixtures/es-modules/bare-dynamic-import.js",
"react": "https://ga.jspm.io/npm:react@17.0.2/dev.index.js"
},
"scopes": {
"https://ga.jspm.io/": {
"object-assign": "https://ga.jspm.io/npm:object-assign@4.1.1/index.js"
}
Expand Down