Skip to main content

rust_anything/
package.rs

1//! Step 6: turn a gated port into packages end users install, the way maturin and
2//! `@napi-rs/cli` lay them out. Writes files only: it never builds for other platforms (the
3//! generated GitHub Actions workflow does) and never publishes.
4//!
5//! - PyO3: a self-contained maturin project (abi3 wheel, importable under the original's module
6//!   name) and a workflow that builds wheels for macOS, Linux (manylinux) and Windows.
7//! - napi-rs: a main npm package whose loader picks `<name>-<platform>` from its
8//!   `optionalDependencies` and falls back to the original JS, one package per platform holding
9//!   one `.node`, and a workflow that builds and packs them.
10//! - wasm-bindgen: one npm package with the built `pkg/`, the same on every platform.
11//! - A CLI front door (`rust/app`) of an npm CLI: a main package whose command runs this
12//!   platform's front door binary, with the original pinned as a dependency for every case the
13//!   port does not cover, and one package per platform holding the binary (`cli.rs`).
14
15use std::path::{Component, Path, PathBuf};
16
17use anyhow::{Context, Result, bail};
18use serde::{Deserialize, Serialize};
19use serde_json::json;
20
21use crate::bridge::{Kind, Manifest};
22
23mod cli;
24
25/// Written into the output folder; lists what the last run wrote, so a rerun replaces only that.
26pub const STAMP: &str = "rust-anything-package.json";
27const STAMP_SCHEMA: &str = "rust-anything/package@1";
28
29pub struct Options<'a> {
30    pub crate_dir: &'a Path,
31    /// Package name on npm or PyPI; defaults to the crate name.
32    pub name: Option<String>,
33    /// Package version; defaults to the original package's.
34    pub version: Option<String>,
35    /// Output folder; defaults to `<crate>/package`.
36    pub out: Option<PathBuf>,
37    /// List what would be written, write nothing.
38    pub dry_run: bool,
39    /// napi: the module the loader requires when no binary fits the platform.
40    pub fallback: Option<String>,
41    /// CLI: the commands the package installs; defaults to the package name without its scope.
42    pub bin: Vec<String>,
43    /// CLI: the original npm package the front door falls back to, as `name@version`; defaults
44    /// to the one in `node_modules` of the repository the front door belongs to.
45    pub original: Option<String>,
46}
47
48/// What a package folder holds.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "lowercase")]
51pub enum Layout {
52    Napi,
53    Wasm,
54    Pyo3,
55    /// A front door's binary per platform behind an npm command.
56    Cli,
57}
58
59impl From<Kind> for Layout {
60    fn from(kind: Kind) -> Self {
61        match kind {
62            Kind::Wasm => Layout::Wasm,
63            Kind::Pyo3 => Layout::Pyo3,
64            _ => Layout::Napi,
65        }
66    }
67}
68
69#[derive(Debug, Serialize)]
70pub struct Outcome {
71    pub kind: Layout,
72    pub name: String,
73    pub version: String,
74    pub out: PathBuf,
75    /// Python: the module the wheel installs (`import <module>`).
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub module: Option<String>,
78    /// napi: the platform packages, `<name>-<key>`.
79    #[serde(skip_serializing_if = "Vec::is_empty")]
80    pub platforms: Vec<String>,
81    /// CLI: the commands the package installs.
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub bin: Vec<String>,
84    /// CLI: the original the package depends on, `name@version`.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub original: Option<String>,
87    pub files: Vec<String>,
88    pub dry_run: bool,
89    pub notes: Vec<String>,
90}
91
92#[derive(Serialize, Deserialize)]
93struct Stamp {
94    schema: String,
95    kind: Layout,
96    name: String,
97    version: String,
98    files: Vec<String>,
99}
100
101enum Content {
102    Text(String),
103    Copy(PathBuf),
104}
105
106/// A platform a napi port ships a binary for: the npm key napi-rs uses, the Rust target, and
107/// the runner that builds it.
108pub struct Platform {
109    pub key: &'static str,
110    pub target: &'static str,
111    os: &'static str,
112    cpu: &'static str,
113    libc: Option<&'static str>,
114    runner: &'static str,
115    /// Whether the runner can load what it built (no cross-compiled check).
116    native: bool,
117}
118
119pub const PLATFORMS: &[Platform] = &[
120    Platform {
121        key: "darwin-arm64",
122        target: "aarch64-apple-darwin",
123        os: "darwin",
124        cpu: "arm64",
125        libc: None,
126        runner: "macos-latest",
127        native: true,
128    },
129    Platform {
130        key: "darwin-x64",
131        target: "x86_64-apple-darwin",
132        os: "darwin",
133        cpu: "x64",
134        libc: None,
135        runner: "macos-latest",
136        native: false,
137    },
138    Platform {
139        key: "linux-x64-gnu",
140        target: "x86_64-unknown-linux-gnu",
141        os: "linux",
142        cpu: "x64",
143        libc: Some("glibc"),
144        runner: "ubuntu-22.04",
145        native: true,
146    },
147    Platform {
148        key: "linux-arm64-gnu",
149        target: "aarch64-unknown-linux-gnu",
150        os: "linux",
151        cpu: "arm64",
152        libc: Some("glibc"),
153        runner: "ubuntu-22.04-arm",
154        native: true,
155    },
156    Platform {
157        key: "win32-x64-msvc",
158        target: "x86_64-pc-windows-msvc",
159        os: "win32",
160        cpu: "x64",
161        libc: None,
162        runner: "windows-latest",
163        native: true,
164    },
165];
166
167/// The napi key of the machine running rust-anything, if a package is built for it.
168pub fn host_key() -> Option<&'static str> {
169    let target = match (std::env::consts::OS, std::env::consts::ARCH) {
170        ("macos", "aarch64") => "aarch64-apple-darwin",
171        ("macos", "x86_64") => "x86_64-apple-darwin",
172        ("linux", "x86_64") if cfg!(target_env = "gnu") => "x86_64-unknown-linux-gnu",
173        ("linux", "aarch64") if cfg!(target_env = "gnu") => "aarch64-unknown-linux-gnu",
174        ("windows", "x86_64") if cfg!(target_env = "msvc") => "x86_64-pc-windows-msvc",
175        _ => return None,
176    };
177    PLATFORMS.iter().find(|p| p.target == target).map(|p| p.key)
178}
179
180pub fn package(opts: &Options) -> Result<Outcome> {
181    let crate_dir = std::path::absolute(opts.crate_dir)?;
182    if let Some(v) = &opts.version {
183        validate_version(v)?;
184    }
185    if cli::is_front_door(&crate_dir) {
186        return cli::package(&crate_dir, opts);
187    }
188    let manifest = Manifest::load(&crate_dir)?;
189    let out = match &opts.out {
190        Some(out) => std::path::absolute(out)?,
191        None => crate_dir.join("package"),
192    };
193    let name = match &opts.name {
194        Some(name) => name.clone(),
195        None => manifest.crate_name.clone(),
196    };
197    let mut notes = Vec::new();
198    let version = match &opts.version {
199        Some(v) => v.clone(),
200        None => original_version(&manifest).unwrap_or_else(|| {
201            let v = cargo_version(&crate_dir).unwrap_or_else(|| "0.1.0".into());
202            notes.push(format!(
203                "No version found in the original package; using {v}. Pass --version to set one."
204            ));
205            v
206        }),
207    };
208    let mut files: Vec<(String, Content)> = Vec::new();
209    let mut module = None;
210    let mut platforms = Vec::new();
211    match manifest.kind {
212        Kind::Pyo3 => {
213            let m = python_module(&manifest);
214            python_files(&crate_dir, &manifest, &name, &version, &m, &out, &mut files)?;
215            notes.push(format!(
216                "pip install {0} builds the wheel locally (maturin, from PyPI); `maturin build \
217                 --release` in {0} writes it to target/wheels. The wheel installs `import {m}`.",
218                out.display()
219            ));
220            module = Some(m);
221        }
222        Kind::Napi => {
223            validate_npm_name(&name)?;
224            platforms = PLATFORMS
225                .iter()
226                .map(|p| format!("{name}-{}", p.key))
227                .collect();
228            napi_files(
229                &crate_dir, &manifest, &name, &version, opts, &out, &mut files, &mut notes,
230            )?;
231        }
232        Kind::Wasm => {
233            validate_npm_name(&name)?;
234            wasm_files(&crate_dir, &manifest, &name, &version, &mut files)?;
235            notes.push(format!(
236                "npm pack {} gives one tarball that runs on every platform.",
237                out.display()
238            ));
239        }
240        Kind::CAbi | Kind::Ffi => {
241            let label = manifest
242                .kind
243                .label()
244                .trim_start_matches("a ")
245                .trim_start_matches("the ");
246            bail!(
247                "package covers napi-rs, wasm-bindgen and PyO3 crates; this one is a {} crate ({label})",
248                manifest.language.name()
249            );
250        }
251    }
252    if matches!(manifest.kind, Kind::Pyo3 | Kind::Napi) {
253        let (workflow, note) = workflow_file(&manifest, &name, &version, &crate_dir, &out)?;
254        files.push(workflow);
255        notes.push(note);
256    }
257    notes.push("Nothing was published.".into());
258    let listed: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();
259    if !opts.dry_run {
260        write(&out, manifest.kind.into(), &name, &version, files)?;
261    }
262    Ok(Outcome {
263        kind: manifest.kind.into(),
264        name,
265        version,
266        out,
267        module,
268        platforms,
269        bin: Vec::new(),
270        original: None,
271        files: listed,
272        dry_run: opts.dry_run,
273        notes,
274    })
275}
276
277fn write(
278    out: &Path,
279    kind: Layout,
280    name: &str,
281    version: &str,
282    files: Vec<(String, Content)>,
283) -> Result<()> {
284    let stamp_path = out.join(STAMP);
285    if stamp_path.exists() {
286        let text = std::fs::read_to_string(&stamp_path)?;
287        let old: Stamp = serde_json::from_str(&text)
288            .with_context(|| format!("parsing {}", stamp_path.display()))?;
289        for file in old.files {
290            let path = out.join(&file);
291            if safe_relative(&file) && path.is_file() {
292                std::fs::remove_file(&path)?;
293            }
294        }
295    } else if out.exists() && std::fs::read_dir(out)?.next().is_some() {
296        bail!(
297            "{} is not empty and was not written by `rust-anything package`; pass --out with an \
298             empty or new folder",
299            out.display()
300        );
301    }
302    for (path, content) in &files {
303        let target = out.join(path);
304        if let Some(parent) = target.parent() {
305            std::fs::create_dir_all(parent)?;
306        }
307        match content {
308            Content::Text(text) => std::fs::write(&target, text),
309            Content::Copy(from) => std::fs::copy(from, &target).map(|_| ()),
310        }
311        .with_context(|| format!("writing {}", target.display()))?;
312    }
313    let stamp = Stamp {
314        schema: STAMP_SCHEMA.into(),
315        kind,
316        name: name.into(),
317        version: version.into(),
318        files: files.into_iter().map(|(p, _)| p).collect(),
319    };
320    std::fs::write(&stamp_path, serde_json::to_string_pretty(&stamp)? + "\n")?;
321    Ok(())
322}
323
324fn safe_relative(path: &str) -> bool {
325    Path::new(path)
326        .components()
327        .all(|c| matches!(c, Component::Normal(_)))
328}
329
330fn validate_npm_name(name: &str) -> Result<()> {
331    // A scoped name is exactly `@scope/name`, and npm applies the `.`/`_` rule to each segment:
332    // `@x18n/.hidden`, `@x18n/_private`, `@x18n/fuzzy/extra`, `@x18n` and `@/fuzzy` are all
333    // refused at publish time, so they are refused here instead of in the generated package.
334    let (scope, bare) = match name.strip_prefix('@') {
335        Some(rest) => match rest.split_once('/') {
336            Some((scope, pkg)) => (Some(scope), pkg),
337            None => (None, ""),
338        },
339        None => (None, name),
340    };
341    let segment = |s: &str| !s.is_empty() && !s.starts_with(['.', '_']) && !s.contains(['/', '@']);
342    let ok = segment(bare)
343        && scope.is_none_or(segment)
344        && name.len() <= 214
345        && name.chars().all(|c| {
346            c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '.' | '_' | '@' | '/')
347        });
348    if !ok {
349        bail!("`{name}` is not a valid npm package name (lowercase, URL-safe); pass --name");
350    }
351    Ok(())
352}
353
354/// `MAJOR.MINOR.PATCH` with an optional `-prerelease`, as npm's semver takes it (and PyPI
355/// accepts): no whitespace, no leading zeros in a number.
356fn validate_version(version: &str) -> Result<()> {
357    let number = |s: &str| {
358        !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'))
359    };
360    let (core, pre) = match version.split_once('-') {
361        Some((core, pre)) => (core, Some(pre)),
362        None => (version, None),
363    };
364    let parts: Vec<&str> = core.split('.').collect();
365    let ok = parts.len() == 3
366        && parts.iter().all(|p| number(p))
367        && pre.is_none_or(|pre| {
368            pre.split('.').all(|id| {
369                !id.is_empty()
370                    && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
371                    && (!id.bytes().all(|b| b.is_ascii_digit()) || number(id))
372            })
373        });
374    if !ok {
375        bail!(
376            "`{version}` is not a valid package version (MAJOR.MINOR.PATCH, e.g. 1.2.0); pass --version"
377        );
378    }
379    Ok(())
380}
381
382/// The version of the package the unit belongs to: the nearest `package.json` for JS, the
383/// `pyproject.toml` (or `setup.cfg`, or `__version__`) for Python.
384pub fn original_version(manifest: &Manifest) -> Option<String> {
385    let root = &manifest.root;
386    let unit = root.join(manifest.unit.trim_end_matches('/'));
387    match manifest.language {
388        crate::lang::Lang::Python => python_version(root, &unit),
389        _ => {
390            let mut dir = unit.parent()?.to_path_buf();
391            loop {
392                let pkg = dir.join("package.json");
393                if let Ok(text) = std::fs::read_to_string(&pkg)
394                    && let Ok(value) = serde_json::from_str::<serde_json::Value>(&text)
395                    && let Some(v) = value["version"].as_str()
396                {
397                    return Some(v.to_string());
398                }
399                if dir == *root || !dir.pop() || !dir.starts_with(root) {
400                    return None;
401                }
402            }
403        }
404    }
405}
406
407fn python_version(root: &Path, unit: &Path) -> Option<String> {
408    if let Ok(text) = std::fs::read_to_string(root.join("pyproject.toml"))
409        && let Ok(doc) = text.parse::<toml_edit::DocumentMut>()
410    {
411        let v = doc
412            .get("project")
413            .and_then(|p| p.get("version"))
414            .or_else(|| {
415                doc.get("tool")
416                    .and_then(|t| t.get("poetry"))
417                    .and_then(|p| p.get("version"))
418            })
419            .and_then(|v| v.as_str());
420        if let Some(v) = v {
421            return Some(v.to_string());
422        }
423    }
424    if let Ok(text) = std::fs::read_to_string(root.join("setup.cfg")) {
425        let mut in_metadata = false;
426        for line in text.lines() {
427            let line = line.trim();
428            if line.starts_with('[') {
429                in_metadata = line == "[metadata]";
430            } else if in_metadata
431                && let Some((key, value)) = line.split_once('=')
432                && key.trim() == "version"
433                && !value.trim().starts_with("attr:")
434            {
435                return Some(value.trim().to_string());
436            }
437        }
438    }
439    let init = if unit.is_dir() {
440        unit.join("__init__.py")
441    } else {
442        unit.parent()?.join("__init__.py")
443    };
444    let text = std::fs::read_to_string(init).ok()?;
445    text.lines().find_map(|l| {
446        let rest = l.trim().strip_prefix("__version__")?.trim_start();
447        let rest = rest.strip_prefix('=')?.trim();
448        let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
449        rest[1..].split(quote).next().map(str::to_string)
450    })
451}
452
453fn cargo_version(crate_dir: &Path) -> Option<String> {
454    let text = std::fs::read_to_string(crate_dir.join("Cargo.toml")).ok()?;
455    let doc = text.parse::<toml_edit::DocumentMut>().ok()?;
456    Some(doc.get("package")?.get("version")?.as_str()?.to_string())
457}
458
459/// The dotted module the original unit is imported as: `src/textkit/` is `textkit`,
460/// `src/textkit/words.py` is `textkit.words`. Folders above count while they are packages
461/// (hold `__init__.py`); without the sources, a leading `src/` or `lib/` is dropped.
462pub fn python_module(manifest: &Manifest) -> String {
463    let unit = manifest.unit.trim_end_matches('/');
464    let unit = unit.strip_suffix("/__init__.py").unwrap_or(unit);
465    let unit = unit.strip_suffix(".py").unwrap_or(unit);
466    let parts: Vec<&str> = unit.split('/').filter(|p| !p.is_empty()).collect();
467    let root = &manifest.root;
468    let mut start = parts.len().saturating_sub(1);
469    if root.join(unit).exists() || root.join(format!("{unit}.py")).exists() {
470        while start > 0
471            && root
472                .join(parts[..start].join("/"))
473                .join("__init__.py")
474                .exists()
475        {
476            start -= 1;
477        }
478    } else {
479        start = usize::from(matches!(parts.first(), Some(&"src" | &"lib")) && parts.len() > 1);
480    }
481    parts[start..].join(".")
482}
483
484#[allow(clippy::too_many_arguments)]
485fn python_files(
486    crate_dir: &Path,
487    manifest: &Manifest,
488    name: &str,
489    version: &str,
490    module: &str,
491    out: &Path,
492    files: &mut Vec<(String, Content)>,
493) -> Result<()> {
494    if out.starts_with(crate_dir.join("src")) || out.starts_with(crate_dir.join("python")) {
495        bail!("--out cannot be inside the crate's src/ or python/ folder");
496    }
497    let (wrapper_dir, wrapper_name) = crate::harness_py::package(crate_dir, manifest);
498    let wrapper = wrapper_dir.join(&wrapper_name);
499    if !wrapper.join("__init__.py").exists() {
500        bail!(
501            "{} has no __init__.py; run `rust-anything refresh {}`",
502            wrapper.display(),
503            crate_dir.display()
504        );
505    }
506    let cargo =
507        std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
508    let mut doc: toml_edit::DocumentMut = cargo.parse().context("parsing Cargo.toml")?;
509    if !doc.contains_key("workspace") {
510        doc.insert("workspace", toml_edit::Item::Table(toml_edit::Table::new()));
511    }
512    files.push(("Cargo.toml".into(), Content::Text(doc.to_string())));
513    for extra in ["Cargo.lock", "build.rs"] {
514        if crate_dir.join(extra).exists() {
515            files.push((extra.into(), Content::Copy(crate_dir.join(extra))));
516        }
517    }
518    for file in tree(&crate_dir.join("src"))? {
519        files.push((
520            format!("src/{}", slash(&file)),
521            Content::Copy(crate_dir.join("src").join(&file)),
522        ));
523    }
524    let module_dir = format!("python/{}", module.replace('.', "/"));
525    for file in tree(&wrapper)? {
526        let file_name = file.file_name().unwrap_or_default().to_string_lossy();
527        if file_name.starts_with("_native.")
528            || file.components().any(|c| c.as_os_str() == "__pycache__")
529        {
530            continue;
531        }
532        files.push((
533            format!("{module_dir}/{}", slash(&file)),
534            Content::Copy(wrapper.join(&file)),
535        ));
536    }
537    files.push((
538        "pyproject.toml".into(),
539        Content::Text(pyproject(manifest, name, version, module)),
540    ));
541    files.push((
542        ".gitignore".into(),
543        Content::Text("target/\ndist/\n*.so\n*.pyd\n__pycache__/\n".into()),
544    ));
545    Ok(())
546}
547
548fn pyproject(manifest: &Manifest, name: &str, version: &str, module: &str) -> String {
549    format!(
550        "[build-system]\nrequires = [\"maturin>=1.7,<2\"]\nbuild-backend = \"maturin\"\n\n\
551         [project]\nname = \"{name}\"\nversion = \"{version}\"\n\
552         description = \"Rust port of `{unit}`, generated by rust-anything\"\n\
553         requires-python = \">=3.9\"\n\
554         classifiers = [\"Programming Language :: Rust\", \"Programming Language :: Python :: Implementation :: CPython\"]\n\n\
555         [tool.maturin]\nbindings = \"pyo3\"\nmodule-name = \"{module}._native\"\npython-source = \"python\"\n",
556        unit = manifest.unit
557    )
558}
559
560#[allow(clippy::too_many_arguments)]
561fn napi_files(
562    crate_dir: &Path,
563    manifest: &Manifest,
564    name: &str,
565    version: &str,
566    opts: &Options,
567    out: &Path,
568    files: &mut Vec<(String, Content)>,
569    notes: &mut Vec<String>,
570) -> Result<()> {
571    let lib = manifest.lib_name();
572    let index = std::fs::read_to_string(crate_dir.join("index.cjs")).with_context(|| {
573        format!(
574            "reading index.cjs (run `rust-anything refresh {}`)",
575            crate_dir.display()
576        )
577    })?;
578    let load = format!("require('./{lib}.node')");
579    if !index.contains(&load) {
580        bail!(
581            "index.cjs does not load `./{lib}.node`; run `rust-anything refresh {}` to regenerate it",
582            crate_dir.display()
583        );
584    }
585    files.push((
586        "binding.cjs".into(),
587        Content::Text(index.replacen(&load, "require('./native.cjs').load().binding", 1)),
588    ));
589    files.push(("native.cjs".into(), Content::Text(native_cjs(name, &lib))));
590
591    let mut shipped = vec!["index.cjs", "binding.cjs", "native.cjs"];
592    let fallback = match &opts.fallback {
593        Some(spec) => Some(spec.clone()),
594        None => match original_fallback(manifest) {
595            Ok((file, path)) => {
596                files.push((format!("fallback/{file}"), Content::Copy(path)));
597                shipped.push("fallback/");
598                Some(format!("./fallback/{file}"))
599            }
600            Err(why) => {
601                notes.push(format!(
602                    "No fallback: {why}. On a platform without a binary the package throws; pass \
603                     --fallback <module> (e.g. the original npm package) to load it instead."
604                ));
605                None
606            }
607        },
608    };
609    files.push((
610        "index.cjs".into(),
611        Content::Text(index_cjs(name, fallback.as_deref())),
612    ));
613
614    let mut optional = serde_json::Map::new();
615    for p in PLATFORMS {
616        let pkg = format!("{name}-{}", p.key);
617        optional.insert(pkg.clone(), json!(version));
618        let node = format!("{lib}.{}.node", p.key);
619        let mut platform = json!({
620            "name": pkg,
621            "version": version,
622            "description": format!("{} binary of {name}, generated by rust-anything", p.target),
623            "main": node,
624            "files": [node],
625            "os": [p.os],
626            "cpu": [p.cpu],
627        });
628        if let Some(libc) = p.libc {
629            platform["libc"] = json!([libc]);
630        }
631        files.push((
632            format!("npm/{}/package.json", p.key),
633            Content::Text(serde_json::to_string_pretty(&platform)? + "\n"),
634        ));
635    }
636    let main = json!({
637        "name": name,
638        "version": version,
639        "description": format!("Rust port of `{}`, generated by rust-anything", manifest.unit),
640        "main": "index.cjs",
641        "files": shipped,
642        "optionalDependencies": optional,
643    });
644    files.push((
645        "package.json".into(),
646        Content::Text(serde_json::to_string_pretty(&main)? + "\n"),
647    ));
648    files.push((
649        ".gitignore".into(),
650        Content::Text("target/\ntarballs/\nnpm-built/\n*.node\n*.tgz\n".into()),
651    ));
652
653    let built = crate_dir.join(format!("{lib}.node"));
654    match host_key() {
655        Some(key) if built.exists() => {
656            files.push((
657                format!("npm/{key}/{lib}.{key}.node"),
658                Content::Copy(built.clone()),
659            ));
660            if crate::harness::sources_newer_than(crate_dir, &built) {
661                notes.push(format!(
662                    "{} is older than the crate's sources; run `rust-anything build {}` and \
663                     package again",
664                    built.display(),
665                    crate_dir.display()
666                ));
667            }
668            notes.push(format!(
669                "This machine's binary is in npm/{key}/. To try it: npm pack {0}/npm/{key} and \
670                 npm pack {0}, then npm install both tarballs.",
671                out.display()
672            ));
673        }
674        Some(_) => notes.push(format!(
675            "No {lib}.node in the crate: run `rust-anything build {}` and package again to try \
676             the package on this machine.",
677            crate_dir.display()
678        )),
679        None => {}
680    }
681    Ok(())
682}
683
684/// The original unit as a file the package can ship and require: one JS file that imports
685/// nothing.
686fn original_fallback(manifest: &Manifest) -> Result<(String, PathBuf), String> {
687    let path = manifest.root.join(&manifest.unit);
688    if !path.is_file() {
689        return Err(format!(
690            "the original `{}` is not a single file in {}",
691            manifest.unit,
692            manifest.root.display()
693        ));
694    }
695    let file = path
696        .file_name()
697        .map(|f| f.to_string_lossy().to_string())
698        .unwrap_or_default();
699    if ["ts", "mts", "cts", "tsx"]
700        .iter()
701        .any(|e| file.ends_with(&format!(".{e}")))
702    {
703        return Err(format!(
704            "`{file}` is TypeScript, and Node does not strip types under node_modules"
705        ));
706    }
707    if !["js", "cjs", "mjs"]
708        .iter()
709        .any(|e| file.ends_with(&format!(".{e}")))
710    {
711        return Err(format!("`{file}` is not a JS file"));
712    }
713    let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
714    let imports = text.lines().any(|l| {
715        let l = l.trim_start();
716        l.starts_with("import ")
717            || l.starts_with("import{")
718            || (l.starts_with("export ") && l.contains(" from "))
719            || l.contains("require(")
720            || l.contains("import(")
721    });
722    if imports {
723        return Err(format!("`{file}` imports other modules"));
724    }
725    Ok((file, path))
726}
727
728fn index_cjs(name: &str, fallback: Option<&str>) -> String {
729    let otherwise = match fallback {
730        Some(spec) => format!("  module.exports = require({})\n", js_string(spec)),
731        None => format!(
732            "  throw new Error(\n    `{name} has no Rust build for ${{key}} (built for: ${{supported.join(', ')}})` +\n      (errors.length ? `:\\n${{errors.join('\\n')}}` : '')\n  )\n"
733        ),
734    };
735    format!(
736        "'use strict'\n// Generated by `rust-anything package`: the Rust port for this platform, or the original.\n\
737         const {{ load, supported }} = require('./native.cjs')\nconst {{ binding, key, errors }} = load()\n\
738         if (binding && process.env.RUST_ANYTHING_MODE !== 'old') {{\n  module.exports = require('./binding.cjs')\n}} else {{\n{otherwise}}}\n"
739    )
740}
741
742fn native_cjs(name: &str, lib: &str) -> String {
743    let keys: Vec<String> = PLATFORMS.iter().map(|p| format!("'{}'", p.key)).collect();
744    format!(
745        r#"'use strict'
746// Generated by `rust-anything package`: finds the binary for this platform.
747const {{ platform, arch }} = process
748
749function abi() {{
750  if (platform === 'win32') return '-msvc'
751  if (platform !== 'linux') return ''
752  try {{
753    return process.report.getReport().header.glibcVersionRuntime ? '-gnu' : '-musl'
754  }} catch {{
755    return '-gnu'
756  }}
757}}
758
759const key = `${{platform}}-${{arch}}${{abi()}}`
760const supported = [{keys}]
761let loaded = null
762
763function load() {{
764  if (loaded) return loaded
765  const errors = []
766  let binding = null
767  if (supported.includes(key)) {{
768    for (const id of [`./npm/${{key}}/{lib}.${{key}}.node`, `{name}-${{key}}`]) {{
769      try {{
770        binding = require(id)
771        break
772      }} catch (e) {{
773        errors.push(`${{id}}: ${{e.message.split('\n')[0]}}`)
774      }}
775    }}
776  }}
777  loaded = {{ binding, key, errors }}
778  return loaded
779}}
780
781module.exports = {{ load, key, supported }}
782"#,
783        keys = keys.join(", ")
784    )
785}
786
787fn js_string(s: &str) -> String {
788    serde_json::to_string(s).unwrap_or_else(|_| "''".into())
789}
790
791fn wasm_files(
792    crate_dir: &Path,
793    manifest: &Manifest,
794    name: &str,
795    version: &str,
796    files: &mut Vec<(String, Content)>,
797) -> Result<()> {
798    let pkg = crate_dir.join("pkg");
799    let lib = manifest.lib_name();
800    if !pkg.join(format!("{lib}.js")).exists() {
801        bail!(
802            "no wasm build in {}; run `rust-anything build {}` first",
803            pkg.display(),
804            crate_dir.display()
805        );
806    }
807    files.push((
808        "index.cjs".into(),
809        Content::Copy(crate_dir.join("index.cjs")),
810    ));
811    for file in tree(&pkg)? {
812        let file_name = file.file_name().unwrap_or_default().to_string_lossy();
813        if file_name == ".gitignore" || file_name == "package.json" {
814            continue;
815        }
816        files.push((
817            format!("pkg/{}", slash(&file)),
818            Content::Copy(pkg.join(&file)),
819        ));
820    }
821    let main = json!({
822        "name": name,
823        "version": version,
824        "description": format!("Rust port of `{}` (WebAssembly), generated by rust-anything", manifest.unit),
825        "main": "index.cjs",
826        "types": format!("pkg/{lib}.d.ts"),
827        "files": ["index.cjs", "pkg/"],
828    });
829    files.push((
830        "package.json".into(),
831        Content::Text(serde_json::to_string_pretty(&main)? + "\n"),
832    ));
833    Ok(())
834}
835
836/// The GitHub Actions workflow, written inside the output folder; GitHub runs workflows only
837/// from the repository's `.github/workflows`, so the note says where to move it.
838fn workflow_file(
839    manifest: &Manifest,
840    name: &str,
841    version: &str,
842    crate_dir: &Path,
843    out: &Path,
844) -> Result<((String, Content), String)> {
845    let repo = git_root(out);
846    let out_rel = repo
847        .as_deref()
848        .and_then(|r| relative(r, out))
849        .unwrap_or_else(|| ".".into());
850    let slug: String = name
851        .trim_start_matches('@')
852        .chars()
853        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
854        .collect();
855    let (file, text) = match manifest.kind {
856        Kind::Pyo3 => (
857            format!("{slug}-wheels.yml"),
858            wheels_yml(name, version, &python_module(manifest), &out_rel),
859        ),
860        _ => {
861            let crate_rel = relative(out, crate_dir).context("relating the crate to --out")?;
862            (
863                format!("{slug}-npm.yml"),
864                npm_yml(name, version, &manifest.lib_name(), &out_rel, &crate_rel),
865            )
866        }
867    };
868    let path = format!(".github/workflows/{file}");
869    let note = match &repo {
870        Some(repo) => format!(
871            "CI: move {path} to {}/.github/workflows/ (GitHub runs workflows only from there); it \
872             builds every platform and uploads the packages as artifacts.",
873            repo.display()
874        ),
875        None => format!(
876            "CI: {path} assumes {} is the repository root; move it to the repository's \
877             .github/workflows/ and set `working-directory` to this folder.",
878            out.display()
879        ),
880    };
881    Ok(((path, Content::Text(text)), note))
882}
883
884fn wheels_yml(name: &str, version: &str, module: &str, dir: &str) -> String {
885    format!(
886        r#"# Generated by `rust-anything package`: abi3 wheels of {name} {version} (one per platform,
887# every CPython from 3.9 on) and an sdist, uploaded as artifacts. Nothing is published.
888name: {name} wheels
889
890on:
891  workflow_dispatch:
892  push:
893    tags: ['v*']
894
895defaults:
896  run:
897    shell: bash
898    working-directory: {dir}
899
900jobs:
901  wheels:
902    name: ${{{{ matrix.target }}}}
903    runs-on: ${{{{ matrix.os }}}}
904    strategy:
905      fail-fast: false
906      matrix:
907        include:
908          - {{ os: macos-latest, target: aarch64-apple-darwin, check: true }}
909          - {{ os: macos-latest, target: x86_64-apple-darwin, check: false }}
910          - {{ os: ubuntu-latest, target: x86_64-unknown-linux-gnu, check: true }}
911          - {{ os: ubuntu-latest, target: aarch64-unknown-linux-gnu, check: false }}
912          - {{ os: windows-latest, target: x86_64-pc-windows-msvc, check: true }}
913    steps:
914      - uses: actions/checkout@v4
915      - uses: actions/setup-python@v5
916        with:
917          python-version: '3.12'
918      - uses: PyO3/maturin-action@v1
919        with:
920          target: ${{{{ matrix.target }}}}
921          manylinux: auto
922          args: --release --out dist
923          working-directory: {dir}
924      - name: Import check
925        if: matrix.check
926        run: |
927          python -m pip install {name} --no-index --find-links dist --force-reinstall
928          python -c "import {module}"
929      - uses: actions/upload-artifact@v4
930        with:
931          name: wheel-${{{{ matrix.target }}}}
932          path: {dir}/dist
933
934  sdist:
935    runs-on: ubuntu-latest
936    steps:
937      - uses: actions/checkout@v4
938      - uses: PyO3/maturin-action@v1
939        with:
940          command: sdist
941          args: --out dist
942          working-directory: {dir}
943      - uses: actions/upload-artifact@v4
944        with:
945          name: sdist
946          path: {dir}/dist
947"#
948    )
949}
950
951fn npm_yml(name: &str, version: &str, lib: &str, dir: &str, crate_rel: &str) -> String {
952    let matrix: String = PLATFORMS
953        .iter()
954        .map(|p| {
955            let file = match p.os {
956                "darwin" => format!("lib{lib}.dylib"),
957                "linux" => format!("lib{lib}.so"),
958                _ => format!("{lib}.dll"),
959            };
960            format!(
961                "          - {{ key: {}, target: {}, os: {}, lib: {file}, check: {} }}\n",
962                p.key, p.target, p.runner, p.native
963            )
964        })
965        .collect();
966    format!(
967        r#"# Generated by `rust-anything package`: the {name} {version} npm packages (one per
968# platform, plus the main one), packed and uploaded as artifacts. Nothing is published.
969name: {name} npm packages
970
971on:
972  workflow_dispatch:
973  push:
974    tags: ['v*']
975
976defaults:
977  run:
978    shell: bash
979    working-directory: {dir}
980
981jobs:
982  build:
983    name: ${{{{ matrix.key }}}}
984    runs-on: ${{{{ matrix.os }}}}
985    strategy:
986      fail-fast: false
987      matrix:
988        include:
989{matrix}    steps:
990      - uses: actions/checkout@v4
991      - uses: actions/setup-node@v4
992        with:
993          node-version: 22
994      - run: rustup target add ${{{{ matrix.target }}}}
995      - run: cargo build --release --target ${{{{ matrix.target }}}} --manifest-path {crate_rel}/Cargo.toml --target-dir target
996      - run: cp target/${{{{ matrix.target }}}}/release/${{{{ matrix.lib }}}} npm/${{{{ matrix.key }}}}/{lib}.${{{{ matrix.key }}}}.node
997      - name: Load check
998        if: matrix.check
999        run: node -e "const r = require('./native.cjs').load(); if (!r.binding) throw new Error(r.errors.join('\n'))"
1000      - uses: actions/upload-artifact@v4
1001        with:
1002          name: npm-${{{{ matrix.key }}}}
1003          path: {dir}/npm/${{{{ matrix.key }}}}/*.node
1004
1005  pack:
1006    needs: build
1007    runs-on: ubuntu-latest
1008    steps:
1009      - uses: actions/checkout@v4
1010      - uses: actions/setup-node@v4
1011        with:
1012          node-version: 22
1013      - uses: actions/download-artifact@v4
1014        with:
1015          pattern: npm-*
1016          path: {dir}/npm-built
1017      - run: |
1018          for built in npm-built/npm-*; do cp "$built"/*.node "npm/${{built##*/npm-}}/"; done
1019          mkdir -p tarballs
1020          for platform in npm/*/; do npm pack "./$platform" --pack-destination tarballs; done
1021          npm pack --pack-destination tarballs
1022      - uses: actions/upload-artifact@v4
1023        with:
1024          name: npm-tarballs
1025          path: {dir}/tarballs
1026"#
1027    )
1028}
1029
1030fn git_root(from: &Path) -> Option<PathBuf> {
1031    let mut dir = from.to_path_buf();
1032    loop {
1033        if dir.join(".git").exists() {
1034            return Some(dir);
1035        }
1036        if !dir.pop() {
1037            return None;
1038        }
1039    }
1040}
1041
1042/// `to` relative to `from`, with `/` separators; `.` when they are the same folder.
1043fn relative(from: &Path, to: &Path) -> Option<String> {
1044    let from: Vec<Component> = from.components().collect();
1045    let to: Vec<Component> = to.components().collect();
1046    if from.first() != to.first() {
1047        return None;
1048    }
1049    let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
1050    let mut parts: Vec<String> = vec!["..".into(); from.len() - common];
1051    parts.extend(
1052        to[common..]
1053            .iter()
1054            .map(|c| c.as_os_str().to_string_lossy().to_string()),
1055    );
1056    Some(if parts.is_empty() {
1057        ".".into()
1058    } else {
1059        parts.join("/")
1060    })
1061}
1062
1063/// Every file under `dir`, relative to it, sorted.
1064fn tree(dir: &Path) -> Result<Vec<PathBuf>> {
1065    let mut out = Vec::new();
1066    let mut stack = vec![PathBuf::new()];
1067    while let Some(rel) = stack.pop() {
1068        let entries = std::fs::read_dir(dir.join(&rel))
1069            .with_context(|| format!("reading {}", dir.display()))?;
1070        for entry in entries {
1071            let entry = entry?;
1072            let path = rel.join(entry.file_name());
1073            if entry.file_type()?.is_dir() {
1074                stack.push(path);
1075            } else {
1076                out.push(path);
1077            }
1078        }
1079    }
1080    out.sort();
1081    Ok(out)
1082}
1083
1084fn slash(path: &Path) -> String {
1085    path.components()
1086        .map(|c| c.as_os_str().to_string_lossy())
1087        .collect::<Vec<_>>()
1088        .join("/")
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use super::*;
1094
1095    #[test]
1096    fn relative_paths() {
1097        assert_eq!(
1098            relative(Path::new("/r/a/package"), Path::new("/r/a")).as_deref(),
1099            Some("..")
1100        );
1101        assert_eq!(
1102            relative(Path::new("/r"), Path::new("/r/rust/x/package")).as_deref(),
1103            Some("rust/x/package")
1104        );
1105        assert_eq!(
1106            relative(Path::new("/r"), Path::new("/r")).as_deref(),
1107            Some(".")
1108        );
1109    }
1110
1111    #[test]
1112    fn npm_names() {
1113        assert!(validate_npm_name("fuzzy-rs").is_ok());
1114        assert!(validate_npm_name("@x18n/fuzzy").is_ok());
1115        assert!(validate_npm_name("Fuzzy").is_err());
1116        assert!(validate_npm_name("@x18n/").is_err());
1117        // npm applies the `.`/`_` rule to each segment, and a scope is `@scope/name` exactly.
1118        assert!(validate_npm_name("@x18n/.hidden").is_err());
1119        assert!(validate_npm_name("@x18n/_private").is_err());
1120        assert!(validate_npm_name("@x18n/fuzzy/extra").is_err());
1121        assert!(validate_npm_name("@x18n").is_err());
1122        assert!(validate_npm_name("@/fuzzy").is_err());
1123        assert!(validate_npm_name("fuzzy/extra").is_err());
1124        assert!(validate_npm_name("fuzzy@1").is_err());
1125        assert!(validate_npm_name("@x18n/fuzzy@1").is_err());
1126    }
1127
1128    #[test]
1129    fn package_versions() {
1130        for ok in ["1.2.3", "0.1.0", "1.2.3-beta.1", "10.0.0-rc-1", "1.0.0-0"] {
1131            assert!(validate_version(ok).is_ok(), "{ok}");
1132        }
1133        for bad in [
1134            "",
1135            "bogus",
1136            "1.0",
1137            " 1.0.0",
1138            "1.0.0 ",
1139            "1.2.3.4",
1140            "01.2.3",
1141            "1.2.3-",
1142            "1.2.3-beta..1",
1143            "1.2.3-01",
1144            "v1.2.3",
1145        ] {
1146            assert!(validate_version(bad).is_err(), "{bad:?}");
1147        }
1148    }
1149
1150    #[test]
1151    fn every_platform_has_a_unique_key() {
1152        let mut keys: Vec<&str> = PLATFORMS.iter().map(|p| p.key).collect();
1153        keys.sort_unstable();
1154        keys.dedup();
1155        assert_eq!(keys.len(), PLATFORMS.len());
1156    }
1157
1158    #[test]
1159    fn stamp_paths_stay_inside() {
1160        assert!(safe_relative("npm/darwin-arm64/package.json"));
1161        assert!(!safe_relative("../x"));
1162        assert!(!safe_relative("/etc/passwd"));
1163    }
1164}