Skip to content

Commit f3b190a

Browse files
committed
Implement transitive support for NPM dependencies
This commit implements [RFC 8], which enables transitive and transparent dependencies on NPM. The `module` attribute, when seen and not part of a local JS snippet, triggers detection of a `package.json` next to `Cargo.toml`. If found it will cause the `wasm-bindgen` CLI tool to load and parse the `package.json` within each crate and then create a merged `package.json` at the end. [RFC 8]: rustwasm/rfcs#8
1 parent 6522968 commit f3b190a

File tree

6 files changed

+112
-3
lines changed

6 files changed

+112
-3
lines changed
File renamed without changes.

crates/backend/src/encode.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use proc_macro2::{Ident, Span};
2-
use std::cell::RefCell;
3-
use std::collections::HashMap;
2+
use std::cell::{RefCell, Cell};
3+
use std::collections::{HashMap, HashSet};
44
use std::env;
55
use std::fs;
66
use std::path::PathBuf;
@@ -28,6 +28,7 @@ struct Interner {
2828
files: RefCell<HashMap<String, LocalFile>>,
2929
root: PathBuf,
3030
crate_name: String,
31+
has_package_json: Cell<bool>,
3132
}
3233

3334
struct LocalFile {
@@ -43,6 +44,7 @@ impl Interner {
4344
files: RefCell::new(HashMap::new()),
4445
root: env::var_os("CARGO_MANIFEST_DIR").unwrap().into(),
4546
crate_name: env::var("CARGO_PKG_NAME").unwrap(),
47+
has_package_json: Cell::new(false),
4648
}
4749
}
4850

@@ -67,6 +69,7 @@ impl Interner {
6769
if let Some(file) = files.get(id) {
6870
return Ok(self.intern_str(&file.new_identifier))
6971
}
72+
self.check_for_package_json();
7073
let path = if id.starts_with("/") {
7174
self.root.join(&id[1..])
7275
} else if id.starts_with("./") || id.starts_with("../") {
@@ -92,6 +95,16 @@ impl Interner {
9295
fn unique_crate_identifier(&self) -> String {
9396
format!("{}-{}", self.crate_name, ShortHash(0))
9497
}
98+
99+
fn check_for_package_json(&self) {
100+
if self.has_package_json.get() {
101+
return
102+
}
103+
let path = self.root.join("package.json");
104+
if path.exists() {
105+
self.has_package_json.set(true);
106+
}
107+
}
95108
}
96109

97110
fn shared_program<'a>(
@@ -144,6 +157,11 @@ fn shared_program<'a>(
144157
.map(|js| intern.intern_str(js))
145158
.collect(),
146159
unique_crate_identifier: intern.intern_str(&intern.unique_crate_identifier()),
160+
package_json: if intern.has_package_json.get() {
161+
Some(intern.intern_str(intern.root.join("package.json").to_str().unwrap()))
162+
} else {
163+
None
164+
},
147165
})
148166
}
149167

crates/cli-support/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ base64 = "0.9"
1616
failure = "0.1.2"
1717
log = "0.4"
1818
rustc-demangle = "0.1.13"
19+
serde_json = "1.0"
1920
tempfile = "3.0"
2021
walrus = "0.5.0"
2122
wasm-bindgen-anyref-xform = { path = '../anyref-xform', version = '=0.2.40' }

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

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use crate::{Bindgen, EncodeInto, OutputMode};
44
use failure::{bail, Error, ResultExt};
55
use std::collections::{HashMap, HashSet, BTreeMap};
66
use std::env;
7+
use std::fs;
78
use walrus::{MemoryId, Module};
89
use wasm_bindgen_wasm_interpreter::Interpreter;
910

@@ -64,6 +65,10 @@ pub struct Context<'a> {
6465
/// the same `Program`.
6566
pub snippet_offsets: HashMap<&'a str, usize>,
6667

68+
/// All package.json dependencies we've learned about so far
69+
pub package_json_read: HashSet<&'a str>,
70+
pub npm_dependencies: HashMap<String, (&'a str, String)>,
71+
6772
pub anyref: wasm_bindgen_anyref_xform::Context,
6873
}
6974

@@ -2480,6 +2485,10 @@ impl<'a, 'b> SubContext<'a, 'b> {
24802485
self.cx.typescript.push_str("\n\n");
24812486
}
24822487

2488+
if let Some(path) = self.program.package_json {
2489+
self.add_package_json(path)?;
2490+
}
2491+
24832492
Ok(())
24842493
}
24852494

@@ -2951,6 +2960,67 @@ impl<'a, 'b> SubContext<'a, 'b> {
29512960
let import = self.determine_import(import, item)?;
29522961
Ok(self.cx.import_identifier(import))
29532962
}
2963+
2964+
fn add_package_json(&mut self, path: &'b str) -> Result<(), Error> {
2965+
if !self.cx.package_json_read.insert(path) {
2966+
return Ok(());
2967+
}
2968+
if !self.cx.config.mode.nodejs() && !self.cx.config.mode.bundler() {
2969+
bail!("NPM dependencies have been specified in `{}` but \
2970+
this is only compatible with the default output of \
2971+
`wasm-bindgen` or the `--nodejs` flag");
2972+
}
2973+
let contents = fs::read_to_string(path).context(format!("failed to read `{}`", path))?;
2974+
let json: serde_json::Value = serde_json::from_str(&contents)?;
2975+
let object = match json.as_object() {
2976+
Some(s) => s,
2977+
None => bail!(
2978+
"expected `package.json` to have an JSON object in `{}`",
2979+
path
2980+
),
2981+
};
2982+
let mut iter = object.iter();
2983+
let (key, value) = match iter.next() {
2984+
Some(pair) => pair,
2985+
None => return Ok(()),
2986+
};
2987+
if key != "dependencies" || iter.next().is_some() {
2988+
bail!(
2989+
"NPM manifest found at `{}` can currently only have one key, \
2990+
`dependencies`, and no other fields",
2991+
path
2992+
);
2993+
}
2994+
let value = match value.as_object() {
2995+
Some(s) => s,
2996+
None => bail!("expected `dependencies` to be a JSON object in `{}`", path),
2997+
};
2998+
2999+
for (name, value) in value.iter() {
3000+
let value = match value.as_str() {
3001+
Some(s) => s,
3002+
None => bail!(
3003+
"keys in `dependencies` are expected to be strings in `{}`",
3004+
path
3005+
),
3006+
};
3007+
if let Some((prev, _prev_version)) = self.cx.npm_dependencies.get(name) {
3008+
bail!(
3009+
"dependency on NPM package `{}` specified in two `package.json` files, \
3010+
which at the time is not allowed:\n * {}\n * {}",
3011+
name,
3012+
path,
3013+
prev
3014+
)
3015+
}
3016+
3017+
self.cx
3018+
.npm_dependencies
3019+
.insert(name.to_string(), (path, value.to_string()));
3020+
}
3021+
3022+
Ok(())
3023+
}
29543024
}
29553025

29563026
#[derive(Hash, Eq, PartialEq)]

crates/cli-support/src/lib.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#![doc(html_root_url = "https://docs.rs/wasm-bindgen-cli-support/0.2")]
22

33
use failure::{bail, Error, ResultExt};
4-
use std::collections::BTreeSet;
4+
use std::collections::{BTreeSet, BTreeMap};
55
use std::env;
66
use std::fs;
77
use std::mem;
@@ -329,6 +329,8 @@ impl Bindgen {
329329
start: None,
330330
anyref: Default::default(),
331331
snippet_offsets: Default::default(),
332+
npm_dependencies: Default::default(),
333+
package_json_read: Default::default(),
332334
};
333335
cx.anyref.enabled = self.anyref;
334336
cx.anyref.prepare(cx.module)?;
@@ -366,6 +368,16 @@ impl Bindgen {
366368
.with_context(|_| format!("failed to write `{}`", path.display()))?;
367369
}
368370

371+
if cx.npm_dependencies.len() > 0 {
372+
let map = cx
373+
.npm_dependencies
374+
.iter()
375+
.map(|(k, v)| (k, &v.1))
376+
.collect::<BTreeMap<_, _>>();
377+
let json = serde_json::to_string_pretty(&map)?;
378+
fs::write(out_dir.join("package.json"), json)?;
379+
}
380+
369381
cx.finalize(stem)?
370382
};
371383

@@ -701,4 +713,11 @@ impl OutputMode {
701713
_ => false,
702714
}
703715
}
716+
717+
fn bundler(&self) -> bool {
718+
match self {
719+
OutputMode::Bundler => true,
720+
_ => false,
721+
}
722+
}
704723
}

crates/shared/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ macro_rules! shared_api {
1717
local_modules: Vec<LocalModule<'a>>,
1818
inline_js: Vec<&'a str>,
1919
unique_crate_identifier: &'a str,
20+
package_json: Option<&'a str>,
2021
}
2122

2223
struct Import<'a> {

0 commit comments

Comments
 (0)