Skip to content

Commit

Permalink
Support JavaScript URL imports
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkTiedemann committed Jul 31, 2019
1 parent dd65943 commit 5130b09
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
Expand Up @@ -10,6 +10,16 @@ Array [
]
`;

exports[`normaliseResolverResults converts { registry: 'npm', target: 'foo' } 1`] = `
Array [
Object {
"registry": "npm",
"target": "foo",
"type": "registry",
},
]
`;

exports[`normaliseResolverResults converts {BASE_URL}/file.js 1`] = `
Array [
Object {
Expand Down
23 changes: 23 additions & 0 deletions packages/plugin-javascript/__tests__/index.js
Expand Up @@ -25,6 +25,29 @@ describe('javascript-universal', () => {
});
});

it("resolves 'https://example.org/foo.ts' to 'https://example.org/foo.ts'", () => {
expect(plugin.resolve(path, ['https://example.org/foo.ts'])).toEqual({
target: 'https://example.org/foo.ts',
type: 'trusted-url',
});
});

it("does not resolve 'https://example.org/'", () => {
// TODO: Currently resolves incorrectly as 'https' module,
// but should not resolve.
expect(plugin.resolve(path, ['https://example.org'])).toEqual({
registry: 'npm',
target: 'https',
});
});

it("resolves 'https://example.org/foo.js' to 'https://example.org/foo.js'", () => {
expect(plugin.resolve(path, ['https://example.org/foo.js'])).toEqual({
target: 'https://example.org/foo.js',
type: 'trusted-url',
});
});

it("resolves './modules/es6.symbol' without stripping .symbol suffix", () => {
expect(plugin.resolve('', ['./modules/es6.symbol'])).toMatchSnapshot();
});
Expand Down
21 changes: 18 additions & 3 deletions packages/plugin-javascript/index.js
Expand Up @@ -59,17 +59,32 @@ export function javascriptFile({ path, target }) {
});
}

function isURLImport(target) {
try {
const { protocol, pathname } = new URL(target);
if (protocol !== 'https:' && protocol !== 'http:') return false;
const ext = extname(pathname);
if (ext !== '.js' && ext !== '.ts') return false;
return true;
} catch (err) {
return false;
}
}

export default {
name: 'JavaScript',

resolve(path, [target]) {
const isPath = !!target.match(/^\.\.?[\\|\/]?/);
const isBuildIn = target in builtinsDocs;
if (isURLImport(target)) {
return resolverTrustedUrl({ target });
}

if (isBuildIn) {
const isBuiltIn = target in builtinsDocs;
if (isBuiltIn) {
return resolverTrustedUrl({ target: builtinsDocs[target] });
}

const isPath = !!target.match(/^\.\.?[\\|\/]?/);
if (isPath) {
return javascriptFile({ target, path });
}
Expand Down

0 comments on commit 5130b09

Please sign in to comment.