From 2c511a400eb4239c220cfe13a3e66fd232584efa Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Sat, 21 Oct 2023 18:11:39 +0200 Subject: [PATCH] Add support for `baseUrl` as a `URL` --- packages/mdx/lib/core.js | 2 +- packages/mdx/lib/plugin/recma-document.js | 3 ++- packages/mdx/readme.md | 2 +- packages/mdx/test/evaluate.js | 12 ++++++++++++ 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/mdx/lib/core.js b/packages/mdx/lib/core.js index ca888ae35..6b231feac 100644 --- a/packages/mdx/lib/core.js +++ b/packages/mdx/lib/core.js @@ -15,7 +15,7 @@ * @property {SourceMapGenerator | null | undefined} [SourceMapGenerator] * Add a source map (object form) as the `map` field on the resulting file * (optional). - * @property {string | null | undefined} [baseUrl] + * @property {URL | string | null | undefined} [baseUrl] * Resolve `import`s (and `export … from`, and `import.meta.url`) from this * URL (optional, example: `import.meta.url`); * this option is useful when code will run in a different place, such as diff --git a/packages/mdx/lib/plugin/recma-document.js b/packages/mdx/lib/plugin/recma-document.js index c3dd96ccd..53ed68ed5 100644 --- a/packages/mdx/lib/plugin/recma-document.js +++ b/packages/mdx/lib/plugin/recma-document.js @@ -46,7 +46,8 @@ import {specifiersToDeclarations} from '../util/estree-util-specifiers-to-declar * Transform. */ export function recmaDocument(options) { - const baseUrl = options.baseUrl || undefined + const baseUrl_ = options.baseUrl || undefined + const baseUrl = typeof baseUrl_ === 'object' ? baseUrl_.href : baseUrl_ const useDynamicImport = options.useDynamicImport || undefined const outputFormat = options.outputFormat || 'program' const pragma = diff --git a/packages/mdx/readme.md b/packages/mdx/readme.md index eb9bf5152..503a9fc40 100644 --- a/packages/mdx/readme.md +++ b/packages/mdx/readme.md @@ -493,7 +493,7 @@ Configuration for `createProcessor` (TypeScript type). ``` -* `baseUrl` (`string`, optional, example: `import.meta.url`) +* `baseUrl` (`URL` or `string`, optional, example: `import.meta.url`) — resolve `import`s (and `export … from`, and `import.meta.url`) from this URL; this option is useful when code will run in a different place, such as when diff --git a/packages/mdx/test/evaluate.js b/packages/mdx/test/evaluate.js index 38551857c..a3e2c7e16 100644 --- a/packages/mdx/test/evaluate.js +++ b/packages/mdx/test/evaluate.js @@ -360,6 +360,18 @@ test('@mdx-js/mdx: evaluate', async function (t) { } ) + await t.test( + 'should support rewriting `import.meta.url` w/ `baseUrl` as an URL', + async function () { + const mod = await evaluate( + 'export const x = new URL("example.png", import.meta.url).href', + {baseUrl: new URL('https://example.com'), ...runtime} + ) + + assert.equal(mod.x, 'https://example.com/example.png') + } + ) + await t.test('should throw on an export all from', async function () { try { await evaluate('export * from "a"', runtime)