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 = ( ...@@ -56,7 +56,10 @@ type GetChunkRelativeURL = (
type CommonJsRequire = (moduleId: ModuleId) => Exports type CommonJsRequire = (moduleId: ModuleId) => Exports
type RuntimeRequire = (request: string) => Exports type RuntimeRequire = (request: string) => Exports
type ModuleContextFactory = (map: ModuleContextMap) => ModuleContext type ModuleContextFactory = (
map: ModuleContextMap,
isUrl?: boolean
) => ModuleContext
type EsmImport = ( type EsmImport = (
moduleId: ModuleId, moduleId: ModuleId,
allowExportDefault: boolean allowExportDefault: boolean
......
...@@ -83,7 +83,8 @@ contextPrototype.M = moduleFactories ...@@ -83,7 +83,8 @@ contextPrototype.M = moduleFactories
type ModuleContextMap = Record<ModuleId, ModuleContextEntry> type ModuleContextMap = Record<ModuleId, ModuleContextEntry>
interface ModuleContextEntry { interface ModuleContextEntry {
id: () => ModuleId // Not present for `new URL()` contexts, which are never asked for module ids
id?: () => ModuleId
module: () => any module: () => any
} }
...@@ -671,11 +672,9 @@ function commonJsRequire( ...@@ -671,11 +672,9 @@ function commonJsRequire(
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ */
function parseRequest(request: string): string { function parseRequest(request: string): string {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // Per the URI spec fragments can contain `?` characters, so we should trim it off first
...@@ -692,14 +691,28 @@ function parseRequest(request: string): string { ...@@ -692,14 +691,28 @@ function parseRequest(request: string): string {
return request 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(map: ModuleContextMap, isUrl?: boolean): ModuleContext {
function moduleContext(id: string): Exports { function lookup(id: string): ModuleContextEntry {
id = parseRequest(id)
if (hasOwnProperty.call(map, 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}'`) const e = new Error(`Cannot find module '${id}'`)
...@@ -707,19 +720,16 @@ function moduleContext(map: ModuleContextMap): ModuleContext { ...@@ -707,19 +720,16 @@ function moduleContext(map: ModuleContextMap): ModuleContext {
throw e throw e
} }
function moduleContext(id: string): Exports {
return lookup(id).module()
}
moduleContext.keys = (): string[] => { moduleContext.keys = (): string[] => {
return Object.keys(map) return Object.keys(map)
} }
moduleContext.resolve = (id: string): ModuleId => { moduleContext.resolve = (id: string): ModuleId => {
id = parseRequest(id) return lookup(id).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
} }
moduleContext.import = async (id: string) => { moduleContext.import = async (id: string) => {
......
...@@ -381,8 +381,8 @@ impl ReferencedAsset { ...@@ -381,8 +381,8 @@ impl ReferencedAsset {
impl ReferencedAsset { impl ReferencedAsset {
pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Self> { 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 // 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 // results (e.g. `new URL()`, see `UrlAssetReferenceCodeGen`) have to map them with
// with `PatternMapping` instead. // `PatternMapping` instead.
let result = resolve_result.await?; let result = resolve_result.await?;
if result.is_unresolvable() { if result.is_unresolvable() {
return Ok(ReferencedAsset::Unresolvable); return Ok(ReferencedAsset::Unresolvable);
......
...@@ -149,8 +149,8 @@ use crate::{ ...@@ -149,8 +149,8 @@ use crate::{
}, },
}, },
runtime_functions::{ runtime_functions::{
TURBOPACK_EXPORTS, TURBOPACK_GLOBAL, TURBOPACK_REQUIRE_REAL, TURBOPACK_REQUIRE_STUB, TURBOPACK_EXPORTS, TURBOPACK_GLOBAL, TURBOPACK_REQUIRE, TURBOPACK_REQUIRE_REAL,
TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS, TURBOPACK_REQUIRE_STUB, TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS,
}, },
source_map::parse_source_map_comment, source_map::parse_source_map_comment,
utils::{AstPathRange, js_value_to_pattern, module_value_to_well_known_object}, utils::{AstPathRange, js_value_to_pattern, module_value_to_well_known_object},
...@@ -2297,6 +2297,25 @@ where ...@@ -2297,6 +2297,25 @@ where
} }
match func { 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 => { WellKnownFunctionKind::Import => {
let args = linked_args().await?; let args = linked_args().await?;
let export_usage = match &attributes.export_names { let export_usage = match &attributes.export_names {
......
...@@ -271,14 +271,11 @@ pub(crate) enum UrlModuleMode { ...@@ -271,14 +271,11 @@ pub(crate) enum UrlModuleMode {
impl SinglePatternMapping { impl SinglePatternMapping {
/// Creates an expression evaluating to the URL (the first `new URL()` argument) this mapping /// 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. /// points to. URL externals evaluate to their request, and anything that can't be resolved
fn create_url(&self, module_mode: UrlModuleMode) -> Expr { /// to a URL evaluates to `about:blank`.
pub fn create_url(&self, module_mode: UrlModuleMode) -> Expr {
match self { match self {
Self::Invalid => quote!( Self::Invalid | Self::Unresolvable(_) => quote!("'about:blank'" as Expr),
"(() => {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::Ignored => quote!("{}" as Expr), Self::Ignored => quote!("{}" as Expr),
Self::Dropped => quote!("0" as Expr), Self::Dropped => quote!("0" as Expr),
Self::Module(module_id) | Self::ModuleLoader(module_id) => match module_mode { Self::Module(module_id) | Self::ModuleLoader(module_id) => match module_mode {
...@@ -294,10 +291,7 @@ impl SinglePatternMapping { ...@@ -294,10 +291,7 @@ impl SinglePatternMapping {
), ),
}, },
Self::External(request, ExternalType::Url) => request.as_str().into(), Self::External(request, ExternalType::Url) => request.as_str().into(),
Self::External(request, ty) => throw_module_not_found_error_expr( Self::External(_, _) => quote!("'about:blank'" as Expr),
request,
&format!("Unsupported external type {ty:?} for URL reference"),
),
} }
} }
} }
...@@ -305,7 +299,6 @@ impl SinglePatternMapping { ...@@ -305,7 +299,6 @@ impl SinglePatternMapping {
enum ImportMode { enum ImportMode {
Require, Require,
Import { import_externals: bool }, Import { import_externals: bool },
Url(UrlModuleMode),
} }
fn create_context_map( fn create_context_map(
...@@ -320,8 +313,7 @@ fn create_context_map( ...@@ -320,8 +313,7 @@ fn create_context_map(
"{id: () => $id, module: () => $module}", "{id: () => $id, module: () => $module}",
id: Expr = v.create_id(Cow::Borrowed(key_expr)), id: Expr = v.create_id(Cow::Borrowed(key_expr)),
module: Expr = match import_mode {ImportMode::Require => v.create_require(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::Import {import_externals} => v.create_import(Cow::Borrowed(key_expr), import_externals),},
ImportMode::Url(module_mode) => v.create_url(module_mode),},
),})))}) ),})))})
.collect(); .collect();
...@@ -331,6 +323,46 @@ fn create_context_map( ...@@ -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 { impl PatternMapping {
pub fn create_id(&self, key_expr: Expr) -> Expr { pub fn create_id(&self, key_expr: Expr) -> Expr {
match self { match self {
...@@ -362,24 +394,29 @@ impl PatternMapping { ...@@ -362,24 +394,29 @@ impl PatternMapping {
} }
} }
/// Creates an expression that looks up, at runtime, the URL (the first `new URL()` argument) /// Creates an expression evaluating to the URL (the first `new URL()` argument) of the asset
/// of the asset matching `key_expr`. It throws `MODULE_NOT_FOUND` when nothing matches, and /// matching `key_expr`. With multiple possible assets, it's looked up at runtime (with the
/// `key_expr` is evaluated exactly once. /// 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
/// Only used for dynamic or multi-result requests, so a [`PatternMapping::Single`] here means /// without a leading `./` at runtime (i.e. it isn't a relative request).
/// that the request matched nothing and is mapped to an empty context. pub fn create_url(
pub fn create_url_lookup(&self, key_expr: Expr, module_mode: UrlModuleMode) -> Expr { &self,
let empty = FxIndexMap::default(); key_expr: Expr,
let map = match self { module_mode: UrlModuleMode,
PatternMapping::Single(_) => &empty, bare_aliases: bool,
PatternMapping::Map(map) => map, ) -> Expr {
}; match self {
quote!( PatternMapping::Single(pm) => pm.create_url(module_mode),
"$turbopack_module_context($map)($key)" as Expr, PatternMapping::Map(map) => {
turbopack_module_context: Expr = TURBOPACK_MODULE_CONTEXT.into(), let map = create_url_context_map(map, module_mode, bare_aliases);
map: Expr = create_context_map(map, &key_expr, ImportMode::Url(module_mode)),
key: Expr = key_expr 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 { pub fn create_import(&self, key_expr: Expr, import_externals: bool) -> Expr {
...@@ -551,12 +588,40 @@ impl PatternMapping { ...@@ -551,12 +588,40 @@ impl PatternMapping {
} }
_ => { _ => {
let primary = &result.primary; 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 mut set = HashSet::new();
let items: Vec<(RcStr, &ModuleResolveResultItem)> = primary let items: Vec<(RcStr, &ModuleResolveResultItem)> = primary
.iter() .iter()
.filter_map(|(k, v)| { .filter_map(|(k, v)| {
let request = k.request.as_ref()?; 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(); .collect();
let map = items let map = items
......
...@@ -8,24 +8,24 @@ const assetUrl = (name) => ...@@ -8,24 +8,24 @@ const assetUrl = (name) =>
new URL(`./assets/${track(name)}`, import.meta.url).toString() new URL(`./assets/${track(name)}`, import.meta.url).toString()
const singleUrl = (name) => const singleUrl = (name) =>
new URL(`./single/${track(name)}`, import.meta.url).toString() new URL(`./single/${track(name)}`, import.meta.url).toString()
const noMatchUrl = (name) => { const bareUrl = (name) => new URL(`assets/${name}`, import.meta.url).toString()
try { const suffixedUrl = (name, suffix) =>
return new URL(`./no-match/${track(name)}`, import.meta.url).toString() new URL(`./assets/${name}${suffix}`, import.meta.url).toString()
} catch (e) { const constantSuffixUrl = (name) =>
return e 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 const before = evaluations
let error expect(fn()).toBe('about:blank')
try {
fn()
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1) expect(evaluations - before).toBe(1)
} }
...@@ -44,17 +44,36 @@ it('should resolve a dynamic new URL that matches a single file', () => { ...@@ -44,17 +44,36 @@ it('should resolve a dynamic new URL that matches a single file', () => {
expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/) expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/)
}) })
it('should throw MODULE_NOT_FOUND for a request that matched no file', () => { it('should resolve a request that matched no file to about:blank', () => {
expectModuleNotFound(() => assetUrl('missing.txt')) expectAboutBlank(() => assetUrl('missing.txt'))
expectModuleNotFound(() => singleUrl('missing.txt')) expectAboutBlank(() => singleUrl('missing.txt'))
}) })
it('should throw MODULE_NOT_FOUND for a pattern that matched nothing', () => { it('should resolve a pattern that matched nothing to about:blank', () => {
const before = evaluations expect(noMatchUrl('anything.txt')).toBe('about:blank')
const error = noMatchUrl('anything.txt') })
expect(error).toBeInstanceOf(Error)
expect(error.code).toBe('MODULE_NOT_FOUND') it('should resolve a dynamic new URL without a leading ./', () => {
expect(evaluations - before).toBe(1) 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', () => { 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) => 20 | const fullyDynamicUrl = (request) =>
10 | new URL(`./single/${track(name)}`, import.meta.url).toString() 21 | new URL(request, import.meta.url).toString()
11 | const noMatchUrl = (name) => { 22 |
12 | try { 23 | const noMatchUrl = (name) =>
+ v---------------------------------------------------v + v---------------------------------------------------v
13 + return new URL(`./no-match/${track(name)}`, import.meta.url).toString() 24 + new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^ + ^---------------------------------------------------^
14 | } catch (e) { 25 |
15 | return e 26 | const expectAboutBlank = (fn) => {
16 | } 27 | const before = evaluations
17 | } 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) => ...@@ -8,24 +8,24 @@ const assetUrl = (name) =>
new URL(`./assets/${track(name)}`, import.meta.url).toString() new URL(`./assets/${track(name)}`, import.meta.url).toString()
const singleUrl = (name) => const singleUrl = (name) =>
new URL(`./single/${track(name)}`, import.meta.url).toString() new URL(`./single/${track(name)}`, import.meta.url).toString()
const noMatchUrl = (name) => { const bareUrl = (name) => new URL(`assets/${name}`, import.meta.url).toString()
try { const suffixedUrl = (name, suffix) =>
return new URL(`./no-match/${track(name)}`, import.meta.url).toString() new URL(`./assets/${name}${suffix}`, import.meta.url).toString()
} catch (e) { const constantSuffixUrl = (name) =>
return e 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 const before = evaluations
let error expect(fn()).toBe('about:blank')
try {
fn()
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(error.code).toBe('MODULE_NOT_FOUND')
expect(evaluations - before).toBe(1) expect(evaluations - before).toBe(1)
} }
...@@ -44,17 +44,36 @@ it('should resolve a dynamic new URL that matches a single file', () => { ...@@ -44,17 +44,36 @@ it('should resolve a dynamic new URL that matches a single file', () => {
expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/) expect(singleUrl('only.txt')).toMatch(/only\.[^/]*txt$/)
}) })
it('should throw MODULE_NOT_FOUND for a request that matched no file', () => { it('should resolve a request that matched no file to about:blank', () => {
expectModuleNotFound(() => assetUrl('missing.txt')) expectAboutBlank(() => assetUrl('missing.txt'))
expectModuleNotFound(() => singleUrl('missing.txt')) expectAboutBlank(() => singleUrl('missing.txt'))
}) })
it('should throw MODULE_NOT_FOUND for a pattern that matched nothing', () => { it('should resolve a pattern that matched nothing to about:blank', () => {
const before = evaluations expect(noMatchUrl('anything.txt')).toBe('about:blank')
const error = noMatchUrl('anything.txt') })
expect(error).toBeInstanceOf(Error)
expect(error.code).toBe('MODULE_NOT_FOUND') it('should resolve a dynamic new URL without a leading ./', () => {
expect(evaluations - before).toBe(1) 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', () => { 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) => 20 | const fullyDynamicUrl = (request) =>
10 | new URL(`./single/${track(name)}`, import.meta.url).toString() 21 | new URL(request, import.meta.url).toString()
11 | const noMatchUrl = (name) => { 22 |
12 | try { 23 | const noMatchUrl = (name) =>
+ v---------------------------------------------------v + v---------------------------------------------------v
13 + return new URL(`./no-match/${track(name)}`, import.meta.url).toString() 24 + new URL(`./no-match/${track(name)}`, import.meta.url).toString()
+ ^---------------------------------------------------^ + ^---------------------------------------------------^
14 | } catch (e) { 25 |
15 | return e 26 | const expectAboutBlank = (fn) => {
16 | } 27 | const before = evaluations
17 | } 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([ (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)"]}
...@@ -511,11 +511,9 @@ function commonJsRequire(id) { ...@@ -511,11 +511,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -529,29 +527,39 @@ contextPrototype.r = commonJsRequire; ...@@ -529,29 +527,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(id); return await moduleContext(id);
...@@ -2659,5 +2667,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -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 //# 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) { ...@@ -488,11 +488,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -506,29 +504,39 @@ contextPrototype.r = commonJsRequire; ...@@ -506,29 +504,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(id); return await moduleContext(id);
......
...@@ -22,14 +22,12 @@ var __TURBOPACK__import$2e$meta__ = { ...@@ -22,14 +22,12 @@ var __TURBOPACK__import$2e$meta__ = {
const name = globalThis.assetName; const name = globalThis.assetName;
const assetUrl = new URL(__turbopack_context__.f({ const assetUrl = new URL(__turbopack_context__.f({
"./assets/a.txt": { "./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)") 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": { "./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)") 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); 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); console.log(assetUrl, staticUrl);
}), }),
......
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
"version": 3, "version": 3,
"sources": [], "sources": [],
"sections": [ "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__ = { ...@@ -22,14 +22,12 @@ var __TURBOPACK__import$2e$meta__ = {
const name = globalThis.assetName; const name = globalThis.assetName;
const assetUrl = new __turbopack_context__.U(__turbopack_context__.f({ const assetUrl = new __turbopack_context__.U(__turbopack_context__.f({
"./assets/a.txt": { "./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)") 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": { "./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)") 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)")); 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); console.log(assetUrl, staticUrl);
}), }),
......
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
"version": 3, "version": 3,
"sources": [], "sources": [],
"sections": [ "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) { ...@@ -488,11 +488,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -506,29 +504,39 @@ contextPrototype.r = commonJsRequire; ...@@ -506,29 +504,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(id); return await moduleContext(id);
......
...@@ -510,11 +510,9 @@ function commonJsRequire(id) { ...@@ -510,11 +510,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire; ...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(id); return await moduleContext(id);
......
...@@ -716,11 +716,9 @@ function commonJsRequire(id) { ...@@ -716,11 +716,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -734,29 +732,41 @@ contextPrototype.r = commonJsRequire; ...@@ -734,29 +732,41 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
var URL_CONTEXT_FALLBACK = {
module: function module() {
return 'about:blank';
}
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); var e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = function() { moduleContext.keys = function() {
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = function(id) { moduleContext.resolve = function(id) {
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = function(id) { moduleContext.import = function(id) {
return _async_to_generator(function() { return _async_to_generator(function() {
......
...@@ -510,11 +510,9 @@ function commonJsRequire(id) { ...@@ -510,11 +510,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire; ...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(id); return await moduleContext(id);
......
...@@ -510,11 +510,9 @@ function commonJsRequire(id) { ...@@ -510,11 +510,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire; ...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(id); return await moduleContext(id);
......
...@@ -510,11 +510,9 @@ function commonJsRequire(id) { ...@@ -510,11 +510,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire; ...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(id); return await moduleContext(id);
......
...@@ -510,11 +510,9 @@ function commonJsRequire(id) { ...@@ -510,11 +510,9 @@ function commonJsRequire(id) {
} }
contextPrototype.r = 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 * This matches how we parse patterns at resolving time.
* strings passed to `import` but the resolve does it for `import` and `require` and so we do
* here as well.
*/ function parseRequest(request) { */ function parseRequest(request) {
// Per the URI spec fragments can contain `?` characters, so we should trim it off first // 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 // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire; ...@@ -528,29 +526,39 @@ contextPrototype.r = commonJsRequire;
} }
return request; return request;
} }
const URL_CONTEXT_FALLBACK = {
module: ()=>'about:blank'
};
/** /**
* `require.context` and require/import expression runtime. * `require.context`, require/import expression and `new URL()` runtime.
*/ function moduleContext(map) { *
function moduleContext(id) { * A `new URL()` context (`isUrl`) looks a request that doesn't exactly match a key up again
id = parseRequest(id); * 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)) { 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}'`); const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND'; e.code = 'MODULE_NOT_FOUND';
throw e; throw e;
} }
function moduleContext(id) {
return lookup(id).module();
}
moduleContext.keys = ()=>{ moduleContext.keys = ()=>{
return Object.keys(map); return Object.keys(map);
}; };
moduleContext.resolve = (id)=>{ moduleContext.resolve = (id)=>{
id = parseRequest(id); return lookup(id).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;
}; };
moduleContext.import = async (id)=>{ moduleContext.import = async (id)=>{
return await moduleContext(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