-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcompiler_core.py
More file actions
6943 lines (6441 loc) · 268 KB
/
Copy pathcompiler_core.py
File metadata and controls
6943 lines (6441 loc) · 268 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
"""Side-effect-free build engine and command line interface for Universal Compiler.
The GUI is intentionally kept out of this module. The engine can therefore be
used by the CLI, tests, batch automation, and the graphical front end without
creating windows, changing the current desktop, or installing Python packages
as an import side effect.
"""
from __future__ import annotations
import argparse
import copy
import concurrent.futures
from contextlib import contextmanager
import hashlib
import importlib.metadata as importlib_metadata
import importlib.util
import json
import locale as _system_locale
import math
import os
import py_compile
import platform
import re
import shlex
import shutil
import sqlite3
import struct
import subprocess
import sys
import tempfile
import threading
import time
import zipfile
import xml.etree.ElementTree as ET
import uuid
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from dataclasses import asdict, dataclass, field, replace
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Protocol
_fcntl: Any
try:
import fcntl as _fcntl
except ImportError: # pragma: no cover - Windows uses msvcrt.
_fcntl = None
_msvcrt: Any
try:
import msvcrt as _msvcrt
except ImportError: # pragma: no cover - POSIX uses fcntl.
_msvcrt = None
APP_NAME = "Universal Compiler"
VERSION_SCHEMA_VERSION = "uc.version.v1"
VERSION_KIND = "universal-compiler.version"
VERSION_FILENAME = "version.json"
_SEMVER_PATTERN = re.compile(r"^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$")
def _load_app_version() -> str:
"""Load and validate the repository's single application version source."""
version_path = Path(__file__).resolve().with_name(VERSION_FILENAME)
try:
payload = json.loads(version_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
raise RuntimeError(f"Unable to load {VERSION_FILENAME}: {error}") from error
if (
not isinstance(payload, Mapping)
or payload.get("schema_version") != VERSION_SCHEMA_VERSION
or payload.get("kind") != VERSION_KIND
):
raise RuntimeError(f"Invalid {VERSION_FILENAME} schema")
version = payload.get("version")
if not isinstance(version, str) or not _SEMVER_PATTERN.fullmatch(version):
raise RuntimeError(f"Invalid application version in {VERSION_FILENAME}")
return version
APP_VERSION = _load_app_version()
I18N_SCHEMA_VERSION = "uc.i18n.v1"
DEFAULT_LOCALE = "en"
I18N_CATALOG_FILENAME = "catalog.json"
REQUEST_SCHEMA_VERSION = "uc.request.v1"
RESULT_SCHEMA_VERSION = "uc.result.v1"
CAPABILITY_SCHEMA_VERSION = "uc.capability.v1"
COMPATIBILITY_SCHEMA_VERSION = "uc.compatibility.v1"
COMPATIBILITY_KIND = "universal-compiler.compatibility"
TARGET_POLICY_SCHEMA_VERSION = "uc.target-policy.v1"
TARGET_POLICY_KIND = "universal-compiler.target-policy"
ARTIFACT_MANIFEST_SCHEMA_VERSION = "uc.artifact-manifest.v1"
PROJECT_MANIFEST_SCHEMA_VERSION = "uc.project.v1"
PROJECT_MANIFEST_KIND = "universal-compiler.project"
PROJECT_MANIFEST_FILENAME = "universal-compiler.json"
DEPENDENCY_LOCK_SCHEMA_VERSION = "uc.dependencies.v1"
DEPENDENCY_LOCK_KIND = "universal-compiler.dependencies"
DEPENDENCY_LOCK_FILENAME = "universal-compiler.lock.json"
DEPENDENCY_POLICY_VERSION = "uc.dependency-policy.v1"
RELEASE_SCHEMA_VERSION = "uc.release.v1"
RELEASE_KIND = "universal-compiler.release"
SBOM_SCHEMA_VERSION = "uc.sbom.v1"
PROVENANCE_SCHEMA_VERSION = "uc.provenance.v1"
DIAGNOSTICS_SCHEMA_VERSION = "uc.diagnostics.v1"
DIAGNOSTICS_KIND = "universal-compiler.diagnostics"
DEFAULT_DIAGNOSTICS_RETENTION_DAYS = 30
DEFAULT_DIAGNOSTICS_MAX_EVENTS = 2000
ADAPTER_API_VERSION = "uc.adapter.v1"
ADAPTER_ENTRY_POINT_GROUP = "universal_compiler.adapters"
ADAPTER_ALLOWLIST_ENV = "UC_ADAPTER_ALLOWLIST"
ADAPTER_POLICY_VERSION = "uc.adapter-policy.v1"
TARGET_POLICY: dict[str, Any] = {
"schema_version": TARGET_POLICY_SCHEMA_VERSION,
"kind": TARGET_POLICY_KIND,
"families": {
"windows-desktop": {
"status": "supported",
"host_platforms": ["windows"],
"targets": ["native", "windows"],
"artifact_model": "Windows PE or Windows package",
"mobile": False,
},
"non-windows-host": {
"status": "catalog-only",
"host_platforms": ["linux", "darwin"],
"targets": ["linux", "darwin"],
"artifact_model": "Non-Windows platform executable when an adapter provides CI proof",
"mobile": False,
"built_in_adapter_support": False,
},
"wasm-module": {
"status": "supported",
"host_platforms": ["windows"],
"targets": ["wasm"],
"artifact_model": "WebAssembly module requiring a host runtime",
"mobile": False,
},
"wasi-module": {
"status": "experimental",
"host_platforms": ["windows"],
"targets": ["wasi"],
"artifact_model": "WebAssembly module requiring a matching WASI host/profile",
"mobile": False,
},
"native-mobile": {
"status": "out-of-scope",
"host_platforms": ["windows", "linux", "darwin"],
"targets": ["android", "ios"],
"artifact_model": "Installable native mobile package",
"mobile": True,
"supported": False,
"installable_artifact": False,
"ci_proof": False,
"reason": "No platform-valid Android/iOS adapter and CI install proof exists in this major line",
},
},
}
NATIVE_MOBILE_TARGETS = frozenset({"android", "ios"})
def target_policy() -> dict[str, Any]:
"""Return a copy of the explicit host, portable, and mobile target policy."""
return copy.deepcopy(TARGET_POLICY)
def target_family_for(value: str) -> str | None:
"""Classify a target token without treating a name as build proof."""
token = str(value or "").strip().lower().replace("_", "-")
if not token or token in {"native", "auto"}:
return "windows-desktop"
if any(
token == mobile or token.startswith(f"{mobile}-") or token.endswith(f"-{mobile}")
or f"-{mobile}-" in token
for mobile in NATIVE_MOBILE_TARGETS
):
return "native-mobile"
if "wasi" in token:
return "wasi-module"
if token == "wasm" or token.startswith("wasm-") or token.endswith("-wasm"):
return "wasm-module"
if token in {"windows", "win32", "win64"} or "windows" in token:
return "windows-desktop"
if token in {"linux", "darwin", "macos", "osx"} or any(
token.endswith(f"-{platform}") or f"-{platform}-" in token
for platform in ("linux", "darwin")
):
return "non-windows-host"
return None
_BUILTIN_I18N_CATALOG: dict[str, Any] = {
"schema_version": I18N_SCHEMA_VERSION,
"default_locale": DEFAULT_LOCALE,
"locales": {
"en": {
"messages": {
"app.title": APP_NAME,
"status.ready": "Ready",
"status.compiling": "Compiling...",
"status.cancelling": "Cancelling...",
"status.complete": "Complete!",
"status.failed": "Failed",
"cli.error": "ERROR: {error}",
"cli.warning": "WARNING: {warning}",
},
"plurals": {
"queue.files": {"one": "{count} file", "other": "{count} files"}
},
"format": {
"decimal_separator": ".",
"group_separator": ",",
"date_format": "%Y-%m-%d",
"time_format": "%H:%M:%S",
},
}
},
}
def normalize_locale(value: str | None) -> str:
"""Normalize a BCP-47/POSIX locale token for catalog lookup."""
if not value:
return ""
token = str(value).strip().replace("_", "-")
if not token or token.lower() in {"auto", "c", "posix"}:
return ""
parts = token.split("-")
return "-".join(
[parts[0].lower(), *[part.upper() if len(part) == 2 else part for part in parts[1:]]]
)
def resolve_locale(
preferred: str | None = None,
environment: Mapping[str, str] | None = None,
available: Iterable[str] | None = None,
) -> str:
"""Choose a catalog locale using explicit, environment, then OS settings.
``UC_LOCALE`` and ``UNIVERSAL_COMPILER_LOCALE`` are intentionally first-class
overrides so CLI, Tk, and PowerShell launches can select the same locale
without mutating the process-wide C/POSIX locale.
"""
values = {normalize_locale(value) for value in (available or (DEFAULT_LOCALE,))}
values.discard("")
default = normalize_locale(DEFAULT_LOCALE) or DEFAULT_LOCALE
if default not in values:
values.add(default)
env = os.environ if environment is None else environment
candidates = [preferred]
candidates.extend(
env.get(name)
for name in ("UC_LOCALE", "UNIVERSAL_COMPILER_LOCALE", "LC_ALL", "LANG")
)
try:
candidates.append(_system_locale.getlocale()[0])
except ValueError:
pass
for candidate in candidates:
normalized = normalize_locale(candidate)
if not normalized:
continue
if normalized in values:
return normalized
base = normalized.split("-", 1)[0]
if base in values:
return base
return default
def _catalog_value(mapping: Any, key: str) -> Any:
if isinstance(mapping, Mapping):
return mapping.get(key)
return None
class MessageCatalog:
"""Shared, dependency-free message and locale formatting catalog."""
def __init__(
self,
locale_name: str | None = None,
catalog_path: os.PathLike[str] | str | None = None,
environment: Mapping[str, str] | None = None,
) -> None:
source = (
Path(catalog_path).expanduser()
if catalog_path
else Path(__file__).resolve().parent / "resources" / "i18n" / I18N_CATALOG_FILENAME
)
payload: Mapping[str, Any] = _BUILTIN_I18N_CATALOG
try:
loaded = json.loads(source.read_text(encoding="utf-8"))
if (
isinstance(loaded, Mapping)
and loaded.get("schema_version") == I18N_SCHEMA_VERSION
and isinstance(loaded.get("locales"), Mapping)
):
payload = loaded
except (OSError, ValueError, TypeError):
pass
self.source = source
self.default_locale = normalize_locale(
str(payload.get("default_locale", DEFAULT_LOCALE))
) or DEFAULT_LOCALE
raw_locales = payload.get("locales", {})
self.locales: dict[str, Mapping[str, Any]] = {
normalize_locale(str(name)): value
for name, value in raw_locales.items()
if normalize_locale(str(name)) and isinstance(value, Mapping)
}
if self.default_locale not in self.locales:
self.locales[DEFAULT_LOCALE] = _BUILTIN_I18N_CATALOG["locales"]["en"]
self.locale = resolve_locale(
locale_name,
environment=environment,
available=self.locales,
)
@property
def available_locales(self) -> tuple[str, ...]:
return tuple(sorted(self.locales))
def _locale_data(self) -> Mapping[str, Any]:
return self.locales.get(self.locale, self.locales[self.default_locale])
def message(self, key: str, default: str | None = None, **values: Any) -> str:
"""Return a translated message, falling back to English and the key."""
localized = _catalog_value(self._locale_data().get("messages"), key)
fallback = _catalog_value(self.locales[self.default_locale].get("messages"), key)
template = localized or fallback or default or key
if not isinstance(template, str):
template = str(template)
try:
return template.format(**values)
except (IndexError, KeyError, ValueError):
return template
def plural(
self,
key: str,
quantity: int | float,
default: str | None = None,
**values: Any,
) -> str:
"""Format a two-form plural message with an English fallback."""
forms = _catalog_value(self._locale_data().get("plurals"), key)
if not isinstance(forms, Mapping):
forms = _catalog_value(
self.locales[self.default_locale].get("plurals"), key
)
template = forms.get("one" if quantity == 1 else "other") if forms else None
if not isinstance(template, str):
template = default or key
values.setdefault("count", quantity)
return self.message_from_template(template, **values)
@staticmethod
def message_from_template(template: str, **values: Any) -> str:
try:
return template.format(**values)
except (IndexError, KeyError, ValueError):
return template
def format_number(self, value: int | float, decimals: int = 0) -> str:
"""Format a number using catalog separators without changing global locale."""
formatting = self._locale_data().get("format", {})
decimal_separator = str(formatting.get("decimal_separator", "."))
group_separator = str(formatting.get("group_separator", ","))
rendered = f"{float(value):,.{max(0, int(decimals))}f}"
integer, _, fraction = rendered.partition(".")
integer = integer.replace(",", group_separator)
return integer if not fraction else integer + decimal_separator + fraction
def format_size(self, size: int) -> str:
"""Format bytes with locale-aware separators and stable binary units."""
value = float(size)
for unit in ("B", "KB", "MB", "GB", "TB"):
if abs(value) < 1024 or unit == "TB":
decimals = 0 if unit == "B" else 1
return f"{self.format_number(value, decimals)} {unit}"
value /= 1024
return f"{self.format_number(value, 1)} TB"
def format_datetime(self, value: datetime) -> str:
"""Format a timestamp using the catalog's locale date/time pattern."""
formatting = self._locale_data().get("format", {})
date_format = str(formatting.get("date_format", "%Y-%m-%d"))
time_format = str(formatting.get("time_format", "%H:%M:%S"))
return value.strftime(f"{date_format} {time_format}")
def get_message_catalog(
locale_name: str | None = None,
catalog_path: os.PathLike[str] | str | None = None,
environment: Mapping[str, str] | None = None,
) -> MessageCatalog:
"""Return the shared catalog used by CLI and graphical shells."""
return MessageCatalog(locale_name, catalog_path, environment)
def contrast_ratio(foreground: str, background: str) -> float:
"""Return the WCAG relative-luminance contrast ratio for two hex colors."""
def luminance(color: str) -> float:
token = color.strip().lstrip("#")
if len(token) == 3:
token = "".join(character * 2 for character in token)
if len(token) != 6:
raise ValueError(f"Expected a six-digit hex color, got {color!r}")
channels = [int(token[index : index + 2], 16) / 255 for index in (0, 2, 4)]
linear = [
channel / 12.92
if channel <= 0.04045
else ((channel + 0.055) / 1.055) ** 2.4
for channel in channels
]
return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
lighter = max(luminance(foreground), luminance(background))
darker = min(luminance(foreground), luminance(background))
return (lighter + 0.05) / (darker + 0.05)
DEFAULT_PROFILES: dict[str, dict[str, Any]] = {
"Default": {
"console": False,
"admin": False,
"single_file": True,
"backend": "auto",
"target": "native",
"architecture": "native",
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
"prefetch": False,
"verify": True,
"cache": True,
"toolchain_versions": {},
"upx": False,
},
"Console App": {
"console": True,
"admin": False,
"single_file": True,
"backend": "auto",
"target": "native",
"architecture": "native",
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
"prefetch": False,
"verify": True,
"cache": True,
"toolchain_versions": {},
"upx": False,
},
"Admin Tool": {
"console": True,
"admin": True,
"single_file": True,
"backend": "auto",
"target": "native",
"architecture": "native",
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
"prefetch": False,
"verify": True,
"cache": True,
"toolchain_versions": {},
"upx": False,
},
"GUI Application": {
"console": False,
"admin": False,
"single_file": True,
"backend": "auto",
"target": "native",
"architecture": "native",
"version": "1.0.0.0",
"company": "",
"copyright": "",
"description": "",
"product": "",
"prefetch": False,
"verify": True,
"cache": True,
"toolchain_versions": {},
"upx": False,
},
}
DEFAULT_MANIFEST_SETTINGS: dict[str, Any] = {
"theme": "Dark",
"locale": "",
"post_build_action": "None",
"post_build_copy_path": "",
"show_notifications": True,
"auto_check_updates": True,
"max_recent_files": 10,
"max_history_items": 50,
"default_profile": "Default",
}
PROJECT_MANIFEST_PROFILE_FIELDS = frozenset(
{
"console",
"admin",
"single_file",
"backend",
"target",
"architecture",
"version",
"company",
"copyright",
"description",
"product",
"assets",
"permissions",
"prefetch",
"verify",
"cache",
"force",
"extra_args",
"toolchain_versions",
"upx",
"timeout_seconds",
"max_output_bytes",
"allow_network",
"allow_dependency_install",
"dependency_lockfile",
"dependency_cache_dir",
"dependency_mirror",
}
)
PROJECT_MANIFEST_SETTINGS_FIELDS = frozenset(DEFAULT_MANIFEST_SETTINGS)
PROJECT_MANIFEST_HISTORY_FIELDS = frozenset(
{"timestamp", "source", "output", "type", "success", "profile", "size", "backend", "message", "manifest"}
)
PROJECT_MANIFEST_ANALYTICS_FIELDS = frozenset({"enabled", "scope", "database"})
BACKEND_CATALOG: dict[str, dict[str, Any]] = {
"ps2exe": {
"name": "PowerShell PS2EXE", "extensions": ("ps1",), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": ("PowerShell",),
},
"pyinstaller": {
"name": "Python PyInstaller", "extensions": ("py", "pyw"), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": ("Python",),
},
"python-zipapp": {
"name": "Python zipapp", "extensions": ("py", "pyw"), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native",), "required_sdks": ("Python",), "auto_select": False,
},
"pex": {
"name": "Python PEX", "extensions": ("py", "pyw"), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native",), "required_sdks": ("Python", "PEX"), "auto_select": False,
},
"nuitka": {
"name": "Python Nuitka", "extensions": ("py", "pyw"), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": ("Python", "C compiler"),
},
"iexpress": {
"name": "Windows IExpress", "extensions": ("bat", "cmd", "vbs"), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native",), "required_sdks": ("Windows",),
},
"bun": {
"name": "Bun compile", "extensions": ("js", "ts"), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": ("Bun",),
},
"deno": {
"name": "Deno compile", "extensions": ("js",), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": ("Deno",),
},
"pkg": {
"name": "Node.js pkg", "extensions": ("js",), "status": "deprecated",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": ("Node.js",),
},
"node-sea": {
"name": "Node.js Single Executable Applications", "extensions": ("js",), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native", "x64", "arm64"), "required_sdks": ("Node.js", "postject"),
"auto_select": False,
},
"ahk2exe": {
"name": "AutoHotkey Ahk2Exe", "extensions": ("ahk",), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native",), "required_sdks": ("AutoHotkey",),
},
"csc": {
"name": "C# CSC", "extensions": ("cs",), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": (".NET Framework",),
},
"go": {
"name": "Go build", "extensions": ("go",), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native", "x86", "x64", "amd64", "arm64"), "required_sdks": ("Go",),
},
"ocra": {
"name": "Ruby Ocra", "extensions": ("rb",), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native",), "required_sdks": ("Ruby",),
},
"rust": {
"name": "Rust cargo/rustc", "extensions": ("rs",), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native", "x86", "x64", "amd64", "arm64"), "required_sdks": ("Rust",),
},
"srlua": {
"name": "Lua srlua", "extensions": ("lua",), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native",), "required_sdks": ("srlua",),
},
"luastatic": {
"name": "Lua luastatic", "extensions": ("lua",), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native",), "required_sdks": ("luastatic",),
},
"perl-pp": {
"name": "Perl PAR::Packer", "extensions": ("pl", "pm"), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native",), "required_sdks": ("Perl",),
},
"kotlin-native": {
"name": "Kotlin/Native", "extensions": ("kt", "kts"), "status": "experimental",
"host_platforms": ("windows",), "target_platforms": ("native", "windows", "linux", "darwin"),
"architectures": ("native", "x86", "x64", "arm64"), "required_sdks": ("Kotlin/Native",),
},
"wat2wasm": {
"name": "WebAssembly wat2wasm", "extensions": ("wat",), "status": "stable",
"host_platforms": ("windows",), "target_platforms": ("native", "wasm", "wasi"),
"architectures": ("native",), "required_sdks": ("WABT",),
},
"upx": {
"name": "UPX compressor", "extensions": (), "status": "optional",
"host_platforms": ("windows",), "target_platforms": ("native", "windows"),
"architectures": ("native",), "required_sdks": ("UPX",),
},
}
BACKEND_ARTIFACT_POLICIES: dict[str, dict[str, str]] = {
"ps2exe": {
"type": "windows-pe",
"runtime": "PowerShell runtime selected by PS2EXE",
"assets": "Source and declared assets follow PS2EXE packaging rules",
"verification": "Static PE/container structure and optional sidecar",
},
"pyinstaller": {
"type": "windows-pe",
"runtime": "Python runtime is bundled by PyInstaller",
"assets": "Imports and data files must be collected by the packaging plan",
"verification": "Static PE/container structure and optional sidecar",
},
"python-zipapp": {
"type": "python-zipapp",
"runtime": "The invoking Python interpreter supplies the runtime",
"assets": "Declared files are copied into the archive under assets/",
"verification": "Static ZIP structure and optional sidecar",
},
"pex": {
"type": "python-pex",
"runtime": "PEX selects or bootstraps a Python runtime at launch",
"assets": "Declared files are copied into the PEX source tree under assets/",
"verification": "Static ZIP structure and optional sidecar",
},
"nuitka": {
"type": "windows-pe",
"runtime": "Compiled Python code plus toolchain/runtime dependencies",
"assets": "Dynamic imports and data files remain packaging inputs",
"verification": "Static PE/container structure and optional sidecar",
},
"iexpress": {
"type": "windows-self-extracting-package",
"runtime": "Payload runtime is external to the package wrapper",
"assets": "The payload archive is the explicit asset boundary",
"verification": "Static PE/container structure and optional sidecar",
},
"bun": {
"type": "platform-executable",
"runtime": "Bun JavaScript runtime is bundled by the selected target",
"assets": "Runtime assets and dynamic modules follow Bun compile rules",
"verification": "Static executable/container structure and optional sidecar",
},
"deno": {
"type": "platform-executable",
"runtime": "Deno JavaScript runtime is bundled by the selected target",
"assets": "Permissions, imports, and assets follow Deno compile rules",
"verification": "Static executable/container structure and optional sidecar",
},
"pkg": {
"type": "platform-executable",
"runtime": "Node.js runtime is bundled by the archived pkg toolchain",
"assets": "Dynamic modules and assets require explicit pkg configuration",
"verification": "Static executable/container structure and optional sidecar",
},
"node-sea": {
"type": "platform-executable",
"runtime": "Node.js runtime is embedded through SEA and postject",
"assets": "Declared files are encoded in the SEA assets map",
"verification": "Static PE/container structure and optional sidecar",
},
"ahk2exe": {
"type": "windows-pe",
"runtime": "AutoHotkey runtime is embedded by Ahk2Exe",
"assets": "Included script resources follow Ahk2Exe packaging rules",
"verification": "Static PE/container structure and optional sidecar",
},
"csc": {
"type": "managed-executable",
"runtime": ".NET Framework/runtime dependencies remain framework-dependent",
"assets": "Referenced assemblies and data files are external deployment inputs",
"verification": "Static PE/container structure and optional sidecar",
},
"go": {
"type": "platform-executable",
"runtime": "Native Go runtime and platform libraries",
"assets": "External files and platform services remain deployment inputs",
"verification": "Static executable/container structure and optional sidecar",
},
"ocra": {
"type": "windows-pe",
"runtime": "Ruby runtime is bundled according to Ocra packaging rules",
"assets": "Ruby dependencies and data files require explicit collection",
"verification": "Static PE/container structure and optional sidecar",
},
"rust": {
"type": "platform-executable",
"runtime": "Native Rust runtime and platform libraries",
"assets": "External files and platform services remain deployment inputs",
"verification": "Static executable/container structure and optional sidecar",
},
"srlua": {
"type": "windows-pe",
"runtime": "Lua interpreter is embedded by the srlua toolchain",
"assets": "Lua modules and data files require explicit collection",
"verification": "Static PE/container structure and optional sidecar",
},
"luastatic": {
"type": "windows-pe",
"runtime": "Lua interpreter is linked by the luastatic toolchain",
"assets": "Lua modules and data files require explicit collection",
"verification": "Static PE/container structure and optional sidecar",
},
"perl-pp": {
"type": "windows-pe",
"runtime": "Perl runtime is bundled according to PAR::Packer rules",
"assets": "Perl modules and data files require explicit collection",
"verification": "Static PE/container structure and optional sidecar",
},
"kotlin-native": {
"type": "platform-executable",
"runtime": "Kotlin/Native runtime and target libraries",
"assets": "External files and platform services remain deployment inputs",
"verification": "Static executable/container structure and optional sidecar",
},
"wat2wasm": {
"type": "wasm-module",
"runtime": "A WebAssembly host or WASI runtime is required",
"assets": "Imports, host APIs, and data files remain external",
"verification": "Static WebAssembly sections and optional sidecar",
},
"upx": {
"type": "compressed-executable-transform",
"runtime": "The input artifact's runtime is unchanged",
"assets": "The input artifact and its deployment assets remain authoritative",
"verification": "Static container/PE structure and optional sidecar",
},
}
def artifact_policy_for_backend(backend: str) -> dict[str, str]:
"""Return an immutable-shaped artifact policy for a backend identifier."""
policy = BACKEND_ARTIFACT_POLICIES.get(
backend,
{
"type": "adapter-defined",
"runtime": "Defined by the external adapter",
"assets": "Defined by the external adapter contract",
"verification": "Static verification required by the adapter contract",
},
)
return {str(key): str(value) for key, value in policy.items()}
EXTENSION_BACKENDS: dict[str, tuple[str, ...]] = {}
for _backend_name, _backend_spec in BACKEND_CATALOG.items():
for _extension in _backend_spec["extensions"]:
EXTENSION_BACKENDS.setdefault(_extension, ())
EXTENSION_BACKENDS[_extension] += (_backend_name,)
BACKEND_NAMES: dict[str, str] = {
backend: str(spec["name"]) for backend, spec in BACKEND_CATALOG.items()
}
OBFUSCATOR_NAMES: dict[str, str] = {
"pyarmor": "PyArmor Python obfuscator",
"javascript-obfuscator": "JavaScript Obfuscator",
"confuserex": "ConfuserEx .NET obfuscator",
}
class BuildValidationError(ValueError):
"""Raised when a build request cannot be safely planned."""
class StateLockError(BuildValidationError):
"""Raised when a local state file cannot be locked within the bound."""
DEFAULT_EXECUTION_TIMEOUT_SECONDS = 15 * 60
DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024
DEFAULT_STATE_LOCK_TIMEOUT_SECONDS = 15.0
STATE_LOCK_POLL_SECONDS = 0.05
ANALYTICS_BUSY_TIMEOUT_MS = 10_000
ANALYTICS_SCHEMA_VERSION = 1
MAX_CLEANUP_PATHS = 32
DEFAULT_INHERITED_ENVIRONMENT = (
"APPDATA",
"COMSPEC",
"HOME",
"HOMEDRIVE",
"HOMEPATH",
"LOCALAPPDATA",
"NUMBER_OF_PROCESSORS",
"PATH",
"PATHEXT",
"PROCESSOR_ARCHITECTURE",
"PROGRAMDATA",
"PROGRAMFILES",
"PROGRAMFILES(X86)",
"SYSTEMDRIVE",
"SYSTEMROOT",
"TEMP",
"TMP",
"USERDOMAIN",
"USERNAME",
"USERPROFILE",
"VIRTUAL_ENV",
"WINDIR",
)
_STATE_LOCKS: dict[str, threading.RLock] = {}
_STATE_LOCKS_GUARD = threading.Lock()
_BUILD_LOCKS: dict[str, threading.RLock] = {}
def _state_lock_key(path: os.PathLike[str] | str) -> str:
candidate = Path(path).expanduser()
try:
candidate = candidate.resolve()
except OSError:
candidate = Path(os.path.abspath(candidate))
return os.path.normcase(str(candidate))
def _state_thread_lock(path: os.PathLike[str] | str) -> threading.RLock:
key = _state_lock_key(path)
with _STATE_LOCKS_GUARD:
lock = _STATE_LOCKS.get(key)
if lock is None:
lock = threading.RLock()
_STATE_LOCKS[key] = lock
return lock
@contextmanager
def state_lock(
path: os.PathLike[str] | str,
timeout: float = DEFAULT_STATE_LOCK_TIMEOUT_SECONDS,
) -> Iterator[Path]:
"""Coordinate state writers across threads and processes.
The lock file is deliberately retained beside the state file. OS-level
locks are released when the owning process exits, so a stale lock file
never becomes a false permanent lock and remains discoverable for support.
"""
destination = Path(path).expanduser()
lock_path = destination.with_name(f".{destination.name}.lock")
lock_path.parent.mkdir(parents=True, exist_ok=True)
thread_lock = _state_thread_lock(lock_path)
if not thread_lock.acquire(timeout=max(0.0, float(timeout))):
raise StateLockError(f"Timed out waiting for state lock: {lock_path}")
handle = None
deadline = time.monotonic() + max(0.0, float(timeout))
try:
handle = lock_path.open("a+b")
handle.seek(0, os.SEEK_END)
if handle.tell() == 0:
handle.write(b"0")
handle.flush()
while True:
try:
handle.seek(0)
if os.name == "nt" and _msvcrt is not None:
_msvcrt.locking(handle.fileno(), _msvcrt.LK_NBLCK, 1)
elif _fcntl is not None:
_fcntl.flock(handle.fileno(), _fcntl.LOCK_EX | _fcntl.LOCK_NB)
else: # pragma: no cover - supported runtimes have one backend.
raise StateLockError("No supported process lock implementation")
break
except OSError as error:
if time.monotonic() >= deadline:
raise StateLockError(
f"Timed out waiting for state lock: {lock_path}"
) from error
time.sleep(STATE_LOCK_POLL_SECONDS)
try:
yield lock_path
finally:
try:
handle.seek(0)
if os.name == "nt" and _msvcrt is not None:
_msvcrt.locking(handle.fileno(), _msvcrt.LK_UNLCK, 1)
elif _fcntl is not None:
_fcntl.flock(handle.fileno(), _fcntl.LOCK_UN)
except OSError:
pass
finally:
if handle is not None:
handle.close()
thread_lock.release()
_BUILD_LOCKS_GUARD = threading.Lock()
def _output_lock_key(path: os.PathLike[str] | str) -> str:
"""Return a case-insensitive identity for a build output path."""
candidate = Path(path).expanduser()
try:
candidate = candidate.resolve()
except OSError:
candidate = Path(os.path.abspath(candidate))
return os.path.normcase(str(candidate))
def _output_lock(path: os.PathLike[str] | str) -> threading.RLock:
"""Return a process-wide lock so separate engines cannot publish together."""
key = _output_lock_key(path)
with _BUILD_LOCKS_GUARD:
lock = _BUILD_LOCKS.get(key)
if lock is None:
lock = threading.RLock()
_BUILD_LOCKS[key] = lock
return lock
def _cleanup_paths(paths: Iterable[Path]) -> None:
"""Remove only bounded, build-owned temporary paths."""
unique: list[Path] = []
seen: set[str] = set()
for raw_path in paths:
path = Path(raw_path)
key = _output_lock_key(path)
if key not in seen:
seen.add(key)
unique.append(path)
if len(unique) >= MAX_CLEANUP_PATHS:
break
for path in reversed(unique):
try:
if path.is_dir():
shutil.rmtree(path)
elif path.exists():
path.unlink()
except OSError:
pass