django-vite-kit 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,385 @@
1
+ """Django management command: ``python manage.py vite <subcommand>``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from django.conf import settings
12
+ from django.core.management.base import BaseCommand, CommandError, CommandParser
13
+
14
+ from djvite.conf import get_config
15
+ from djvite.npm import NpmManager, parse_npm_package_spec
16
+ from djvite.presets import get_preset, list_presets
17
+ from djvite.registry import load_registry, register_package, register_preset, unregister_item
18
+ from djvite.scaffolding import scaffold_frontend
19
+
20
+
21
+ class Command(BaseCommand):
22
+ help = (
23
+ "Manage Vite + Tailwind CSS + JavaScript/TypeScript libraries "
24
+ "(init, install, build, dev, typecheck, add, remove, preset, npm)."
25
+ )
26
+
27
+ def add_arguments(self, parser: CommandParser) -> None:
28
+ parser.add_argument(
29
+ "subcommand",
30
+ choices=["init", "install", "build", "dev", "typecheck", "add", "remove", "preset", "npm"],
31
+ help="Subcommand to execute.",
32
+ )
33
+ parser.add_argument(
34
+ "extra_args",
35
+ nargs="*",
36
+ help="Package names, preset names, or npm arguments.",
37
+ )
38
+ parser.add_argument(
39
+ "--force",
40
+ action="store_true",
41
+ help="Overwrite existing files when running `init`.",
42
+ )
43
+ parser.add_argument(
44
+ "--ts",
45
+ "--typescript",
46
+ dest="typescript",
47
+ action="store_true",
48
+ help="Scaffold a TypeScript setup (tsconfig.json, src/index.ts, djvite.d.ts) when running `init`.",
49
+ )
50
+ parser.add_argument(
51
+ "--use-honcho",
52
+ action="store_true",
53
+ help="Run `honcho start` instead of Vite directly when running `dev`.",
54
+ )
55
+ parser.add_argument(
56
+ "--dev",
57
+ dest="save_dev",
58
+ action="store_true",
59
+ help="Install packages as devDependencies when running `add`.",
60
+ )
61
+ parser.add_argument(
62
+ "--expose",
63
+ default=None,
64
+ help="Expose the added JS package globally on `window.<NAME>` in src/djvite.plugins.js.",
65
+ )
66
+ parser.add_argument(
67
+ "--css",
68
+ default=None,
69
+ help="Also import a CSS file from the added package (e.g. flatpickr/dist/flatpickr.min.css).",
70
+ )
71
+ parser.add_argument(
72
+ "--namespace",
73
+ action="store_true",
74
+ help="Use `import * as <NAME>` instead of default import when combined with --expose.",
75
+ )
76
+ parser.add_argument(
77
+ "--import-path",
78
+ default=None,
79
+ help="Custom module import path for --expose (e.g. chart.js/auto).",
80
+ )
81
+ parser.add_argument(
82
+ "--list",
83
+ dest="list_presets",
84
+ action="store_true",
85
+ help="List available built-in presets when running `preset`.",
86
+ )
87
+ parser.add_argument(
88
+ "--no-install",
89
+ action="store_true",
90
+ help="Skip running npm install/uninstall during `add`, `remove`, or `preset`.",
91
+ )
92
+ parser.add_argument(
93
+ "--dir",
94
+ dest="frontend_dir",
95
+ default=None,
96
+ help="Override DJVITE_FRONTEND_DIR for this invocation.",
97
+ )
98
+
99
+ def _get_frontend_dir(self, options: dict[str, Any]) -> Path:
100
+ if options.get("frontend_dir"):
101
+ return Path(options["frontend_dir"]).resolve()
102
+ return Path(get_config("DJVITE_FRONTEND_DIR"))
103
+
104
+ def handle(self, *args: Any, **options: Any) -> None:
105
+ subcommand = options["subcommand"]
106
+ frontend_dir = self._get_frontend_dir(options)
107
+ extra: list[str] = list(options.get("extra_args") or [])
108
+
109
+ if subcommand == "init":
110
+ self._handle_init(
111
+ frontend_dir,
112
+ typescript=bool(options["typescript"]),
113
+ force=bool(options["force"]),
114
+ )
115
+ elif subcommand == "install":
116
+ self._handle_npm(frontend_dir, ["install"])
117
+ elif subcommand == "build":
118
+ self._handle_npm(frontend_dir, ["run", "build"])
119
+ elif subcommand == "dev":
120
+ self._handle_dev(frontend_dir, use_honcho=bool(options["use_honcho"]))
121
+ elif subcommand == "typecheck":
122
+ self._handle_npm(frontend_dir, ["run", "typecheck"])
123
+ elif subcommand == "add":
124
+ self._handle_add(
125
+ frontend_dir,
126
+ extra,
127
+ dev=bool(options["save_dev"]),
128
+ expose=options.get("expose"),
129
+ css=options.get("css"),
130
+ namespace=bool(options["namespace"]),
131
+ import_path=options.get("import_path"),
132
+ no_install=bool(options["no_install"]),
133
+ )
134
+ elif subcommand == "remove":
135
+ self._handle_remove(frontend_dir, extra, no_install=bool(options["no_install"]))
136
+ elif subcommand == "preset":
137
+ self._handle_preset(
138
+ frontend_dir,
139
+ extra,
140
+ show_list=bool(options["list_presets"]),
141
+ no_install=bool(options["no_install"]),
142
+ )
143
+ elif subcommand == "npm":
144
+ if not extra:
145
+ raise CommandError("Provide npm arguments, e.g. `manage.py vite npm install alpinejs`.")
146
+ self._handle_npm(frontend_dir, extra)
147
+
148
+ def _handle_init(self, frontend_dir: Path, *, typescript: bool, force: bool) -> None:
149
+ static_url = getattr(settings, "STATIC_URL", "/static/") or "/static/"
150
+ static_prefix = get_config("DJVITE_STATIC_URL_PREFIX")
151
+ manifest_path = Path(get_config("DJVITE_MANIFEST_PATH"))
152
+
153
+ out_abs = (
154
+ manifest_path.parent.parent
155
+ if manifest_path.parent.name == ".vite"
156
+ else manifest_path.parent
157
+ )
158
+ try:
159
+ out_dir = out_abs.relative_to(frontend_dir).as_posix()
160
+ except ValueError:
161
+ try:
162
+ out_dir = Path(os.path.relpath(out_abs, frontend_dir)).as_posix()
163
+ except ValueError:
164
+ out_dir = "../static/dist"
165
+
166
+ result = scaffold_frontend(
167
+ frontend_dir,
168
+ static_url=static_url,
169
+ static_prefix=static_prefix,
170
+ out_dir=out_dir,
171
+ typescript=typescript,
172
+ force=force,
173
+ )
174
+
175
+ for path in result.created:
176
+ self.stdout.write(self.style.SUCCESS(f"Created {path}"))
177
+ for path in result.skipped:
178
+ self.stdout.write(self.style.WARNING(f"Skipped existing {path} (use --force to overwrite)"))
179
+
180
+ lang_label = "TypeScript" if typescript else "JavaScript"
181
+ self.stdout.write(
182
+ self.style.SUCCESS(
183
+ f"\nVite + Tailwind CSS v4 ({lang_label}) scaffolded in {frontend_dir}.\n"
184
+ "Next steps:\n"
185
+ " 1. python manage.py vite install\n"
186
+ " 2. python manage.py vite preset alpine htmx # optional JS presets\n"
187
+ " 3. python manage.py vite dev"
188
+ )
189
+ )
190
+
191
+ def _handle_npm(self, frontend_dir: Path, npm_args: list[str]) -> None:
192
+ npm = NpmManager(cwd=frontend_dir)
193
+ if not npm.is_npm_installed():
194
+ raise CommandError(
195
+ f"npm binary '{npm.npm_bin}' not found. Ensure Node.js and npm are installed."
196
+ )
197
+
198
+ ok = npm.run_command(npm_args)
199
+ if not ok:
200
+ raise CommandError(f"Command `npm {' '.join(npm_args)}` failed in '{frontend_dir}'.")
201
+
202
+ def _handle_add(
203
+ self,
204
+ frontend_dir: Path,
205
+ packages: list[str],
206
+ *,
207
+ dev: bool,
208
+ expose: str | None,
209
+ css: str | None,
210
+ namespace: bool,
211
+ import_path: str | None,
212
+ no_install: bool,
213
+ ) -> None:
214
+ if not packages:
215
+ raise CommandError("Specify at least one npm package, e.g. `manage.py vite add chart.js --expose Chart`.")
216
+
217
+ if (expose or css or import_path) and len(packages) > 1:
218
+ raise CommandError("--expose, --css, and --import-path can only be used with a single package.")
219
+
220
+ parsed_specs = []
221
+ for raw_pkg in packages:
222
+ try:
223
+ parsed_specs.append(parse_npm_package_spec(raw_pkg))
224
+ except ValueError as exc:
225
+ raise CommandError(str(exc)) from exc
226
+
227
+ if not no_install:
228
+ npm = NpmManager(cwd=frontend_dir)
229
+ if not npm.is_npm_installed():
230
+ raise CommandError(
231
+ f"npm binary '{npm.npm_bin}' not found. Ensure Node.js and npm are installed."
232
+ )
233
+ raw_to_install = [spec.raw for spec in parsed_specs]
234
+ if not npm.npm_install_packages(raw_to_install, dev=dev):
235
+ raise CommandError(f"Failed to install npm package(s): {', '.join(raw_to_install)}")
236
+
237
+ if expose or css or import_path:
238
+ pkg_spec = parsed_specs[0]
239
+ try:
240
+ plugins_path = register_package(
241
+ frontend_dir,
242
+ pkg_spec.name,
243
+ expose=expose,
244
+ css=css,
245
+ namespace=namespace,
246
+ import_path=import_path,
247
+ )
248
+ except ValueError as exc:
249
+ raise CommandError(str(exc)) from exc
250
+ self.stdout.write(
251
+ self.style.SUCCESS(f"Registered '{pkg_spec.name}' in {plugins_path}")
252
+ )
253
+ else:
254
+ names = ", ".join(spec.name for spec in parsed_specs)
255
+ self.stdout.write(
256
+ self.style.SUCCESS(
257
+ f"Added {names}. Import them directly in your JS modules "
258
+ "or re-run with `--expose <GlobalName>` to expose on `window`."
259
+ )
260
+ )
261
+
262
+ def _handle_remove(
263
+ self,
264
+ frontend_dir: Path,
265
+ items: list[str],
266
+ *,
267
+ no_install: bool,
268
+ ) -> None:
269
+ if not items:
270
+ raise CommandError("Specify at least one package or preset name to remove.")
271
+
272
+ registry = load_registry(frontend_dir)
273
+ npm_packages_to_uninstall: list[str] = []
274
+ registry_keys_to_remove: list[str] = []
275
+
276
+ for item in items:
277
+ entry = registry.get("plugins", {}).get(item)
278
+ if entry and entry.get("type") == "preset":
279
+ npm_packages_to_uninstall.extend(entry.get("packages", []))
280
+ registry_keys_to_remove.append(item)
281
+ else:
282
+ try:
283
+ spec = parse_npm_package_spec(item)
284
+ except ValueError as exc:
285
+ raise CommandError(str(exc)) from exc
286
+ npm_packages_to_uninstall.append(spec.name)
287
+ registry_keys_to_remove.append(spec.name)
288
+
289
+ if not no_install and npm_packages_to_uninstall:
290
+ npm = NpmManager(cwd=frontend_dir)
291
+ if not npm.is_npm_installed():
292
+ raise CommandError(
293
+ f"npm binary '{npm.npm_bin}' not found. Ensure Node.js and npm are installed."
294
+ )
295
+ if not npm.npm_uninstall_packages(npm_packages_to_uninstall):
296
+ raise CommandError(
297
+ f"Failed to uninstall npm package(s): {', '.join(npm_packages_to_uninstall)}"
298
+ )
299
+
300
+ removed_from_registry = [
301
+ key for key in registry_keys_to_remove if unregister_item(frontend_dir, key)
302
+ ]
303
+ if removed_from_registry:
304
+ self.stdout.write(
305
+ self.style.SUCCESS(
306
+ f"Removed {', '.join(removed_from_registry)} from djvite plugin registry."
307
+ )
308
+ )
309
+ else:
310
+ self.stdout.write(self.style.SUCCESS(f"Removed {', '.join(items)}."))
311
+
312
+ def _handle_preset(
313
+ self,
314
+ frontend_dir: Path,
315
+ preset_names: list[str],
316
+ *,
317
+ show_list: bool,
318
+ no_install: bool,
319
+ ) -> None:
320
+ if show_list or not preset_names:
321
+ self.stdout.write("Available djvite JavaScript presets:\n")
322
+ for preset in list_presets():
323
+ pkgs = ", ".join(preset.packages)
324
+ self.stdout.write(f" - {preset.name:<10} {preset.description} [{pkgs}]")
325
+ return
326
+
327
+ resolved_presets = []
328
+ packages_to_install: list[str] = []
329
+ for name in preset_names:
330
+ try:
331
+ preset = get_preset(name)
332
+ except KeyError as exc:
333
+ raise CommandError(str(exc)) from exc
334
+ resolved_presets.append(preset)
335
+ for pkg in preset.packages:
336
+ if pkg not in packages_to_install:
337
+ packages_to_install.append(pkg)
338
+
339
+ if not no_install and packages_to_install:
340
+ npm = NpmManager(cwd=frontend_dir)
341
+ if not npm.is_npm_installed():
342
+ raise CommandError(
343
+ f"npm binary '{npm.npm_bin}' not found. Ensure Node.js and npm are installed."
344
+ )
345
+ if not npm.npm_install_packages(packages_to_install):
346
+ raise CommandError(
347
+ f"Failed to install preset packages: {', '.join(packages_to_install)}"
348
+ )
349
+
350
+ for preset in resolved_presets:
351
+ plugins_path = register_preset(frontend_dir, preset.name)
352
+ self.stdout.write(
353
+ self.style.SUCCESS(f"Enabled preset '{preset.name}' in {plugins_path}")
354
+ )
355
+
356
+ def _handle_dev(self, frontend_dir: Path, *, use_honcho: bool) -> None:
357
+ npm = NpmManager(cwd=frontend_dir)
358
+ if not npm.is_npm_installed():
359
+ raise CommandError(
360
+ f"npm binary '{npm.npm_bin}' not found. Ensure Node.js and npm are installed."
361
+ )
362
+
363
+ if use_honcho:
364
+ honcho_bin = get_config("DJVITE_HONCHO_BIN_PATH")
365
+ if not shutil.which(honcho_bin):
366
+ raise CommandError(
367
+ f"'{honcho_bin}' is not installed. Install it (e.g. `uv add honcho`) or omit --use-honcho."
368
+ )
369
+ base_dir = Path(getattr(settings, "BASE_DIR", Path.cwd()))
370
+ self.stdout.write(self.style.SUCCESS("Starting Vite and Django with Honcho..."))
371
+ try:
372
+ subprocess.run([honcho_bin, "start"], cwd=base_dir, check=True)
373
+ except KeyboardInterrupt:
374
+ self.stdout.write(self.style.WARNING("\nStopping processes..."))
375
+ except subprocess.CalledProcessError as exc:
376
+ raise CommandError(f"Honcho exited with status {exc.returncode}") from exc
377
+ return
378
+
379
+ self.stdout.write(self.style.SUCCESS(f"Starting Vite dev server in {frontend_dir}..."))
380
+ try:
381
+ ok = npm.run_command(["run", "dev"])
382
+ if not ok:
383
+ raise CommandError("Vite dev server exited with an error.")
384
+ except KeyboardInterrupt:
385
+ self.stdout.write(self.style.WARNING("\nVite dev server stopped."))
djvite/manifest.py ADDED
@@ -0,0 +1,166 @@
1
+ """Vite production manifest loading and asset resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import threading
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from django.conf import settings
12
+
13
+ from djvite.conf import get_config
14
+
15
+ _MANIFEST_CACHE: dict[Path, dict[str, Any]] = {}
16
+ _MANIFEST_LOCK = threading.Lock()
17
+
18
+
19
+ class ViteManifestError(RuntimeError):
20
+ """Raised when the Vite manifest cannot be read or an entry cannot be resolved."""
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ResolvedEntry:
25
+ """Resolved static asset paths (relative to Django STATIC_URL) for a Vite entry."""
26
+
27
+ js_files: list[str] = field(default_factory=list)
28
+ css_files: list[str] = field(default_factory=list)
29
+ preload_files: list[str] = field(default_factory=list)
30
+
31
+
32
+ def clear_manifest_cache() -> None:
33
+ """Clear the in-memory Vite manifest cache."""
34
+ with _MANIFEST_LOCK:
35
+ _MANIFEST_CACHE.clear()
36
+
37
+
38
+ def get_manifest(
39
+ manifest_path: Path | str | None = None,
40
+ *,
41
+ use_cache: bool | None = None,
42
+ ) -> dict[str, Any]:
43
+ """Load and return the Vite ``manifest.json`` as a dictionary."""
44
+ path = Path(manifest_path) if manifest_path is not None else Path(get_config("DJVITE_MANIFEST_PATH"))
45
+ should_cache = (not getattr(settings, "DEBUG", False)) if use_cache is None else use_cache
46
+
47
+ if should_cache:
48
+ with _MANIFEST_LOCK:
49
+ cached = _MANIFEST_CACHE.get(path)
50
+ if cached is not None:
51
+ return cached
52
+
53
+ if not path.is_file():
54
+ raise ViteManifestError(
55
+ f"Vite manifest not found at '{path}'. "
56
+ "Run `python manage.py vite build` or set DJVITE_MANIFEST_PATH."
57
+ )
58
+
59
+ try:
60
+ with path.open(encoding="utf-8") as fh:
61
+ manifest = json.load(fh)
62
+ except json.JSONDecodeError as exc:
63
+ raise ViteManifestError(f"Invalid JSON in Vite manifest '{path}': {exc}") from exc
64
+
65
+ if not isinstance(manifest, dict):
66
+ raise ViteManifestError(
67
+ f"Invalid Vite manifest '{path}': expected a JSON object at top level."
68
+ )
69
+
70
+ if should_cache:
71
+ with _MANIFEST_LOCK:
72
+ _MANIFEST_CACHE[path] = manifest
73
+
74
+ return manifest
75
+
76
+
77
+ def _prefix_asset(asset_path: str, prefix: str) -> str:
78
+ clean = asset_path.lstrip("/")
79
+ if not prefix:
80
+ return clean
81
+ return f"{prefix}/{clean}"
82
+
83
+
84
+ def _collect_imported_assets(
85
+ manifest: dict[str, Any],
86
+ entry: str,
87
+ prefix: str,
88
+ ) -> tuple[list[str], list[str]]:
89
+ visited: set[str] = set()
90
+ css_files: list[str] = []
91
+ preload_files: list[str] = []
92
+
93
+ def _visit(chunk_key: str, *, is_root: bool = False) -> None:
94
+ if chunk_key in visited:
95
+ return
96
+ visited.add(chunk_key)
97
+
98
+ chunk = manifest.get(chunk_key)
99
+ if not isinstance(chunk, dict):
100
+ return
101
+
102
+ for imported in chunk.get("imports", []):
103
+ _visit(imported, is_root=False)
104
+
105
+ if not is_root:
106
+ chunk_file = chunk.get("file")
107
+ if isinstance(chunk_file, str) and chunk_file and not chunk_file.lower().endswith(".css"):
108
+ prefixed_js = _prefix_asset(chunk_file, prefix)
109
+ if prefixed_js not in preload_files:
110
+ preload_files.append(prefixed_js)
111
+
112
+ for css in chunk.get("css", []):
113
+ prefixed = _prefix_asset(css, prefix)
114
+ if prefixed not in css_files:
115
+ css_files.append(prefixed)
116
+
117
+ _visit(entry, is_root=True)
118
+ return css_files, preload_files
119
+
120
+
121
+ def resolve_entry(
122
+ entry: str = "index.html",
123
+ *,
124
+ manifest: dict[str, Any] | None = None,
125
+ static_prefix: str | None = None,
126
+ ) -> ResolvedEntry:
127
+ """Resolve JS, CSS, and modulepreload static paths for a Vite manifest entry.
128
+
129
+ Also walks transitive ``imports`` chunks so imported CSS and JS chunks are included.
130
+ """
131
+ loaded_manifest = manifest if manifest is not None else get_manifest()
132
+ if entry not in loaded_manifest:
133
+ raise ViteManifestError(
134
+ f"Entry '{entry}' not found in Vite manifest. "
135
+ f"Available entries: {', '.join(sorted(loaded_manifest.keys())) or '(none)'}"
136
+ )
137
+
138
+ entry_data = loaded_manifest[entry]
139
+ if not isinstance(entry_data, dict):
140
+ raise ViteManifestError(
141
+ f"Invalid entry '{entry}' in Vite manifest: expected a JSON object."
142
+ )
143
+
144
+ prefix = (
145
+ get_config("DJVITE_STATIC_URL_PREFIX")
146
+ if static_prefix is None
147
+ else static_prefix.strip("/")
148
+ )
149
+
150
+ css_files, preload_files = _collect_imported_assets(loaded_manifest, entry, prefix)
151
+
152
+ js_files: list[str] = []
153
+ entry_file = entry_data.get("file")
154
+ if isinstance(entry_file, str) and entry_file:
155
+ prefixed_entry = _prefix_asset(entry_file, prefix)
156
+ if entry_file.lower().endswith(".css"):
157
+ if prefixed_entry not in css_files:
158
+ css_files.append(prefixed_entry)
159
+ else:
160
+ js_files.append(prefixed_entry)
161
+
162
+ return ResolvedEntry(
163
+ js_files=js_files,
164
+ css_files=css_files,
165
+ preload_files=preload_files,
166
+ )
djvite/npm.py ADDED
@@ -0,0 +1,152 @@
1
+ """Subprocess wrapper around npm for managing Vite frontend assets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import subprocess
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from djvite.conf import get_config
12
+
13
+ _NPM_PACKAGE_NAME_RE = re.compile(r"^(?:@[a-z0-9][a-z0-9._-]*/)?[a-z0-9][a-z0-9._-]*$")
14
+ _MAX_NPM_NAME_LEN = 214
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class NpmPackageSpec:
19
+ """Parsed npm package specifier (e.g. ``chart.js@4.4.0`` or ``@alpinejs/focus@^3.14.0``)."""
20
+
21
+ raw: str
22
+ name: str
23
+ version: str | None = None
24
+
25
+
26
+ def parse_npm_package_spec(spec: str) -> NpmPackageSpec:
27
+ """Validate and parse an npm-compatible package specifier.
28
+
29
+ Supports unscoped (``lodash``, ``chart.js@^4.4.0``) and scoped
30
+ (``@alpinejs/focus``, ``@tiptap/core@2.11.0``) npm package names.
31
+ Raises ``ValueError`` if the package name is not valid for npm.
32
+ """
33
+ cleaned = spec.strip()
34
+ if not cleaned or any(ch.isspace() for ch in cleaned):
35
+ raise ValueError(f"Invalid npm package specifier {spec!r}: must not be empty or contain whitespace.")
36
+
37
+ if cleaned.startswith("@"):
38
+ if "/" not in cleaned:
39
+ raise ValueError(
40
+ f"Invalid scoped npm package specifier {spec!r}: expected '@scope/package'."
41
+ )
42
+ scope_part, rest = cleaned.split("/", 1)
43
+ if "@" in rest:
44
+ pkg_part, version = rest.split("@", 1)
45
+ name = f"{scope_part}/{pkg_part}"
46
+ else:
47
+ name = cleaned
48
+ version = None
49
+ elif "@" in cleaned:
50
+ name, version = cleaned.split("@", 1)
51
+ else:
52
+ name = cleaned
53
+ version = None
54
+
55
+ if len(name) > _MAX_NPM_NAME_LEN or not _NPM_PACKAGE_NAME_RE.match(name):
56
+ raise ValueError(
57
+ f"Invalid npm package name {name!r} in {spec!r}. "
58
+ "npm package names must be lowercase, start with a letter or digit, "
59
+ "and use only letters, digits, '.', '_', '-', with an optional '@scope/' prefix."
60
+ )
61
+
62
+ if version is not None and not version:
63
+ raise ValueError(f"Invalid npm package specifier {spec!r}: version after '@' cannot be empty.")
64
+
65
+ return NpmPackageSpec(raw=cleaned, name=name, version=version)
66
+
67
+
68
+ class NpmManager:
69
+ """Manage npm commands inside a frontend directory."""
70
+
71
+ def __init__(self, cwd: str | Path | None = None, npm_bin: str | None = None) -> None:
72
+ self.cwd = Path(cwd) if cwd is not None else Path(os.getcwd())
73
+ self.npm_bin = npm_bin or get_config("DJVITE_NPM_BIN_PATH")
74
+
75
+ def ensure_cwd_exists(self) -> Path:
76
+ self.cwd.mkdir(parents=True, exist_ok=True)
77
+ return self.cwd
78
+
79
+ def is_npm_installed(self) -> bool:
80
+ try:
81
+ subprocess.run(
82
+ [self.npm_bin, "--version"],
83
+ capture_output=True,
84
+ check=True,
85
+ )
86
+ return True
87
+ except (FileNotFoundError, subprocess.CalledProcessError):
88
+ return False
89
+
90
+ def run_command(
91
+ self,
92
+ args: list[str],
93
+ *,
94
+ stream_output: bool = True,
95
+ return_process: bool = False,
96
+ ) -> bool | subprocess.Popen[str]:
97
+ """Run an npm command in ``self.cwd``.
98
+
99
+ ``args`` may either start with ``self.npm_bin`` / ``"npm"`` or be the subcommand
100
+ arguments directly (e.g. ``["install"]`` or ``["npm", "install"]``).
101
+ """
102
+ if not self.is_npm_installed():
103
+ return False
104
+
105
+ self.ensure_cwd_exists()
106
+
107
+ if args and args[0] in ("npm", self.npm_bin):
108
+ cmd = [self.npm_bin, *args[1:]]
109
+ else:
110
+ cmd = [self.npm_bin, *args]
111
+
112
+ if return_process:
113
+ return subprocess.Popen(cmd, cwd=self.cwd, text=True)
114
+
115
+ try:
116
+ if stream_output:
117
+ subprocess.run(cmd, cwd=self.cwd, check=True)
118
+ else:
119
+ subprocess.run(
120
+ cmd,
121
+ cwd=self.cwd,
122
+ capture_output=True,
123
+ text=True,
124
+ check=True,
125
+ )
126
+ return True
127
+ except subprocess.CalledProcessError:
128
+ return False
129
+
130
+ def npm_install(self) -> bool:
131
+ return bool(self.run_command(["install"]))
132
+
133
+ def npm_run_dev(self, *, return_process: bool = False) -> bool | subprocess.Popen[str]:
134
+ return self.run_command(["run", "dev"], return_process=return_process)
135
+
136
+ def npm_run_build(self) -> bool:
137
+ return bool(self.run_command(["run", "build"]))
138
+
139
+ def npm_install_package(self, package_name: str, *, dev: bool = False) -> bool:
140
+ args = ["install", "--save-dev", package_name] if dev else ["install", package_name]
141
+ return bool(self.run_command(args))
142
+
143
+ def npm_install_packages(self, packages: list[str], *, dev: bool = False) -> bool:
144
+ if not packages:
145
+ return True
146
+ args = ["install", "--save-dev", *packages] if dev else ["install", *packages]
147
+ return bool(self.run_command(args))
148
+
149
+ def npm_uninstall_packages(self, packages: list[str]) -> bool:
150
+ if not packages:
151
+ return True
152
+ return bool(self.run_command(["uninstall", *packages]))