Unverified Commit c58c6b70 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: more static typeof replacements for ESM (#69914)

Closes PACK-3117
Closes PACK-3235

- Also replace `typeof` of `module`, `exports`, `require` in ESM with
the corresponding value
- Also replace `typeof import.meta` with `object`.

This is what we talked about, @sokra
parent cfdd5dcd
......@@ -23,6 +23,7 @@ use super::{
use crate::{
analyzer::{is_unresolved, WellKnownObjectKind},
utils::{unparen, AstPathRange},
SpecifiedModuleType,
};
#[derive(Debug, Clone)]
......@@ -312,8 +313,8 @@ impl EvalContext {
}
}
pub fn is_esm(&self) -> bool {
self.imports.is_esm()
pub fn is_esm(&self, specified_type: SpecifiedModuleType) -> bool {
self.imports.is_esm(specified_type)
}
fn eval_prop_name(&self, prop: &PropName) -> JsValue {
......
......@@ -17,7 +17,10 @@ use turbo_tasks::{RcStr, Vc};
use turbopack_core::{issue::IssueSource, source::Source};
use super::{top_level_await::has_top_level_await, JsValue, ModuleValue};
use crate::tree_shake::{find_turbopack_part_id_in_asserts, PartId};
use crate::{
tree_shake::{find_turbopack_part_id_in_asserts, PartId},
SpecifiedModuleType,
};
#[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Default, Debug, Clone, Hash)]
......@@ -209,8 +212,14 @@ pub(crate) struct ImportMapReference {
}
impl ImportMap {
pub fn is_esm(&self) -> bool {
self.has_exports || self.has_imports || self.has_top_level_await
pub fn is_esm(&self, specified_type: SpecifiedModuleType) -> bool {
match specified_type {
SpecifiedModuleType::Automatic => {
self.has_exports || self.has_imports || self.has_top_level_await
}
SpecifiedModuleType::CommonJs => false,
SpecifiedModuleType::EcmaScript => true,
}
}
pub fn get_import(&self, id: &Id) -> Option<JsValue> {
......
......@@ -885,8 +885,7 @@ async fn gen_content_with_visitors(
Ok(EcmascriptModuleContent {
inner_code: bytes.into(),
source_map: Some(Vc::upcast(srcmap)),
is_esm: eval_context.is_esm()
|| specified_module_type == SpecifiedModuleType::EcmaScript,
is_esm: eval_context.is_esm(specified_module_type),
}
.cell())
}
......
......@@ -491,23 +491,35 @@ pub(crate) async fn analyse_ecmascript_module_internal(
return analysis.build(false).await;
};
let compile_time_info = if (specified_type == SpecifiedModuleType::CommonJs)
|| (specified_type == SpecifiedModuleType::Automatic && !eval_context.is_esm())
{
let compile_time_info = {
let compile_time_info = raw_module.compile_time_info.await?;
let mut free_var_references = compile_time_info.free_var_references.await?.clone_value();
let (typeof_exports, typeof_module) = if eval_context.is_esm(specified_type) {
("undefined", "undefined")
} else {
("object", "object")
};
free_var_references
.entry(vec![
DefineableNameSegment::Name("exports".into()),
DefineableNameSegment::Name("import".into()),
DefineableNameSegment::Name("meta".into()),
DefineableNameSegment::TypeOf,
])
.or_insert("object".into());
free_var_references
.entry(vec![
DefineableNameSegment::Name("exports".into()),
DefineableNameSegment::TypeOf,
])
.or_insert(typeof_exports.into());
free_var_references
.entry(vec![
DefineableNameSegment::Name("module".into()),
DefineableNameSegment::TypeOf,
])
.or_insert("object".into());
.or_insert(typeof_module.into());
free_var_references
.entry(vec![
DefineableNameSegment::Name("require".into()),
......@@ -521,8 +533,6 @@ pub(crate) async fn analyse_ecmascript_module_internal(
free_var_references: FreeVarReferences(free_var_references).cell(),
}
.cell()
} else {
raw_module.compile_time_info
};
let mut import_references = Vec::new();
......@@ -844,7 +854,7 @@ pub(crate) async fn analyse_ecmascript_module_internal(
set_handler_and_globals(&handler, globals, || has_top_level_await(program));
let has_top_level_await = top_level_await_span.is_some();
if eval_context.is_esm() || specified_type == SpecifiedModuleType::EcmaScript {
if eval_context.is_esm(specified_type) {
let async_module = AsyncModule {
has_top_level_await,
import_externals,
......
console.log("typeof require", typeof require)
console.log("typeof import.meta", typeof import.meta)
// CJS, should be `object`
console.log("typeof module", typeof module)
console.log("typeof exports", typeof exports)
import './dep.js'
console.log("typeof require", typeof require)
console.log("typeof import.meta", typeof import.meta)
// ESM, should be `undefined`
console.log("typeof module", typeof module)
console.log("typeof exports", typeof exports)
console.log("typeof require", typeof require)
console.log("typeof import.meta", typeof import.meta)
// ESM, should be `undefined`
console.log("typeof module", typeof module)
console.log("typeof exports", typeof exports)
import "./cjs.js"
import "./esm-automatic.js"
import "./esm-specified.mjs"
warning - [analysis] [project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs Specified module format (EcmaScript Modules) is not matching the module format of the source code (CommonJs)
The EcmaScript module format was specified in the package.json that is affecting this source file or by using an special extension, but it looks like that CommonJs syntax is used in the source code.
Exports made by CommonJs syntax will lead to a runtime error, since the module is in EcmaScript mode. Either change the "type" field in the package.json or replace CommonJs syntax with EcmaScript import/export syntax in the source file.
\ No newline at end of file
(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push([
"output/4e721_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_index_4cb5df.js",
{},
{"otherChunks":["output/turbopack_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_80f572._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_80f572._.js", {
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js [test] (ecmascript)": (function({ r: __turbopack_require__, f: __turbopack_module_context__, i: __turbopack_import__, s: __turbopack_esm__, v: __turbopack_export_value__, n: __turbopack_export_namespace__, c: __turbopack_cache__, M: __turbopack_modules__, l: __turbopack_load__, j: __turbopack_dynamic__, P: __turbopack_resolve_absolute_path__, U: __turbopack_relative_url__, R: __turbopack_resolve_module_id_path__, b: __turbopack_worker_blob_url__, g: global, __dirname, m: module, e: exports, t: require }) { !function() {
const __TURBOPACK__import$2e$meta__ = {
get url () {
return `file://${__turbopack_resolve_absolute_path__("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js")}`;
}
};
"__TURBOPACK__ecmascript__hoisting__location__";
console.log("typeof require", ("TURBOPACK compile-time value", "function"));
console.log("typeof import.meta", ("TURBOPACK compile-time value", "object"));
// CJS, should be `object`
console.log("typeof module", ("TURBOPACK compile-time value", "object"));
console.log("typeof exports", ("TURBOPACK compile-time value", "object"));
}.call(this) }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/dep.js [test] (ecmascript)": (function({ r: __turbopack_require__, f: __turbopack_module_context__, i: __turbopack_import__, s: __turbopack_esm__, v: __turbopack_export_value__, n: __turbopack_export_namespace__, c: __turbopack_cache__, M: __turbopack_modules__, l: __turbopack_load__, j: __turbopack_dynamic__, P: __turbopack_resolve_absolute_path__, U: __turbopack_relative_url__, R: __turbopack_resolve_module_id_path__, b: __turbopack_worker_blob_url__, g: global, __dirname, m: module, e: exports, t: require }) { !function() {
}.call(this) }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js [test] (ecmascript)": (({ r: __turbopack_require__, f: __turbopack_module_context__, i: __turbopack_import__, s: __turbopack_esm__, v: __turbopack_export_value__, n: __turbopack_export_namespace__, c: __turbopack_cache__, M: __turbopack_modules__, l: __turbopack_load__, j: __turbopack_dynamic__, P: __turbopack_resolve_absolute_path__, U: __turbopack_relative_url__, R: __turbopack_resolve_module_id_path__, b: __turbopack_worker_blob_url__, g: global, __dirname }) => (() => {
"use strict";
__turbopack_esm__({});
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$comptime$2f$typeof$2f$input$2f$dep$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_import__("[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/dep.js [test] (ecmascript)");
const __TURBOPACK__import$2e$meta__ = {
get url () {
return `file://${__turbopack_resolve_absolute_path__("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js")}`;
}
};
"__TURBOPACK__ecmascript__hoisting__location__";
;
console.log("typeof require", ("TURBOPACK compile-time value", "function"));
console.log("typeof import.meta", ("TURBOPACK compile-time value", "object"));
// ESM, should be `undefined`
console.log("typeof module", ("TURBOPACK compile-time value", "undefined"));
console.log("typeof exports", ("TURBOPACK compile-time value", "undefined"));
})()),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs [test] (ecmascript)": (({ r: __turbopack_require__, f: __turbopack_module_context__, i: __turbopack_import__, s: __turbopack_esm__, v: __turbopack_export_value__, n: __turbopack_export_namespace__, c: __turbopack_cache__, M: __turbopack_modules__, l: __turbopack_load__, j: __turbopack_dynamic__, P: __turbopack_resolve_absolute_path__, U: __turbopack_relative_url__, R: __turbopack_resolve_module_id_path__, b: __turbopack_worker_blob_url__, g: global, __dirname }) => (() => {
"use strict";
__turbopack_esm__({});
const __TURBOPACK__import$2e$meta__ = {
get url () {
return `file://${__turbopack_resolve_absolute_path__("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs")}`;
}
};
"__TURBOPACK__ecmascript__hoisting__location__";
console.log("typeof require", ("TURBOPACK compile-time value", "function"));
console.log("typeof import.meta", ("TURBOPACK compile-time value", "object"));
// ESM, should be `undefined`
console.log("typeof module", ("TURBOPACK compile-time value", "undefined"));
console.log("typeof exports", ("TURBOPACK compile-time value", "undefined"));
})()),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/index.js [test] (ecmascript)": (({ r: __turbopack_require__, f: __turbopack_module_context__, i: __turbopack_import__, s: __turbopack_esm__, v: __turbopack_export_value__, n: __turbopack_export_namespace__, c: __turbopack_cache__, M: __turbopack_modules__, l: __turbopack_load__, j: __turbopack_dynamic__, P: __turbopack_resolve_absolute_path__, U: __turbopack_relative_url__, R: __turbopack_resolve_module_id_path__, b: __turbopack_worker_blob_url__, g: global, __dirname }) => (() => {
"use strict";
__turbopack_esm__({});
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$comptime$2f$typeof$2f$input$2f$cjs$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_import__("[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$comptime$2f$typeof$2f$input$2f$esm$2d$automatic$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_import__("[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$comptime$2f$typeof$2f$input$2f$esm$2d$specified$2e$mjs__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_import__("[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs [test] (ecmascript)");
"__TURBOPACK__ecmascript__hoisting__location__";
;
;
;
})()),
}]);
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_80f572._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack://[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js"],"sourcesContent":["console.log(\"typeof require\", typeof require)\nconsole.log(\"typeof import.meta\", typeof import.meta)\n// CJS, should be `object`\nconsole.log(\"typeof module\", typeof module)\nconsole.log(\"typeof exports\", typeof exports)\n"],"names":[],"mappings":";;;;;;AAAA,QAAQ,GAAG,CAAC;AACZ,QAAQ,GAAG,CAAC;AACZ,0BAA0B;AAC1B,QAAQ,GAAG,CAAC;AACZ,QAAQ,GAAG,CAAC"}},
{"offset": {"line": 15, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":"A"}},
{"offset": {"line": 19, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}},
{"offset": {"line": 19, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":"A"}},
{"offset": {"line": 24, "column": 0}, "map": {"version":3,"sources":["turbopack://[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js"],"sourcesContent":["import './dep.js'\n\nconsole.log(\"typeof require\", typeof require)\nconsole.log(\"typeof import.meta\", typeof import.meta)\n// ESM, should be `undefined`\nconsole.log(\"typeof module\", typeof module)\nconsole.log(\"typeof exports\", typeof exports)\n"],"names":[],"mappings":";;;;;;;;;AAEA,QAAQ,GAAG,CAAC;AACZ,QAAQ,GAAG,CAAC;AACZ,6BAA6B;AAC7B,QAAQ,GAAG,CAAC;AACZ,QAAQ,GAAG,CAAC"}},
{"offset": {"line": 38, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":"A"}},
{"offset": {"line": 43, "column": 0}, "map": {"version":3,"sources":["turbopack://[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs"],"sourcesContent":["console.log(\"typeof require\", typeof require)\nconsole.log(\"typeof import.meta\", typeof import.meta)\n// ESM, should be `undefined`\nconsole.log(\"typeof module\", typeof module)\nconsole.log(\"typeof exports\", typeof exports)\n"],"names":[],"mappings":";;;;;;;AAAA,QAAQ,GAAG,CAAC;AACZ,QAAQ,GAAG,CAAC;AACZ,6BAA6B;AAC7B,QAAQ,GAAG,CAAC;AACZ,QAAQ,GAAG,CAAC"}},
{"offset": {"line": 55, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":"A"}},
{"offset": {"line": 60, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}},
{"offset": {"line": 68, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":"A"}}]
}
\ No newline at end of file
import './other-dep.js'
// this cannot be an execution test, because `module` is always defined when running the test in Node.js
console.log(typeof module)
(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4c35f_tests_snapshot_typeof-exports-esm_typeof-exports-esm_input_ccc25d._.js", {
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/typeof-exports-esm/typeof-exports-esm/input/other-dep.js [test] (ecmascript)": (function({ r: __turbopack_require__, f: __turbopack_module_context__, i: __turbopack_import__, s: __turbopack_esm__, v: __turbopack_export_value__, n: __turbopack_export_namespace__, c: __turbopack_cache__, M: __turbopack_modules__, l: __turbopack_load__, j: __turbopack_dynamic__, P: __turbopack_resolve_absolute_path__, U: __turbopack_relative_url__, R: __turbopack_resolve_module_id_path__, b: __turbopack_worker_blob_url__, g: global, __dirname, m: module, e: exports, t: require }) { !function() {
console.log('other-dep');
}.call(this) }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/typeof-exports-esm/typeof-exports-esm/input/index.js [test] (ecmascript)": (({ r: __turbopack_require__, f: __turbopack_module_context__, i: __turbopack_import__, s: __turbopack_esm__, v: __turbopack_export_value__, n: __turbopack_export_namespace__, c: __turbopack_cache__, M: __turbopack_modules__, l: __turbopack_load__, j: __turbopack_dynamic__, P: __turbopack_resolve_absolute_path__, U: __turbopack_relative_url__, R: __turbopack_resolve_module_id_path__, b: __turbopack_worker_blob_url__, g: global, __dirname }) => (() => {
"use strict";
__turbopack_esm__({});
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$typeof$2d$exports$2d$esm$2f$typeof$2d$exports$2d$esm$2f$input$2f$other$2d$dep$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_import__("[project]/turbopack/crates/turbopack-tests/tests/snapshot/typeof-exports-esm/typeof-exports-esm/input/other-dep.js [test] (ecmascript)");
"__TURBOPACK__ecmascript__hoisting__location__";
;
// this cannot be an execution test, because `module` is always defined when running the test in Node.js
console.log(typeof module);
})()),
}]);
//# sourceMappingURL=4c35f_tests_snapshot_typeof-exports-esm_typeof-exports-esm_input_ccc25d._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack://[project]/turbopack/crates/turbopack-tests/tests/snapshot/typeof-exports-esm/typeof-exports-esm/input/other-dep.js"],"sourcesContent":["console.log('other-dep')\n"],"names":[],"mappings":"AAAA,QAAQ,GAAG,CAAC"}},
{"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":"A"}},
{"offset": {"line": 10, "column": 0}, "map": {"version":3,"sources":["turbopack://[project]/turbopack/crates/turbopack-tests/tests/snapshot/typeof-exports-esm/typeof-exports-esm/input/index.js"],"sourcesContent":["import './other-dep.js'\n\n// this cannot be an execution test, because `module` is always defined when running the test in Node.js\nconsole.log(typeof module)\n"],"names":[],"mappings":";;;;AAEA,wGAAwG;AACxG,QAAQ,GAAG,CAAC,OAAO"}},
{"offset": {"line": 16, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":"A"}}]
}
\ No newline at end of file
(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push([
"output/4c35f_tests_snapshot_typeof-exports-esm_typeof-exports-esm_input_index_eeae37.js",
{},
{"otherChunks":["output/4c35f_tests_snapshot_typeof-exports-esm_typeof-exports-esm_input_ccc25d._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/typeof-exports-esm/typeof-exports-esm/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
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