Repository navigation
Expand file tree
/
Copy pathpackages.py
More file actions
1067 lines (925 loc) · 43.4 KB
/
Copy pathpackages.py
File metadata and controls
1067 lines (925 loc) · 43.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""NodeForge package inventory, manifest validation, and installation helpers.
A package is an isolated directory with a ``nodeforge_package.json`` manifest and
optional ``functions/``, ``examples/``, and ``systems/`` content roots. Runtime
availability is controlled only by active records in ``state.json`` under the
user package inventory.
"""
from __future__ import annotations
import json
import keyword
import os
import re
import shutil
import stat
import tempfile
import uuid
from types import SimpleNamespace
import zipfile
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Any, Iterable
from urllib.parse import urlsplit
from .errors import CompileError
MANIFEST_NAME = "nodeforge_package.json"
STATE_SCHEMA_VERSION = 1
PACKAGE_SCHEMA_VERSION = 1
_PACKAGE_ID_RE = re.compile(r"^[a-z][a-z0-9]*(?:\.[a-z0-9_]+)+$")
_PUBLIC_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_INSTALL_TOKEN_RE = re.compile(r"^install_[A-Za-z0-9_\-]+$")
_TEST_PACKAGES_DIR: Path | None = None
def _current_nodeforge_version() -> tuple[int, ...]:
"""Return the runtime version without relying on Blender's stripped bl_info."""
from . import NODEFORGE_VERSION
raw = NODEFORGE_VERSION
if not isinstance(raw, (tuple, list)) or not raw:
raise PackageError("NodeForge runtime version is unavailable")
try:
return tuple(int(part) for part in raw)
except Exception as exc:
raise PackageError("NodeForge runtime version is malformed") from exc
def _parse_dotted_numeric_version(value: Any, field: str, *, nullable: bool = False) -> tuple[int, ...] | None:
"""Parse a manifest dotted numeric version field for deterministic comparison."""
if value is None and nullable:
return None
if not isinstance(value, str) or not value.strip():
raise PackageError(f"Package manifest {field} must be a dotted numeric version string")
parts = value.strip().split(".")
if not parts or any(not part.isdigit() for part in parts):
raise PackageError(f"Package manifest {field} must be a dotted numeric version string")
return tuple(int(part) for part in parts)
def _compare_versions(left: tuple[int, ...], right: tuple[int, ...]) -> int:
"""Compare dotted numeric version tuples with zero padding."""
size = max(len(left), len(right))
a = left + (0,) * (size - len(left))
b = right + (0,) * (size - len(right))
return (a > b) - (a < b)
def _validate_nodeforge_version_bounds(raw: dict[str, Any]) -> None:
"""Reject packages that declare incompatible NodeForge runtime bounds."""
_parse_dotted_numeric_version(raw.get("version"), "version")
min_version = _parse_dotted_numeric_version(raw.get("nodeforge_min_version"), "nodeforge_min_version")
max_version = _parse_dotted_numeric_version(raw.get("nodeforge_max_version"), "nodeforge_max_version", nullable=True)
current = _current_nodeforge_version()
if _compare_versions(current, min_version) < 0:
raise PackageError(
f"Package requires NodeForge {raw.get('nodeforge_min_version')} or newer; current version is {'.'.join(str(p) for p in current)}"
)
def package_compatibility_warning(manifest: "PackageManifest") -> str:
"""Return an advisory for a package targeting an older NodeForge maximum."""
maximum = manifest.nodeforge_max_version
if maximum is None:
return ""
parsed = _parse_dotted_numeric_version(maximum, "nodeforge_max_version")
current = _current_nodeforge_version()
if _compare_versions(current, parsed) <= 0:
return ""
return (f"Package supports NodeForge up to {maximum}; current version is "
f"{'.'.join(map(str, current))}. Compatibility is not guaranteed.")
def _validate_raw_posix_relative_path(value: Any, field: str) -> str:
"""Validate raw POSIX relative path text before pathlib can normalize segments."""
if not isinstance(value, str) or not value.strip():
raise PackageError(f"{field} must be a relative path string")
raw = value.strip()
if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
raise PackageError(f"{field} must be a non-empty relative path")
parts = raw.split("/")
if any(part in {"", ".", ".."} for part in parts):
raise PackageError(f"{field} must not contain empty, . or .. segments")
return raw
class PackageError(CompileError):
"""Raised when package metadata, state, or files are invalid."""
def _optional_repository_url(raw: dict[str, Any]) -> str | None:
"""Validate optional package repository metadata without accessing the URL."""
value = raw.get("repository_url")
if value is None:
return None
if not isinstance(value, str) or not value or any(ch.isspace() for ch in value):
raise PackageError("Package manifest repository_url must be an HTTP(S) URL")
try:
parsed = urlsplit(value)
valid = parsed.scheme in {"http", "https"} and bool(parsed.hostname)
except ValueError:
valid = False
if not valid:
raise PackageError("Package manifest repository_url must be an HTTP(S) URL")
return value
@dataclass(frozen=True)
class PackageManifest:
"""Validated package manifest and owning package root."""
package_id: str
import_name: str
name: str
version: str
author: str
description: str
root: Path
contents: dict[str, str]
nodeforge_max_version: str | None = None
repository_url: str | None = None
origin: str = "user"
def root_for(self, namespace: str) -> Path | None:
"""Return an existing declared content root for *namespace*."""
rel = self.contents.get(namespace)
if rel is None:
return None
path = (self.root / rel).resolve()
if not _is_relative_to(path, self.root.resolve()) or not path.exists() or not path.is_dir():
return None
return path
@dataclass(frozen=True)
class LibraryRoot:
"""One manifest-declared library root contributed by an active package."""
namespace: str
path: Path
package_id: str
package_name: str
package_version: str
origin: str
@dataclass(frozen=True)
class SystemPackageRecord:
"""One system directory contributed by an active package."""
package_id: str
package_name: str
package_version: str
system_id: str
root: Path
interface_path: Path
origin: str
@dataclass(frozen=True)
class PackageDiagnostic:
"""Diagnostic for a package record that could not become active."""
package_id: str
message: str
path: str = ""
name: str = ""
version: str = ""
origin: str = ""
@dataclass(frozen=True)
class ActivePackage:
"""Validated active package state record and computed diagnostics."""
manifest: PackageManifest
state_record: dict[str, Any]
def set_packages_dir_for_tests(path: Path | None) -> None:
"""Override the user package inventory path for ordinary CPython tests."""
global _TEST_PACKAGES_DIR
_TEST_PACKAGES_DIR = Path(path).resolve() if path is not None else None
def packages_dir() -> Path:
"""Return the user package inventory directory, creating it when possible."""
if _TEST_PACKAGES_DIR is not None:
_TEST_PACKAGES_DIR.mkdir(parents=True, exist_ok=True)
return _TEST_PACKAGES_DIR
try:
import bpy # type: ignore
return Path(bpy.utils.user_resource("DATAFILES", path="nodeforge/packages", create=True))
except Exception:
fallback = Path(os.environ.get("NODEFORGE_PACKAGES_DIR", Path(tempfile.gettempdir()) / "nodeforge/packages"))
fallback.mkdir(parents=True, exist_ok=True)
return fallback
def installed_dir() -> Path:
"""Return the package inventory install directory."""
path = packages_dir() / "installed"
path.mkdir(parents=True, exist_ok=True)
return path
def state_path() -> Path:
"""Return the active package state file path."""
return packages_dir() / "state.json"
def _default_state() -> dict[str, Any]:
return {"schema_version": STATE_SCHEMA_VERSION, "packages": {}}
def load_package_state() -> dict[str, Any]:
"""Load package state as untrusted JSON with a normalized top-level shape."""
path = state_path()
if not path.exists():
return _default_state()
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
raise PackageError(f"Could not read package state: {exc}") from exc
if not isinstance(data, dict):
raise PackageError("Package state must be a JSON object")
if data.get("schema_version") != STATE_SCHEMA_VERSION:
raise PackageError("Unsupported package state schema_version")
if not isinstance(data.get("packages"), dict):
raise PackageError("Package state packages must be an object")
data.pop("seed_sources", None)
return data
def save_package_state(state: dict[str, Any]) -> None:
"""Durably save package state using a same-directory temp file and replace."""
root = packages_dir()
root.mkdir(parents=True, exist_ok=True)
cleaned = {**state, "packages": {
key: ({k: v for k, v in record.items() if k != "allow_python"}
if isinstance(record, dict) else record)
for key, record in state["packages"].items()
}}
payload = json.dumps(cleaned, indent=2, sort_keys=True) + "\n"
fd, tmp_name = tempfile.mkstemp(prefix="state.", suffix=".tmp", dir=root)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_name, state_path())
try:
_fsync_directory(root)
except OSError:
# State is already published: a durability failure cannot trigger rollback.
pass
finally:
try:
if os.path.exists(tmp_name):
os.unlink(tmp_name)
except OSError:
pass
def _fsync_directory(path: Path) -> None:
"""Attempt directory fsync; the state writer handles durability errors."""
if not hasattr(os, "O_DIRECTORY"):
return
try:
fd = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY)
except OSError:
return
try:
os.fsync(fd)
finally:
os.close(fd)
def invalidate_caches() -> None:
"""Invalidate package-related runtime caches.
Package resolution snapshots owner-qualified exports per compilation, so no
process-global package-name cache remains.
"""
return None
def validate_package_root(root: Path, *, origin: str = "user") -> PackageManifest:
"""Validate a directory package root and return its manifest."""
root = Path(root).resolve()
manifest_path = root / MANIFEST_NAME
if not manifest_path.exists() or not manifest_path.is_file():
raise PackageError(f"Package is missing {MANIFEST_NAME}")
try:
raw = json.loads(manifest_path.read_text(encoding="utf-8"))
except Exception as exc:
raise PackageError(f"Could not parse {MANIFEST_NAME}: {exc}") from exc
if not isinstance(raw, dict):
raise PackageError("Package manifest must be a JSON object")
if raw.get("schema_version") != PACKAGE_SCHEMA_VERSION:
raise PackageError("Unsupported package manifest schema_version")
package_id = _require_string(raw, "id")
if not _PACKAGE_ID_RE.match(package_id):
raise PackageError("Package id must be a dotted lowercase identifier")
import_name = _package_import_name(raw, package_id)
name = _require_string(raw, "name")
version = _require_string(raw, "version")
_validate_nodeforge_version_bounds(raw)
author = str(raw.get("author") or "")
description = str(raw.get("description") or "")
contents_raw = raw.get("contents")
if not isinstance(contents_raw, dict) or not contents_raw:
raise PackageError("Package manifest contents must be a non-empty object")
contents: dict[str, str] = {}
for key in ("functions", "examples", "systems"):
if key in contents_raw:
rel = _validate_manifest_relative_path(contents_raw[key], f"contents.{key}")
root_path = (root / rel).resolve()
if not _is_relative_to(root_path, root) or not root_path.exists() or not root_path.is_dir():
raise PackageError(f"Manifest {key} root does not exist inside package: {rel}")
contents[key] = rel
if not contents:
raise PackageError("Package manifest must declare at least one supported content root")
_validate_root_contents(root, contents)
return PackageManifest(
package_id=package_id,
import_name=import_name,
name=name,
version=version,
author=author,
description=description,
root=root,
contents=contents,
nodeforge_max_version=raw.get("nodeforge_max_version"),
repository_url=_optional_repository_url(raw),
origin=origin,
)
def _package_import_name(raw: dict[str, Any], package_id: str) -> str:
"""Return one validated source import spelling for a canonical package id."""
value = raw.get("import_name")
if value is None:
value = package_id.rsplit(".", 1)[-1]
if not isinstance(value, str) or not value.strip():
raise PackageError("Package manifest import_name must be a non-empty source identifier")
name = value.strip()
if not _PUBLIC_NAME_RE.match(name) or name.startswith("_") or keyword.iskeyword(name):
raise PackageError("Package manifest import_name must be a valid public source identifier")
return name
def _require_string(raw: dict[str, Any], key: str) -> str:
value = raw.get(key)
if not isinstance(value, str) or not value.strip():
raise PackageError(f"Package manifest {key} must be a non-empty string")
return value.strip()
def _validate_manifest_relative_path(value: Any, field: str) -> str:
raw = _validate_raw_posix_relative_path(value, field)
path = PurePosixPath(raw)
if path.is_absolute() or str(path) in {".", ""}:
raise PackageError(f"{field} must be a non-empty relative path")
return path.as_posix()
def _validate_root_contents(root: Path, contents: dict[str, str]) -> None:
"""Validate package content-root conventions without loading implementation code."""
from .package_function_index import scan_package_functions
functions_rel = contents.get("functions")
if functions_rel:
try:
scan_package_functions(root / functions_rel)
except CompileError as exc:
raise PackageError(str(exc)) from exc
for namespace in ("examples",):
rel = contents.get(namespace)
if not rel:
continue
content_root = (root / rel).resolve()
seen: dict[str, str] = {}
for child in content_root.iterdir():
public_name: str | None = None
if child.name.startswith("__"):
continue
if child.is_file() and child.suffix in {".nf", ".nodeforge"}:
public_name = child.stem
elif child.is_dir() and not child.name.startswith("."):
public_name = child.name
if public_name is None:
continue
_validate_public_name(public_name, f"{namespace} entry")
previous = seen.get(public_name)
if previous is not None:
raise PackageError(
f"Duplicate {namespace} library entry {public_name!r} inside package: {previous} and {child.name}"
)
seen[public_name] = child.name
systems_rel = contents.get("systems")
if systems_rel:
systems_root = (root / systems_rel).resolve()
for child in systems_root.iterdir():
if not child.is_dir() or child.name.startswith(".") or child.name.startswith("__"):
continue
_validate_public_name(child.name, "system id")
interface_path = child / "interface.py"
legacy_path = child / "system.py"
if interface_path.is_file():
continue
if legacy_path.is_file():
raise PackageError(
f"System {child.name!r} uses unsupported Extension API v1 system.py; "
"migrate the owner to interface.py (EXTENSION_API = 2)"
)
raise PackageError(f"System {child.name!r} must contain interface.py")
def _validate_public_name(name: str, context: str) -> None:
if not _PUBLIC_NAME_RE.match(name) or name.startswith("_") or keyword.iskeyword(name):
raise PackageError(f"{context} {name!r} must be a valid public identifier")
def validate_package_system_declarations(manifest: PackageManifest) -> None:
"""Validate that every structurally accepted system uses Extension API v2.
Package root validation rejects legacy ``system.py``-only owners before this
function runs. Keeping this public validator structural guarantees that active
package/UI enumeration never imports package implementation modules.
"""
system_package_records_from_manifests((manifest,))
def active_package_records(include_invalid: bool = False) -> list[ActivePackage | PackageDiagnostic]:
"""Return validated active package records from the unified inventory."""
state = load_package_state()
records: list[ActivePackage | PackageDiagnostic] = []
for package_id, record in sorted(state.get("packages", {}).items()):
try:
records.append(_active_package_from_state(package_id, record))
except PackageError as exc:
if include_invalid:
records.append(_package_diagnostic_from_state(package_id, record, str(exc)))
return records
def active_package_manifests(include_invalid: bool = False) -> list[PackageManifest | PackageDiagnostic]:
"""Return active package manifests or optional diagnostics."""
out: list[PackageManifest | PackageDiagnostic] = []
for record in active_package_records(include_invalid=include_invalid):
if isinstance(record, ActivePackage):
out.append(record.manifest)
else:
out.append(record)
return out
def _structural_active_package_from_state(package_id: str, record: Any) -> ActivePackage:
"""Validate active package state without executing package declaration Python."""
if not isinstance(record, dict):
raise PackageError("Package state record must be an object")
rel = _validate_state_installed_path(package_id, record.get("installed_path"))
root = (packages_dir() / rel).resolve()
if not root.exists() or not root.is_dir():
raise PackageError("Installed package directory is missing")
manifest = validate_package_root(root, origin=str(record.get("origin") or "user"))
if manifest.package_id != package_id:
raise PackageError("Manifest id does not match package state key")
if manifest.version != record.get("installed_version"):
raise PackageError("Manifest version does not match package state version")
return ActivePackage(manifest, record)
def active_package_manifest_snapshot() -> tuple[PackageManifest, ...]:
"""Return one structurally active manifest snapshot without declaration execution."""
state = load_package_state()
manifests: list[PackageManifest] = []
for package_id, record in sorted(state.get("packages", {}).items()):
try:
active = _structural_active_package_from_state(package_id, record)
except PackageError:
continue
manifests.append(active.manifest)
return tuple(manifests)
def _active_package_from_state(package_id: str, record: Any) -> ActivePackage:
"""Return one active package while keeping v2 interface execution out of enumeration."""
active = _structural_active_package_from_state(package_id, record)
# Active-package/UI enumeration is intentionally structural for v2. Retained
# v1 declarations may still be checked without creating a third v2 executor.
validate_package_system_declarations(active.manifest)
return active
def _package_diagnostic_from_state(package_id: str, record: Any, message: str) -> PackageDiagnostic:
"""Build UI-facing diagnostics from an invalid state record without activating it."""
path = str(record.get("installed_path", "")) if isinstance(record, dict) else ""
origin = str(record.get("origin", "")) if isinstance(record, dict) else ""
name = package_id
version = str(record.get("installed_version", "")) if isinstance(record, dict) else ""
if isinstance(record, dict):
try:
rel = _validate_state_installed_path(package_id, record.get("installed_path"))
root = (packages_dir() / rel).resolve()
manifest = validate_package_root(root, origin=origin or "user")
name = manifest.name
version = manifest.version
except Exception:
pass
return PackageDiagnostic(
package_id=package_id, message=message, path=path,
name=name, version=version, origin=origin,
)
def _validate_state_installed_path(package_id: str, value: Any) -> Path:
try:
raw = _validate_raw_posix_relative_path(value, "installed_path")
except PackageError as exc:
raise PackageError("installed_path must be a contained relative path") from exc
path = PurePosixPath(raw)
if path.is_absolute():
raise PackageError("installed_path must be a contained relative path")
parts = path.parts
if len(parts) != 3 or parts[0] != "installed" or parts[1] != package_id or not _INSTALL_TOKEN_RE.match(parts[2]):
raise PackageError("installed_path must match installed/<package_id>/install_<token>")
resolved = (packages_dir() / Path(*parts)).resolve()
if not _is_relative_to(resolved, packages_dir().resolve()):
raise PackageError("installed_path resolves outside package inventory")
return Path(*parts)
def package_manifests(include_invalid: bool = False):
"""Compatibility alias for active package manifests."""
return active_package_manifests(include_invalid=include_invalid)
def library_roots_from_manifests(
namespace: str,
manifests: Iterable[PackageManifest],
) -> tuple[LibraryRoot, ...]:
"""Derive package library roots from an explicit validated manifest snapshot."""
if namespace not in {"functions", "examples"}:
return ()
roots: list[LibraryRoot] = []
for item in manifests:
if isinstance(item, PackageDiagnostic):
continue
path = item.root_for(namespace)
if path is not None:
roots.append(LibraryRoot(namespace, path, item.package_id, item.name, item.version, item.origin))
return tuple(roots)
def library_roots(namespace: str) -> list[LibraryRoot]:
"""Return active package roots for the requested library namespace."""
return list(library_roots_from_manifests(namespace, active_package_manifests()))
def system_package_records_from_manifests(
manifests: Iterable[PackageManifest],
) -> tuple[SystemPackageRecord, ...]:
"""Derive system entrypoint records from an explicit validated manifest snapshot."""
records: list[SystemPackageRecord] = []
for item in manifests:
if isinstance(item, PackageDiagnostic):
continue
systems_root = item.root_for("systems")
if systems_root is None:
continue
for child in sorted(systems_root.iterdir(), key=lambda p: p.name.lower()):
if not child.is_dir() or child.name.startswith(".") or child.name.startswith("__"):
continue
interface_path = child / "interface.py"
if not interface_path.is_file():
# ``validate_package_root`` rejects legacy system.py-only layouts.
# Keep derivation fail-closed if a caller somehow supplies an
# unvalidated manifest-like object.
raise PackageError(
f"System {child.name!r} must use interface.py (EXTENSION_API = 2)"
)
records.append(
SystemPackageRecord(
package_id=item.package_id,
package_name=item.name,
package_version=item.version,
system_id=child.name,
root=child.resolve(),
interface_path=interface_path.resolve(),
origin=item.origin,
)
)
return tuple(records)
def system_package_records() -> list[SystemPackageRecord]:
"""Return active system directories discovered by package convention."""
return list(system_package_records_from_manifests(active_package_manifests()))
def install_included_packages(extension_root: Path) -> tuple[str, ...]:
"""Install newer versioned ZIPs shipped with this extension as regular Packages.
All candidate IDs are validated before mutation, and the installed state
remains the sole version authority. An invalid top-level state aborts the batch.
"""
archive_dir = Path(extension_root) / "package_install"
if not archive_dir.is_dir():
return ()
archives = sorted(archive_dir.glob("*.zip"))
if not archives:
return ()
# Fail closed before even extracting one archive into the user inventory.
state = load_package_state()
candidates = []
errors = []
seen = set()
for archive in archives:
staging = packages_dir() / ".staging" / uuid.uuid4().hex
staging.mkdir(parents=True, exist_ok=False)
try:
root = _extract_zip_to_staging(archive, staging)
manifest = validate_package_root(root)
if manifest.package_id in seen:
# Ambiguous release contents must not partially change inventory.
return (f"Duplicate included package ID: {manifest.package_id}",)
seen.add(manifest.package_id)
candidates.append((archive, manifest.package_id, manifest.version))
except Exception as exc:
errors.append(f"{archive.name}: {exc}")
finally:
shutil.rmtree(staging, ignore_errors=True)
for archive, package_id, version in candidates:
installed = state["packages"].get(package_id)
origin = "user"
if installed is not None:
try:
active = _active_package_from_state(package_id, installed)
if _compare_versions(
_parse_dotted_numeric_version(active.manifest.version, "version"),
_parse_dotted_numeric_version(version, "version"),
) >= 0:
continue
origin = str(active.state_record.get("origin") or "user")
except Exception as exc:
errors.append(f"{package_id}: installed package is invalid: {exc}")
continue
try:
install_package_zip(archive, replace=installed is not None, origin=origin)
except Exception as exc:
errors.append(f"{archive.name}: {exc}")
return tuple(errors)
def install_package_directory(source_dir: Path, *, replace: bool = False, origin: str = "user") -> PackageManifest:
"""Install a package after validating the exact copied bytes that may be published."""
source_dir = Path(source_dir).resolve()
manifest = validate_package_root(source_dir, origin=origin)
state = load_package_state()
if manifest.package_id in state.get("packages", {}) and not replace:
raise PackageError(f"Package {manifest.package_id!r} is already installed")
record: dict[str, Any] | None = None
committed = False
old_record = None
try:
# Copy first. V2 declaration Python is normalized only from these exact
# candidate bytes, never once from source and again from the installed copy.
record = _install_validated_directory(
source_dir, manifest, origin=origin
)
installed_root = (packages_dir() / record["installed_path"]).resolve()
installed_manifest = validate_package_root(installed_root, origin=origin)
candidate_inventory = _normalize_package_callable_inventory(
installed_manifest,
normalize_native_libraries=True,
)
new_state = load_package_state()
packages_map = new_state.setdefault("packages", {})
old_record = packages_map.get(manifest.package_id)
if old_record is not None and not replace:
raise PackageError(f"Package {manifest.package_id!r} is already installed")
_validate_no_package_name_collisions(
installed_manifest,
ignore_package_id=manifest.package_id if replace else None,
new_inventory=candidate_inventory,
)
packages_map[manifest.package_id] = record
save_package_state(new_state)
committed = True
except Exception:
if record is not None and not committed:
_delete_old_install_dir_best_effort(manifest.package_id, record)
raise
if old_record:
_delete_old_install_dir_best_effort(manifest.package_id, old_record)
invalidate_caches()
return validate_package_root((packages_dir() / record["installed_path"]).resolve(), origin=origin)
def _install_validated_directory(source_dir: Path, manifest: PackageManifest, *, origin: str) -> dict[str, Any]:
"""Copy one structurally validated package without executing declaration Python."""
token = f"install_{uuid.uuid4().hex[:12]}"
target_parent = installed_dir() / manifest.package_id
target_parent.mkdir(parents=True, exist_ok=True)
target = target_parent / token
if target.exists():
raise PackageError("Install target collision")
try:
shutil.copytree(source_dir, target, symlinks=False, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo"))
installed_manifest = validate_package_root(target, origin=origin)
if installed_manifest.package_id != manifest.package_id or installed_manifest.version != manifest.version:
raise PackageError("Copied package manifest identity changed during installation")
except Exception:
shutil.rmtree(target, ignore_errors=True)
raise
rel = Path("installed") / manifest.package_id / token
return {
"installed_path": rel.as_posix(),
"installed_version": installed_manifest.version,
"origin": origin,
}
def install_package_zip(zip_path: Path, *, replace: bool = False, origin: str = "user") -> PackageManifest:
"""Install a package from a hostile zip archive after safe extraction."""
zip_path = Path(zip_path)
staging = packages_dir() / ".staging" / uuid.uuid4().hex
staging.mkdir(parents=True, exist_ok=False)
try:
root = _extract_zip_to_staging(zip_path, staging)
return install_package_directory(root, replace=replace, origin=origin)
finally:
shutil.rmtree(staging, ignore_errors=True)
def uninstall_package(package_id: str) -> None:
"""Remove a package record and safely delete files only when its pointer validates.
Invalid package records must remain removable from the inventory. Their file
paths are treated as untrusted and are not deleted unless full active-record
validation succeeds.
"""
state = load_package_state()
packages = state.setdefault("packages", {})
record = packages.get(package_id)
if record is None:
raise PackageError(f"Package {package_id!r} is not installed")
install_root = None
try:
install_root = _active_package_from_state(package_id, record).manifest.root
except Exception:
pass
packages.pop(package_id)
save_package_state(state)
invalidate_caches()
if install_root is not None:
_delete_validated_install_dir_best_effort(install_root)
def _delete_old_install_dir_best_effort(package_id: str, record: Any) -> None:
"""Delete a previous install directory only when its state pointer validates."""
try:
active = _active_package_from_state(package_id, record)
except Exception:
return
_delete_validated_install_dir_best_effort(active.manifest.root)
def _delete_validated_install_dir_best_effort(path: Path) -> None:
"""Best-effort remove a directory that came from validated active package state."""
try:
root = path.resolve()
if _is_relative_to(root, installed_dir().resolve()) and root.name.startswith("install_"):
shutil.rmtree(root, ignore_errors=True)
except Exception:
pass
def _extract_zip_to_staging(zip_path: Path, staging: Path) -> Path:
seen: set[str] = set()
seen_casefold: set[str] = set()
entries: list[tuple[zipfile.ZipInfo, PurePosixPath, bool]] = []
manifest_candidates: list[PurePosixPath] = []
with zipfile.ZipFile(zip_path) as zf:
for info in zf.infolist():
name = info.filename
is_dir = info.is_dir() or name.endswith("/")
raw_name = name[:-1] if is_dir and name.endswith("/") else name
try:
checked_name = _validate_raw_posix_relative_path(raw_name, "zip member path")
except PackageError as exc:
raise PackageError(f"Unsafe zip member path: {name}") from exc
rel = PurePosixPath(checked_name)
if rel.is_absolute():
raise PackageError(f"Unsafe zip member path: {name}")
if any(part == "__pycache__" for part in rel.parts) or rel.suffix in {".pyc", ".pyo"}:
raise PackageError(f"Unsupported Python cache artifact in package archive: {name}")
mode = (info.external_attr >> 16) & 0o170000
if mode and stat.S_ISLNK(mode):
raise PackageError(f"Unsupported special file in package archive: {name}")
if mode and not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)):
raise PackageError(f"Unsupported special file in package archive: {name}")
normalized = rel.as_posix()
folded = normalized.casefold()
if normalized in seen or folded in seen_casefold:
raise PackageError(f"Duplicate zip destination path: {name}")
seen.add(normalized)
seen_casefold.add(folded)
if rel.name == MANIFEST_NAME:
if is_dir:
raise PackageError(f"Package archive manifest must be a file: {name}")
manifest_candidates.append(rel)
entries.append((info, rel, is_dir))
package_root_rel = _zip_package_root_from_manifest_candidates(manifest_candidates, entries)
staging_root = staging.resolve()
for info, rel, is_dir in entries:
dest = (staging / Path(*rel.parts)).resolve()
if not _is_relative_to(dest, staging_root):
raise PackageError(f"Zip member escapes staging root: {info.filename}")
if is_dir:
dest.mkdir(parents=True, exist_ok=True)
continue
dest.parent.mkdir(parents=True, exist_ok=True)
with zf.open(info) as src, dest.open("wb") as dst:
shutil.copyfileobj(src, dst)
return (staging / Path(*package_root_rel.parts)).resolve() if package_root_rel.parts else staging
def _zip_package_root_from_manifest_candidates(
manifest_candidates: list[PurePosixPath],
entries: list[tuple[zipfile.ZipInfo, PurePosixPath, bool]],
) -> PurePosixPath:
"""Return the only allowed package root layout for a safe zip archive."""
if len(manifest_candidates) != 1:
raise PackageError(f"Package archive must contain exactly one {MANIFEST_NAME}")
manifest = manifest_candidates[0]
if len(manifest.parts) == 1:
return PurePosixPath()
if len(manifest.parts) != 2:
raise PackageError(f"Package archive must contain {MANIFEST_NAME} at root or one top-level directory")
top = manifest.parts[0]
for _info, rel, _is_dir in entries:
if rel.parts and not rel.parts[0].startswith(".") and rel.parts[0] != top:
raise PackageError(f"Package archive with nested {MANIFEST_NAME} must contain one top-level package directory")
return PurePosixPath(top)
@dataclass(frozen=True)
class _PackageCallableInventory:
"""Temporary install-validation inventory for cross-package Examples collisions."""
systems: dict[str, str]
examples: dict[str, Path]
def _normalize_package_callable_inventory(
manifest: PackageManifest,
*,
normalize_native_libraries: bool,
) -> _PackageCallableInventory:
"""Validate every physical Functions owner and collect Examples collisions."""
from .extensions.registry import (
ExtensionOwnerSession,
capture_owner_code_snapshot,
library_owner_key,
system_owner_key,
)
from .package_function_index import scan_package_functions
system_names: dict[str, str] = {}
try:
for record in system_package_records_from_manifests((manifest,)):
session = ExtensionOwnerSession(
capture_owner_code_snapshot(system_owner_key(record), record.root)
)
families, _refs = session.normalize_interface()
for callable_id in families:
name = callable_id.name
if name in system_names:
raise PackageError(
f"Duplicate system constructor {name!r} inside {manifest.package_id}"
)
_validate_public_name(name, "system constructor")
system_names[name] = record.system_id
functions_root = manifest.root_for("functions")
function_owners = scan_package_functions(functions_root) if functions_root else ()
examples_root = manifest.root_for("examples")
examples = _public_entry_entries(examples_root) if examples_root else {}
if normalize_native_libraries:
def validate_native(namespace, name, path, leaf, folder_path):
if (path / "source.nf").is_file():
raise PackageError(
f"V2 hybrid library owner {namespace}/{name} is not supported by this backend-only platform"
)
record = SimpleNamespace(
namespace=namespace, name=leaf, folder_path=folder_path,
package_id=manifest.package_id,
)
session = ExtensionOwnerSession(
capture_owner_code_snapshot(library_owner_key(record), path.resolve())
)
families, _refs = session.normalize_interface()
declared = tuple(callable_id.name for callable_id in families)
if declared != (leaf,):
raise PackageError(
f"Native-only library {namespace}/{name} must declare exactly one EXTENSIONS key equal to {leaf!r}"
)
for owner in function_owners:
if owner.interface_path is not None:
validate_native(
"functions", owner.canonical_owner, owner.path,
owner.name, owner.folder_path,
)
for name, path in examples.items():
if path.is_dir() and (path / "interface.py").is_file():
validate_native("examples", name, path, name, "")
# Only root native Functions owners occupy the same callable slot as a
# systems constructor. Source modules occupy their qualified children.
for owner in function_owners:
if owner.interface_path is not None and not owner.folder_path and owner.name in system_names:
raise PackageError(
f"Public name collision {owner.name!r}: function and constructor both declared by "
f"{manifest.package_id} ({owner.path} and system {system_names[owner.name]})"
)
return _PackageCallableInventory(system_names, examples)
except PackageError:
raise
except CompileError as exc:
raise PackageError(str(exc)) from exc
except Exception as exc:
raise PackageError(f"Could not validate callable declarations for {manifest.package_id}: {exc}") from exc
def _existing_package_validation_inventories(
*,
ignore_package_id: str | None,
) -> list[tuple[PackageManifest, _PackageCallableInventory]]:
"""Return declaration-valid installed package inventories for collision checks."""
state = load_package_state()
inventories = []
for package_id, record in sorted(state.get("packages", {}).items()):
if package_id == ignore_package_id:
continue
try:
active = _structural_active_package_from_state(package_id, record)
inventory = _normalize_package_callable_inventory(
active.manifest,
normalize_native_libraries=False,
)
except PackageError:
# Preserve package-atomic activation: declaration-invalid packages do
# not contribute systems or package library roots to this environment.
continue
inventories.append((active.manifest, inventory))
return inventories
def _validate_no_package_name_collisions(
new_manifest: PackageManifest,
*,
ignore_package_id: str | None = None,
new_inventory: _PackageCallableInventory | None = None,
) -> None:
"""Reject only package/source namespaces that must remain globally unambiguous."""
candidate = new_inventory or _normalize_package_callable_inventory(
new_manifest,
normalize_native_libraries=True,
)
# Source import ownership belongs to the structurally valid manifest, even