A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: include local wheels in WASM exports (#10071)
Péter Gyarmati53e7962bb028
diff --git a/docs/guides/exporting/webassembly_html.md b/docs/guides/exporting/webassembly_html.mdindex 0a6b7368d8..a340f79e0a 100644--- a/docs/guides/exporting/webassembly_html.md+++ b/docs/guides/exporting/webassembly_html.md@@ -58,6 +58,59 @@ exclude native-only dependencies from WASM installs.npx wrangler deploy```+## Including local modules and wheels++`marimo export html-wasm` includes Python modules imported by your notebook+when they resolve to local files. For example, if `notebook.py` imports `foo`+and `foo.py` lives in the same directory, marimo builds a pure-Python wheel for+`foo.py`, copies it to `public/wheels` in the export directory, and installs+the wheel when the notebook starts in the browser.++```text+notebooks/+|-- notebook.py+`-- foo.py+```++```python title="notebooks/notebook.py"+import foo+```++```bash+marimo export html-wasm notebooks/notebook.py -o output_dir+```++Package imports keep their package layout. A local `foo.py` is written into the+wheel as top-level `foo.py`, while a local package such as `helpers/__init__.py`+stays under `helpers/`. If a local module imports another local module, the+imported file is included in the export too.++Local module resolution requires [`uv`](https://docs.astral.sh/uv/). Install it+with `pip install "marimo[sandbox]"` or use the+[uv installation guide](https://docs.astral.sh/uv/getting-started/installation/).++For local modules outside the notebook directory, configure+[`pythonpath`](../configuration/runtime_configuration.md#python-path) so marimo+can resolve the import.++If you already build a local wheel, reference it from the notebook's+[inline script metadata](../package_management/inlining_dependencies.md):++```python+# /// script+# dependencies = ["my-package"]+# [tool.uv.sources]+# my-package = { path = "dist/my_package-0.1.0-py3-none-any.whl" }+# ///+```++During export, marimo copies the referenced wheel to `public/wheels` and+rewrites the browser metadata to install that hosted wheel URL.++Local modules and wheels run in Pyodide at browser startup. Imported+third-party packages must be available in Pyodide or installable from a+WASM-compatible wheel.+## Testing the exportYou can test the export by running the following command in the directory containing your notebook:diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex e5f122e51a..961d37d4ac 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -5,6 +5,7 @@ import asyncioimport osimport sysfrom dataclasses import replace+from functools import partialfrom pathlib import Pathfrom typing import TYPE_CHECKING, Literal@@ -12,6 +13,19 @@ import clickfrom marimo._cli.errors import MarimoCLIMissingDependencyErrorfrom marimo._cli.export.cloudflare import create_cloudflare_files+from marimo._cli.export.local_modules import (+ LocalWheelError,+ resolve_notebook_local_modules,+)+from marimo._cli.export.local_wheels import (+ WASM_WHEEL_DIR,+ auto_wheel_dependencies,+ build_local_module_wheels,+ copy_local_wheels,+ resolve_metadata_wheel_dependencies,+ wheel_dependency_names,+ with_wheel_dependencies,+)from marimo._cli.export.session import sessionfrom marimo._cli.export.thumbnail import thumbnailfrom marimo._cli.help_formatter import ColoredCommand, ColoredGroup@@ -52,9 +66,16 @@ from marimo._utils.paths import maybe_make_dirsif TYPE_CHECKING:from collections.abc import Callable+ from typing import Protocolfrom marimo._convert.markdown.flavor.base import MarkdownFlavorName+ class _ExportWithCodeTransform(Protocol):+ def __call__(+ self, *, code_transform: Callable[[str], str]+ ) -> ExportResult: ...++_watch_message = ("Watch notebook for changes and regenerate the output on modification. ""If watchdog is installed, it will be used to watch the file. "@@ -983,6 +1004,42 @@ def html_wasm(marimo_file = MarimoPath(name)+ def export_with_local_wheels(+ file_path: MarimoPath,+ export_callback: _ExportWithCodeTransform,+ ) -> ExportResult:+ """Export with notebook-local wheels injected into PEP 723 metadata."""+ metadata_wheels = resolve_metadata_wheel_dependencies(file_path)+ metadata_wheel_names = wheel_dependency_names(metadata_wheels)+ modules = tuple(+ resolve_notebook_local_modules(+ file_path.absolute_name,+ exclude_names=metadata_wheel_names,+ )+ )+ try:+ with build_local_module_wheels(modules) as local_wheels:+ wheel_dependencies = (+ *metadata_wheels,+ *auto_wheel_dependencies(local_wheels),+ )+ result = export_callback(+ code_transform=partial(+ with_wheel_dependencies,+ wheel_dependencies=wheel_dependencies,+ )+ )+ copy_local_wheels(+ out_dir,+ tuple(+ dependency.path for dependency in wheel_dependencies+ ),+ source_wheel_dir=file_path.path.parent / WASM_WHEEL_DIR,+ )+ return result+ except LocalWheelError as error:+ raise click.UsageError(str(error)) from error+if execute:cli_args = parse_args(args)@@ -996,7 +1053,11 @@ def html_wasm(pipe=lambda msg: echo(msg, err=True),)- def export_callback(file_path: MarimoPath) -> ExportResult:+ def export_executed_wasm(+ file_path: MarimoPath,+ *,+ code_transform: Callable[[str], str],+ ) -> ExportResult:return asyncio_run(run_app_then_export_as_wasm(file_path,@@ -1005,14 +1066,29 @@ def html_wasm(cli_args=cli_args,argv=list(args),cache_export_dir=out_dir,+ code_transform=code_transform,))+ def export_callback(file_path: MarimoPath) -> ExportResult:+ return export_with_local_wheels(+ file_path,+ partial(export_executed_wasm, file_path),+ )+echo("Executing notebook...")else:def export_callback(file_path: MarimoPath) -> ExportResult:- return export_as_wasm(file_path, mode, show_code=show_code)+ return export_with_local_wheels(+ file_path,+ partial(+ export_as_wasm,+ file_path,+ mode,+ show_code=show_code,+ ),+ )# Export assets firstExporter().export_assets(out_dir)@@ -1045,7 +1121,13 @@ def html_wasm(outfile = out_dir / filename# NB. with --execute, the callback also bundles session caches into the# export's public/cache/.- watch_and_export(MarimoPath(name), outfile, watch, export_callback, force)+ return watch_and_export(+ MarimoPath(name),+ outfile,+ watch,+ export_callback,+ force,+ )export.add_command(html)diff --git a/marimo/_cli/export/local_modules.py b/marimo/_cli/export/local_modules.pynew file mode 100644index 0000000000..e3c0901fae--- /dev/null+++ b/marimo/_cli/export/local_modules.py@@ -0,0 +1,317 @@+# Copyright 2026 Marimo. All rights reserved.+"""Resolve notebook-local Python imports from Ruff's import graph.++Ruff reports file-to-file dependencies for the notebook directory plus+configured import roots. marimo keeps the html-wasm specific step: filter those+dependencies to local Python files and group them into wheel-shaped modules:++ import foo -> foo.py or foo/__init__.py+ from foo import bar -> foo.py or package files under foo/++If notebook.py imports foo.py and foo.py imports bar.py from the same root, the+Ruff graph links both files and both are returned for export.++`LocalModuleKind` records the source layout the wheel builder must preserve. A+`module` is a single-file import such as `foo.py`, which becomes top-level+`foo.py` in the wheel. A `package` is a directory-backed import such as+`foo/__init__.py` or `foo/bar.py`, which keeps files under `foo/` in the wheel.+"""++from __future__ import annotations++import json+import re+import subprocess+import sys+from dataclasses import dataclass+from operator import attrgetter+from pathlib import Path+from typing import TYPE_CHECKING, Literal++from marimo._cli.errors import MarimoCLIMissingDependencyError+from marimo._dependencies.dependencies import DependencyManager+from marimo._utils.uv import find_uv_bin++if TYPE_CHECKING:+ from collections.abc import Collection, Mapping, Sequence++LocalModuleKind = Literal["module", "package"]+_RUFF_REQUIREMENT = "ruff==0.15.18"+_RUFF_GRAPH_TIMEOUT_SECONDS = 120+++class LocalWheelError(Exception):+ pass+++@dataclass(frozen=True)+class LocalModule:+ name: str+ path: Path+ kind: LocalModuleKind+ root: Path | None = None+ files: tuple[Path, ...] = ()+++def resolve_local_modules(+ notebook: Path,+ roots: Sequence[Path] | None = None,+ exclude_names: Collection[str] | None = None,+) -> tuple[LocalModule, ...]:+ """Return local modules reached from the notebook's imports.++ For example, if notebook.py imports foo.py and foo.py imports bar.py from+ the same import root, this returns entries for both foo.py and bar.py so+ both files can be packaged into the html-wasm export.+ """+ notebook_path = notebook.absolute().resolve()+ import_roots = _import_roots(notebook_path, roots)+ excluded_names = {_canonical_name(name) for name in exclude_names or ()}+ graph = _ruff_import_graph(+ (notebook_path, *import_roots), import_roots, notebook_path+ )+ pending = [notebook_path]+ scanned: set[Path] = set()+ modules: dict[tuple[str, Path], LocalModule] = {}+ module_files: dict[tuple[str, Path], set[Path]] = {}++ while pending:+ path = pending.pop().resolve()+ if path in scanned:+ continue+ scanned.add(path)++ for dependency in graph.get(path, ()):+ module = _local_module_from_path(dependency, import_roots)+ if module is None:+ continue+ if (+ module.path == notebook_path+ or _canonical_name(module.name) in excluded_names+ ):+ continue+ key = (module.name, module.path)+ modules.setdefault(key, module)+ module_files.setdefault(key, set()).update(+ _module_files_for_dependency(module, dependency)+ )+ if dependency not in scanned:+ pending.append(dependency)++ return tuple(+ sorted(+ (+ LocalModule(+ module.name,+ module.path,+ module.kind,+ module.root,+ tuple(sorted(module_files.get(key, ()))),+ )+ for key, module in modules.items()+ ),+ key=attrgetter("name", "path"),+ )+ )+++def resolve_notebook_local_modules(+ name: str, *, exclude_names: Collection[str] | None = None+) -> tuple[LocalModule, ...]:+ """Resolve local modules with the notebook's configured import roots."""+ from marimo._config.manager import get_default_config_manager+ from marimo._utils.marimo_path import MarimoPath++ marimo_path = MarimoPath(name)+ if not marimo_path.is_python():+ return ()++ config = get_default_config_manager(+ current_path=marimo_path.absolute_name+ ).get_config()+ pythonpath = config["runtime"].get("pythonpath") or []+ roots = tuple(reversed([Path(path) for path in pythonpath]))+ return resolve_local_modules(+ marimo_path.path, roots=roots, exclude_names=exclude_names+ )+++def module_python_files(module: LocalModule) -> tuple[Path, ...]:+ """Return the Python files that should be written into a local wheel."""+ if module.kind == "module":+ return (module.path,)+ if module.files:+ return module.files+ init = module.path / "__init__.py"+ return (init.resolve(),) if init.is_file() else ()+++def _canonical_name(name: str) -> str:+ return re.sub(r"[-_.]+", "-", name).lower()+++def _import_roots(+ notebook: Path, roots: Sequence[Path] | None+) -> tuple[Path, ...]:+ import_roots: list[Path] = []+ seen: set[Path] = set()+ for root in (notebook.parent, *(roots or ())):+ resolved = root.resolve()+ if resolved in seen:+ continue+ seen.add(resolved)+ import_roots.append(resolved)+ return tuple(import_roots)+++def _ruff_import_graph(+ files: Sequence[Path], roots: Sequence[Path], notebook: Path+) -> Mapping[Path, tuple[Path, ...]]:+ """Return Ruff's direct import graph for the files being scanned."""+ if not files:+ return {}++ command = _ruff_graph_command(files, roots)+ try:+ result = subprocess.run(+ command,+ cwd=notebook.parent,+ capture_output=True,+ text=True,+ timeout=_RUFF_GRAPH_TIMEOUT_SECONDS,+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired) as error:+ raise LocalWheelError(+ "Failed to run uv while resolving local imports for "+ "html-wasm export."+ ) from error++ if result.returncode != 0:+ detail = result.stderr.strip() or result.stdout.strip()+ raise LocalWheelError(+ "Failed to analyze local imports with Ruff"+ + (f": {detail}" if detail else ".")+ )++ try:+ raw_graph = json.loads(result.stdout or "{}")+ except json.JSONDecodeError as error:+ raise LocalWheelError(+ "Ruff returned invalid import graph output."+ ) from error+ if not isinstance(raw_graph, dict):+ raise LocalWheelError("Ruff returned invalid import graph output.")++ graph: dict[Path, tuple[Path, ...]] = {}+ for source, dependencies in raw_graph.items():+ if not isinstance(source, str) or not isinstance(dependencies, list):+ raise LocalWheelError("Ruff returned invalid import graph output.")+ graph[_graph_path(source, notebook)] = tuple(+ _graph_path(dependency, notebook)+ for dependency in dependencies+ if isinstance(dependency, str)+ )+ return graph+++def _ruff_graph_command(+ files: Sequence[Path], roots: Sequence[Path]+) -> tuple[str, ...]:+ return (+ _uv_bin(),+ "--quiet",+ "--no-progress",+ "tool",+ "run",+ "--from",+ _RUFF_REQUIREMENT,+ "--python",+ sys.executable,+ "--no-python-downloads",+ "ruff",+ "analyze",+ "graph",+ "--preview",+ "--isolated",+ "--config",+ _ruff_src_config(roots),+ *(str(path) for path in files),+ )+++def _uv_bin() -> str:+ uv_bin = find_uv_bin()+ if uv_bin == "uv" and not DependencyManager.which("uv"):+ raise MarimoCLIMissingDependencyError(+ "uv must be installed to resolve local imports for "+ "html-wasm export.",+ "uv",+ additional_tip="Install uv from https://github.com/astral-sh/uv",+ )+ return uv_bin+++def _ruff_src_config(roots: Sequence[Path]) -> str:+ return "src = [" + ", ".join(json.dumps(str(root)) for root in roots) + "]"+++def _graph_path(path: str, notebook: Path) -> Path:+ graph_path = Path(path)+ if not graph_path.is_absolute():+ graph_path = notebook.parent / graph_path+ return graph_path.resolve()+++def _local_module_from_path(+ path: Path, roots: Sequence[Path]+) -> LocalModule | None:+ if path.suffix != ".py":+ return None+ path = path.resolve()+ for root in roots:+ try:+ relative = path.relative_to(root)+ except ValueError:+ continue+ if not relative.parts:+ continue+ if len(relative.parts) == 1:+ return LocalModule(relative.stem, path, "module", root)+ package_dir = (root / relative.parts[0]).resolve()+ if package_dir.is_dir():+ return LocalModule(relative.parts[0], package_dir, "package", root)+ return None+++def _module_files_for_dependency(+ module: LocalModule, dependency: Path+) -> tuple[Path, ...]:+ if module.kind == "module":+ return (module.path,)++ files: list[Path] = []+ seen: set[Path] = set()++ def add(path: Path) -> None:+ resolved = path.resolve()+ if resolved not in seen:+ seen.add(resolved)+ files.append(resolved)++ current = module.path+ init = current / "__init__.py"+ if init.is_file():+ add(init)+ try:+ relative = dependency.resolve().relative_to(module.path)+ except ValueError:+ return tuple(files)+ for part in relative.parts[:-1]:+ current = current / part+ init = current / "__init__.py"+ if init.is_file():+ add(init)+ if dependency.is_file():+ add(dependency)+ return tuple(files)diff --git a/marimo/_cli/export/local_wheels.py b/marimo/_cli/export/local_wheels.pynew file mode 100644index 0000000000..b6999c7260--- /dev/null+++ b/marimo/_cli/export/local_wheels.py@@ -0,0 +1,464 @@+# Copyright 2026 Marimo. All rights reserved.+"""Create hosted wheel dependencies for html-wasm exports.++The export pipeline needs browser-installable requirements. This module turns+two local inputs into that shape:++* PEP 723 local wheel references, such as `pkg @ ./dist/pkg.whl`.+* `LocalModule` values resolved from notebook imports.++Referenced wheels are copied into `public/wheels`. Resolved modules are written+as deterministic pure-Python wheels in a temporary directory. A `module` keeps+the user's single-file layout as top-level `foo.py`. A `package` keeps its+package files under `foo/`. The notebook metadata is then rewritten to+`name @ ../public/wheels/<wheel>.whl` so Pyodide can install the files with+micropip during worker startup.+"""++from __future__ import annotations++import base64+import csv+import hashlib+import io+import re+import shutil+import tempfile+import zipfile+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING+from urllib.parse import quote, unquote, urlparse+from urllib.request import url2pathname++from marimo._cli.export.local_modules import (+ LocalModule,+ LocalWheelError,+ module_python_files,+)+from marimo._utils.inline_script_metadata import PyProjectReader+from marimo._utils.scripts import (+ REGEX,+ read_pyproject_from_script,+ write_pyproject_to_script,+)++if TYPE_CHECKING:+ from collections.abc import Iterator, Sequence++ from marimo._utils.marimo_path import MarimoPath++WASM_WHEEL_DIR = "public/wheels"+WASM_WHEEL_URL_PREFIX = "../public/wheels"+_DIST_INFO_TIMESTAMP = (1980, 1, 1, 0, 0, 0)+_AUTO_WHEEL_VERSION_MARKER = "-0.0.0+marimo."+_DIRECT_REF_RE = re.compile(+ r"^\s*(?P<name>[A-Za-z0-9][A-Za-z0-9._-]*(?:\[[^\]]+\])?)"+ r"\s*@\s*(?P<url>.+?)(?:\s*;\s*(?P<marker>.+))?\s*$"+)+_VALID_METADATA_NAME_RE = re.compile(r"^[a-z0-9]+(?:[._-][a-z0-9]+)*$")+++@dataclass(frozen=True)+class _WheelDependency:+ name: str+ path: Path+ marker: str | None = None+++def copy_local_wheels(+ out_dir: Path,+ wheel_paths: Sequence[Path],+ *,+ source_wheel_dir: Path | None = None,+) -> None:+ wheel_dir = out_dir / WASM_WHEEL_DIR+ current_names = {wheel_path.name for wheel_path in wheel_paths}+ same_as_source = (+ source_wheel_dir is not None+ and wheel_dir.resolve() == source_wheel_dir.resolve()+ )+ if wheel_dir.exists():+ for wheel_path in wheel_dir.glob("*.whl"):+ if wheel_path.name in current_names:+ continue+ if (+ same_as_source+ and _AUTO_WHEEL_VERSION_MARKER not in wheel_path.name+ ):+ continue+ wheel_path.unlink()+ if not wheel_paths:+ return++ wheel_dir.mkdir(parents=True, exist_ok=True)+ for wheel_path in wheel_paths:+ target = wheel_dir / wheel_path.name+ if wheel_path.resolve() != target.resolve():+ shutil.copyfile(wheel_path, target)+++def resolve_metadata_wheel_dependencies(+ file_path: MarimoPath,+) -> tuple[_WheelDependency, ...]:+ """Return local wheels referenced by notebook PEP 723 metadata.++ Supported entries are direct wheel references and uv source paths. The+ returned dependency names are later rewritten to hosted wheel URLs.+ """+ if not file_path.is_python():+ return ()+ project = read_pyproject_from_script(+ file_path.path.read_text(encoding="utf-8")+ )+ return (+ ()+ if project is None+ else _metadata_wheel_dependencies_from_project(project, file_path.path)+ )+++def wheel_dependency_names(+ dependencies: Sequence[_WheelDependency],+) -> set[str]:+ return {+ _canonical_package_name(dependency.name.split("[", 1)[0])+ for dependency in dependencies+ }+++def auto_wheel_dependencies(+ wheel_paths: Sequence[Path],+) -> tuple[_WheelDependency, ...]:+ return tuple(+ _WheelDependency(+ wheel_path.name.split(_AUTO_WHEEL_VERSION_MARKER, 1)[0],+ wheel_path,+ )+ for wheel_path in wheel_paths+ )+++def with_wheel_dependencies(+ code: str, wheel_dependencies: Sequence[_WheelDependency]+) -> str:+ """Rewrite notebook PEP 723 dependencies to install hosted wheels."""+ if not wheel_dependencies:+ return code++ project = read_pyproject_from_script(code) or {}+ dependencies = project.get("dependencies")+ if not isinstance(dependencies, list):+ dependencies = []+ dependencies = [str(dependency) for dependency in dependencies]+ replacements = {+ _canonical_package_name(dependency.name.split("[", 1)[0]): dependency+ for dependency in wheel_dependencies+ }+ replaced: set[str] = set()+ rewritten_dependencies: list[str] = []+ for dependency in dependencies:+ package_name = _requirement_package_name(dependency)+ canonical = (+ _canonical_package_name(package_name)+ if package_name is not None+ else None+ )+ if canonical in replacements:+ if canonical not in replaced:+ rewritten_dependencies.append(+ _wheel_requirement(replacements[canonical])+ )+ replaced.add(canonical)+ continue+ rewritten_dependencies.append(dependency)++ for wheel_dependency in wheel_dependencies:+ dependency = _wheel_requirement(wheel_dependency)+ if dependency not in rewritten_dependencies:+ rewritten_dependencies.append(dependency)+ dependencies = rewritten_dependencies+ project["dependencies"] = dependencies+ _remove_uv_sources(project, set(replacements))++ metadata = write_pyproject_to_script(project)+ if read_pyproject_from_script(code) is None:+ return f"{metadata}\n\n{code}"+ return re.sub(REGEX, metadata, code, count=1)+++@contextmanager+def build_local_module_wheels(+ modules: Sequence[LocalModule],+) -> Iterator[tuple[Path, ...]]:+ """Build local module wheels and keep their temp directory alive."""+ if not modules:+ yield ()+ return++ with tempfile.TemporaryDirectory(prefix="marimo-html-wasm-wheels-") as tmp:+ wheel_dir = Path(tmp)+ yield tuple(+ write_pure_python_wheel(module, wheel_dir) for module in modules+ )+++def write_pure_python_wheel(+ module: LocalModule,+ wheel_dir: Path,+) -> Path:+ """Write a pure Python wheel preserving the resolved module layout."""+ files = _wheel_files(module)+ content_hash = _content_hash(files)+ metadata_name = _metadata_name(module.name)+ distribution = _wheel_distribution_name(metadata_name)+ version = f"0.0.0+marimo.{content_hash}"+ dist_info = f"{distribution}-{version}.dist-info"+ wheel_path = wheel_dir / f"{distribution}-{version}-py3-none-any.whl"++ payloads = {+ archive_name: path.read_bytes() for archive_name, path in files+ }+ payloads[f"{dist_info}/METADATA"] = _metadata(+ name=metadata_name,+ version=version,+ dependencies=_dependencies(files),+ )+ payloads[f"{dist_info}/WHEEL"] = _wheel_metadata()+ payloads[f"{dist_info}/RECORD"] = _record(payloads, dist_info)++ with zipfile.ZipFile(wheel_path, "w") as wheel:+ for archive_name, data in sorted(payloads.items()):+ info = zipfile.ZipInfo(archive_name, _DIST_INFO_TIMESTAMP)+ info.compress_type = zipfile.ZIP_DEFLATED+ info.external_attr = 0o644 << 16+ wheel.writestr(info, data)++ return wheel_path+++def _canonical_package_name(name: str) -> str:+ return re.sub(r"[-_.]+", "-", name).lower()+++def _requirement_package_name(dependency: str) -> str | None:+ match = re.match(r"\s*([A-Za-z0-9][A-Za-z0-9._-]*)", dependency)+ return match.group(1) if match is not None else None+++def _local_wheel_path(url: str, notebook_path: Path) -> Path | None:+ raw_url = url.split("#", 1)[0]+ parsed = urlparse(raw_url)+ if parsed.scheme == "file":+ source_url_path = url2pathname(unquote(parsed.path))+ source_netloc = unquote(parsed.netloc)+ if source_netloc and source_netloc.lower() != "localhost":+ source_url_path = f"//{source_netloc}{source_url_path}"+ source_path = Path(source_url_path)+ elif parsed.scheme:+ return None+ else:+ source_path = Path(raw_url)+ if source_path.suffix != ".whl":+ return None+ if not source_path.is_absolute():+ source_path = notebook_path.parent / source_path+ return source_path.resolve()+++def _direct_reference_wheel_dependency(+ dependency: str, notebook_path: Path+) -> _WheelDependency | None:+ match = _DIRECT_REF_RE.match(dependency)+ if match is None:+ return None+ marker = (match.group("marker") or "").strip() or None+ wheel_path = _local_wheel_path(match.group("url"), notebook_path)+ if wheel_path is None:+ return None+ return _WheelDependency(+ match.group("name"),+ wheel_path,+ marker,+ )+++def _dependency_metadata(+ dependency: str,+) -> tuple[str, str | None] | None:+ match = re.match(+ r"\s*([A-Za-z0-9][A-Za-z0-9._-]*(?:\[[^\]]+\])?)", dependency+ )+ if match is None:+ return None+ name = match.group(1)+ _, _, marker = dependency.partition(";")+ return name, marker.strip() or None+++def _metadata_wheel_dependencies_from_project(+ project: dict[str, object], notebook_path: Path+) -> tuple[_WheelDependency, ...]:+ wheel_dependencies: dict[str, _WheelDependency] = {}+ dependencies = project.get("dependencies")+ dependency_metadata: dict[str, tuple[str, str | None]] = {}+ if isinstance(dependencies, list):+ for dependency in (str(dependency) for dependency in dependencies):+ metadata = _dependency_metadata(dependency)+ if metadata is None:+ continue+ name, _ = metadata+ dependency_metadata[+ _canonical_package_name(name.split("[", 1)[0])+ ] = metadata+ wheel_dependency = _direct_reference_wheel_dependency(+ dependency, notebook_path+ )+ if wheel_dependency is not None:+ canonical = _canonical_package_name(+ wheel_dependency.name.split("[", 1)[0]+ )+ wheel_dependencies[canonical] = wheel_dependency++ uv_sources = {}+ tool = project.get("tool")+ if isinstance(tool, dict):+ uv = tool.get("uv")+ if isinstance(uv, dict):+ sources = uv.get("sources")+ if isinstance(sources, dict):+ uv_sources = sources+ for source_name, source_config in uv_sources.items():+ if not isinstance(source_config, dict):+ continue+ source_url = source_config.get("path")+ canonical = _canonical_package_name(str(source_name))+ metadata = dependency_metadata.get(canonical)+ if source_url is None or metadata is None:+ continue+ wheel_path = _local_wheel_path(str(source_url), notebook_path)+ if wheel_path is None:+ continue+ name, dependency_marker = metadata+ wheel_dependencies[canonical] = _WheelDependency(+ name,+ wheel_path,+ dependency_marker,+ )++ for wheel_dependency in wheel_dependencies.values():+ if not wheel_dependency.path.is_file():+ raise LocalWheelError(+ f"PEP 723 local wheel dependency does not exist: "+ f"{wheel_dependency.path}"+ )++ return tuple(wheel_dependencies.values())+++def _wheel_requirement(dependency: _WheelDependency) -> str:+ url = f"{WASM_WHEEL_URL_PREFIX}/{quote(dependency.path.name)}"+ requirement = f"{dependency.name} @ {url}"+ if dependency.marker is not None:+ requirement += f" ; {dependency.marker}"+ return requirement+++def _remove_uv_sources(project: dict[str, object], names: set[str]) -> None:+ tool = project.get("tool")+ if not isinstance(tool, dict):+ return+ uv = tool.get("uv")+ if not isinstance(uv, dict):+ return+ sources = uv.get("sources")+ if not isinstance(sources, dict):+ return+ for source_name in tuple(sources):+ if _canonical_package_name(str(source_name)) in names:+ del sources[source_name]+ if not sources:+ del uv["sources"]+ if not uv:+ del tool["uv"]+ if not tool:+ del project["tool"]+++def _wheel_files(module: LocalModule) -> tuple[tuple[str, Path], ...]:+ if module.kind == "module":+ return ((f"{module.name}.py", module.path),)++ return tuple(+ (f"{module.name}/{path.relative_to(module.path).as_posix()}", path)+ for path in module_python_files(module)+ )+++def _content_hash(files: Sequence[tuple[str, Path]]) -> str:+ digest = hashlib.sha256()+ for archive_name, path in files:+ digest.update(archive_name.encode())+ digest.update(b"\0")+ digest.update(path.read_bytes())+ digest.update(b"\0")+ return digest.hexdigest()[:12]+++def _dependencies(files: Sequence[tuple[str, Path]]) -> tuple[str, ...]:+ dependencies: set[str] = set()+ for _, path in files:+ project = PyProjectReader.from_script(path.read_text(encoding="utf-8"))+ dependencies.update(+ str(dependency) for dependency in project.dependencies+ )+ return tuple(sorted(dependencies))+++def _metadata(+ *, name: str, version: str, dependencies: Sequence[str]+) -> bytes:+ lines = [+ "Metadata-Version: 2.1",+ f"Name: {name}",+ f"Version: {version}",+ ]+ lines.extend(f"Requires-Dist: {dependency}" for dependency in dependencies)+ return ("\n".join(lines) + "\n").encode()+++def _wheel_metadata() -> bytes:+ return (+ b"Wheel-Version: 1.0\n"+ b"Generator: marimo\n"+ b"Root-Is-Purelib: true\n"+ b"Tag: py3-none-any\n"+ )+++def _record(payloads: dict[str, bytes], dist_info: str) -> bytes:+ output = io.StringIO()+ writer = csv.writer(output, lineterminator="\n")+ for archive_name, data in sorted(payloads.items()):+ digest = (+ base64.urlsafe_b64encode(hashlib.sha256(data).digest())+ .rstrip(b"=")+ .decode()+ )+ writer.writerow([archive_name, f"sha256={digest}", str(len(data))])+ writer.writerow([f"{dist_info}/RECORD", "", ""])+ return output.getvalue().encode()+++def _wheel_distribution_name(name: str) -> str:+ return re.sub(r"[-_.]+", "_", name).lower()+++def _metadata_name(name: str) -> str:+ normalized = re.sub(r"[-_.]+", "-", name).lower()+ if _VALID_METADATA_NAME_RE.match(normalized):+ return normalized+ stem = re.sub(r"[^a-z0-9]+", "-", normalized).strip("-") or "module"+ digest = hashlib.sha256(name.encode()).hexdigest()[:8]+ return f"marimo-local-{stem}-{digest}"diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex c278305cc6..225b9dfcc1 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -57,7 +57,7 @@ from marimo._utils.marimo_path import MarimoPathLOGGER = _loggers.marimo_logger()if TYPE_CHECKING:- from collections.abc import Mapping+ from collections.abc import Callable, Mappingfrom marimo._server.export._pdf_raster import PDFRasterizationOptionsfrom marimo._server.export._status import PDFExportStatusCallback@@ -165,6 +165,7 @@ def export_as_wasm(mode: Literal["edit", "run"],show_code: bool,asset_url: str | None = None,+ code_transform: Callable[[str], str] | None = None,) -> ExportResult:_app = load_app(path.absolute_name)if _app is None:@@ -181,12 +182,16 @@ def export_as_wasm(config = get_default_config_manager(current_path=path.absolute_name)resolved = config.get_config()+ code = app.to_py()+ if code_transform is not None:+ code = code_transform(code)+result = Exporter().export_as_wasm(filename=path.short_name,app=app,display_config=resolved["display"],mode=mode,- code=app.to_py(),+ code=code,asset_url=asset_url,show_code=show_code,sharing_config=resolved.get("sharing"),@@ -444,6 +449,7 @@ async def run_app_then_export_as_wasm(*,asset_url: str | None = None,cache_export_dir: Path | None = None,+ code_transform: Callable[[str], str] | None = None,) -> ExportResult:"""Execute notebook and export as WASM HTML with embedded session.@@ -499,6 +505,8 @@ async def run_app_then_export_as_wasm()code = pin_pep723_dependencies_for_wasm(file_manager.app.to_py(), path)+ if code_transform is not None:+ code = code_transform(code)html, filename = Exporter().export_as_wasm(filename=file_manager.filename,diff --git a/pyproject.toml b/pyproject.tomlindex c38193588b..7ea8101899 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -94,7 +94,7 @@ sql = [# For per-notebook sandboxed kernelssandbox = ["pyzmq>=27.1.0", # IPC communication for sandbox kernels- "uv>=0.9.21", # for sandbox management+ "uv>=0.9.21", # for sandbox management and local html-wasm exports]# List of deps that are recommended for most usersdiff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex a968a306a3..9480f886e5 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -19,11 +19,15 @@ from click.testing import CliRunner, Resultfrom marimo._cli.cli import mainfrom marimo._cli.export.commands import pdf+from marimo._cli.export.local_modules import _ruff_import_graph+from marimo._cli.export.local_wheels import _local_wheel_pathfrom marimo._dependencies.dependencies import DependencyManager+from marimo._output.utils import uri_decode_componentfrom marimo._session.state.serialize import get_session_cache_filefrom marimo._utils import async_pathfrom marimo._utils.paths import marimo_package_pathfrom marimo._utils.platform import is_windows+from marimo._utils.scripts import read_pyproject_from_scriptfrom tests._server.templates.utils import normalize_index_htmlfrom tests.mocks import (_sanitize_version,@@ -100,6 +104,8 @@ def _run_export(stdin: str | None = None,) -> Result:"""Helper to run marimo export commands via CliRunner."""+ if export_format == "html-wasm" and not HAS_UV:+ pytest.skip("uv is required for html-wasm export tests")return _runner.invoke(main,["export", export_format, file, *extra_args],@@ -146,6 +152,56 @@ async def _wait_for_file(file: str, timeout: float = 10.0) -> None:)+def _write_minimal_wasm_notebook(+ file: Path, cell: str, metadata: str = ""+) -> None:+ file.write_text(+ f"{metadata}import marimo\n\n"+ "app = marimo.App()\n\n"+ "@app.cell\n"+ "def __():\n"+ f"{cell}\n\n"+ 'if __name__ == "__main__":\n'+ " app.run()\n"+ )+++def test_local_wheel_path_preserves_file_url_netloc(tmp_path: Path) -> None:+ notebook = tmp_path / "notebook.py"+ assert (+ _local_wheel_path("file://server/share/pkg.whl", notebook)+ == Path("//server/share/pkg.whl").resolve()+ )+ assert (+ _local_wheel_path("file://localhost/tmp/pkg.whl", notebook)+ == Path("/tmp/pkg.whl").resolve()+ )+++def test_ruff_import_graph_ignores_successful_stderr(tmp_path: Path) -> None:+ notebook = tmp_path / "notebook.py"+ module = tmp_path / "module.py"+ result = subprocess.CompletedProcess(+ args=(),+ returncode=0,+ stdout=json.dumps({str(notebook): [str(module)]}),+ stderr="warning",+ )+ with (+ mock.patch(+ "marimo._cli.export.local_modules._ruff_graph_command",+ return_value=("ruff",),+ ),+ mock.patch(+ "marimo._cli.export.local_modules.subprocess.run",+ return_value=result,+ ),+ ):+ graph = _ruff_import_graph((notebook,), (tmp_path,), notebook)++ assert graph == {notebook.resolve(): (module.resolve(),)}++class TestExportHTML:@staticmethoddef test_cli_export_html(temp_marimo_file: str) -> None:@@ -183,6 +239,127 @@ class TestExportHTML:assert '"showAppCode": false' in htmlassert Path(out_dir / ".nojekyll").exists()+ @staticmethod+ def test_cli_export_html_wasm_packages_local_modules(+ tmp_path: Path,+ ) -> None:+ notebook = tmp_path / "notebook.py"+ _write_minimal_wasm_notebook(+ notebook,+ " import foo\n"+ " from baz import hmm, other\n"+ " return foo, hmm, other\n",+ """+# /// script+# dependencies = ["foo>=1"]+# ///+""".lstrip(),+ )+ (tmp_path / "foo.py").write_text("from helpers import value\n")+ (tmp_path / "helpers.py").write_text("value = 'helper'\n")+ baz = tmp_path / "baz"+ baz.mkdir()+ (baz / "hmm.py").write_text("value = 'hmm'\n")+ (baz / "other.py").write_text("value = 'other'\n")++ out_dir = tmp_path / "out"+ stale_wheel_dir = out_dir / "public" / "wheels"+ stale_wheel_dir.mkdir(parents=True)+ (+ stale_wheel_dir / "stale-0.0.0+marimo.old-py3-none-any.whl"+ ).write_bytes(b"stale")+ (stale_wheel_dir / "old_explicit-0.1.0-py3-none-any.whl").write_bytes(+ b"stale"+ )+ p = _run_export(+ "html-wasm",+ str(notebook),+ "--output",+ str(out_dir),+ )+ _assert_success(p)++ html = (out_dir / "index.html").read_text()+ code = html.split('<marimo-code hidden="">', 1)[1].split(+ "</marimo-code>", 1+ )[0]+ decoded_code = uri_decode_component(code)+ dependencies = (read_pyproject_from_script(decoded_code) or {}).get(+ "dependencies", []+ )+ assert any(+ dependency.startswith("foo @ ../public/wheels/foo-")+ for dependency in dependencies+ )+ assert not any(dependency == "foo>=1" for dependency in dependencies)+ assert any(+ dependency.startswith("helpers @ ../public/wheels/helpers-")+ for dependency in dependencies+ )+ assert any(+ dependency.startswith("baz @ ../public/wheels/baz-")+ for dependency in dependencies+ )+ wheel_dir = out_dir / "public" / "wheels"+ assert not (+ wheel_dir / "stale-0.0.0+marimo.old-py3-none-any.whl"+ ).exists()+ assert not (wheel_dir / "old_explicit-0.1.0-py3-none-any.whl").exists()++ @staticmethod+ def test_cli_export_html_wasm_copies_pep723_local_wheels(+ tmp_path: Path,+ ) -> None:+ dist = tmp_path / "dist"+ dist.mkdir()+ uv_wheel = dist / "demo_local-0.1.0-py3-none-any.whl"+ direct_wheel = dist / "direct_wheel-0.2.0-py3-none-any.whl"+ uv_wheel.write_bytes(b"wheel")+ direct_wheel.write_bytes(b"wheel")+ notebook = tmp_path / "notebook.py"+ _write_minimal_wasm_notebook(+ notebook,+ ' value = "plain"\n return value,\n',+ f"""+# /// script+# dependencies = [+# "demo-local[extra]",+# "direct-wheel @ {direct_wheel.as_uri()} ; python_version >= '3.11' ",+# ]+# [tool.uv.sources]+# demo-local = {{ path = "dist/demo_local-0.1.0-py3-none-any.whl" }}+# ///+""".lstrip(),+ )++ out_dir = tmp_path / "out"+ p = _run_export(+ "html-wasm",+ str(notebook),+ "--output",+ str(out_dir),+ )+ _assert_success(p)++ wheel_dir = out_dir / "public" / "wheels"+ assert (wheel_dir / uv_wheel.name).read_bytes() == b"wheel"+ assert (wheel_dir / direct_wheel.name).read_bytes() == b"wheel"+ html = (out_dir / "index.html").read_text()+ code = html.split('<marimo-code hidden="">', 1)[1].split(+ "</marimo-code>", 1+ )[0]+ dependencies = (+ read_pyproject_from_script(uri_decode_component(code)) or {}+ ).get("dependencies", [])+ assert (+ f"demo-local[extra] @ ../public/wheels/{uv_wheel.name}"+ in dependencies+ )+ assert (+ f"direct-wheel @ ../public/wheels/{direct_wheel.name}"+ " ; python_version >= '3.11'"+ ) in dependencies+@staticmethoddef test_cli_export_html_wasm_no_override(temp_marimo_file: str) -> None:out_dir = Path(temp_marimo_file).parent / "out"@@ -308,8 +485,8 @@ class TestExportHTML:@pytest.mark.skipif(# if hangs on watchdog, add a dependency check- condition=_is_win32(),- reason="flaky on Windows",+ condition=_is_win32() or not HAS_UV,+ reason="requires uv and is flaky on Windows",)@staticmethoddef test_cli_export_html_wasm_watch(temp_marimo_file: str) -> None: