Skip to content

Commit 27df7a9

Browse files
committed
Add wasm_bindgen::script_url
1 parent 5c3f6ed commit 27df7a9

File tree

5 files changed

+48
-29
lines changed

5 files changed

+48
-29
lines changed

crates/cli-support/src/intrinsic.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,9 @@ intrinsics! {
229229
#[symbol = "__wbindgen_module"]
230230
#[signature = fn() -> Externref]
231231
Module,
232+
#[symbol = "__wbindgen_script_url"]
233+
#[signature = fn() -> String]
234+
ScriptUrl,
232235
#[symbol = "__wbindgen_function_table"]
233236
#[signature = fn() -> Externref]
234237
FunctionTable,

crates/cli-support/src/js/mod.rs

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,7 @@ impl<'a> Context<'a> {
378378
// function.
379379
OutputMode::NoModules { global } => {
380380
js.push_str("const __exports = {};\n");
381+
js.push_str("let script_src;\n");
381382
js.push_str("let wasm;\n");
382383
init = self.gen_init(needs_manual_start, None)?;
383384
footer.push_str(&format!("{} = Object.assign(init, __exports);\n", global));
@@ -700,14 +701,13 @@ impl<'a> Context<'a> {
700701
stem = self.config.stem()?
701702
),
702703
OutputMode::NoModules { .. } => "\
704+
if (typeof document === 'undefined') {
705+
script_src = location.href;
706+
} else {
707+
script_src = document.currentScript.src;
708+
}
703709
if (typeof input === 'undefined') {
704-
let src;
705-
if (typeof document === 'undefined') {
706-
src = location.href;
707-
} else {
708-
src = document.currentScript.src;
709-
}
710-
input = src.replace(/\\.js$/, '_bg.wasm');
710+
input = script_src.replace(/\\.js$/, '_bg.wasm');
711711
}"
712712
.to_string(),
713713
_ => "".to_string(),
@@ -3426,6 +3426,22 @@ impl<'a> Context<'a> {
34263426
format!("wasm.{}", self.export_name_of(memory))
34273427
}
34283428

3429+
Intrinsic::ScriptUrl => {
3430+
assert_eq!(args.len(), 0);
3431+
match self.config.mode {
3432+
OutputMode::Web
3433+
| OutputMode::Deno
3434+
| OutputMode::Node {
3435+
experimental_modules: true,
3436+
} => format!("import.meta.url"),
3437+
OutputMode::Node {
3438+
experimental_modules: false,
3439+
} => format!("__filename"),
3440+
OutputMode::NoModules { .. } => format!("script_src"),
3441+
OutputMode::Bundler { .. } => format!("__webpack_public_path__"),
3442+
}
3443+
}
3444+
34293445
Intrinsic::FunctionTable => {
34303446
assert_eq!(args.len(), 0);
34313447
let name = self.export_function_table()?;

crates/cli/tests/wasm-bindgen/main.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -261,14 +261,13 @@ fn default_module_path_target_no_modules() {
261261
assert!(contents.contains(
262262
"\
263263
async function init(input) {
264+
if (typeof document === 'undefined') {
265+
script_src = location.href;
266+
} else {
267+
script_src = document.currentScript.src;
268+
}
264269
if (typeof input === 'undefined') {
265-
let src;
266-
if (typeof document === 'undefined') {
267-
src = location.href;
268-
} else {
269-
src = document.currentScript.src;
270-
}
271-
input = src.replace(/\\.js$/, '_bg.wasm');
270+
input = script_src.replace(/\\.js$/, '_bg.wasm');
272271
}",
273272
));
274273
}

examples/wasm-audio-worklet/src/dependent_module.rs

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,11 @@ use js_sys::{Array, JsString};
22
use wasm_bindgen::prelude::*;
33
use web_sys::{Blob, BlobPropertyBag, Url};
44

5-
// This is a not-so-clean approach to get the current bindgen ES module URL
6-
// in Rust. This will fail at run time on bindgen targets not using ES modules.
7-
#[wasm_bindgen]
8-
extern "C" {
9-
#[wasm_bindgen]
10-
type ImportMeta;
11-
12-
#[wasm_bindgen(method, getter)]
13-
fn url(this: &ImportMeta) -> JsString;
14-
15-
#[wasm_bindgen(js_namespace = import, js_name = meta)]
16-
static IMPORT_META: ImportMeta;
17-
}
18-
195
pub fn on_the_fly(code: &str) -> Result<String, JsValue> {
206
// Generate the import of the bindgen ES module, assuming `--target web`:
217
let header = format!(
228
"import init, * as bindgen from '{}';\n\n",
23-
IMPORT_META.url(),
9+
&wasm_bindgen::script_url(),
2410
);
2511

2612
Url::create_object_url_with_blob(&Blob::new_with_str_sequence_and_options(

src/lib.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -972,6 +972,7 @@ externs! {
972972

973973
fn __wbindgen_memory() -> u32;
974974
fn __wbindgen_module() -> u32;
975+
fn __wbindgen_script_url(ret: *mut [usize; 2]) -> ();
975976
fn __wbindgen_function_table() -> u32;
976977
}
977978
}
@@ -1251,6 +1252,20 @@ pub fn memory() -> JsValue {
12511252
unsafe { JsValue::_new(__wbindgen_memory()) }
12521253
}
12531254

1255+
/// Returns the URL to the script that instantiated the wasm module.
1256+
///
1257+
/// On some wasm-bindgen targets, this script is a module or a bundle.
1258+
/// Also, the returned URL is relative on some wasm-bindgen targets.
1259+
#[cfg(feature = "std")]
1260+
pub fn script_url() -> String {
1261+
unsafe {
1262+
let mut ret = [0; 2];
1263+
__wbindgen_script_url(&mut ret);
1264+
let data = Vec::from_raw_parts(ret[0] as *mut u8, ret[1], ret[1]);
1265+
String::from_utf8_unchecked(data)
1266+
}
1267+
}
1268+
12541269
/// Returns a handle to this wasm instance's `WebAssembly.Table` which is the
12551270
/// indirect function table used by Rust
12561271
pub fn function_table() -> JsValue {

0 commit comments

Comments
 (0)