diff --git a/src/index.js b/src/index.js index 114bd99..d010c66 100644 --- a/src/index.js +++ b/src/index.js @@ -1,3 +1,4 @@ +/* eslint-disable no-restricted-syntax */ import { request } from 'undici'; import { join } from 'path'; import loader from '@eik/common-config-loader'; @@ -6,16 +7,15 @@ import Asset from './asset.js'; const trimSlash = (value = '') => { if (value.endsWith('/')) return value.substring(0, value.length - 1); return value; -} +}; const fetchImportMaps = async (urls = []) => { - try{ + try { const maps = urls.map(async (map) => { - const { - statusCode, - body - } = await request(map, { maxRedirections: 2 }); - + const { statusCode, body } = await request(map, { + maxRedirections: 2, + }); + if (statusCode === 404) { throw new Error('Import map could not be found on server'); } else if (statusCode >= 400 && statusCode < 500) { @@ -31,7 +31,7 @@ const fetchImportMaps = async (urls = []) => { `Unable to load import map file from server: ${err.message}`, ); } -} +}; export default class NodeClient { #development; @@ -83,7 +83,8 @@ export default class NodeClient { } get pathname() { - if (this.#config.type && this.#config.name && this.#config.version) return join('/', this.type, this.name, this.version); + if (this.#config.type && this.#config.name && this.#config.version) + return join('/', this.type, this.name, this.version); throw new Error('Eik config was not loaded before calling .pathname'); } @@ -101,6 +102,16 @@ export default class NodeClient { maps() { if (this.#config.version && this.#loadMaps) return this.#maps; - throw new Error('Eik config was not loaded or "loadMaps" is "false" when calling .maps()'); + throw new Error( + 'Eik config was not loaded or "loadMaps" is "false" when calling .maps()', + ); + } + + mapping(dependency) { + let mapping = null; + for (const map of this.maps()) { + if (map?.imports[dependency]) mapping = map.imports[dependency]; + } + return mapping; } } diff --git a/test/index.js b/test/index.js index 5c2d3bb..f91e0b7 100644 --- a/test/index.js +++ b/test/index.js @@ -255,3 +255,16 @@ tap.test('Client - Retrieve a base - Development mode is set to "false"', async t.equal(resolved, `${t.context.address}/pkg/eik-fixture/1.0.2`); t.end(); }); + +tap.test('Client - Resolve a mapping', async (t) => { + const client = new NodeClient({ + path: t.context.fixture, + loadMaps: true, + }); + await client.load(); + + const mapping = client.mapping('eik'); + + t.equal(mapping, '/src/eik.js'); + t.end(); +});