Unverified Commit 2db21526 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Address new URL pattern-map review feedback

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent b3449ee2
......@@ -56,7 +56,10 @@ type GetChunkRelativeURL = (
type CommonJsRequire = (moduleId: ModuleId) => Exports
type RuntimeRequire = (request: string) => Exports
type ModuleContextFactory = (map: ModuleContextMap) => ModuleContext
type ModuleContextFactory = (
map: ModuleContextMap,
isUrl?: boolean
) => ModuleContext
type EsmImport = (
moduleId: ModuleId,
allowExportDefault: boolean
......
......@@ -83,7 +83,8 @@ contextPrototype.M = moduleFactories
type ModuleContextMap = Record<ModuleId, ModuleContextEntry>
interface ModuleContextEntry {
id: () => ModuleId
// Not present for `new URL()` contexts, which are never asked for module ids
id?: () => ModuleId
module: () => any
}
......@@ -671,11 +672,9 @@ function commonJsRequire(
contextPrototype.r = commonJsRequire
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/
function parseRequest(request: string): string {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
......@@ -692,14 +691,28 @@ function parseRequest(request: string): string {
return request
}
const URL_CONTEXT_FALLBACK: ModuleContextEntry = {
module: () => 'about:blank',
}
/**
* `require.context` and require/import expression runtime.
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/
function moduleContext(map: ModuleContextMap): ModuleContext {
function moduleContext(id: string): Exports {
id = parseRequest(id)
function moduleContext(map: ModuleContextMap, isUrl?: boolean): ModuleContext {
function lookup(id: string): ModuleContextEntry {
if (hasOwnProperty.call(map, id)) {
return map[id].module()
return map[id]
}
if (isUrl) {
const parsedId = parseRequest(id)
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId]
}
return URL_CONTEXT_FALLBACK
}
const e = new Error(`Cannot find module '${id}'`)
......@@ -707,19 +720,16 @@ function moduleContext(map: ModuleContextMap): ModuleContext {
throw e
}
function moduleContext(id: string): Exports {
return lookup(id).module()
}
moduleContext.keys = (): string[] => {
return Object.keys(map)
}
moduleContext.resolve = (id: string): ModuleId => {
id = parseRequest(id)
if (hasOwnProperty.call(map, id)) {
return map[id].id()
}
const e = new Error(`Cannot find module '${id}'`)
;(e as any).code = 'MODULE_NOT_FOUND'
throw e
return lookup(id).id!()
}
moduleContext.import = async (id: string) => {
......
......@@ -381,8 +381,8 @@ impl ReferencedAsset {
impl ReferencedAsset {
pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Self> {
// Only the first matching result is used. Callers whose request can match multiple keyed
// results (e.g. a dynamic `new URL()`, see `UrlAssetReferenceCodeGen`) have to map them
// with `PatternMapping` instead.
// results (e.g. `new URL()`, see `UrlAssetReferenceCodeGen`) have to map them with
// `PatternMapping` instead.
let result = resolve_result.await?;
if result.is_unresolvable() {
return Ok(ReferencedAsset::Unresolvable);
......
......@@ -149,8 +149,8 @@ use crate::{
},
},
runtime_functions::{
TURBOPACK_EXPORTS, TURBOPACK_GLOBAL, TURBOPACK_REQUIRE_REAL, TURBOPACK_REQUIRE_STUB,
TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS,
TURBOPACK_EXPORTS, TURBOPACK_GLOBAL, TURBOPACK_REQUIRE, TURBOPACK_REQUIRE_REAL,
TURBOPACK_REQUIRE_STUB, TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS,
},
source_map::parse_source_map_comment,
utils::{AstPathRange, js_value_to_pattern, module_value_to_well_known_object},
......@@ -2297,6 +2297,25 @@ where
}
match func {
WellKnownFunctionKind::CreateRequire => {
let args = linked_args().await?;
// `createRequire(import.meta.url)` and `createRequire(new URL("<rel>",
// import.meta.url))` are statically analyzed (as `Require` and `RequireFrom`), so the
// calls on the returned require are rewritten to `__turbopack_require__`. Replace the
// `createRequire()` call with it as well, so its argument isn't evaluated at runtime.
if let [arg] = &args[..]
&& (matches!(arg, JsValue::Url(_, JsValueUrlKind::Relative))
|| matches!(arg, JsValue::Member(_, obj, prop)
if matches!(&**obj, JsValue::WellKnownObject(WellKnownObjectKind::ImportMeta))
&& matches!(&**prop, JsValue::Constant(JsConstantValue::Str(prop)) if prop.as_str() == "url")))
{
analysis.add_code_gen(MemberReplacement::new(
rcstr!("__turbopack_context__"),
TURBOPACK_REQUIRE.shortcut.into(),
analysis.intern_path(ast_path),
));
}
}
WellKnownFunctionKind::Import => {
let args = linked_args().await?;
let export_usage = match &attributes.export_names {
......
......@@ -271,14 +271,11 @@ pub(crate) enum UrlModuleMode {
impl SinglePatternMapping {
/// Creates an expression evaluating to the URL (the first `new URL()` argument) this mapping
/// points to. URL externals evaluate to their request, as with a single `new URL()` match.
fn create_url(&self, module_mode: UrlModuleMode) -> Expr {
/// points to. URL externals evaluate to their request, and anything that can't be resolved
/// to a URL evaluates to `about:blank`.
pub fn create_url(&self, module_mode: UrlModuleMode) -> Expr {
match self {
Self::Invalid => quote!(
"(() => {throw new Error('could not resolve the new URL() request into an \
asset');})()" as Expr
),
Self::Unresolvable(request) => throw_module_not_found_expr(request),
Self::Invalid | Self::Unresolvable(_) => quote!("'about:blank'" as Expr),
Self::Ignored => quote!("{}" as Expr),
Self::Dropped => quote!("0" as Expr),
Self::Module(module_id) | Self::ModuleLoader(module_id) => match module_mode {
......@@ -294,10 +291,7 @@ impl SinglePatternMapping {
),
},
Self::External(request, ExternalType::Url) => request.as_str().into(),
Self::External(request, ty) => throw_module_not_found_error_expr(
request,
&format!("Unsupported external type {ty:?} for URL reference"),
),
Self::External(_, _) => quote!("'about:blank'" as Expr),
}
}
}
......@@ -305,7 +299,6 @@ impl SinglePatternMapping {
enum ImportMode {
Require,
Import { import_externals: bool },
Url(UrlModuleMode),
}
fn create_context_map(
......@@ -320,8 +313,7 @@ fn create_context_map(
"{id: () => $id, module: () => $module}",
id: Expr = v.create_id(Cow::Borrowed(key_expr)),
module: Expr = match import_mode {ImportMode::Require => v.create_require(Cow::Borrowed(key_expr)),
ImportMode::Import {import_externals} => v.create_import(Cow::Borrowed(key_expr), import_externals),
ImportMode::Url(module_mode) => v.create_url(module_mode),},
ImportMode::Import {import_externals} => v.create_import(Cow::Borrowed(key_expr), import_externals),},
),})))})
.collect();
......@@ -331,6 +323,46 @@ fn create_context_map(
})
}
/// Like [`create_context_map`], but for `new URL()`: entries only have a `module` (the URL), as
/// a URL context is never asked for module ids.
///
/// A request without a leading `./` (e.g. `new URL(`assets/${name}`, import.meta.url)`) is
/// resolved relatively, so its keys have a leading `./` that the runtime request doesn't have.
/// With `bare_aliases`, each `./x` key therefore also gets an `x` alias, unless `x` is a key
/// itself.
fn create_url_context_map(
map: &FxIndexMap<RcStr, SinglePatternMapping>,
module_mode: UrlModuleMode,
bare_aliases: bool,
) -> Expr {
let aliases = map.iter().filter_map(|(k, v)| {
if !bare_aliases {
return None;
}
let alias = k.strip_prefix("./")?;
(!map.contains_key(alias)).then_some((alias, v))
});
let props = map
.iter()
.map(|(k, v)| (k.as_str(), v))
.chain(aliases)
.map(|(k, v)| {
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Str(k.into()),
value: quote_expr!(
"{module: () => $module}",
module: Expr = v.create_url(module_mode),
),
})))
})
.collect();
Expr::Object(ObjectLit {
span: DUMMY_SP,
props,
})
}
impl PatternMapping {
pub fn create_id(&self, key_expr: Expr) -> Expr {
match self {
......@@ -362,24 +394,29 @@ impl PatternMapping {
}
}
/// Creates an expression that looks up, at runtime, the URL (the first `new URL()` argument)
/// of the asset matching `key_expr`. It throws `MODULE_NOT_FOUND` when nothing matches, and
/// `key_expr` is evaluated exactly once.
///
/// Only used for dynamic or multi-result requests, so a [`PatternMapping::Single`] here means
/// that the request matched nothing and is mapped to an empty context.
pub fn create_url_lookup(&self, key_expr: Expr, module_mode: UrlModuleMode) -> Expr {
let empty = FxIndexMap::default();
let map = match self {
PatternMapping::Single(_) => &empty,
PatternMapping::Map(map) => map,
};
quote!(
"$turbopack_module_context($map)($key)" as Expr,
turbopack_module_context: Expr = TURBOPACK_MODULE_CONTEXT.into(),
map: Expr = create_context_map(map, &key_expr, ImportMode::Url(module_mode)),
key: Expr = key_expr
)
/// Creates an expression evaluating to the URL (the first `new URL()` argument) of the asset
/// matching `key_expr`. With multiple possible assets, it's looked up at runtime (with the
/// request's query and fragment ignored when there's no exact match), evaluating to
/// `about:blank` when nothing matches. `bare_aliases` must be set when the request can be
/// without a leading `./` at runtime (i.e. it isn't a relative request).
pub fn create_url(
&self,
key_expr: Expr,
module_mode: UrlModuleMode,
bare_aliases: bool,
) -> Expr {
match self {
PatternMapping::Single(pm) => pm.create_url(module_mode),
PatternMapping::Map(map) => {
let map = create_url_context_map(map, module_mode, bare_aliases);
quote!("$turbopack_module_context($map, true)($key)" as Expr,
turbopack_module_context: Expr = TURBOPACK_MODULE_CONTEXT.into(),
map: Expr = map,
key: Expr = key_expr
)
}
}
}
pub fn create_import(&self, key_expr: Expr, import_externals: bool) -> Expr {
......@@ -551,12 +588,40 @@ impl PatternMapping {
}
_ => {
let primary = &result.primary;
// The query and fragment of the request (e.g. the `#frag` of
// `import('./' + name + '#frag')`) are split off when parsing and aren't part of
// the resolved request keys, but they are part of the request at runtime.
let key_suffix = match &*request.await? {
Request::Raw {
query, fragment, ..
}
| Request::Relative {
query, fragment, ..
}
| Request::Module {
query, fragment, ..
}
| Request::ServerRelative {
query, fragment, ..
}
| Request::Windows {
query, fragment, ..
} => format!("{query}{fragment}"),
_ => String::new(),
};
let mut set = HashSet::new();
let items: Vec<(RcStr, &ModuleResolveResultItem)> = primary
.iter()
.filter_map(|(k, v)| {
let request = k.request.as_ref()?;
set.insert(request).then(|| (request.clone(), v))
set.insert(request).then(|| {
let key = if key_suffix.is_empty() {
request.clone()
} else {
format!("{request}{key_suffix}").into()
};
(key, v)
})
})
.collect();
let map = items
......
......@@ -8,24 +8,24 @@ const assetUrl = (name) =>
new URL(`./assets/${track(name)}`, import.meta.url).toString()
const singleUrl = (name) =>
new URL(`./single/${track(name)}`, import.meta.url).toString()
const noMatchUrl = (name) => {
try {
return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
} catch (e) {
return e
}
}
const bareUrl = (name) => new URL(`assets/${name}`, import.meta.url).toString()
const suffixedUrl = (name, suffix) =>
new URL(`./assets/${name}${suffix}`, import.meta.url).toString()
const constantSuffixUrl = (name) =>
new URL(`./assets/${name}?v=1`, import.meta.url).toString()
let externalRequest = 'https://example.invalid/asset?v=1'
const externalUrl = () => new URL(externalRequest, import.meta.url).toString()
const fullyDynamicUrl = (request) =>
new URL(request, import.meta.url).toString()
const noMatchUrl = (name) =>
new URL(`./no-match/${track(name)}`, import.meta.url).toString()
const expectModuleNotFound = (fn) => {
const expectAboutBlank = (fn) => {
const before = evaluations
let error
try {
fn()
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(fn()).toBe('about:blank')
expect(evaluations - before).toBe(1)
}
......@@ -44,17 +44,36 @@ it('should resolve a dynamic new URL that matches a single file', () => {
expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/)
})
it('should throw MODULE_NOT_FOUND for a request that matched no file', () => {
expectModuleNotFound(() => assetUrl('missing.txt'))
expectModuleNotFound(() => singleUrl('missing.txt'))
it('should resolve a request that matched no file to about:blank', () => {
expectAboutBlank(() => assetUrl('missing.txt'))
expectAboutBlank(() => singleUrl('missing.txt'))
})
it('should throw MODULE_NOT_FOUND for a pattern that matched nothing', () => {
const before = evaluations
const error = noMatchUrl('anything.txt')
expect(error).toBeInstanceOf(Error)
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1)
it('should resolve a pattern that matched nothing to about:blank', () => {
expect(noMatchUrl('anything.txt')).toBe('about:blank')
})
it('should resolve a dynamic new URL without a leading ./', () => {
expect(bareUrl('alpha.txt')).toMatch(/alpha\.[^/]*txt$/)
expect(bareUrl('beta.txt')).toMatch(/beta\.[^/]*txt$/)
})
it('should resolve a dynamic new URL with a query or fragment', () => {
expect(suffixedUrl('alpha.txt', '?v=1')).toMatch(/alpha\.[^/]*txt$/)
expect(suffixedUrl('beta.txt', '#fragment')).toMatch(/beta\.[^/]*txt$/)
expect(constantSuffixUrl('gamma.txt')).toMatch(/gamma\.[^/]*txt$/)
})
it('should keep external URL alternatives that differ only by query distinct', () => {
expect(externalUrl()).toBe('https://example.invalid/asset?v=1')
externalRequest = 'https://example.invalid/asset?v=2'
expect(externalUrl()).toBe('https://example.invalid/asset?v=2')
})
it('should leave a fully dynamic new URL untouched', () => {
expect(fullyDynamicUrl('https://example.invalid/native.txt')).toBe(
'https://example.invalid/native.txt'
)
})
it('should evaluate the request expression exactly once', () => {
......
warning - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic-full/input/index.js:13:11 Module not found: Can't resolve './no-match/' <dynamic>
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic-full/input/index.js:24:2 Module not found: Can't resolve './no-match/' <dynamic>
9 | const singleUrl = (name) =>
10 | new URL(`./single/${track(name)}`, import.meta.url).toString()
11 | const noMatchUrl = (name) => {
12 | try {
+ v---------------------------------------------------v
13 + return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^
14 | } catch (e) {
15 | return e
16 | }
17 | }
20 | const fullyDynamicUrl = (request) =>
21 | new URL(request, import.meta.url).toString()
22 |
23 | const noMatchUrl = (name) =>
+ v---------------------------------------------------v
24 + new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^
25 |
26 | const expectAboutBlank = (fn) => {
27 | const before = evaluations
28 | expect(fn()).toBe('about:blank')
......
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic-full/input/index.js:21:2 Module not found: Can't resolve <dynamic>
17 | let externalRequest = 'https://example.invalid/asset?v=1'
18 | const externalUrl = () => new URL(externalRequest, import.meta.url).toString()
19 |
20 | const fullyDynamicUrl = (request) =>
+ v-------------------------------v
21 + new URL(request, import.meta.url).toString()
+ ^-------------------------------^
22 |
23 | const noMatchUrl = (name) =>
24 | new URL(`./no-match/${track(name)}`, import.meta.url).toString()
25 |
| It was not possible to find the requested file.
| Parsed request as written in source code: dynamic
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic-full/input/index.js
| Type of request: url request
|
\ No newline at end of file
suggestion - [analysis] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic-full/input/index.js:21:2 lint TP1201 new URL(???*0*, import.meta*1*["url"]) is very dynamic
17 | let externalRequest = 'https://example.invalid/asset?v=1'
18 | const externalUrl = () => new URL(externalRequest, import.meta.url).toString()
19 |
20 | const fullyDynamicUrl = (request) =>
+ v-------------------------------v
21 + new URL(request, import.meta.url).toString()
+ ^-------------------------------^
22 |
23 | const noMatchUrl = (name) =>
24 | new URL(`./no-match/${track(name)}`, import.meta.url).toString()
25 |
- *0* arguments[0]
⚠️ function calls are not analyzed yet
- *1* import.meta: The import.meta object
\ No newline at end of file
......@@ -8,24 +8,24 @@ const assetUrl = (name) =>
new URL(`./assets/${track(name)}`, import.meta.url).toString()
const singleUrl = (name) =>
new URL(`./single/${track(name)}`, import.meta.url).toString()
const noMatchUrl = (name) => {
try {
return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
} catch (e) {
return e
}
}
const bareUrl = (name) => new URL(`assets/${name}`, import.meta.url).toString()
const suffixedUrl = (name, suffix) =>
new URL(`./assets/${name}${suffix}`, import.meta.url).toString()
const constantSuffixUrl = (name) =>
new URL(`./assets/${name}?v=1`, import.meta.url).toString()
let externalRequest = 'https://example.invalid/asset?v=1'
const externalUrl = () => new URL(externalRequest, import.meta.url).toString()
const fullyDynamicUrl = (request) =>
new URL(request, import.meta.url).toString()
const noMatchUrl = (name) =>
new URL(`./no-match/${track(name)}`, import.meta.url).toString()
const expectModuleNotFound = (fn) => {
const expectAboutBlank = (fn) => {
const before = evaluations
let error
try {
fn()
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(fn()).toBe('about:blank')
expect(evaluations - before).toBe(1)
}
......@@ -44,17 +44,36 @@ it('should resolve a dynamic new URL that matches a single file', () => {
expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/)
})
it('should throw MODULE_NOT_FOUND for a request that matched no file', () => {
expectModuleNotFound(() => assetUrl('missing.txt'))
expectModuleNotFound(() => singleUrl('missing.txt'))
it('should resolve a request that matched no file to about:blank', () => {
expectAboutBlank(() => assetUrl('missing.txt'))
expectAboutBlank(() => singleUrl('missing.txt'))
})
it('should throw MODULE_NOT_FOUND for a pattern that matched nothing', () => {
const before = evaluations
const error = noMatchUrl('anything.txt')
expect(error).toBeInstanceOf(Error)
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1)
it('should resolve a pattern that matched nothing to about:blank', () => {
expect(noMatchUrl('anything.txt')).toBe('about:blank')
})
it('should resolve a dynamic new URL without a leading ./', () => {
expect(bareUrl('alpha.txt')).toMatch(/alpha\.[^/]*txt$/)
expect(bareUrl('beta.txt')).toMatch(/beta\.[^/]*txt$/)
})
it('should resolve a dynamic new URL with a query or fragment', () => {
expect(suffixedUrl('alpha.txt', '?v=1')).toMatch(/alpha\.[^/]*txt$/)
expect(suffixedUrl('beta.txt', '#fragment')).toMatch(/beta\.[^/]*txt$/)
expect(constantSuffixUrl('gamma.txt')).toMatch(/gamma\.[^/]*txt$/)
})
it('should keep external URL alternatives that differ only by query distinct', () => {
expect(externalUrl()).toBe('https://example.invalid/asset?v=1')
externalRequest = 'https://example.invalid/asset?v=2'
expect(externalUrl()).toBe('https://example.invalid/asset?v=2')
})
it('should leave a fully dynamic new URL untouched', () => {
expect(fullyDynamicUrl('https://example.invalid/native.txt')).toBe(
'https://example.invalid/native.txt'
)
})
it('should evaluate the request expression exactly once', () => {
......
warning - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic/input/index.js:13:11 Module not found: Can't resolve './no-match/' <dynamic>
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic/input/index.js:24:2 Module not found: Can't resolve './no-match/' <dynamic>
9 | const singleUrl = (name) =>
10 | new URL(`./single/${track(name)}`, import.meta.url).toString()
11 | const noMatchUrl = (name) => {
12 | try {
+ v---------------------------------------------------v
13 + return new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^
14 | } catch (e) {
15 | return e
16 | }
17 | }
20 | const fullyDynamicUrl = (request) =>
21 | new URL(request, import.meta.url).toString()
22 |
23 | const noMatchUrl = (name) =>
+ v---------------------------------------------------v
24 + new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^
25 |
26 | const expectAboutBlank = (fn) => {
27 | const before = evaluations
28 | expect(fn()).toBe('about:blank')
......
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic/input/index.js:21:2 Module not found: Can't resolve <dynamic>
17 | let externalRequest = 'https://example.invalid/asset?v=1'
18 | const externalUrl = () => new URL(externalRequest, import.meta.url).toString()
19 |
20 | const fullyDynamicUrl = (request) =>
+ v-------------------------------v
21 + new URL(request, import.meta.url).toString()
+ ^-------------------------------^
22 |
23 | const noMatchUrl = (name) =>
24 | new URL(`./no-match/${track(name)}`, import.meta.url).toString()
25 |
| It was not possible to find the requested file.
| Parsed request as written in source code: dynamic
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic/input/index.js
| Type of request: url request
|
\ No newline at end of file
suggestion - [analysis] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/new-url-dynamic/input/index.js:21:2 lint TP1201 new URL(???*0*, import.meta*1*["url"]) is very dynamic
17 | let externalRequest = 'https://example.invalid/asset?v=1'
18 | const externalUrl = () => new URL(externalRequest, import.meta.url).toString()
19 |
20 | const fullyDynamicUrl = (request) =>
+ v-------------------------------v
21 + new URL(request, import.meta.url).toString()
+ ^-------------------------------^
22 |
23 | const noMatchUrl = (name) =>
24 | new URL(`./no-match/${track(name)}`, import.meta.url).toString()
25 |
- *0* arguments[0]
⚠️ function calls are not analyzed yet
- *1* import.meta: The import.meta object
\ No newline at end of file
;!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]="bdf2a5bb-33ac-1b9f-2ecf-28033b73cc7f")}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]="2bb6848a-179e-056d-37a2-e994a18f4ae6")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"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)"]}
......@@ -511,11 +511,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -529,29 +527,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
......@@ -2659,5 +2667,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=bdf2a5bb-33ac-1b9f-2ecf-28033b73cc7f
//# debugId=2bb6848a-179e-056d-37a2-e994a18f4ae6
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map
\ No newline at end of file
......@@ -488,11 +488,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -506,29 +504,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
......
......@@ -22,14 +22,12 @@ var __TURBOPACK__import$2e$meta__ = {
const name = globalThis.assetName;
const assetUrl = new URL(__turbopack_context__.f({
"./assets/a.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/a.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/a.txt (static in ecmascript)")
},
"./assets/b.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/b.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/b.txt (static in ecmascript)")
}
})(`./assets/${name}`), location.origin);
}, true)(`./assets/${name}`), location.origin);
const staticUrl = new URL(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/assets/a.txt (static in ecmascript)"), location.origin);
console.log(assetUrl, staticUrl);
}),
......
......@@ -2,5 +2,5 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 9, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/index.js"],"sourcesContent":["const name = globalThis.assetName\nconst assetUrl = new URL(`./assets/${name}`, import.meta.url)\nconst staticUrl = new URL('./assets/a.txt', import.meta.url)\n\nconsole.log(assetUrl, staticUrl)\n"],"names":["name","globalThis","assetName","assetUrl","URL","staticUrl","console","log"],"mappings":";;;;;;;;;;;;AAAA,MAAMA,OAAOC,WAAWC,SAAS;AACjC,MAAMC,WAAW,IAAIC;;;;;;;;;GAAI,CAAC,SAAS,EAAEJ,MAAM;AAC3C,MAAMK,YAAY,IAAID;AAEtBE,QAAQC,GAAG,CAACJ,UAAUE"}}]
{"offset": {"line": 9, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic-full/input/index.js"],"sourcesContent":["const name = globalThis.assetName\nconst assetUrl = new URL(`./assets/${name}`, import.meta.url)\nconst staticUrl = new URL('./assets/a.txt', import.meta.url)\n\nconsole.log(assetUrl, staticUrl)\n"],"names":["name","globalThis","assetName","assetUrl","URL","staticUrl","console","log"],"mappings":";;;;;;;;;;;;AAAA,MAAMA,OAAOC,WAAWC,SAAS;AACjC,MAAMC,WAAW,IAAIC;;;;;;;SAAI,CAAC,SAAS,EAAEJ,MAAM;AAC3C,MAAMK,YAAY,IAAID;AAEtBE,QAAQC,GAAG,CAACJ,UAAUE"}}]
}
\ No newline at end of file
......@@ -22,14 +22,12 @@ var __TURBOPACK__import$2e$meta__ = {
const name = globalThis.assetName;
const assetUrl = new __turbopack_context__.U(__turbopack_context__.f({
"./assets/a.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/a.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/a.txt (static in ecmascript)")
},
"./assets/b.txt": {
id: ()=>"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/b.txt (static in ecmascript)",
module: ()=>__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/b.txt (static in ecmascript)")
}
})(`./assets/${name}`));
}, true)(`./assets/${name}`));
const staticUrl = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/assets/a.txt (static in ecmascript)"));
console.log(assetUrl, staticUrl);
}),
......
......@@ -2,5 +2,5 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 9, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/index.js"],"sourcesContent":["const name = globalThis.assetName\nconst assetUrl = new URL(`./assets/${name}`, import.meta.url)\nconst staticUrl = new URL('./assets/a.txt', import.meta.url)\n\nconsole.log(assetUrl, staticUrl)\n"],"names":["name","globalThis","assetName","assetUrl","staticUrl","console","log"],"mappings":";;;;;;;;;;;;AAAA,MAAMA,OAAOC,WAAWC,SAAS;AACjC,MAAMC;;;;;;;;;GAAmB,CAAC,SAAS,EAAEH,MAAM;AAC3C,MAAMI;AAENC,QAAQC,GAAG,CAACH,UAAUC"}}]
{"offset": {"line": 9, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url-dynamic/input/index.js"],"sourcesContent":["const name = globalThis.assetName\nconst assetUrl = new URL(`./assets/${name}`, import.meta.url)\nconst staticUrl = new URL('./assets/a.txt', import.meta.url)\n\nconsole.log(assetUrl, staticUrl)\n"],"names":["name","globalThis","assetName","assetUrl","staticUrl","console","log"],"mappings":";;;;;;;;;;;;AAAA,MAAMA,OAAOC,WAAWC,SAAS;AACjC,MAAMC;;;;;;;SAAmB,CAAC,SAAS,EAAEH,MAAM;AAC3C,MAAMI;AAENC,QAAQC,GAAG,CAACH,UAAUC"}}]
}
\ No newline at end of file
......@@ -488,11 +488,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -506,29 +504,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
......
......@@ -510,11 +510,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
......
......@@ -716,11 +716,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -734,29 +732,41 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
var URL_CONTEXT_FALLBACK = {
module: function module() {
return 'about:blank';
}
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
var parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
var e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = function() {
return Object.keys(map);
};
moduleContext.resolve = function(id) {
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
var e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = function(id) {
return _async_to_generator(function() {
......
......@@ -510,11 +510,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
......
......@@ -510,11 +510,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
......
......@@ -510,11 +510,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
......
......@@ -510,11 +510,9 @@ function commonJsRequire(id) {
}
contextPrototype.r = commonJsRequire;
/**
* Remove fragments and query parameters since they are never part of the context map keys
* Remove fragments and query parameters.
*
* This matches how we parse patterns at resolving time. Arguably we should only do this for
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
* This matches how we parse patterns at resolving time.
*/ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first
// https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
......@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
}
return request;
}
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/**
* `require.context` and require/import expression runtime.
*/ function moduleContext(map) {
function moduleContext(id) {
id = parseRequest(id);
* `require.context`, require/import expression and `new URL()` runtime.
*
* A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
* without its query and fragment (e.g. a dynamic query that isn't part of a module key), and
* evaluates to `about:blank` when nothing matches.
*/ function moduleContext(map, isUrl) {
function lookup(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
return map[id];
}
if (isUrl) {
const parsedId = parseRequest(id);
if (hasOwnProperty.call(map, parsedId)) {
return map[parsedId];
}
return URL_CONTEXT_FALLBACK;
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
id = parseRequest(id);
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
return lookup(id).id();
};
moduleContext.import = async (id)=>{
return await moduleContext(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