Unverified Commit aa78e963 authored by Benjamin Woodruff ‮'s avatar Benjamin Woodruff Committed by GitHub

Turbopack: Support import.meta.url in additional roots (#99511)

## Current State

- In the runtime, `import.meta.url` tries to give you a real on-disk
path if the file exists in the project filesystem and you're running in
node. If you're running in the browser you get a fake `file:///ROOT/...`
URL.
- `__dirname` and `__filename` always give fake `/ROOT/...` paths

This panics if `import.meta.url` exists in an additional root.

## Proposed Modification

If `import.meta.url` exists in an additional root, just give a fake
`file:///@rootName/...` URL.

Common cases where you're reading a file relative to `import.meta.url`
should still work, as those are handled by the analyzer. Externalized
node modules should be unaffected because they don't call the Turbopack
runtime for `import.meta.url`.

---------
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 3683479a
'use client'
import { useEffect, useState } from 'react'
import { moduleUrl } from '../../linked/root-info.mjs'
export default function Client() {
const [url, setUrl] = useState<string | null>(null)
useEffect(() => {
setUrl(moduleUrl)
}, [])
return <pre id="client-root-info">{url && JSON.stringify({ url })}</pre>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import { moduleUrl } from '../../linked/root-info.mjs'
import Client from './client'
// Rendered at request time, so the URL comes from the server running the page
// rather than from a prerender at build time.
async function ServerRootInfo() {
await connection()
return <pre id="server-root-info">{JSON.stringify({ url: moduleUrl })}</pre>
}
export default function Page() {
return (
<>
<Suspense>
<ServerRootInfo />
</Suspense>
<Client />
</>
)
}
...@@ -31,6 +31,9 @@ describe('turbopack additional roots', () => { ...@@ -31,6 +31,9 @@ describe('turbopack additional roots', () => {
}) })
let externalRoot: string | undefined let externalRoot: string | undefined
const rootInfoPath = 'packages/linked/root-info.mjs'
// The `@` in the filesystem name is percent-encoded.
const placeholderRootInfoUrl = `file:///%40linkedPackages/${rootInfoPath}`
beforeAll(async () => { beforeAll(async () => {
if (!isNextDeploy) { if (!isNextDeploy) {
...@@ -70,6 +73,20 @@ describe('turbopack additional roots', () => { ...@@ -70,6 +73,20 @@ describe('turbopack additional roots', () => {
expect(await browser.elementByCss('#loader-value').text()).toBe('processed') expect(await browser.elementByCss('#loader-value').text()).toBe('processed')
}) })
it('uses a placeholder for import.meta.url in an additional root', async () => {
const $ = await next.render$('/root-info')
expect(JSON.parse($('#server-root-info').text())).toEqual({
url: placeholderRootInfoUrl,
})
const browser = await next.browser('/root-info')
await retry(async () => {
expect(
JSON.parse(await browser.elementByCss('#client-root-info').text())
).toEqual({ url: placeholderRootInfoUrl })
})
})
it('reports initialization warnings when startup succeeds', () => { it('reports initialization warnings when startup succeeds', () => {
expect(next.cliOutput).toContain('Invalid Turbopack additional root') expect(next.cliOutput).toContain('Invalid Turbopack additional root')
expect(next.cliOutput).not.toContain('overlaps the project root') expect(next.cliOutput).not.toContain('overlaps the project root')
......
...@@ -451,18 +451,11 @@ function resolveAbsolutePath(modulePath?: string): string { ...@@ -451,18 +451,11 @@ function resolveAbsolutePath(modulePath?: string): string {
browserContextPrototype.P = resolveAbsolutePath browserContextPrototype.P = resolveAbsolutePath
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ */
function resolveFileUrl(modulePath?: string): string { browserContextPrototype.F = placeholderFileUrl
if (!modulePath) return 'file:///ROOT/'
return `file:///ROOT/${modulePath
.split('/')
.map(encodeURIComponent)
.join('/')}`
}
browserContextPrototype.F = resolveFileUrl
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
......
...@@ -33,13 +33,20 @@ function resolveAbsolutePath(modulePath?: string): string { ...@@ -33,13 +33,20 @@ function resolveAbsolutePath(modulePath?: string): string {
Context.prototype.P = resolveAbsolutePath Context.prototype.P = resolveAbsolutePath
/** /**
* Returns an absolute `file://` URL for the given module path. * Returns an absolute `file://` URL for the given module path, which is
* relative to the project root or the named `root`.
* *
* Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on * Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on
* all platforms (forward slashes on Windows, drive letters handled * all platforms (forward slashes on Windows, drive letters handled
* correctly, path segments URL-encoded). * correctly, path segments URL-encoded).
*
* The location of a named `root` isn't known at runtime (the output may have
* been moved away from the sources), so this returns a placeholder URL for it.
*/ */
function resolveFileUrl(modulePath?: string): string { function resolveFileUrl(modulePath?: string, root?: string): string {
if (root !== undefined) {
return placeholderFileUrl(modulePath, root)
}
return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href
} }
Context.prototype.F = resolveFileUrl Context.prototype.F = resolveFileUrl
...@@ -846,6 +846,20 @@ function factoryNotAvailableMessage( ...@@ -846,6 +846,20 @@ function factoryNotAvailableMessage(
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.` return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/
function placeholderFileUrl(modulePath?: string, root?: string): string {
if (modulePath === undefined) return 'file:///ROOT/'
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath
.split('/')
.map(encodeURIComponent)
.join('/')}`
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ */
......
...@@ -8,8 +8,8 @@ use swc_core::{ ...@@ -8,8 +8,8 @@ use swc_core::{
quote, quote,
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat}; use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::{DiskFileSystem, FileSystemPath};
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
...@@ -57,10 +57,16 @@ impl ImportMetaBinding { ...@@ -57,10 +57,16 @@ impl ImportMetaBinding {
_trie: &AstPathTrie, _trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let rel_path = chunking_context let root_path = chunking_context.root_path().await?;
.root_path() // A module from another disk filesystem (such as an additional root) isn't inside the root
.await? // path, so the runtime returns a placeholder URL named after that filesystem.
.get_relative_path_to(&self.path); let (root, rel_path) = if self.path.fs != root_path.fs
&& let Some(fs) = ResolvedVc::try_downcast_type::<DiskFileSystem>(self.path.fs)
{
(Some(fs.await?.name().clone()), Some(self.path.path.clone()))
} else {
(None, root_path.get_relative_path_to(&self.path))
};
let path = rel_path.map_or_else( let path = rel_path.map_or_else(
|| { || {
quote!( quote!(
...@@ -73,11 +79,20 @@ impl ImportMetaBinding { ...@@ -73,11 +79,20 @@ impl ImportMetaBinding {
// we embed `formatted` into. The runtime helper (`TURBOPACK_RESOLVE_FILE_URL`) // we embed `formatted` into. The runtime helper (`TURBOPACK_RESOLVE_FILE_URL`)
// is responsible for producing the final, properly URL-encoded `file://` URI. // is responsible for producing the final, properly URL-encoded `file://` URI.
let formatted = encode_path(path.trim_start_matches("./")).to_string(); let formatted = encode_path(path.trim_start_matches("./")).to_string();
quote!( if let Some(root) = &root {
"$turbopack_resolve_file_url($formatted)" as Expr, quote!(
turbopack_resolve_file_url: Expr = TURBOPACK_RESOLVE_FILE_URL.into(), "$turbopack_resolve_file_url($formatted, $root)" as Expr,
formatted: Expr = formatted.into() turbopack_resolve_file_url: Expr = TURBOPACK_RESOLVE_FILE_URL.into(),
) formatted: Expr = formatted.into(),
root: Expr = root.as_str().into()
)
} else {
quote!(
"$turbopack_resolve_file_url($formatted)" as Expr,
turbopack_resolve_file_url: Expr = TURBOPACK_RESOLVE_FILE_URL.into(),
formatted: Expr = formatted.into()
)
}
}, },
); );
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="30bdd4b9-98f8-d92c-1735-98906e239378")}catch(e){}}(); ;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="2022e681-3b00-13d9-2dc9-3315d13b4a9b")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js", "output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -650,6 +650,15 @@ contextPrototype.U = relativeURL; ...@@ -650,6 +650,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -1053,14 +1062,10 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1053,14 +1062,10 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ function resolveFileUrl(modulePath) { */ browserContextPrototype.F = placeholderFileUrl;
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
...@@ -2610,5 +2615,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2610,5 +2615,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=30bdd4b9-98f8-d92c-1735-98906e239378 //# debugId=2022e681-3b00-13d9-2dc9-3315d13b4a9b
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map //# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map
\ No newline at end of file
...@@ -627,6 +627,15 @@ contextPrototype.U = relativeURL; ...@@ -627,6 +627,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -704,12 +713,19 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot); ...@@ -704,12 +713,19 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot);
} }
Context.prototype.P = resolveAbsolutePath; Context.prototype.P = resolveAbsolutePath;
/** /**
* Returns an absolute `file://` URL for the given module path. * Returns an absolute `file://` URL for the given module path, which is
* relative to the project root or the named `root`.
* *
* Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on * Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on
* all platforms (forward slashes on Windows, drive letters handled * all platforms (forward slashes on Windows, drive letters handled
* correctly, path segments URL-encoded). * correctly, path segments URL-encoded).
*/ function resolveFileUrl(modulePath) { *
* The location of a named `root` isn't known at runtime (the output may have
* been moved away from the sources), so this returns a placeholder URL for it.
*/ function resolveFileUrl(modulePath, root) {
if (root !== undefined) {
return placeholderFileUrl(modulePath, root);
}
return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href; return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href;
} }
Context.prototype.F = resolveFileUrl; Context.prototype.F = resolveFileUrl;
......
...@@ -627,6 +627,15 @@ contextPrototype.U = relativeURL; ...@@ -627,6 +627,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -704,12 +713,19 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot); ...@@ -704,12 +713,19 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot);
} }
Context.prototype.P = resolveAbsolutePath; Context.prototype.P = resolveAbsolutePath;
/** /**
* Returns an absolute `file://` URL for the given module path. * Returns an absolute `file://` URL for the given module path, which is
* relative to the project root or the named `root`.
* *
* Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on * Uses `url.pathToFileURL` so that the resulting URL is a valid file URI on
* all platforms (forward slashes on Windows, drive letters handled * all platforms (forward slashes on Windows, drive letters handled
* correctly, path segments URL-encoded). * correctly, path segments URL-encoded).
*/ function resolveFileUrl(modulePath) { *
* The location of a named `root` isn't known at runtime (the output may have
* been moved away from the sources), so this returns a placeholder URL for it.
*/ function resolveFileUrl(modulePath, root) {
if (root !== undefined) {
return placeholderFileUrl(modulePath, root);
}
return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href; return require('url').pathToFileURL(resolveAbsolutePath(modulePath)).href;
} }
Context.prototype.F = resolveFileUrl; Context.prototype.F = resolveFileUrl;
......
...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL; ...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ function resolveFileUrl(modulePath) { */ browserContextPrototype.F = placeholderFileUrl;
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -877,6 +877,15 @@ contextPrototype.U = relativeURL; ...@@ -877,6 +877,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root !== null && root !== void 0 ? root : 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -1439,14 +1448,10 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1439,14 +1448,10 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ function resolveFileUrl(modulePath) { */ browserContextPrototype.F = placeholderFileUrl;
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL; ...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ function resolveFileUrl(modulePath) { */ browserContextPrototype.F = placeholderFileUrl;
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL; ...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ function resolveFileUrl(modulePath) { */ browserContextPrototype.F = placeholderFileUrl;
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL; ...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ function resolveFileUrl(modulePath) { */ browserContextPrototype.F = placeholderFileUrl;
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL; ...@@ -649,6 +649,15 @@ contextPrototype.U = relativeURL;
} }
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`; return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
} }
/**
* Returns a `file://` URL under a synthetic directory named after `root`
* (`ROOT` for the project root), for when the real filesystem path is unknown.
* Without a `modulePath`, this is `file:///ROOT/`. The root name and path
* segments are percent-encoded so the result is always a valid file URI.
*/ function placeholderFileUrl(modulePath, root) {
if (modulePath === undefined) return 'file:///ROOT/';
return `file:///${encodeURIComponent(root ?? 'ROOT')}/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
/** /**
* A stub function to make `require` available but non-functional in ESM. * A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) { */ function requireStub(_moduleId) {
...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1052,14 +1061,10 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a placeholder `file://` URL for the given module path. The browser * Returns a placeholder `file://` URL for the given module path, which is
* runtime intentionally does not expose the real filesystem path. Path * relative to the project root or the named `root`. The browser runtime
* segments are percent-encoded so the result is always a valid file URI. * intentionally does not expose the real filesystem path.
*/ function resolveFileUrl(modulePath) { */ browserContextPrototype.F = placeholderFileUrl;
if (!modulePath) return 'file:///ROOT/';
return `file:///ROOT/${modulePath.split('/').map(encodeURIComponent).join('/')}`;
}
browserContextPrototype.F = resolveFileUrl;
/** /**
* Exports a URL with the static suffix appended. * Exports a URL with the static suffix appended.
*/ function exportUrl(url, id) { */ function exportUrl(url, id) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment