rea-agents 6.3.0 → 6.5.0

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.
Files changed (1332) hide show
  1. package/DISCLAIMER.md +136 -0
  2. package/README.md +72 -18
  3. package/THIRD_PARTY_NOTICES.md +134 -0
  4. package/bridge/android/ReaJadxBridge.java +123 -11
  5. package/bridge/cutter/rea_bridge.py +816 -0
  6. package/bridge/ghidra/ReaGhidraAnalysisOptions.java +38 -0
  7. package/bridge/ghidra/ReaGhidraApplySeeds.java +151 -0
  8. package/bridge/ghidra/ReaGhidraBridge.java +1729 -283
  9. package/bridge/ghidra/ReaGhidraBundleActivator.java +14 -0
  10. package/bridge/ghidra/ReaGhidraMipsSoftFloat.java +176 -0
  11. package/bridge/ghidra/ReaGhidraNoReturnFix.java +123 -0
  12. package/bridge/ghidra/ReaGhidraPrepareRaw.java +49 -0
  13. package/bridge/hopper_bridge.py +103 -69
  14. package/bridge/mitmproxy/capture.py +189 -13
  15. package/bridge/native/rea_lldb_tracer.py +40 -6
  16. package/bridge/process/ProcessRunTokenReader.swift +76 -34
  17. package/bridge/pwntools/layout_impl.py +5 -0
  18. package/bridge/pwntools/recorded_crash_impl.py +31 -10
  19. package/dist/adb/AdbConfiguration.js +100 -0
  20. package/dist/adb/AdbDeviceOutput.js +208 -0
  21. package/dist/adb/AdbDirectoryListing.js +80 -0
  22. package/dist/adb/AdbHostFileName.js +34 -0
  23. package/dist/adb/AdbProvider.js +1433 -0
  24. package/dist/adb/AdbShellOutput.js +307 -0
  25. package/dist/android/AndroidTargetSnapshot.js +104 -22
  26. package/dist/android/JadxAnalysis.js +32 -7
  27. package/dist/android/JadxConfiguration.js +163 -53
  28. package/dist/android/JadxDoctor.js +115 -0
  29. package/dist/android/JadxMcpTransport.js +5 -3
  30. package/dist/android/JadxProtocol.js +14 -0
  31. package/dist/android/JadxProvider.js +63 -25
  32. package/dist/android/JadxRelease.js +12 -1
  33. package/dist/android/JadxWorkspaceRoot.js +157 -0
  34. package/dist/apktool/ApktoolConfiguration.js +227 -0
  35. package/dist/apktool/ApktoolDecodeOutput.js +142 -0
  36. package/dist/apktool/ApktoolProvider.js +543 -0
  37. package/dist/application/AnalysisContextQueries.js +5 -8
  38. package/dist/application/AnalysisProvider.js +24 -14
  39. package/dist/application/AppBundleExecutable.js +30 -25
  40. package/dist/application/BinaryTargetResolver.js +210 -33
  41. package/dist/application/BrowserEvidence.js +1 -1
  42. package/dist/application/BrowserObservationService.js +13 -2
  43. package/dist/application/BrowserScenarioCaptureService.js +0 -1
  44. package/dist/application/CallPathTracing.js +52 -13
  45. package/dist/application/CapabilityInventory.js +179 -29
  46. package/dist/application/ClaudeDesktopConfigLocation.js +152 -0
  47. package/dist/application/ClientConfigurationDocument.js +154 -7
  48. package/dist/application/ClientConfigurationFiles.js +128 -0
  49. package/dist/application/ClientRegistrationEnvironment.js +41 -0
  50. package/dist/application/ClientRegistrationIdentity.js +94 -29
  51. package/dist/application/ClientRegistrationStatus.js +223 -67
  52. package/dist/application/DirectAnalysis.js +86 -31
  53. package/dist/application/DirectAnalysisCleanup.js +1 -1
  54. package/dist/application/DirectAnalysisStatus.js +14 -2
  55. package/dist/application/Doctor.js +117 -34
  56. package/dist/application/DoctorDiagnostics.js +34 -12
  57. package/dist/application/DoctorProviderIds.js +2 -0
  58. package/dist/application/DoctorScope.js +11 -2
  59. package/dist/application/DshCordisPatch.js +355 -0
  60. package/dist/application/DshCordisYaml.js +155 -0
  61. package/dist/application/EnhancedLiteralTracing.js +30 -16
  62. package/dist/application/EnhancedToolTypes.js +0 -1
  63. package/dist/application/EnhancedTools.js +164 -54
  64. package/dist/application/EvidenceBundleCommands.js +36 -19
  65. package/dist/application/EvidenceBundleFiles.js +29 -7
  66. package/dist/application/FunctionAnalysisEvidence.js +3 -0
  67. package/dist/application/GeminiClientSettings.js +151 -0
  68. package/dist/application/HermesClientHome.js +115 -0
  69. package/dist/application/HermesConfigurationYaml.js +272 -0
  70. package/dist/application/HopperDownload.js +39 -0
  71. package/dist/application/InventoryProjectionEvidence.js +0 -1
  72. package/dist/application/InvestigationProviders.js +19 -3
  73. package/dist/application/JsonFiles.js +114 -23
  74. package/dist/application/JsonInputFile.js +410 -0
  75. package/dist/application/LinuxHopper.js +130 -60
  76. package/dist/application/MacHopper.js +177 -150
  77. package/dist/application/MacHopperPaths.js +40 -0
  78. package/dist/application/MipsElfMetadata.js +201 -0
  79. package/dist/application/MipsElfSharedLoad.js +164 -0
  80. package/dist/application/MipsGnuAttributes.js +90 -0
  81. package/dist/application/MsixPackageStorage.js +133 -0
  82. package/dist/application/ProgressReporter.js +1 -1
  83. package/dist/application/ProviderOperationExecution.js +39 -0
  84. package/dist/application/ReconstructionCoverageService.js +0 -1
  85. package/dist/application/ReconstructionObligationCandidates.js +12 -5
  86. package/dist/application/ReconstructionObligationLedgerDiagnostics.js +2 -2
  87. package/dist/application/ReconstructionObligationLedgerEvaluation.js +15 -33
  88. package/dist/application/ReconstructionObligationLedgerProjection.js +3 -72
  89. package/dist/application/ReconstructionObligationLedgerService.js +3 -1
  90. package/dist/application/ReconstructionObligationOriginalCases.js +2 -1
  91. package/dist/application/ReferenceSourceImport.js +94 -31
  92. package/dist/application/ReferenceSourceImportEntries.js +40 -30
  93. package/dist/application/ReferenceSourceImportPolicy.js +99 -23
  94. package/dist/application/ReferenceSourceImportTypes.js +30 -23
  95. package/dist/application/ReferenceSourceVcsAdapter.js +163 -31
  96. package/dist/application/RegularFileRead.js +121 -7
  97. package/dist/application/Setup.js +88 -14
  98. package/dist/application/SetupClientConfiguration.js +307 -38
  99. package/dist/application/SetupClients.js +12 -6
  100. package/dist/application/SetupHost.js +158 -38
  101. package/dist/application/SetupInstallFailure.js +42 -2
  102. package/dist/application/SetupPlan.js +83 -57
  103. package/dist/application/SetupRecoveryBackup.js +66 -0
  104. package/dist/application/SetupRegistrationEnvironment.js +2 -1
  105. package/dist/application/SetupSkill.js +354 -88
  106. package/dist/application/SupportedClients.js +429 -70
  107. package/dist/application/TypeScriptEmittedSourceCandidates.js +26 -0
  108. package/dist/application/Uninstall.js +412 -73
  109. package/dist/application/UninstallFailure.js +14 -0
  110. package/dist/application/Update.js +54 -25
  111. package/dist/application/UpdateFailure.js +17 -0
  112. package/dist/application/UpdateMaintenance.js +25 -47
  113. package/dist/application/UpdateRuntime.js +141 -27
  114. package/dist/application/Utf8JsonInput.js +7 -0
  115. package/dist/application/WebModuleTraceService.js +7 -0
  116. package/dist/application/WebNetworkCaptureService.js +16 -7
  117. package/dist/application/WebScriptExportService.js +131 -65
  118. package/dist/application/WebSourceLocationService.js +22 -3
  119. package/dist/application/WindowsCapabilities.js +18 -15
  120. package/dist/application/WorkflowEvidence.js +24 -1
  121. package/dist/application/adb/AdbDeviceAnalysisPort.js +1 -0
  122. package/dist/application/adb/AdbDeviceAnalysisService.js +13 -0
  123. package/dist/application/analysisView/AnalysisViewService.js +122 -6
  124. package/dist/application/android/AndroidPackageInspection.js +25 -0
  125. package/dist/application/android/AndroidSearchEvidenceSummary.js +100 -0
  126. package/dist/application/apktool/ApktoolResourceAnalysisPort.js +1 -0
  127. package/dist/application/apktool/ApktoolResourceAnalysisService.js +13 -0
  128. package/dist/application/binary/AnalysisClientCleanup.js +0 -24
  129. package/dist/application/binary/AnalysisProviderEvaluation.js +1 -1
  130. package/dist/application/binary/AnalysisProviderRegistry.js +36 -21
  131. package/dist/application/binary/AnalysisSnapshotCache.js +41 -20
  132. package/dist/application/binary/AnalysisSnapshotFiles.js +75 -9
  133. package/dist/application/binary/BinarySession.js +250 -97
  134. package/dist/application/binary/BinarySessionExecution.js +5 -4
  135. package/dist/application/binary/BinarySessionOpen.js +13 -6
  136. package/dist/application/binary/BinarySessionRecords.js +33 -7
  137. package/dist/application/binary/BinarySessionStatus.js +93 -23
  138. package/dist/application/binary/BinaryTargetSummary.js +9 -0
  139. package/dist/application/binary/CompositeProvider.js +71 -28
  140. package/dist/application/binary/LazyAnalysisProvider.js +3 -1
  141. package/dist/application/binary/SessionProviderRouter.js +5 -2
  142. package/dist/application/binaryDiagnostics/BinaryLayoutService.js +13 -2
  143. package/dist/application/binaryDiagnostics/PeResourcesPort.js +1 -0
  144. package/dist/application/binaryDiagnostics/PeResourcesService.js +114 -0
  145. package/dist/application/binaryDiagnostics/RecordedCrashService.js +16 -4
  146. package/dist/application/captures/PacketCaptureService.js +83 -0
  147. package/dist/application/closeOwnedWebResources.js +7 -0
  148. package/dist/application/electron/ElectronFusePort.js +1 -0
  149. package/dist/application/electron/ElectronFuseService.js +80 -0
  150. package/dist/application/evm/EvmInterfaceService.js +4 -0
  151. package/dist/application/firmware/FirmwareAnalysisService.js +3 -0
  152. package/dist/application/flutter/DartAotInspection.js +26 -0
  153. package/dist/application/flutter/FlutterBuildAnalysisPort.js +1 -0
  154. package/dist/application/flutter/FlutterBuildAnalysisService.js +13 -0
  155. package/dist/application/frida/FridaInstrumentationPort.js +8 -0
  156. package/dist/application/frida/FridaInstrumentationService.js +310 -0
  157. package/dist/application/frida/fridaInputErrors.js +17 -0
  158. package/dist/application/go/GoBinaryPort.js +1 -0
  159. package/dist/application/go/GoBinaryService.js +80 -0
  160. package/dist/application/harmony/HarmonyApplicationService.js +17 -0
  161. package/dist/application/investigation/EvidenceLedger.js +40 -14
  162. package/dist/application/investigation/InspectEvidenceBundle.js +18 -0
  163. package/dist/application/investigation/InvestigationRecords.js +12 -21
  164. package/dist/application/investigation/UnknownEvidence.js +22 -18
  165. package/dist/application/javascript/ElectronActiveObservationService.js +55 -25
  166. package/dist/application/javascript/ElectronBoundaryAnalysis.js +17 -3
  167. package/dist/application/javascript/ElectronBoundaryGraph.js +2 -0
  168. package/dist/application/javascript/ElectronBoundaryGraphCallPaths.js +144 -0
  169. package/dist/application/javascript/ElectronBoundaryGraphContext.js +3 -2
  170. package/dist/application/javascript/ElectronBoundaryGraphIpc.js +28 -9
  171. package/dist/application/javascript/ElectronBoundaryGraphNative.js +20 -7
  172. package/dist/application/javascript/ElectronBoundaryGraphWindows.js +50 -12
  173. package/dist/application/javascript/ElectronObservationService.js +0 -1
  174. package/dist/application/javascript/JavaScriptApplicationEvidence.js +15 -0
  175. package/dist/application/javascript/JavaScriptApplicationService.js +44 -18
  176. package/dist/application/javascript/JavaScriptApplicationWorkflowEvidence.js +5 -6
  177. package/dist/application/javascript/JavaScriptApplicationWorkflowService.js +0 -1
  178. package/dist/application/javascript/JavaScriptArtifactAnalysis.js +253 -60
  179. package/dist/application/javascript/JavaScriptArtifactGraphAccumulator.js +51 -23
  180. package/dist/application/javascript/JavaScriptArtifactGraphBuilder.js +93 -21
  181. package/dist/application/javascript/JavaScriptArtifactGraphBundlers.js +4 -3
  182. package/dist/application/javascript/JavaScriptArtifactGraphContext.js +35 -8
  183. package/dist/application/javascript/JavaScriptArtifactGraphDocuments.js +25 -14
  184. package/dist/application/javascript/JavaScriptArtifactGraphFindings.js +163 -54
  185. package/dist/application/javascript/JavaScriptArtifactGraphStructure.js +246 -15
  186. package/dist/application/javascript/JavaScriptArtifactPathResolution.js +1057 -323
  187. package/dist/application/javascript/JavaScriptArtifactReconstruction.js +134 -32
  188. package/dist/application/javascript/JavaScriptArtifactReconstructionInput.js +6 -1
  189. package/dist/application/javascript/JavaScriptModuleRelationships.js +39 -15
  190. package/dist/application/javascript/JavaScriptRecoveryService.js +32 -9
  191. package/dist/application/javascript/JavaScriptRuntimeObservationService.js +2 -1
  192. package/dist/application/javascript/JavaScriptRuntimeReconciliationService.js +0 -1
  193. package/dist/application/javascript/JavaScriptSemanticGraphAsyncProjection.js +9 -3
  194. package/dist/application/javascript/JavaScriptSemanticGraphBuilder.js +228 -74
  195. package/dist/application/javascript/JavaScriptSemanticGraphConstruction.js +12 -19
  196. package/dist/application/javascript/JavaScriptSemanticGraphDataProjection.js +4 -1
  197. package/dist/application/javascript/JavaScriptSemanticGraphElectronProjection.js +67 -0
  198. package/dist/application/javascript/JavaScriptSemanticGraphFlowProjection.js +5 -3
  199. package/dist/application/javascript/JavaScriptSemanticGraphObjectProjection.js +5 -3
  200. package/dist/application/javascript/JavaScriptSemanticGraphValueProjection.js +19 -8
  201. package/dist/application/javascript/JavaScriptSemanticTraceService.js +0 -1
  202. package/dist/application/jeb/JebAnalysisPort.js +1 -0
  203. package/dist/application/jeb/JebAnalysisService.js +13 -0
  204. package/dist/application/managed/ManagedApplicationGraphService.js +1 -2
  205. package/dist/application/managed/ManagedMemberComparisonService.js +72 -54
  206. package/dist/application/managed/ManagedNativeVerificationService.js +0 -1
  207. package/dist/application/managed/ManagedReconstructionService.js +0 -1
  208. package/dist/application/native/NativeCallRoutes.js +54 -34
  209. package/dist/application/native/NativeDispatchMetadataInspection.js +6 -2
  210. package/dist/application/native/NativeUiActionTrace.js +51 -30
  211. package/dist/application/native/NativeValueTrace.js +75 -24
  212. package/dist/application/pcap/PcapAnalysisPort.js +1 -0
  213. package/dist/application/pcap/PcapAnalysisService.js +24 -0
  214. package/dist/application/process/ProcessCli.js +57 -32
  215. package/dist/application/reverse/ReverseEngineeringCommandPort.js +1 -0
  216. package/dist/application/reverse/ReverseEngineeringService.js +688 -0
  217. package/dist/application/rust/RustBinaryPort.js +1 -0
  218. package/dist/application/rust/RustBinaryService.js +80 -0
  219. package/dist/application/signals/SignalRecordingService.js +83 -0
  220. package/dist/application/sqlite/SqliteDatabaseCapability.js +30 -0
  221. package/dist/application/sqlite/SqliteDatabasePort.js +1 -0
  222. package/dist/application/sqlite/SqliteDatabaseService.js +76 -0
  223. package/dist/application/wasm/WasmArtifactPort.js +1 -0
  224. package/dist/application/wasm/WasmArtifactService.js +77 -0
  225. package/dist/application/wasm/WasmInterfaceComparisonService.js +188 -0
  226. package/dist/artifacts/ArtifactHash.js +13 -2
  227. package/dist/artifacts/ArtifactPaths.js +133 -15
  228. package/dist/artifacts/ArtifactProvider.js +28 -19
  229. package/dist/artifacts/ArtifactReader.js +35 -0
  230. package/dist/artifacts/ArtifactResourceScope.js +109 -0
  231. package/dist/artifacts/AsarArtifactReader.js +295 -156
  232. package/dist/artifacts/AsarHeader.js +24 -0
  233. package/dist/artifacts/AsarListing.js +78 -0
  234. package/dist/artifacts/DirectoryArtifactReader.js +247 -74
  235. package/dist/artifacts/MachOSliceArtifactReader.js +198 -48
  236. package/dist/artifacts/NativeDmgArtifactReader.js +188 -78
  237. package/dist/artifacts/OrderedReads.js +57 -0
  238. package/dist/artifacts/SafeOutputTree.js +261 -71
  239. package/dist/artifacts/SafeOutputTreeCleanup.js +45 -0
  240. package/dist/artifacts/SafeOutputTreeCreationFailure.js +20 -0
  241. package/dist/artifacts/SafeOutputTreeIdentity.js +42 -0
  242. package/dist/artifacts/SafeOutputTreeReadback.js +33 -0
  243. package/dist/artifacts/ZipArtifactReader.js +186 -31
  244. package/dist/artifacts/apple/AppleAssetCatalogAnalysis.js +77 -68
  245. package/dist/artifacts/apple/DylibResolutionReader.js +11 -5
  246. package/dist/artifacts/apple/InterfaceBuilderAnalysis.js +114 -38
  247. package/dist/artifacts/apple/InterfaceBuilderDecodeBudget.js +125 -35
  248. package/dist/artifacts/apple/KeyedArchiveReader.js +35 -15
  249. package/dist/artifacts/apple/MachoLoadCommandReader.js +62 -61
  250. package/dist/artifacts/apple/NibArchive.js +11 -4
  251. package/dist/artifacts/apple/PlistNumberLiterals.js +2 -2
  252. package/dist/artifacts/extraction/ArtifactExtraction.js +115 -92
  253. package/dist/artifacts/hostExecutableMarking.js +16 -0
  254. package/dist/artifacts/inventory/ArtifactGraphConstruction.js +236 -69
  255. package/dist/artifacts/inventory/ArtifactInventory.js +7 -6
  256. package/dist/artifacts/inventory/classify.js +95 -35
  257. package/dist/artifacts/inventory/hashStableRootArtifact.js +48 -15
  258. package/dist/artifacts/inventory/reader.js +40 -17
  259. package/dist/artifacts/inventory/scanCanonical.js +84 -40
  260. package/dist/artifacts/inventory/scanReader.js +72 -19
  261. package/dist/artifacts/javascript/JavaScriptArtifactFiles.js +177 -15
  262. package/dist/artifacts/javascript/JavaScriptSourceAnalysis.js +3 -0
  263. package/dist/artifacts/readStableArtifact.js +28 -4
  264. package/dist/browser/BrowserProcessStartup.js +20 -9
  265. package/dist/browser/BrowserScenarioPartialObservation.js +60 -38
  266. package/dist/browser/BrowserScenarioSecrets.js +193 -48
  267. package/dist/browser/CdpBrowserProvider.js +74 -98
  268. package/dist/browser/CdpCaptureDocuments.js +261 -65
  269. package/dist/browser/CdpCaptureDomSvg.js +243 -0
  270. package/dist/browser/CdpCaptureEventBodyShapes.js +12 -12
  271. package/dist/browser/CdpCaptureEventHandlers.js +49 -21
  272. package/dist/browser/CdpCaptureEvents.js +53 -19
  273. package/dist/browser/CdpCaptureStorage.js +22 -5
  274. package/dist/browser/CdpCaptureStorageFingerprints.js +54 -11
  275. package/dist/browser/CdpCaptureValues.js +0 -1
  276. package/dist/browser/CdpConnection.js +25 -9
  277. package/dist/browser/CdpElectronInspection.js +14 -4
  278. package/dist/browser/CdpElectronProvider.js +7 -2
  279. package/dist/browser/CdpElectronScripts.js +2 -1
  280. package/dist/browser/CdpElectronWorkers.js +7 -2
  281. package/dist/browser/CdpEndpoint.js +143 -17
  282. package/dist/browser/CdpObservationSession.js +24 -8
  283. package/dist/browser/CdpPageCapture.js +67 -17
  284. package/dist/browser/CdpPageCaptureScripts.js +4 -3
  285. package/dist/browser/CdpPageCaptureWorkers.js +5 -1
  286. package/dist/browser/CdpSafeMetadata.js +9 -5
  287. package/dist/browser/CdpScreenshot.js +5 -14
  288. package/dist/browser/CdpSnapshotStrings.js +21 -0
  289. package/dist/browser/CdpTargetSession.js +59 -36
  290. package/dist/browser/CdpWebMcpDiscovery.js +55 -16
  291. package/dist/browser/ElectronFileScope.js +99 -9
  292. package/dist/browser/PlaywrightBrowserScenarioProvider.js +64 -8
  293. package/dist/browser/PlaywrightElectronActiveActions.js +4 -4
  294. package/dist/browser/PlaywrightElectronActiveProjection.js +16 -4
  295. package/dist/browser/PlaywrightElectronActiveProvider.js +114 -36
  296. package/dist/browser/PlaywrightExecutionBoundary.js +2 -2
  297. package/dist/browser/PlaywrightScenarioArtifacts.js +5 -5
  298. package/dist/browser/PlaywrightScenarioBrowser.js +78 -13
  299. package/dist/browser/PlaywrightScenarioEvents.js +198 -36
  300. package/dist/browser/PlaywrightScenarioServiceWorkers.js +249 -0
  301. package/dist/browser/PlaywrightScenarioSession.js +180 -75
  302. package/dist/browser/PlaywrightScenarioStorage.js +507 -0
  303. package/dist/browser/PngVisualDiff.js +198 -29
  304. package/dist/browser/WebSourceMapFetcher.js +164 -81
  305. package/dist/browser/assets/LocalWebScriptArtifacts.js +27 -4
  306. package/dist/browser/assets/PublishWebScripts.js +88 -22
  307. package/dist/browser/assets/ScenarioScriptCapture.js +2 -1
  308. package/dist/browser/assets/WebArtifactReads.js +34 -4
  309. package/dist/browser/assets/WebSourceLocationArtifacts.js +39 -3
  310. package/dist/browser/execution/CdpExecutionCapture.js +3 -3
  311. package/dist/browser/execution/CdpPreciseCoverage.js +5 -8
  312. package/dist/browser/history/CaptureFailures.js +22 -8
  313. package/dist/browser/history/CaptureFormatError.js +2 -2
  314. package/dist/browser/history/{HarJson.js → CaptureJson.js} +14 -4
  315. package/dist/browser/history/CaptureRedaction.js +16 -3
  316. package/dist/browser/history/CaptureRelease.js +20 -2
  317. package/dist/browser/history/HarCapture.js +16 -9
  318. package/dist/browser/history/HarSchema.js +36 -36
  319. package/dist/browser/history/HistoricalCaptureDecoder.js +93 -25
  320. package/dist/browser/history/MitmproxyCaptureAdapter.js +3 -1
  321. package/dist/browser/history/NodeCaptureAdapter.js +48 -0
  322. package/dist/browser/history/{HarCaptureProcess.js → NodeCaptureProcess.js} +16 -15
  323. package/dist/browser/history/QlogCapture.js +385 -0
  324. package/dist/browser/history/SazCapture.js +130 -0
  325. package/dist/browser/history/SazHttp.js +61 -0
  326. package/dist/browser/history/SazMetadata.js +92 -0
  327. package/dist/browser/history/SazProjection.js +90 -0
  328. package/dist/browser/modules/NativeModuleResolver.js +177 -110
  329. package/dist/browser/modules/WebModuleArtifacts.js +41 -3
  330. package/dist/browser/network/PlaywrightNetworkContent.js +40 -5
  331. package/dist/browser/network/PlaywrightScenarioNetwork.js +125 -11
  332. package/dist/captures/TsharkCaptureProvider.js +370 -0
  333. package/dist/captures/parseFieldDiscovery.js +66 -0
  334. package/dist/captures/parsePacketOutput.js +21 -0
  335. package/dist/catalogIdentity.js +46 -35
  336. package/dist/cli/adbCommands.js +337 -0
  337. package/dist/cli/analysisViewCommands.js +39 -1
  338. package/dist/cli/androidCommands.js +11 -2
  339. package/dist/cli/apktoolCommands.js +52 -0
  340. package/dist/cli/applicationCommands.js +44 -17
  341. package/dist/cli/artifactCommands.js +9 -12
  342. package/dist/cli/binaryDiagnosticsCommands.js +27 -5
  343. package/dist/cli/browserAdvancedCommands.js +97 -55
  344. package/dist/cli/browserCommands.js +46 -29
  345. package/dist/cli/captureCommands.js +72 -0
  346. package/dist/cli/cliResultOutput.js +188 -0
  347. package/dist/cli/coreBinaryCommands.js +73 -32
  348. package/dist/cli/coreNativeCommands.js +54 -45
  349. package/dist/cli/cutterCommands.js +50 -0
  350. package/dist/cli/electronCommands.js +51 -4
  351. package/dist/cli/evmCommands.js +16 -8
  352. package/dist/cli/finishAnalysisCommand.js +44 -0
  353. package/dist/cli/firmwareCommands.js +21 -38
  354. package/dist/cli/flutterCommands.js +69 -0
  355. package/dist/cli/fridaCommands.js +211 -0
  356. package/dist/cli/goCommands.js +20 -0
  357. package/dist/cli/interactiveSetup.js +11 -1
  358. package/dist/cli/javascriptApplicationAnalysis.js +18 -2
  359. package/dist/cli/javascriptRecoveryCommands.js +29 -15
  360. package/dist/cli/jebCommands.js +99 -0
  361. package/dist/cli/jsonOutput.js +13 -6
  362. package/dist/cli/managedCommands.js +31 -3
  363. package/dist/cli/options.js +20 -2
  364. package/dist/cli/pcapCommands.js +47 -0
  365. package/dist/cli/processCommands.js +1 -1
  366. package/dist/cli/referenceSourceImportStatus.js +7 -0
  367. package/dist/cli/reverseEngineeringCommands.js +268 -0
  368. package/dist/cli/rustCommands.js +21 -0
  369. package/dist/cli/setupCommands.js +55 -15
  370. package/dist/cli/signalCommands.js +72 -0
  371. package/dist/cli/sqliteCommands.js +79 -0
  372. package/dist/cli/utilityCommands.js +179 -89
  373. package/dist/cli/wasmCommands.js +61 -0
  374. package/dist/cli/webModuleCommands.js +36 -32
  375. package/dist/cli/webNetworkCaptureCommands.js +8 -8
  376. package/dist/cli/webScriptCommands.js +20 -1
  377. package/dist/cli/webSourceLocationCommands.js +21 -9
  378. package/dist/cli-runtime/AbortablePromise-BVBemxbD.js +123 -0
  379. package/dist/cli-runtime/AnalysisProvider-D0Us2OTk.js +27 -0
  380. package/dist/cli-runtime/AnalysisSnapshotCache-BXS0wRd2.js +710 -0
  381. package/dist/cli-runtime/ArtifactReader-BXkffc1D.js +55 -0
  382. package/dist/cli-runtime/ArtifactResourceScope-DQWTcUwE.js +114 -0
  383. package/dist/cli-runtime/AsarHeader-CnzOzYEH.js +31 -0
  384. package/dist/cli-runtime/BinarySessionStatus-DnMxMk-r.js +211 -0
  385. package/dist/cli-runtime/BinaryTargetResolver-CVIJ_s1A.js +1308 -0
  386. package/dist/cli-runtime/BoundedFileBytes-BU30odTm.js +39 -0
  387. package/dist/cli-runtime/CdpTargetSession-DGX5pV9w.js +650 -0
  388. package/dist/cli-runtime/ClientConfigPath-c6jr6INc.js +36 -0
  389. package/dist/cli-runtime/ClientConfigurationDocument-ffQ9X0Se.js +1957 -0
  390. package/dist/cli-runtime/ClientRegistrationStatus-DszCyPEU.js +509 -0
  391. package/dist/cli-runtime/CurrentEntrypointPath-D5FRNdkq.js +14 -0
  392. package/dist/cli-runtime/DirectAnalysis-BgvAtpN3.js +528 -0
  393. package/dist/cli-runtime/Doctor-DIpf_I7N.js +588 -0
  394. package/dist/cli-runtime/ElectronFileScope-dpHm2nrS.js +1054 -0
  395. package/dist/cli-runtime/ExecFileOutput-BEQs-lDD.js +117 -0
  396. package/dist/cli-runtime/IdaConfiguration-CtGP7EKo.js +1094 -0
  397. package/dist/cli-runtime/InterfaceBuilderDecodeBudget-D4omRUe4.js +279 -0
  398. package/dist/cli-runtime/InventoryProjectionEvidence-DIsI4DJ6.js +49 -0
  399. package/dist/cli-runtime/InvestigationProviders-DoQRIHii.js +117 -0
  400. package/dist/cli-runtime/JavaScriptApplicationEvidenceGraph-D5aI_FSJ.js +160 -0
  401. package/dist/cli-runtime/JavaScriptApplicationWorkflowEvidence-Bz4-V0Ct.js +75 -0
  402. package/dist/cli-runtime/JavaScriptWorkerMemoryLimit-B1bwMM1a.js +86 -0
  403. package/dist/cli-runtime/JebMcpEndpoint-DUytrn5G.js +428 -0
  404. package/dist/cli-runtime/JsonFiles-DQa1PRKy.js +708 -0
  405. package/dist/cli-runtime/MacCodeSignature-MgYbRK_H.js +24 -0
  406. package/dist/cli-runtime/MacHopperPaths-CwL5lYPX.js +434 -0
  407. package/dist/cli-runtime/MachoLoadCommandReader-C7e074Ze.js +510 -0
  408. package/dist/cli-runtime/ManagedSnapshot-rqyBHcdL.js +4185 -0
  409. package/dist/cli-runtime/OwnedCommand-Cj9GhmPR.js +112 -0
  410. package/dist/cli-runtime/PrivateRuntimeRoot-DAy0PiBM.js +263 -0
  411. package/dist/cli-runtime/ProcessOwnership-DXC5-UWt.js +1378 -0
  412. package/dist/cli-runtime/ProviderDeadline-8m2pFRDc.js +122 -0
  413. package/dist/cli-runtime/RegularFile-B_6KPCNQ.js +139 -0
  414. package/dist/cli-runtime/RegularFileRead-DVlC5faM.js +125 -0
  415. package/dist/cli-runtime/SafeOutputTree-D6U15GXd.js +524 -0
  416. package/dist/cli-runtime/SetupHost-FkYWswsq.js +1098 -0
  417. package/dist/cli-runtime/SupportedClients-DaX6Lt2d.js +1049 -0
  418. package/dist/cli-runtime/UninstallFailure-1blyKXHE.js +22 -0
  419. package/dist/cli-runtime/Update-CbTC_eg1.js +143 -0
  420. package/dist/cli-runtime/UpdateFailure-BcFNxEZZ.js +24 -0
  421. package/dist/cli-runtime/ZipArtifactReader-B8ZgNe4D.js +248 -0
  422. package/dist/cli-runtime/analysisErrorCleanup-Do6YeeoD.js +32 -0
  423. package/dist/cli-runtime/analysisErrorPresentation-DGt7TdsH.js +497 -0
  424. package/dist/cli-runtime/appleArchiveFormat-tVoI2ykA.js +263 -0
  425. package/dist/cli-runtime/application__DirectAnalysisStatus-DpOejOf0.js +150 -0
  426. package/dist/cli-runtime/application__EnhancedTools-oFE2bOjs.js +1787 -0
  427. package/dist/cli-runtime/application__FunctionAnalysisEvidence-B6osuhvW.js +41 -0
  428. package/dist/cli-runtime/application__ReconstructionCoverageService-DN3wTFQj.js +32 -0
  429. package/dist/cli-runtime/application__ReconstructionObligationLedgerService-CKcTppX9.js +815 -0
  430. package/dist/cli-runtime/application__Setup-XpMaRNjy.js +514 -0
  431. package/dist/cli-runtime/application__Uninstall-_23pU2yB.js +427 -0
  432. package/dist/cli-runtime/application__UpdateRuntime-DPvY8ohd.js +345 -0
  433. package/dist/cli-runtime/application__android__AndroidApplicationService-CFgIFPM4.js +31 -0
  434. package/dist/cli-runtime/application__apple__AppleApplicationService-Db6QCsun.js +31 -0
  435. package/dist/cli-runtime/application__harmony__HarmonyApplicationService-CFjocHoK.js +31 -0
  436. package/dist/cli-runtime/application__javascript__ElectronActiveObservationService-CmVDUI_Z.js +118 -0
  437. package/dist/cli-runtime/application__javascript__ElectronObservationService-DEsR8KDN.js +63 -0
  438. package/dist/cli-runtime/application__javascript__JavaScriptApplicationService-CCkp8KBh.js +11450 -0
  439. package/dist/cli-runtime/application__javascript__JavaScriptApplicationWorkflowService-lPy0tzr3.js +2329 -0
  440. package/dist/cli-runtime/application__javascript__JavaScriptRuntimeReconciliationService-DWleA8K9.js +88 -0
  441. package/dist/cli-runtime/application__javascript__JavaScriptSemanticTraceService-DkALH4rL.js +299 -0
  442. package/dist/cli-runtime/artifactOperationError-B7n03FbD.js +27 -0
  443. package/dist/cli-runtime/artifacts__ArtifactProvider-zXI0QjSL.js +2187 -0
  444. package/dist/cli-runtime/binary-BVOr2mgE.js +14206 -0
  445. package/dist/cli-runtime/browserObservationError-Dx6xRTjb.js +40 -0
  446. package/dist/cli-runtime/catalogIdentity-DLoXgfIR.js +933 -0
  447. package/dist/cli-runtime/cli.js +41848 -0
  448. package/dist/cli-runtime/cliOutput-BC1BdAcB.js +122 -0
  449. package/dist/cli-runtime/cliOutput.js +5 -0
  450. package/dist/cli-runtime/cliResultOutput-DsRMI8CJ.js +780 -0
  451. package/dist/cli-runtime/cliResultOutput.js +5 -0
  452. package/dist/cli-runtime/composition__browserScenario-DHXC1a8n.js +2927 -0
  453. package/dist/cli-runtime/composition__electronObservation-GecK2EID.js +555 -0
  454. package/dist/cli-runtime/composition__electronScenario-CEZnVrAL.js +653 -0
  455. package/dist/cli-runtime/cutterToolContracts-TZH9EHr5.js +5134 -0
  456. package/dist/cli-runtime/doctorRuntime-BE5ZX8it.js +258 -0
  457. package/dist/cli-runtime/dotnet__ManagedStaticProvider-C8_yZCDc.js +5 -0
  458. package/dist/cli-runtime/errorSchemas-CTRmvMl3.js +601 -0
  459. package/dist/cli-runtime/javascriptApplicationAnalysis-HgMzVMQw.js +2068 -0
  460. package/dist/cli-runtime/javascriptExportReturnShapeProjection-Dg00g35t.js +78 -0
  461. package/dist/cli-runtime/javascriptExportShapeComparisonSchemas-BYnoIqIk.js +1242 -0
  462. package/dist/cli-runtime/javascriptRuntimeReconciliation-DNjDoL3S.js +1507 -0
  463. package/dist/cli-runtime/javascriptRuntimeReconciliationSchemas-BWpGWNcI.js +247 -0
  464. package/dist/cli-runtime/javascriptSemanticTraceSchemas-BTCNcvbc.js +126 -0
  465. package/dist/cli-runtime/lipo-DSWP6fv-.js +396 -0
  466. package/dist/cli-runtime/logger-CQQCI4a2.js +48 -0
  467. package/dist/cli-runtime/machoContainer-C8BIkkq3.js +172 -0
  468. package/dist/cli-runtime/managedApplicationGraph-B08jb3jq.js +1130 -0
  469. package/dist/cli-runtime/managedToolContracts-D60QmIYj.js +99 -0
  470. package/dist/cli-runtime/mcpDoctor.js +359 -0
  471. package/dist/cli-runtime/mcpStartupPolicy-CVVSOmRc.js +21 -0
  472. package/dist/cli-runtime/native__NativeMacOSProvider-YBTvUeJO.js +4875 -0
  473. package/dist/cli-runtime/officialToolContracts-CCFF0an9.js +1501 -0
  474. package/dist/cli-runtime/propertyListKeys-G8e74YWb.js +248 -0
  475. package/dist/cli-runtime/providerAdapterError-DAjhICdr.js +25 -0
  476. package/dist/cli-runtime/providerCleanupError-Ceq8f0wK.js +27 -0
  477. package/dist/cli-runtime/providerIdentities-Ao1XTvwx.js +31 -0
  478. package/dist/cli-runtime/providerStartupTimeout-B2tF2LtZ.js +17 -0
  479. package/dist/cli-runtime/readFileHandleChunks-dp60iZ6v.js +38 -0
  480. package/dist/cli-runtime/reconstructionObligationLedgerSchemas-Bao0xMr-.js +19478 -0
  481. package/dist/cli-runtime/rolldown-runtime-DXoylpqc.js +121 -0
  482. package/dist/cli-runtime/runtimeVersion-CMGd0bDu.js +23 -0
  483. package/dist/cli-runtime/safeJson-DKKACtdy.js +25 -0
  484. package/dist/cli-runtime/scanCanonical-KP4T9jSl.js +2724 -0
  485. package/dist/cli-runtime/snapshotEnvironment-D_tWyOub.js +813 -0
  486. package/dist/cli-runtime/toolContracts-D2FOG_Nb.js +3721 -0
  487. package/dist/cli-runtime/toolOutputSchemaGroups-DRiYs1je.js +12070 -0
  488. package/dist/cli-runtime/workflowInputError-n8Oo-bLA.js +26 -0
  489. package/dist/cli.js +44 -5
  490. package/dist/cliBrowserScenarioCommands.js +41 -5
  491. package/dist/cliCommandNames.js +80 -0
  492. package/dist/cliEvidenceCommands.js +0 -1
  493. package/dist/cliJavaScriptRuntimeCommands.js +16 -14
  494. package/dist/cliJsonInput.js +14 -6
  495. package/dist/cliLogging.js +50 -14
  496. package/dist/cliObservationOptions.js +9 -0
  497. package/dist/cliOutput.js +38 -5
  498. package/dist/composition/adb.js +3 -0
  499. package/dist/composition/apktool.js +3 -0
  500. package/dist/composition/binary.js +4 -0
  501. package/dist/composition/binaryDiagnostics.js +4 -0
  502. package/dist/composition/captures.js +3 -0
  503. package/dist/composition/directAnalysis.js +36 -11
  504. package/dist/composition/electronFuses.js +4 -0
  505. package/dist/composition/evm.js +12 -0
  506. package/dist/composition/flutter.js +3 -0
  507. package/dist/composition/go.js +4 -0
  508. package/dist/composition/javascriptAnalysisWorkerProcess.js +49 -0
  509. package/dist/composition/jeb.js +35 -0
  510. package/dist/composition/pcap.js +3 -0
  511. package/dist/composition/resolveWindowsProviderExecutable.js +61 -0
  512. package/dist/composition/reverseEngineering.js +29 -0
  513. package/dist/composition/rust.js +4 -0
  514. package/dist/composition/signals.js +3 -0
  515. package/dist/composition/sqlite.js +4 -0
  516. package/dist/composition/wasm.js +22 -0
  517. package/dist/composition/webNetworkCaptures.js +7 -2
  518. package/dist/config/environment.js +55 -4
  519. package/dist/config/ghidraDisabledAnalyzers.js +25 -0
  520. package/dist/config/ghidraLanguageOverride.js +9 -0
  521. package/dist/config/homeDirectory.js +9 -6
  522. package/dist/config/mcpInputSchemaProfile.js +31 -0
  523. package/dist/config/mcpOutputSchemaProfile.js +22 -0
  524. package/dist/config/parseConfig.js +36 -19
  525. package/dist/config/parsers.js +4 -3
  526. package/dist/config/{ghidraStartupTimeout.js → providerStartupTimeout.js} +7 -3
  527. package/dist/contracts/adb/adbToolContracts.js +353 -0
  528. package/dist/contracts/advertisedInputExamples.js +48 -0
  529. package/dist/contracts/analysisDetail.js +13 -0
  530. package/dist/contracts/analysisViewApiSurfaceExample.js +68 -0
  531. package/dist/contracts/analysisViewToolContracts.js +39 -3
  532. package/dist/contracts/android/androidToolContracts.js +17 -8
  533. package/dist/contracts/apktool/apktoolToolContracts.js +33 -0
  534. package/dist/contracts/applicationToolContracts.js +17 -2
  535. package/dist/contracts/artifactToolContracts.js +21 -6
  536. package/dist/contracts/browserToolContracts.js +2 -1
  537. package/dist/contracts/captures/captureToolContracts.js +42 -0
  538. package/dist/contracts/compactInputSchema.js +276 -0
  539. package/dist/contracts/cutterToolContracts.js +84 -0
  540. package/dist/contracts/enhancedToolContracts.js +2 -2
  541. package/dist/contracts/evm/evmToolContracts.js +30 -15
  542. package/dist/contracts/firmware/firmwareToolContracts.js +1 -1
  543. package/dist/contracts/flutter/flutterToolContracts.js +47 -0
  544. package/dist/contracts/fridaRemoteAddress.js +23 -0
  545. package/dist/contracts/fridaToolContracts.js +273 -0
  546. package/dist/contracts/functionComparisonExample.js +12 -1
  547. package/dist/contracts/functionWorkflowToolContracts.js +1 -1
  548. package/dist/contracts/gdbToolContracts.js +103 -0
  549. package/dist/contracts/go/goToolContracts.js +20 -0
  550. package/dist/contracts/hopperMemoryContracts.js +15 -0
  551. package/dist/contracts/inputSchemaPresentation.js +91 -24
  552. package/dist/contracts/investigationExamples.js +1 -0
  553. package/dist/contracts/javascript/electronToolContracts.js +40 -3
  554. package/dist/contracts/javascript/javascriptRecoveryToolContracts.js +13 -1
  555. package/dist/contracts/jeb/jebToolContracts.js +64 -0
  556. package/dist/contracts/managed/managedToolContracts.js +43 -4
  557. package/dist/contracts/managed/managedWorkflowExamples.js +7 -1
  558. package/dist/contracts/managed/managedWorkflowToolContracts.js +4 -30
  559. package/dist/contracts/mobileApplicationGraphExamples.js +12 -0
  560. package/dist/contracts/native/binaryDiagnosticsToolContracts.js +27 -4
  561. package/dist/contracts/native/nativeToolContracts.js +10 -6
  562. package/dist/contracts/officialToolContracts.js +9 -9
  563. package/dist/contracts/pcap/pcapToolContracts.js +33 -0
  564. package/dist/contracts/providerSelection.js +1 -0
  565. package/dist/contracts/reconstructionReadinessExample.js +126 -119
  566. package/dist/contracts/reverseEngineeringToolContracts.js +52 -0
  567. package/dist/contracts/rizinDebugToolContracts.js +96 -0
  568. package/dist/contracts/rust/rustToolContracts.js +20 -0
  569. package/dist/contracts/sessionLifecycleInputs.js +34 -2
  570. package/dist/contracts/sessionToolContracts.js +4 -4
  571. package/dist/contracts/sessionToolSchemas.js +20 -2
  572. package/dist/contracts/signals/signalToolContracts.js +40 -0
  573. package/dist/contracts/sqlite/sqliteToolContracts.js +36 -0
  574. package/dist/contracts/toolContractExamples.js +35 -0
  575. package/dist/contracts/toolContractTypes.js +5 -0
  576. package/dist/contracts/toolContracts.js +32 -0
  577. package/dist/contracts/toolEffects.js +414 -8
  578. package/dist/contracts/toolOutputSchemaGroups.js +78 -33
  579. package/dist/contracts/toolOutputSchemaPrimitives.js +111 -10
  580. package/dist/contracts/toolSchemaMetadata.js +98 -9
  581. package/dist/contracts/unknownContractExamples.js +1 -1
  582. package/dist/contracts/wasm/wasmComparisonContracts.js +52 -0
  583. package/dist/contracts/wasm/wasmToolContracts.js +33 -0
  584. package/dist/contracts/webNetworkCaptureToolContracts.js +15 -4
  585. package/dist/cutter/CutterBridgeClient.js +621 -0
  586. package/dist/cutter/CutterBridgeService.js +139 -0
  587. package/dist/doctorRuntime.js +20 -8
  588. package/dist/domain/adb/adbDeviceAnalysis.js +605 -0
  589. package/dist/domain/analysisErrorBase.js +20 -0
  590. package/dist/domain/analysisErrorCleanup.js +29 -0
  591. package/dist/domain/analysisErrorCore.js +19 -0
  592. package/dist/domain/analysisErrorPresentation.js +75 -22
  593. package/dist/domain/analysisErrorProjection.js +35 -13
  594. package/dist/domain/analysisProfile.js +7 -3
  595. package/dist/domain/analysisSnapshot.js +313 -185
  596. package/dist/domain/analysisView/WebNetworkApiSurfaceAccumulator.js +414 -0
  597. package/dist/domain/analysisView/analysisView.js +417 -45
  598. package/dist/domain/analysisView/analysisViewCoverage.js +32 -0
  599. package/dist/domain/analysisView/analysisViewErrors.js +4 -0
  600. package/dist/domain/analysisView/analysisViewParent.js +12 -0
  601. package/dist/domain/analysisView/analysisViewText.js +29 -0
  602. package/dist/domain/analysisView/androidPackageView.js +102 -0
  603. package/dist/domain/analysisView/artifactInventoryView.js +140 -0
  604. package/dist/domain/analysisView/binaryLayoutView.js +13 -4
  605. package/dist/domain/analysisView/dartAotView.js +93 -0
  606. package/dist/domain/analysisView/evmInterfaceView.js +105 -0
  607. package/dist/domain/analysisView/interfaceBuilderView.js +182 -0
  608. package/dist/domain/analysisView/javascriptApplicationView.js +29 -26
  609. package/dist/domain/analysisView/machoView.js +186 -0
  610. package/dist/domain/analysisView/managedArtifactView.js +108 -0
  611. package/dist/domain/analysisView/managedMemberView.js +209 -0
  612. package/dist/domain/analysisView/nativeFunctionView.js +150 -0
  613. package/dist/domain/analysisView/pcapCaptureView.js +264 -0
  614. package/dist/domain/analysisView/qlogCaptureView.js +198 -0
  615. package/dist/domain/analysisView/wasmArtifactView.js +162 -0
  616. package/dist/domain/analysisView/webNetworkApiSurfaceView.js +123 -0
  617. package/dist/domain/analysisView/webNetworkCaptureView.js +388 -0
  618. package/dist/domain/android/androidAnalysis.js +36 -2
  619. package/dist/domain/android/androidApplication.js +57 -80
  620. package/dist/domain/apktool/apktoolResourceAnalysis.js +89 -0
  621. package/dist/domain/apple/appleApplication.js +71 -52
  622. package/dist/domain/apple/appleArchiveFormat.js +184 -0
  623. package/dist/domain/apple/appleAssetCatalog.js +15 -0
  624. package/dist/domain/apple/appleBundleAnatomy.js +96 -29
  625. package/dist/domain/apple/dyldPaths.js +18 -3
  626. package/dist/domain/apple/dylibResolution.js +21 -11
  627. package/dist/domain/apple/dylibResolutionFindings.js +8 -9
  628. package/dist/domain/apple/interfaceBuilderGraph.js +72 -45
  629. package/dist/domain/apple/interfaceBuilderKeyedArchive.js +38 -9
  630. package/dist/domain/apple/machoContainer.js +120 -8
  631. package/dist/domain/apple/machoCpuIdentity.js +4 -0
  632. package/dist/domain/apple/plistValue.js +6 -1
  633. package/dist/domain/artifactComparison.js +130 -25
  634. package/dist/domain/artifactDecompressionBudget.js +26 -0
  635. package/dist/domain/artifactGraph.js +28 -9
  636. package/dist/domain/artifactIdentity.js +33 -2
  637. package/dist/domain/artifactInspection.js +47 -45
  638. package/dist/domain/artifactIntegrityPolicy.js +10 -0
  639. package/dist/domain/artifactInventoryEvidence.js +148 -51
  640. package/dist/domain/artifactPathSyntax.js +1 -1
  641. package/dist/domain/binaryTarget.js +253 -80
  642. package/dist/domain/binaryTargetTypes.js +21 -1
  643. package/dist/domain/browserNetworkEvidence.js +4 -0
  644. package/dist/domain/browserObservation.js +88 -29
  645. package/dist/domain/browserObservationSchemas.js +12 -5
  646. package/dist/domain/browserScenarioCapture.js +2 -1
  647. package/dist/domain/browserScenarioCaptureValues.js +26 -2
  648. package/dist/domain/browserScenarioDiff.js +120 -11
  649. package/dist/domain/browserScenarioDiffEvidence.js +46 -13
  650. package/dist/domain/browserScenarioDiffValues.js +10 -3
  651. package/dist/domain/browserScenarioNetworkComparison.js +158 -0
  652. package/dist/domain/browserScenarioNormalization.js +10 -13
  653. package/dist/domain/browserScenarioValues.js +2 -12
  654. package/dist/domain/browserSession.js +2 -2
  655. package/dist/domain/bundleComparison.js +1 -5
  656. package/dist/domain/callPath.js +40 -3
  657. package/dist/domain/canonicalJsonDigestSteps.js +34 -12
  658. package/dist/domain/captures/packetCapture.js +138 -0
  659. package/dist/domain/captures/packetFields.js +81 -0
  660. package/dist/domain/changedBehavior.js +43 -41
  661. package/dist/domain/compactStringIdentity.js +9 -0
  662. package/dist/domain/comparisonSourceEvidence.js +6 -0
  663. package/dist/domain/dosCom.js +2 -2
  664. package/dist/domain/dosMz.js +52 -14
  665. package/dist/domain/electron/electronFuses.js +360 -0
  666. package/dist/domain/elfFixedHeader.js +42 -0
  667. package/dist/domain/evidence.js +104 -38
  668. package/dist/domain/evidenceBundle.js +58 -20
  669. package/dist/domain/evidenceErrors.js +5 -0
  670. package/dist/domain/evidenceRecordSummary.js +144 -0
  671. package/dist/domain/evm/evmInterface.js +18 -4
  672. package/dist/domain/evm/solidityMetadata.js +70 -0
  673. package/dist/domain/explicitSensitiveFailure.js +42 -24
  674. package/dist/domain/firmware/firmwareAnalysis.js +29 -0
  675. package/dist/domain/flutter/flutterBuildAnalysis.js +141 -0
  676. package/dist/domain/functionCallCoverage.js +60 -0
  677. package/dist/domain/functionComparisonDimensions.js +101 -10
  678. package/dist/domain/functionComparisonNormalization.js +66 -10
  679. package/dist/domain/functionComparisonResults.js +7 -6
  680. package/dist/domain/functionComparisonSchemas.js +14 -3
  681. package/dist/domain/functionDossierEvidence.js +3 -0
  682. package/dist/domain/go/goBinary.js +96 -0
  683. package/dist/domain/harmony/harmonyApplication.js +156 -0
  684. package/dist/domain/hopperErrors.js +15 -16
  685. package/dist/domain/hopperPublisher.js +12 -0
  686. package/dist/domain/hopperValues.js +112 -34
  687. package/dist/domain/inputIssueProjection.js +16 -1
  688. package/dist/domain/javascript/electronObservation.js +4 -1
  689. package/dist/domain/javascript/electronStaticAnalysisBrowser.js +24 -24
  690. package/dist/domain/javascript/electronStaticAnalysisIpc.js +13 -20
  691. package/dist/domain/javascript/electronStaticAnalysisNative.js +85 -41
  692. package/dist/domain/javascript/electronStaticAnalysisValues.js +30 -8
  693. package/dist/domain/javascript/electronWrappedCallPaths.js +498 -0
  694. package/dist/domain/javascript/htmlArtifactReferences.js +94 -4
  695. package/dist/domain/javascript/javascriptAnalysisResourceControls.js +65 -0
  696. package/dist/domain/javascript/javascriptApplicationAnalysis.js +7 -1
  697. package/dist/domain/javascript/javascriptApplicationChangeGraph.js +13 -8
  698. package/dist/domain/javascript/javascriptApplicationEvidenceSchemas.js +1 -1
  699. package/dist/domain/javascript/javascriptApplicationGraph.js +96 -19
  700. package/dist/domain/javascript/javascriptApplicationGraphSchemas.js +1 -0
  701. package/dist/domain/javascript/javascriptApplicationProjectionResources.js +43 -0
  702. package/dist/domain/javascript/javascriptApplicationVersionItems.js +28 -12
  703. package/dist/domain/javascript/javascriptApplicationVersionKeys.js +40 -19
  704. package/dist/domain/javascript/javascriptArtifactFiles.js +2 -1
  705. package/dist/domain/javascript/javascriptAstFingerprint.js +100 -39
  706. package/dist/domain/javascript/javascriptAstValues.js +81 -0
  707. package/dist/domain/javascript/javascriptBootstrap.js +94 -0
  708. package/dist/domain/javascript/javascriptBootstrapIntegrity.js +372 -0
  709. package/dist/domain/javascript/javascriptBuiltinResourceMethods.js +8 -0
  710. package/dist/domain/javascript/javascriptBundledRequireOrigin.js +291 -0
  711. package/dist/domain/javascript/javascriptContextBridgeExposure.js +23 -0
  712. package/dist/domain/javascript/javascriptElectronMemberWrites.js +114 -0
  713. package/dist/domain/javascript/javascriptExportShapeComparisonSchemas.js +6 -5
  714. package/dist/domain/javascript/javascriptExportShapeVariants.js +1 -1
  715. package/dist/domain/javascript/javascriptFeatureSeed.js +33 -16
  716. package/dist/domain/javascript/javascriptFeatureTrace.js +9 -3
  717. package/dist/domain/javascript/javascriptFeatureTraceSchemas.js +42 -11
  718. package/dist/domain/javascript/javascriptIntrinsicInvocation.js +132 -0
  719. package/dist/domain/javascript/javascriptModuleDeclaration.js +28 -0
  720. package/dist/domain/javascript/javascriptModuleInterop.js +618 -0
  721. package/dist/domain/javascript/javascriptModuleResolutionMode.js +18 -0
  722. package/dist/domain/javascript/javascriptModuleSemanticIr.js +15 -0
  723. package/dist/domain/javascript/javascriptModuleSpecifier.js +5 -0
  724. package/dist/domain/javascript/javascriptNativeHandoff.js +6 -2
  725. package/dist/domain/javascript/javascriptPackageImportAliases.js +58 -0
  726. package/dist/domain/javascript/javascriptRecovery.js +12 -5
  727. package/dist/domain/javascript/javascriptRpcEndpoints.js +331 -0
  728. package/dist/domain/javascript/javascriptRuntimeLoadState.js +12 -3
  729. package/dist/domain/javascript/javascriptRuntimeObservation.js +4 -1
  730. package/dist/domain/javascript/javascriptRuntimeReconciliationCaptureParsing.js +10 -4
  731. package/dist/domain/javascript/javascriptRuntimeReconciliationGraph.js +7 -2
  732. package/dist/domain/javascript/javascriptRuntimeReconciliationMatching.js +15 -2
  733. package/dist/domain/javascript/javascriptRuntimeReconciliationResult.js +0 -1
  734. package/dist/domain/javascript/javascriptRuntimeReconciliationSchemas.js +5 -4
  735. package/dist/domain/javascript/javascriptRuntimeStaticCandidates.js +121 -22
  736. package/dist/domain/javascript/javascriptSemanticAmbientWrites.js +251 -0
  737. package/dist/domain/javascript/javascriptSemanticAnalysis.js +493 -104
  738. package/dist/domain/javascript/javascriptSemanticAsyncEffects.js +17 -34
  739. package/dist/domain/javascript/javascriptSemanticCallResolution.js +4 -3
  740. package/dist/domain/javascript/javascriptSemanticCallableResults.js +42 -0
  741. package/dist/domain/javascript/javascriptSemanticCallableStack.js +52 -0
  742. package/dist/domain/javascript/javascriptSemanticCalls.js +14 -12
  743. package/dist/domain/javascript/javascriptSemanticChildProcesses.js +42 -55
  744. package/dist/domain/javascript/javascriptSemanticDataEffectHelpers.js +428 -32
  745. package/dist/domain/javascript/javascriptSemanticDataEffects.js +14 -20
  746. package/dist/domain/javascript/javascriptSemanticDependencies.js +69 -0
  747. package/dist/domain/javascript/javascriptSemanticDerivedAnalysis.js +15 -4
  748. package/dist/domain/javascript/javascriptSemanticFileProjection.js +1 -0
  749. package/dist/domain/javascript/javascriptSemanticFingerprints.js +51 -53
  750. package/dist/domain/javascript/javascriptSemanticGraph.js +74 -24
  751. package/dist/domain/javascript/javascriptSemanticGraphSchemas.js +2 -11
  752. package/dist/domain/javascript/javascriptSemanticIterationSources.js +41 -8
  753. package/dist/domain/javascript/javascriptSemanticMemberMutations.js +538 -151
  754. package/dist/domain/javascript/javascriptSemanticMutationInitializers.js +199 -3
  755. package/dist/domain/javascript/javascriptSemanticMutationValues.js +78 -35
  756. package/dist/domain/javascript/javascriptSemanticObjectReferences.js +671 -0
  757. package/dist/domain/javascript/javascriptSemanticObjects.js +27 -17
  758. package/dist/domain/javascript/javascriptSemanticProjection.js +202 -56
  759. package/dist/domain/javascript/javascriptSemanticPromises.js +6 -9
  760. package/dist/domain/javascript/javascriptSemanticPropertyPaths.js +77 -0
  761. package/dist/domain/javascript/javascriptSemanticProvenance.js +5 -1
  762. package/dist/domain/javascript/javascriptSemanticQuery.js +34 -31
  763. package/dist/domain/javascript/javascriptSemanticQueryIdentity.js +1 -3
  764. package/dist/domain/javascript/javascriptSemanticReferenceSources.js +25 -0
  765. package/dist/domain/javascript/javascriptSemanticRequireOrigin.js +331 -8
  766. package/dist/domain/javascript/javascriptSemanticResources.js +6 -40
  767. package/dist/domain/javascript/javascriptSemanticReturnedReferences.js +233 -0
  768. package/dist/domain/javascript/javascriptSemanticReturns.js +49 -52
  769. package/dist/domain/javascript/javascriptSemanticState.js +61 -4
  770. package/dist/domain/javascript/javascriptSemanticTraversal.js +25 -5
  771. package/dist/domain/javascript/javascriptSemanticValues.js +260 -35
  772. package/dist/domain/javascript/javascriptSourceAnalysis.js +1 -0
  773. package/dist/domain/javascript/javascriptSourceMapPaths.js +44 -17
  774. package/dist/domain/javascript/javascriptSourceParser.js +72 -3
  775. package/dist/domain/javascript/javascriptSourceSelection.js +11 -0
  776. package/dist/domain/javascript/javascriptStaticAnalysis.js +72 -26
  777. package/dist/domain/javascript/javascriptStaticAnalysisBundler.js +100 -24
  778. package/dist/domain/javascript/javascriptStaticAnalysisCalls.js +271 -47
  779. package/dist/domain/javascript/javascriptStaticAnalysisFindings.js +8 -4
  780. package/dist/domain/javascript/javascriptStaticAnalysisHelpers.js +166 -56
  781. package/dist/domain/javascript/javascriptStaticAnalysisState.js +2 -0
  782. package/dist/domain/javascript/javascriptStaticAnalysisTypes.js +2 -1
  783. package/dist/domain/javascript/javascriptSymbolicBindings.js +836 -0
  784. package/dist/domain/javascript/javascriptSymbolicControlFlow.js +40 -0
  785. package/dist/domain/javascript/javascriptSymbolicValues.js +34 -0
  786. package/dist/domain/javascript/sourceToBundleComparison.js +3 -1
  787. package/dist/domain/javascript/sourceToBundleComparisonSchemas.js +2 -0
  788. package/dist/domain/javascript/sourceToBundleSignals.js +47 -13
  789. package/dist/domain/jeb/jebAnalysis.js +114 -0
  790. package/dist/domain/jsonShape.js +63 -52
  791. package/dist/domain/jsonValue.js +40 -12
  792. package/dist/domain/localPath.js +6 -3
  793. package/dist/domain/managed/managedApplicationGraph.js +42 -0
  794. package/dist/domain/managed/managedApplicationGraphCoverage.js +12 -2
  795. package/dist/domain/managed/managedApplicationGraphNodes.js +32 -23
  796. package/dist/domain/managed/managedArtifact.js +52 -1
  797. package/dist/domain/managed/managedInspectionEvidence.js +12 -0
  798. package/dist/domain/managed/managedMemberComparison.js +3 -0
  799. package/dist/domain/managed/managedMemberComparisonCoverage.js +23 -3
  800. package/dist/domain/managed/managedMemberComparisonItems.js +23 -19
  801. package/dist/domain/managed/managedMemberComparisonMatch.js +209 -18
  802. package/dist/domain/managed/managedNativeVerificationMatch.js +49 -26
  803. package/dist/domain/managed/managedNativeVerificationSchemas.js +13 -2
  804. package/dist/domain/managed/managedReconstruction.js +5 -8
  805. package/dist/domain/mobileApplicationGraphProjection.js +80 -0
  806. package/dist/domain/native/addressCoordinate.js +11 -0
  807. package/dist/domain/native/binaryLayout.js +2 -4
  808. package/dist/domain/native/bytePattern.js +100 -0
  809. package/dist/domain/native/nativeAotPe.js +1408 -0
  810. package/dist/domain/native/nativeInspection.js +38 -4
  811. package/dist/domain/native/nativeInstruction.js +38 -2
  812. package/dist/domain/native/nativeInvestigationGraph.js +9 -5
  813. package/dist/domain/native/nativeLoadImage.js +19 -1
  814. package/dist/domain/native/nativeMetadataRecovery.js +79 -6
  815. package/dist/domain/native/nativeUiObservation.js +5 -6
  816. package/dist/domain/native/objcSwiftMetadata.js +4 -1
  817. package/dist/domain/native/peResources.js +100 -0
  818. package/dist/domain/native/recordedCrash.js +79 -10
  819. package/dist/domain/nativeConvention.js +33 -0
  820. package/dist/domain/offsetDateTime.js +60 -0
  821. package/dist/domain/pcap/pcapAnalysis.js +91 -0
  822. package/dist/domain/pcap/pcapEvidence.js +15 -0
  823. package/dist/domain/peMachine.js +36 -0
  824. package/dist/domain/pngHeader.js +18 -0
  825. package/dist/domain/process/processCapture.js +91 -1
  826. package/dist/domain/process/processCaptureCoverage.js +26 -3
  827. package/dist/domain/process/processCaptureExample.js +26 -0
  828. package/dist/domain/process/processCaptureValidation.js +112 -8
  829. package/dist/domain/process/processComparison.js +41 -13
  830. package/dist/domain/process/processScenario.js +66 -7
  831. package/dist/domain/process/processTraceEvaluation.js +54 -50
  832. package/dist/domain/process/processTraceSpecification.js +243 -89
  833. package/dist/domain/propertyListKeys.js +214 -12
  834. package/dist/domain/propertyListXmlText.js +20 -4
  835. package/dist/domain/providerAdapterError.js +0 -5
  836. package/dist/domain/providerConfigurationRefusal.js +12 -0
  837. package/dist/domain/providerSelectionError.js +2 -1
  838. package/dist/domain/qlogCapture.js +62 -0
  839. package/dist/domain/rawBinary.js +96 -0
  840. package/dist/domain/reconstructionCoverage.js +5 -1
  841. package/dist/domain/reconstructionCoverageEvaluation.js +18 -15
  842. package/dist/domain/reconstructionCoverageVerifierResults.js +35 -0
  843. package/dist/domain/reconstructionObligationLedgerIntegrity.js +114 -0
  844. package/dist/domain/reconstructionObligationLedgerSchemas.js +104 -1
  845. package/dist/domain/reconstructionReadiness.js +4 -8
  846. package/dist/domain/reconstructionReadinessJourneyFindings.js +4 -1
  847. package/dist/domain/reconstructionUnknowns.js +9 -1
  848. package/dist/domain/reconstructionVerification.js +54 -25
  849. package/dist/domain/recordedTransportUrl.js +59 -0
  850. package/dist/domain/referenceSourceClassification.js +27 -23
  851. package/dist/domain/referenceSourceGraph.js +70 -23
  852. package/dist/domain/referenceSourceImportParsing.js +29 -16
  853. package/dist/domain/referenceSourcePathIdentity.js +32 -0
  854. package/dist/domain/referenceSourceRequireBindings.js +130 -0
  855. package/dist/domain/referenceSourceSummary.js +92 -0
  856. package/dist/domain/relationshipCoverage.js +44 -0
  857. package/dist/domain/residualUnknown.js +93 -26
  858. package/dist/domain/reverseEngineering.js +31 -0
  859. package/dist/domain/runtimeVersion.js +8 -0
  860. package/dist/domain/rust/rustBinary.js +200 -0
  861. package/dist/domain/signals/annotationTextWindow.js +31 -0
  862. package/dist/domain/signals/signalDecoders.js +69 -0
  863. package/dist/domain/signals/signalRecording.js +115 -0
  864. package/dist/domain/sourceMapContents.js +10 -3
  865. package/dist/domain/sourceMapEnvelope.js +17 -11
  866. package/dist/domain/sqlite/sqliteDatabase.js +188 -0
  867. package/dist/domain/staticRuntimeCorrelation.js +7 -9
  868. package/dist/domain/swiftSymbolClassification.js +17 -0
  869. package/dist/domain/symbolAnalysis.js +16 -4
  870. package/dist/domain/urlComponents.js +6 -0
  871. package/dist/domain/wasm/wasmArtifact.js +119 -0
  872. package/dist/domain/wasm/wasmInterface.js +89 -0
  873. package/dist/domain/webBundleAnalysis.js +14 -3
  874. package/dist/domain/webBundleAnalyzerAst.js +7 -2
  875. package/dist/domain/webBundleAnalyzerInspection.js +68 -40
  876. package/dist/domain/webBundleAnalyzerResult.js +18 -6
  877. package/dist/domain/webCaptureDiff.js +233 -34
  878. package/dist/domain/webCaptureFrameComparison.js +49 -0
  879. package/dist/domain/webMcpDiscovery.js +5 -2
  880. package/dist/domain/webModuleImports.js +22 -27
  881. package/dist/domain/webModuleTrace.js +3 -8
  882. package/dist/domain/webNetworkCapture.js +101 -39
  883. package/dist/domain/webNetworkCaptureCoordinates.js +21 -0
  884. package/dist/domain/webRuntime.js +0 -1
  885. package/dist/domain/webScreenshot.js +2 -2
  886. package/dist/domain/webScriptArtifacts.js +2 -4
  887. package/dist/domain/webScriptExport.js +6 -8
  888. package/dist/domain/webScriptExportError.js +10 -4
  889. package/dist/domain/webScriptExportPlan.js +9 -15
  890. package/dist/domain/webSourceLocation.js +20 -9
  891. package/dist/domain/zipPackageFormat.js +31 -2
  892. package/dist/domain/zodCollectionSteps.js +24 -0
  893. package/dist/dotnet/ManagedArtifactInspector.js +81 -54
  894. package/dist/dotnet/ManagedDecodeBudget.js +138 -0
  895. package/dist/dotnet/ManagedMemberInspector.js +113 -26
  896. package/dist/dotnet/ManagedMemberInspectorCore.js +356 -140
  897. package/dist/dotnet/ManagedMemberInstructionDecoder.js +112 -38
  898. package/dist/dotnet/ManagedMemberOwnership.js +65 -0
  899. package/dist/dotnet/ManagedMemberPointers.js +69 -0
  900. package/dist/dotnet/ManagedMemberRows.js +182 -44
  901. package/dist/dotnet/ManagedMetadataHeaps.js +123 -27
  902. package/dist/dotnet/ManagedMetadataInventory.js +5 -5
  903. package/dist/dotnet/ManagedMetadataInventoryRows.js +56 -63
  904. package/dist/dotnet/ManagedMetadataLayout.js +19 -5
  905. package/dist/dotnet/ManagedMetadataRowSizes.js +1 -1
  906. package/dist/dotnet/ManagedMethodBodyReader.js +34 -11
  907. package/dist/dotnet/ManagedMethodSpecs.js +78 -0
  908. package/dist/dotnet/ManagedNativeBoundaryHelpers.js +5 -4
  909. package/dist/dotnet/ManagedNativeBoundaryInspector.js +52 -44
  910. package/dist/dotnet/ManagedPeReader.js +96 -52
  911. package/dist/dotnet/ManagedReaderFailure.js +11 -1
  912. package/dist/dotnet/ManagedSnapshot.js +88 -0
  913. package/dist/dotnet/ManagedStaticProvider.js +57 -35
  914. package/dist/dotnet/ManagedTypeMemberLists.js +105 -0
  915. package/dist/dotnet/ManagedTypeNames.js +98 -0
  916. package/dist/dotnet/ManagedUserStrings.js +75 -0
  917. package/dist/electron/ElectronFusePath.js +247 -0
  918. package/dist/electron/ElectronFuseProvider.js +113 -0
  919. package/dist/electron/ElectronFuseReader.js +317 -0
  920. package/dist/evaluation/AgentEvaluationFixtures.js +194 -11
  921. package/dist/evaluation/AgentEvaluationReport.js +9 -5
  922. package/dist/evaluation/CodexAgentEval.js +58 -49
  923. package/dist/evaluation/KnownAnswerEvaluation.js +126 -57
  924. package/dist/evm/EvmoleFailures.js +19 -16
  925. package/dist/evm/EvmoleInterfaceAdapter.js +5 -1
  926. package/dist/evm/EvmoleInterfaceProvider.js +198 -23
  927. package/dist/evm/EvmoleInterfaceWorker.js +2 -0
  928. package/dist/evm/SolidityMetadata.js +139 -0
  929. package/dist/filesystem/OwnedDirectoryHandle.js +29 -0
  930. package/dist/filesystem/OwnedFileHandle.js +36 -0
  931. package/dist/filesystem/OwnedStagedOutput.js +138 -0
  932. package/dist/filesystem/RegularFile.js +81 -5
  933. package/dist/filesystem/StableFileHash.js +46 -0
  934. package/dist/filesystem/readFileHandleChunks.js +35 -0
  935. package/dist/firmware/FirmwareCommand.js +27 -5
  936. package/dist/firmware/FirmwareFiles.js +18 -7
  937. package/dist/firmware/FirmwareProvider.js +158 -32
  938. package/dist/firmware/FirmwarePublication.js +242 -4
  939. package/dist/firmware/FirmwareRelease.js +1 -0
  940. package/dist/firmware/FirmwareReports.js +202 -12
  941. package/dist/flutter/DartElf.js +418 -0
  942. package/dist/flutter/ElfBuildId.js +137 -0
  943. package/dist/flutter/ElfLoadMap.js +91 -0
  944. package/dist/flutter/FlutterBuildProvider.js +826 -0
  945. package/dist/flutter/FlutterPayloadScan.js +180 -0
  946. package/dist/frida/FridaInstrumentationManager.js +1104 -0
  947. package/dist/gdb/GdbSessionManager.js +1451 -0
  948. package/dist/generatedPackageMetadata.js +2 -2
  949. package/dist/ghidra/GhidraAnalysisProfile.js +175 -6
  950. package/dist/ghidra/GhidraAnalysisSeeds.js +211 -0
  951. package/dist/ghidra/GhidraClient.js +208 -29
  952. package/dist/ghidra/GhidraDiagnostics.js +18 -8
  953. package/dist/ghidra/GhidraDoctor.js +15 -12
  954. package/dist/ghidra/GhidraFunctionValues.js +73 -2
  955. package/dist/ghidra/GhidraInstallation.js +216 -20
  956. package/dist/ghidra/GhidraInstallationPolicy.js +79 -29
  957. package/dist/ghidra/GhidraInventoryValues.js +53 -1
  958. package/dist/ghidra/GhidraJavaLaunch.js +91 -10
  959. package/dist/ghidra/GhidraJavaProperties.js +117 -0
  960. package/dist/ghidra/GhidraLanguageCatalog.js +169 -0
  961. package/dist/ghidra/GhidraLauncher.js +306 -88
  962. package/dist/ghidra/GhidraLoadImageAttest.js +74 -7
  963. package/dist/ghidra/GhidraLoadImageValues.js +72 -0
  964. package/dist/ghidra/GhidraMipsProfile.js +315 -0
  965. package/dist/ghidra/GhidraPeProfile.js +21 -0
  966. package/dist/ghidra/GhidraPowerPcProfile.js +51 -0
  967. package/dist/ghidra/GhidraProvider.js +106 -20
  968. package/dist/ghidra/GhidraProviderCapabilities.js +30 -19
  969. package/dist/ghidra/GhidraProviderClient.js +520 -56
  970. package/dist/ghidra/GhidraPspExtension.js +140 -0
  971. package/dist/ghidra/GhidraPspProfile.js +59 -0
  972. package/dist/ghidra/GhidraRawBinaryLanguage.js +40 -0
  973. package/dist/ghidra/GhidraRiscvProfile.js +100 -0
  974. package/dist/ghidra/GhidraSessionError.js +155 -11
  975. package/dist/ghidra/GhidraSessionValues.js +75 -2
  976. package/dist/ghidra/GhidraTransport.js +2 -1
  977. package/dist/go/GoBinaryContainer.js +140 -0
  978. package/dist/go/GoBinaryImage.js +210 -0
  979. package/dist/go/GoBinaryProvider.js +151 -0
  980. package/dist/go/GoElfImage.js +211 -0
  981. package/dist/go/GoMachoImage.js +164 -0
  982. package/dist/go/GoModuleText.js +217 -0
  983. package/dist/go/GoPeImage.js +124 -0
  984. package/dist/hopper/BridgeLauncher.js +35 -2
  985. package/dist/hopper/HopperAnalysisProfile.js +21 -9
  986. package/dist/hopper/HopperCleanup.js +15 -3
  987. package/dist/hopper/HopperClient.js +203 -42
  988. package/dist/hopper/HopperMacPublisher.js +29 -0
  989. package/dist/hopper/HopperMachOImage.js +61 -27
  990. package/dist/hopper/HopperProcessDiagnostic.js +27 -0
  991. package/dist/hopper/HopperProvider.js +68 -26
  992. package/dist/hopper/HopperProviderCapabilities.js +7 -3
  993. package/dist/hopper/HopperRequestQueue.js +17 -5
  994. package/dist/hopper/HopperSessionValues.js +10 -1
  995. package/dist/hopper/HopperTargetLease.js +66 -19
  996. package/dist/ida/IdaBusyHealth.js +44 -0
  997. package/dist/ida/IdaCallGraph.js +134 -0
  998. package/dist/ida/IdaConfiguration.js +7 -2
  999. package/dist/ida/IdaDiagnosticRedactor.js +199 -0
  1000. package/dist/ida/IdaDiagnosticWriter.js +62 -0
  1001. package/dist/ida/IdaDoctor.js +7 -5
  1002. package/dist/ida/IdaJsonDiagnostic.js +138 -0
  1003. package/dist/ida/IdaMcpConnection.js +297 -27
  1004. package/dist/ida/IdaNativeProtocol.js +93 -0
  1005. package/dist/ida/IdaOperationRunner.js +249 -40
  1006. package/dist/ida/IdaProtocolValues.js +86 -4
  1007. package/dist/ida/IdaProvider.js +34 -8
  1008. package/dist/ida/IdaProviderCapabilities.js +37 -8
  1009. package/dist/ida/IdaSessionClient.js +332 -53
  1010. package/dist/ida/IdaWorkspace.js +57 -7
  1011. package/dist/inspector/V8InspectorCaptureProjection.js +7 -2
  1012. package/dist/inspector/V8InspectorEndpoint.js +15 -13
  1013. package/dist/inspector/V8InspectorProvider.js +41 -7
  1014. package/dist/javascript/analysis/JavaScriptAnalysisTransfer.js +337 -0
  1015. package/dist/javascript/analysis/JavaScriptAnalysisWorker.js +594 -0
  1016. package/dist/javascript/analysis/JavaScriptAnalysisWorkerProtocol.js +65 -0
  1017. package/dist/javascript/analysis/JavaScriptAnalysisWorkerSchemas.js +590 -0
  1018. package/dist/javascript/analysis/JavaScriptAnalysisWorkerServer.js +126 -0
  1019. package/dist/javascript/recovery/RecoveryFiles.js +68 -12
  1020. package/dist/javascript/recovery/WakaruCommand.js +22 -9
  1021. package/dist/javascript/recovery/WakaruExecution.js +30 -18
  1022. package/dist/javascript/recovery/WakaruProvider.js +150 -24
  1023. package/dist/javascript/recovery/WakaruPublication.js +38 -14
  1024. package/dist/javascript/recovery/WakaruRelease.js +11 -4
  1025. package/dist/javascript/recovery/WakaruReport.js +15 -9
  1026. package/dist/javascript/recovery/WakaruVersion.js +24 -0
  1027. package/dist/javascript/sourceMaps/DecodedSourceMap.js +2 -16
  1028. package/dist/javascript/sourceMaps/SourceMapCommand.js +38 -7
  1029. package/dist/javascript/sourceMaps/SourceMapDecoder.js +84 -10
  1030. package/dist/javascript/sourceMaps/SourceMapFormat.js +26 -28
  1031. package/dist/javascript/sourceMaps/TraceSourceMap.js +34 -6
  1032. package/dist/jeb/JebMcpConnection.js +186 -0
  1033. package/dist/jeb/JebMcpEndpoint.js +45 -0
  1034. package/dist/jeb/JebProvider.js +297 -0
  1035. package/dist/logger.js +14 -1
  1036. package/dist/main/shutdown.js +3 -0
  1037. package/dist/main/transport.js +48 -4
  1038. package/dist/main.js +14 -3
  1039. package/dist/mcp/AnalysisSnapshotFiles-BAbiJQOc.js +1412 -0
  1040. package/dist/mcp/ArtifactProvider-DViCU_rn.js +2183 -0
  1041. package/dist/mcp/ArtifactProviderMetadata-b7pOK5_t.js +76 -0
  1042. package/dist/mcp/ArtifactReader-OyM03Gjn.js +55 -0
  1043. package/dist/mcp/ArtifactResourceScope-P3tq5z8Z.js +162 -0
  1044. package/dist/mcp/AsarHeader-WsPgoooH.js +31 -0
  1045. package/dist/mcp/BinarySessionStatus-B4P9gf-S.js +212 -0
  1046. package/dist/mcp/BinaryTargetResolver-BMaE_0H1.js +1427 -0
  1047. package/dist/mcp/BoundedFileBytes-DuczXiQZ.js +68 -0
  1048. package/dist/mcp/CdpCaptureDocuments-HDiF2O7k.js +746 -0
  1049. package/dist/mcp/CdpCaptureValues-M-j6CIh1.js +90 -0
  1050. package/dist/mcp/CdpConnection-BpDfz4MK.js +570 -0
  1051. package/dist/mcp/CdpOptionalCommand-BPjRD9Kz.js +120 -0
  1052. package/dist/mcp/CdpTargetSession-BsPoKhEU.js +86 -0
  1053. package/dist/mcp/DirectAnalysis-DrafbXke.js +409 -0
  1054. package/dist/mcp/DirectAnalysisStatus-CjjeDLzW.js +44 -0
  1055. package/dist/mcp/ElectronFileScope-BPG_YoyU.js +110 -0
  1056. package/dist/mcp/InterfaceBuilderDecodeBudget-5F2AkxJT.js +652 -0
  1057. package/dist/mcp/ManagedStaticProvider-BthZbKyZ.js +5028 -0
  1058. package/dist/mcp/NativeMacOSProvider-Bh79k8dI.js +4867 -0
  1059. package/dist/mcp/NativeMacOSProviderMetadata-N1lPOaY_.js +307 -0
  1060. package/dist/mcp/ProcedureAddressResolution-CQpuwm1h.js +19 -0
  1061. package/dist/mcp/ProcessOwnership-Bl_3ejLe.js +1502 -0
  1062. package/dist/mcp/ProviderDeadline-DskQ94YD.js +932 -0
  1063. package/dist/mcp/WorkflowEvidence-umWrB_wm.js +111 -0
  1064. package/dist/mcp/analysisErrorCore-DXRTvF_m.js +235 -0
  1065. package/dist/mcp/analysisErrorProjection-BN0EPM-3.js +892 -0
  1066. package/dist/mcp/artifactOperationError-CkHMMaf7.js +27 -0
  1067. package/dist/mcp/artifactToolContracts-Di4qZlEt.js +72 -0
  1068. package/dist/mcp/browserObservation-C0s4i8UI.js +4468 -0
  1069. package/dist/mcp/browserObservationError-CyLugqX4.js +40 -0
  1070. package/dist/mcp/browserObservationSchemas-tgqjH7aA.js +573 -0
  1071. package/dist/mcp/browserScenario-CAQ8Fns9.js +2929 -0
  1072. package/dist/mcp/browserScenarioCapture-CTNFN-FI.js +479 -0
  1073. package/dist/mcp/canonicalDigest-Bi_0_zGi.js +71 -0
  1074. package/dist/mcp/digests-BFoWUT_-.js +223 -0
  1075. package/dist/mcp/electronActiveObservation-lDvQTMR0.js +226 -0
  1076. package/dist/mcp/electronObservation-DFOFEood.js +112 -0
  1077. package/dist/mcp/electronObservation-i7LcILQ-.js +562 -0
  1078. package/dist/mcp/electronScenario-nCzE6IfJ.js +653 -0
  1079. package/dist/mcp/emptyArraySchema-tL6Qymyd.js +140 -0
  1080. package/dist/mcp/enhancedInputs-DgdEnzHy.js +56 -0
  1081. package/dist/mcp/javascriptRuntimeObservation-61NhCf7H.js +690 -0
  1082. package/dist/mcp/javascriptRuntimeObservation-PIUoLfX6.js +121 -0
  1083. package/dist/mcp/jsonSerialization-V-wWiFRE.js +152 -0
  1084. package/dist/mcp/lipo-Bnkoq_6W.js +502 -0
  1085. package/dist/mcp/localPath-AxvW9aPe.js +19 -0
  1086. package/dist/mcp/logger-BQY5ulYv.js +48 -0
  1087. package/dist/mcp/main-kBXHZ8S5.js +69390 -0
  1088. package/dist/mcp/main.js +6 -0
  1089. package/dist/mcp/managedToolContracts-CK--I_s7.js +101 -0
  1090. package/dist/mcp/nativeValueTrace-DR9UE62L.js +3439 -0
  1091. package/dist/mcp/officialToolContracts-B67NJ2tC.js +1413 -0
  1092. package/dist/mcp/pngHeader-DQ-ObyY2.js +147 -0
  1093. package/dist/mcp/propertyListKeys-DD25WsjI.js +553 -0
  1094. package/dist/mcp/providerAdapterError-sDxToNal.js +25 -0
  1095. package/dist/mcp/providerIdentities--ptAh481.js +31 -0
  1096. package/dist/mcp/providerIdentity-BCQ5n5tw.js +16 -0
  1097. package/dist/mcp/providerOperationHealth-CTYa3iLf.js +48 -0
  1098. package/dist/mcp/rolldown-runtime-BjeaiXFo.js +121 -0
  1099. package/dist/mcp/safeJson-NeGfpkrI.js +25 -0
  1100. package/dist/mcp/scanCanonical-CRXSpule.js +3982 -0
  1101. package/dist/mcp/serverIdentity-Cio4iFV3.js +1328 -0
  1102. package/dist/mcp/sourceMapEnvelope-C0uJlrOh.js +94 -0
  1103. package/dist/mcp/toolContracts-BW05wpcr.js +12200 -0
  1104. package/dist/mcp/toolOutputSchemaGroups-ColvNZ1r.js +17533 -0
  1105. package/dist/mcp/unicodeCodePointOrder-BezCbTpg.js +26 -0
  1106. package/dist/mcp/webContentArtifact-Dzjc1z-R.js +284 -0
  1107. package/dist/mcp/webRuntime-K__NYzXm.js +74 -0
  1108. package/dist/mcp/webSourceLocation-DbMAT2J9.js +11130 -0
  1109. package/dist/mcpDoctor.js +108 -76
  1110. package/dist/mcpStartupPolicy.js +3 -0
  1111. package/dist/native/AppleDispatchCoverage.js +81 -28
  1112. package/dist/native/AppleDispatchMetadata.js +20 -9
  1113. package/dist/native/AppleMachoFixups.js +253 -34
  1114. package/dist/native/AppleMachoSelection.js +44 -17
  1115. package/dist/native/AppleObjcCategories.js +1 -2
  1116. package/dist/native/AppleObjcDispatchFacets.js +76 -7
  1117. package/dist/native/CommandRunner.js +142 -32
  1118. package/dist/native/LldbCallTracer.js +5 -3
  1119. package/dist/native/MachoArchitectureSelection.js +50 -0
  1120. package/dist/native/NativeCallObservation.js +2 -1
  1121. package/dist/native/NativeMacOSProvider.js +173 -37
  1122. package/dist/native/NativeMachoInspection.js +142 -78
  1123. package/dist/native/NativeUiHelperRuntime.js +6 -1
  1124. package/dist/native/NativeUiObservation.js +6 -5
  1125. package/dist/native/SignatureTargetBinding.js +118 -55
  1126. package/dist/native/parsers/codesign.js +27 -10
  1127. package/dist/native/parsers/demangle.js +7 -1
  1128. package/dist/native/parsers/dyldInfo.js +73 -4
  1129. package/dist/native/parsers/lipo.js +53 -19
  1130. package/dist/native/parsers/machoUuid.js +150 -0
  1131. package/dist/native/parsers/otool.js +232 -29
  1132. package/dist/native/pe/PeResourceLayout.js +120 -0
  1133. package/dist/native/pe/PeResourceParser.js +286 -0
  1134. package/dist/native/pe/PeResourcesProvider.js +77 -0
  1135. package/dist/native/pwndbg/PwndbgCoreContext.js +20 -20
  1136. package/dist/native/pwntools/PwntoolsDecoder.js +264 -40
  1137. package/dist/native/pwntools/PwntoolsFailures.js +2 -1
  1138. package/dist/native/pwntools/PwntoolsInputLimit.js +27 -0
  1139. package/dist/native/pwntools/PwntoolsRecordedCrashProvider.js +27 -15
  1140. package/dist/native/pwntools/PwntoolsResourceLimits.js +3 -3
  1141. package/dist/native/pwntools/RecordedCrashSourceBindings.js +12 -8
  1142. package/dist/native/pwntools/RecordedCrashStructureBindings.js +3 -1
  1143. package/dist/objdump/ObjdumpCommand.js +21 -0
  1144. package/dist/pcap/PcapCommand.js +146 -0
  1145. package/dist/pcap/PcapConfiguration.js +93 -0
  1146. package/dist/pcap/PcapNativeBound.js +58 -0
  1147. package/dist/pcap/PcapOutput.js +240 -0
  1148. package/dist/pcap/PcapProvider.js +424 -0
  1149. package/dist/pcap/PcapSnapshot.js +171 -0
  1150. package/dist/process/ArtifactAnalysisResources.js +213 -0
  1151. package/dist/process/BoundedFileBytes.js +30 -7
  1152. package/dist/process/CurrentEntrypointPath.js +6 -0
  1153. package/dist/process/DarwinProcessRunTokenReader.js +125 -16
  1154. package/dist/process/ExecFileBoundedOutput.js +44 -0
  1155. package/dist/process/ExecFileOutput.js +30 -6
  1156. package/dist/process/JavaScriptWorkerMemoryLimit.js +25 -0
  1157. package/dist/process/LinuxResourceLimits.js +80 -0
  1158. package/dist/process/MacCodeSignature.js +3 -0
  1159. package/dist/process/OwnedCommand.js +40 -15
  1160. package/dist/process/PrivateRuntimeRoot.js +9 -19
  1161. package/dist/process/PrivateRuntimeRootUnavailableError.js +10 -0
  1162. package/dist/process/ProcessOwnership.js +173 -128
  1163. package/dist/process/ProcessOwnershipObservation.js +131 -43
  1164. package/dist/process/ProcessOwnershipProcessTree.js +4 -4
  1165. package/dist/process/ProcessRunTokenObservations.js +48 -0
  1166. package/dist/process/ProviderDeadline.js +58 -12
  1167. package/dist/process/ProviderDiagnosticRedaction.js +17 -0
  1168. package/dist/process/ProviderProcess.js +112 -14
  1169. package/dist/process/WindowsAuthority.js +48 -39
  1170. package/dist/process/WindowsBatchCommand.js +46 -0
  1171. package/dist/process/boundedUtf8Text.js +13 -0
  1172. package/dist/process/capture/FilesystemSnapshot.js +87 -12
  1173. package/dist/process/capture/ProcessCaptureClock.js +2 -0
  1174. package/dist/process/capture/ProcessCaptureError.js +22 -3
  1175. package/dist/process/capture/ProcessCaptureJournal.js +2 -1
  1176. package/dist/process/capture/ProcessCaptureLifecycle.js +433 -91
  1177. package/dist/process/capture/ProcessCaptureProgress.js +63 -0
  1178. package/dist/process/capture/ProcessHarness.js +209 -38
  1179. package/dist/process/capture/ProcessNormalization.js +278 -34
  1180. package/dist/process/capture/ProcessSampling.js +3 -2
  1181. package/dist/process/capture/ProcessScenarioRuntimeValidation.js +18 -15
  1182. package/dist/process/capture/TerminalRenderer.js +52 -14
  1183. package/dist/process/ownedDebuggerSession.js +203 -0
  1184. package/dist/reference/ReferenceSourceReader.js +22 -6
  1185. package/dist/reference/ReferenceSourceReaderEntries.js +182 -105
  1186. package/dist/reference/ReferenceSourceReaderErrors.js +17 -1
  1187. package/dist/reference/ReferenceSourceReaderFile.js +50 -11
  1188. package/dist/reference/ReferenceSourceReaderTypes.js +1 -2
  1189. package/dist/reference/ReferenceSourceReaderValidate.js +4 -5
  1190. package/dist/rizin/RizinCommand.js +14 -0
  1191. package/dist/rizin/RizinDebugSessionManager.js +1072 -0
  1192. package/dist/rust/RustAuditableReader.js +309 -0
  1193. package/dist/rust/RustBinaryImage.js +116 -0
  1194. package/dist/rust/RustBinaryProvider.js +162 -0
  1195. package/dist/server/EvidenceMcpServer.js +185 -27
  1196. package/dist/server/admittedToolOperation.js +14 -0
  1197. package/dist/server/contractToolHandler.js +28 -0
  1198. package/dist/server/createServer.js +238 -36
  1199. package/dist/server/externalMutationAdmission.js +50 -0
  1200. package/dist/server/mcpProgress.js +4 -2
  1201. package/dist/server/promptCompletion.js +19 -6
  1202. package/dist/server/providerEnvironment.js +3 -0
  1203. package/dist/server/registerAdbTools.js +36 -0
  1204. package/dist/server/registerAnalysisViewTool.js +9 -10
  1205. package/dist/server/registerAndroidTools.js +22 -13
  1206. package/dist/server/registerApktoolTools.js +14 -0
  1207. package/dist/server/registerApplicationTools/compareExportShapes.js +4 -6
  1208. package/dist/server/registerApplicationTools/compareSourceToBundle.js +4 -5
  1209. package/dist/server/registerApplicationTools/compareVersions.js +3 -2
  1210. package/dist/server/registerApplicationTools/coverage.js +3 -2
  1211. package/dist/server/registerApplicationTools/obligationLedger.js +3 -2
  1212. package/dist/server/registerApplicationTools/projectMobileApplicationGraph.js +11 -3
  1213. package/dist/server/registerApplicationTools/traceFeature.js +3 -2
  1214. package/dist/server/registerApplicationTools/traceSemantics.js +4 -5
  1215. package/dist/server/registerArtifactComparisonTool.js +5 -2
  1216. package/dist/server/registerArtifactTools.js +21 -1
  1217. package/dist/server/registerBinaryDiagnosticsTools.js +16 -4
  1218. package/dist/server/registerBrowserScenarioTool.js +10 -7
  1219. package/dist/server/registerBrowserTools.js +14 -13
  1220. package/dist/server/registerBundleComparisonTool.js +20 -6
  1221. package/dist/server/registerCaptureTools.js +12 -0
  1222. package/dist/server/registerCloseLifecycleTool.js +32 -3
  1223. package/dist/server/registerCutterTools.js +33 -0
  1224. package/dist/server/registerElectronTools.js +38 -17
  1225. package/dist/server/registerEnhancedTools.js +7 -6
  1226. package/dist/server/registerEvidenceTools.js +14 -10
  1227. package/dist/server/registerEvmTools.js +24 -11
  1228. package/dist/server/registerFirmwareTools.js +3 -11
  1229. package/dist/server/registerFlutterTools.js +17 -0
  1230. package/dist/server/registerFridaTools.js +205 -0
  1231. package/dist/server/registerFunctionComparisonTool.js +34 -11
  1232. package/dist/server/registerGdbTools.js +64 -0
  1233. package/dist/server/registerGoTools.js +9 -0
  1234. package/dist/server/registerInvestigationTools/helpers.js +2 -2
  1235. package/dist/server/registerInvestigationTools.js +12 -8
  1236. package/dist/server/registerJavaScriptRecoveryTool.js +4 -9
  1237. package/dist/server/registerJavaScriptRuntimeObservationTools.js +10 -11
  1238. package/dist/server/registerJebTools.js +16 -0
  1239. package/dist/server/registerManagedTools.js +11 -1
  1240. package/dist/server/registerManagedWorkflowTools/compareManagedMembers.js +4 -6
  1241. package/dist/server/registerManagedWorkflowTools/importManagedReconstruction.js +3 -2
  1242. package/dist/server/registerManagedWorkflowTools/projectManagedApplicationGraph.js +3 -2
  1243. package/dist/server/registerManagedWorkflowTools/verifyManagedNativeBoundaries.js +3 -2
  1244. package/dist/server/registerNativeTools.js +14 -0
  1245. package/dist/server/registerOfficialTools.js +5 -0
  1246. package/dist/server/registerPcapTools.js +35 -0
  1247. package/dist/server/registerPeResourcesTool.js +9 -0
  1248. package/dist/server/registerProcessComparisonTool.js +14 -4
  1249. package/dist/server/registerRecordedCrashTools.js +4 -9
  1250. package/dist/server/registerReverseEngineeringTools.js +86 -0
  1251. package/dist/server/registerRizinDebugTools.js +53 -0
  1252. package/dist/server/registerRustTools.js +9 -0
  1253. package/dist/server/registerSessionRecordTools.js +21 -14
  1254. package/dist/server/registerSessionStatusTool.js +22 -4
  1255. package/dist/server/registerSessionTools.js +78 -34
  1256. package/dist/server/registerSignalTools.js +12 -0
  1257. package/dist/server/registerSqliteTools.js +9 -0
  1258. package/dist/server/registerWasmTools.js +46 -0
  1259. package/dist/server/registerWebModuleTool.js +4 -9
  1260. package/dist/server/registerWebNetworkCaptureTool.js +26 -17
  1261. package/dist/server/registerWebRuntimeTools.js +6 -5
  1262. package/dist/server/registerWebScriptTool.js +6 -3
  1263. package/dist/server/registerWebSourceLocationTool.js +4 -9
  1264. package/dist/server/retainedSummaryDelivery.js +28 -0
  1265. package/dist/server/sessionAvailabilityPolicy.js +3 -0
  1266. package/dist/server/toolRegistrationOptions.js +8 -0
  1267. package/dist/server/toolResult.js +68 -16
  1268. package/dist/server/toolResultEncoding.js +36 -3
  1269. package/dist/serverIdentity.js +17 -8
  1270. package/dist/signals/SigrokRecordingProvider.js +339 -0
  1271. package/dist/signals/parseDecoderDiscovery.js +65 -0
  1272. package/dist/sqlite/SqliteDatabaseFailures.js +134 -0
  1273. package/dist/sqlite/SqliteDatabaseInspection.js +421 -0
  1274. package/dist/sqlite/SqliteDatabaseLimits.js +16 -0
  1275. package/dist/sqlite/SqliteDatabaseProvider.js +295 -0
  1276. package/dist/sqlite/SqliteDatabaseSnapshot.js +156 -0
  1277. package/dist/sqlite/SqliteDatabaseWorker.js +46 -0
  1278. package/dist/sqlite/SqliteDatabaseWorkerExecution.js +112 -0
  1279. package/dist/wasm/WabtArtifactProvider.js +336 -0
  1280. package/dist/wasm/WabtFailures.js +101 -0
  1281. package/dist/wasm/WabtInterface.js +309 -0
  1282. package/dist/wasm/WabtOutput.js +60 -0
  1283. package/dist/wasm/WabtRelease.js +12 -0
  1284. package/dist/wasm/WabtString.js +48 -0
  1285. package/dist/wasm/WabtWat.js +147 -0
  1286. package/dist/wasm/WasmGlueAdapter.js +53 -0
  1287. package/dist/wasm/WasmInterfaceBudget.js +11 -0
  1288. package/dist/windows/WindowsNativeLoader.js +37 -7
  1289. package/dist/windows/WindowsOwnedProcess.js +150 -17
  1290. package/dist/windows/WindowsPrivateRuntime.js +34 -6
  1291. package/install.sh +157 -95
  1292. package/licenses/Apache-2.0.txt +202 -0
  1293. package/licenses/GCC-Runtime-Library-Exception-3.1.txt +73 -0
  1294. package/licenses/GPL-3.0.txt +674 -0
  1295. package/licenses/LGPL-2.0.txt +480 -0
  1296. package/licenses/MIT-template.txt +18 -0
  1297. package/licenses/MinGW-w64-runtime.txt +240 -0
  1298. package/licenses/Node-22.19.0-LICENSE.txt +2666 -0
  1299. package/licenses/README.md +68 -0
  1300. package/licenses/cfworker-MIT.txt +21 -0
  1301. package/licenses/dotnet-runtime-MIT.txt +23 -0
  1302. package/licenses/frida-17.23.2-COPYING.txt +50 -0
  1303. package/licenses/ghidra-12.1.4-DISCLAIMER.txt +13 -0
  1304. package/licenses/ghidra-12.1.4-LICENSE.txt +201 -0
  1305. package/licenses/ghidra-12.1.4-NOTICE.txt +49 -0
  1306. package/licenses/nativeaot-parser-MIT.txt +28 -0
  1307. package/licenses/npm-dependencies.txt +3612 -0
  1308. package/licenses/npm-runtime-notices.txt +8548 -0
  1309. package/licenses/upstream-sources.json +72 -0
  1310. package/licenses/xterm-MIT.txt +21 -0
  1311. package/native/windows/README.md +92 -11
  1312. package/native/windows/build/manifest.json +2 -2
  1313. package/native/windows/build/rea-windows-x64.node +0 -0
  1314. package/package.json +117 -22
  1315. package/scripts/electron-active-hook.cjs +4 -1
  1316. package/scripts/hopper-demo-x11.py +53 -3
  1317. package/scripts/prepack.mjs +5 -0
  1318. package/scripts/rea-android-workspace-guardian.mjs +46 -0
  1319. package/scripts/rea.mjs +44 -13
  1320. package/scripts/verify-windows-native-artifact.mjs +2 -2
  1321. package/skills/reverse-engineer-anything/SKILL.md +142 -20
  1322. package/skills/reverse-engineer-anything/references/connection-and-recovery.md +127 -0
  1323. package/skills/reverse-engineer-anything/references/evidence-workflows.md +31 -0
  1324. package/skills/reverse-engineer-anything/references/javascript-applications.md +118 -13
  1325. package/skills/reverse-engineer-anything/references/native-and-artifacts.md +147 -16
  1326. package/skills/reverse-engineer-anything/references/runtime-observation.md +57 -7
  1327. package/third_party/README.md +1 -1
  1328. package/third_party/wabt/README.md +24 -0
  1329. package/dist/browser/history/HarCaptureAdapter.js +0 -20
  1330. package/dist/cli/streamedJsonOutput.js +0 -135
  1331. package/dist/cliJsonFile.js +0 -179
  1332. /package/dist/{application/binary → process}/AbortablePromise.js +0 -0
@@ -0,0 +1,4875 @@
1
+ import { __esmMin } from "./rolldown-runtime-DXoylpqc.js";
2
+ import { analysisInputErrorFromIssues, compareUnicodeCodePoints, err, init_binaryTargetTypes, init_inputIssueProjection, init_machoCpuIdentity, init_objcSwiftMetadata, init_result, init_swiftSymbolClassification, init_unicodeCodePointOrder, isMachOFormat, isSwiftMangledSymbolName, machoCpuSubtypeBase, nativeDispatchMetadataResultSchema, objcSwiftMetadataSchema, ok } from "./reconstructionObligationLedgerSchemas-Bao0xMr-.js";
3
+ import { NATIVE_TOOL_CONTRACTS, init_nativeToolContracts } from "./cutterToolContracts-TZH9EHr5.js";
4
+ import { AnalysisAccessDeniedError, AnalysisArtifactChangedError, AnalysisCancelledError, AnalysisCapabilityUnavailableError, AnalysisError, AnalysisInputError, AnalysisOutputError, AnalysisResourceConstraintError, AnalysisTimeoutError, BinaryTargetError, init_analysisErrorBase, init_analysisErrorCore, init_configurationErrors, init_jsonValue, jsonValueSchema } from "./errorSchemas-CTRmvMl3.js";
5
+ import { ArtifactReaderFailure, init_ArtifactReader } from "./ArtifactReader-BXkffc1D.js";
6
+ import { OwnedFileHandle, init_OwnedFileHandle, init_RegularFile, openRegularFile } from "./RegularFile-B_6KPCNQ.js";
7
+ import { createAnalysisExecution, init_AnalysisProvider } from "./AnalysisProvider-D0Us2OTk.js";
8
+ import { ArtifactResourceScope, init_ArtifactResourceScope } from "./ArtifactResourceScope-DQWTcUwE.js";
9
+ import { ProviderAdapterError, init_providerAdapterError } from "./providerAdapterError-DAjhICdr.js";
10
+ import { EvidenceIntegrityError, init_evidenceErrors } from "./analysisErrorPresentation-DGt7TdsH.js";
11
+ import { init_analysisErrorProjection, projectAnalysisError } from "./cliResultOutput-DsRMI8CJ.js";
12
+ import { analysisErrorWithCleanupFailure, init_analysisErrorCleanup } from "./analysisErrorCleanup-Do6YeeoD.js";
13
+ import { ProviderCleanupError, init_providerCleanupError } from "./providerCleanupError-Ceq8f0wK.js";
14
+ import { ProviderProcessSupervisor, init_ProviderProcess, init_snapshotEnvironment, snapshotEnvironment, spawnOwnedProviderProcess } from "./snapshotEnvironment-D_tWyOub.js";
15
+ import { SWIFTC_INTERRUPT, cleanupOwnedProcessGroup, init_DarwinProcessRunTokenReader, init_ProcessOwnership, init_ProcessOwnershipObservation, observeProcessStartIdentity, signalProcessWithStartIdentity } from "./ProcessOwnership-DXC5-UWt.js";
16
+ import { execFileOutput, init_ExecFileOutput } from "./ExecFileOutput-BEQs-lDD.js";
17
+ import { init_safeJson, safeParseJson } from "./safeJson-DKKACtdy.js";
18
+ import { ProviderStartupDeadline, init_ProviderDeadline, waitForAbortableDelay } from "./ProviderDeadline-8m2pFRDc.js";
19
+ import { PrivateRuntimeRoot, init_PrivateRuntimeRoot } from "./PrivateRuntimeRoot-DAy0PiBM.js";
20
+ import { demangleSwiftSchema, init_nativeCallObservation, init_nativeInspection, init_nativeUiObservation, inspectMachoSchema, inspectPlistSchema, inspectSignatureSchema, listArchitecturesSchema, nativeCallEventSchema, nativeCallObservationInputSchema, nativeCallObservationResultSchema, nativeCodeLocationSchema, nativeUiObservationInputSchema, nativeUiResultSchema, nativeUiScenarioInputSchema, nativeUiSnapshotSchema } from "./toolOutputSchemaGroups-DRiYs1je.js";
21
+ import { init_BoundedFileBytes, readBoundedFileBytes } from "./BoundedFileBytes-BU30odTm.js";
22
+ import { init_machoContainer, readFatSliceDeclarations, validateFatSlice } from "./machoContainer-C8BIkkq3.js";
23
+ import { init_plistValue, init_propertyListKeys, omitPrototypeKeys, omittedPrototypeKeysLimitation, parseXmlPropertyList, projectPlistValue } from "./propertyListKeys-G8e74YWb.js";
24
+ import { init_toolContracts, toolContract } from "./toolContracts-D2FOG_Nb.js";
25
+ import { NATIVE_COMMAND_OUTPUT_BUDGET_BYTES, NATIVE_COMMAND_TIMEOUT_MS, NativeCommandFailure, XcrunCommandRunner, failureCapture, init_CommandRunner, init_lipo, parseLipoOutput, resolveXcrunTool } from "./lipo-DSWP6fv-.js";
26
+ import { NATIVE_MACOS_PROVIDER_IDENTITY, init_NativeMacOSProviderMetadata, nativeMacOSCapabilities } from "./binary-BVOr2mgE.js";
27
+ import { z } from "zod";
28
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
29
+ import { createHash, randomUUID } from "node:crypto";
30
+ import { lstat, mkdir, mkdtemp, open, readFile, realpath, rm, stat, symlink, writeFile } from "node:fs/promises";
31
+ import { constants } from "node:fs";
32
+ import { fileURLToPath } from "node:url";
33
+ import { tmpdir } from "node:os";
34
+
35
+ //#region dist/native/AppleDispatchCoverage.js
36
+ var describeFixups, pushDispatchCoverage, formatIssue;
37
+ function init_AppleDispatchCoverage() {
38
+ return (init_AppleDispatchCoverage = __esmMin((() => {
39
+ describeFixups = (fixups) => {
40
+ const unread = fixups.unreadRebaseBytes > 0 ? `LC_DYLD_INFO rebase opcodes were not decoded (${fixups.unreadRebaseBytes} bytes)` : undefined;
41
+ const kind = fixups.kind === "chained" ? `chained fixups: ${fixups.formats.join(", ") || "no fixup segments"}` : fixups.kind === "dyld-info" ? "LC_DYLD_INFO bind opcodes" : unread === undefined ? "no fixup load commands" : undefined;
42
+ return [unread, kind].filter((line) => line !== undefined).join("; ");
43
+ };
44
+ pushDispatchCoverage = (input) => {
45
+ const { result, failures, categoryIssues, examined, categoriesExamined, truncated, objcListScanTruncated, objcClassListScanTruncated, fixups, vtables, swift } = input;
46
+ const classOwnedMethods = result.objc_dispatch_implementations.filter(({ category }) => category === undefined);
47
+ const classRecords = [
48
+ ...result.objc_classes.flatMap((record) => record.decode?.status === "decoded" ? [] : [`class ${record.name}: ${record.decode?.reason ?? record.decode?.status ?? "decode_status_missing"}`]),
49
+ ...result.objc_protocol_records.flatMap((record) => record.decode.status === "decoded" ? [] : [`protocol ${record.name}: ${record.decode.reason ?? record.decode.status}`]),
50
+ ...classOwnedMethods.flatMap((record) => record.decode.status === "decoded" ? [] : [`method ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`]),
51
+ ...result.objc_ivars.flatMap((record) => record.decode.status === "decoded" ? [] : [`ivar ${record.class_name}.${record.name}: ${record.decode.reason ?? record.decode.status}`])
52
+ ];
53
+ const classReasons = [
54
+ ...failures,
55
+ ...classRecords,
56
+ ...truncated || objcListScanTruncated ? ["max_records_reached"] : []
57
+ ];
58
+ const categoryMethods = result.objc_dispatch_implementations.filter(({ category }) => category !== undefined);
59
+ const categoryMethodReasons = categoryMethods.flatMap((record) => record.decode.status === "decoded" ? [] : [`category method ${record.category} ${record.class_name} ${record.method_type} ${record.selector}: ${record.decode.reason ?? record.decode.status}`]);
60
+ result.coverage.push({
61
+ facet: "objc_class_method_ivar_metadata",
62
+ status: classReasons.length > 0 ? "partial" : "complete",
63
+ reason: classReasons.join("; ") || null,
64
+ examined,
65
+ decoded: result.objc_classes.filter(({ decode }) => decode?.status === "decoded").length
66
+ });
67
+ const relativePointerReasons = [...truncated || objcClassListScanTruncated ? ["max_records_reached"] : [], ...result.relative_pointers.some((item) => item.decode.status !== "decoded") ? ["relative_pointer_targets_unresolved"] : []];
68
+ result.coverage.push({
69
+ facet: "binary_relative_pointers",
70
+ status: relativePointerReasons.length > 0 ? "partial" : "complete",
71
+ reason: relativePointerReasons.join("; ") || null,
72
+ examined: result.relative_pointers.length,
73
+ decoded: result.relative_pointers.filter((item) => item.decode.status === "decoded").length
74
+ });
75
+ const categoryFailures = categoryIssues.map(({ code, location, message }) => `${code}${location === undefined ? "" : ` at ${location}`}: ${message}`);
76
+ result.coverage.push({
77
+ facet: "objc_properties_categories",
78
+ status: truncated || objcClassListScanTruncated || categoryFailures.length > 0 || result.objc_categories.some(({ decode }) => decode.status !== "decoded") || categoryMethodReasons.length > 0 ? "partial" : "complete",
79
+ reason: [
80
+ ...categoryFailures,
81
+ ...categoryMethodReasons,
82
+ ...truncated || objcClassListScanTruncated ? ["max_records_reached"] : []
83
+ ].join("; ") || null,
84
+ examined: categoriesExamined,
85
+ decoded: result.objc_categories.filter(({ decode }) => decode.status === "decoded").length
86
+ });
87
+ const fixupReason = [describeFixups(fixups), ...fixups.issues.map(({ code, location, message }) => `${code}${location === undefined ? "" : ` at ${location}`}: ${message}`)].filter((line) => line.length > 0).join("; ");
88
+ result.coverage.push({
89
+ facet: "pointer_fixups",
90
+ status: fixups.issues.length > 0 || fixups.unreadRebaseBytes > 0 ? "partial" : fixups.examined === 0 ? "unsupported" : "complete",
91
+ reason: fixupReason.length > 0 ? fixupReason : null,
92
+ examined: fixups.examined,
93
+ decoded: fixups.decoded
94
+ });
95
+ result.coverage.push({
96
+ facet: "swift_generic_resilient_witnesses_overrides_async_coroutines",
97
+ status: "unsupported",
98
+ reason: "This reader admits simple Swift conformance/static witness records and non-generic, non-resilient class vtables; generic/resilient tables and other Swift metadata families are not decoded",
99
+ examined: 0,
100
+ decoded: 0
101
+ });
102
+ result.coverage.push({
103
+ facet: "swift_conformances_static_witness_slots",
104
+ status: swift.exhaustive && !truncated && !result.swift_conformances.some(({ decode }) => decode.status !== "decoded") && !result.swift_dispatch_slots.some(({ table_kind, decode }) => table_kind === "witness_table" && decode.status !== "decoded") ? "complete" : "partial",
105
+ reason: [
106
+ ...swift.issues.map(formatIssue),
107
+ ...truncated ? ["max_records_reached"] : [],
108
+ ...result.swift_conformances.some(({ decode }) => decode.status !== "decoded") || result.swift_dispatch_slots.some(({ table_kind, decode }) => table_kind === "witness_table" && decode.status !== "decoded") ? ["swift_records_unresolved"] : []
109
+ ].join("; ") || null,
110
+ examined: swift.examined,
111
+ decoded: swift.decoded
112
+ });
113
+ result.coverage.push({
114
+ facet: "swift_class_vtable_descriptors",
115
+ status: vtables.exhaustive && !truncated && !result.swift_dispatch_slots.some(({ table_kind, decode }) => table_kind === "class_vtable" && decode.status !== "decoded") ? "complete" : "partial",
116
+ reason: [
117
+ ...vtables.issues.map(formatIssue),
118
+ ...truncated ? ["max_records_reached"] : [],
119
+ ...result.swift_dispatch_slots.some(({ table_kind, decode }) => table_kind === "class_vtable" && decode.status !== "decoded") ? ["vtable_implementations_unresolved"] : []
120
+ ].join("; ") || null,
121
+ examined: vtables.examined,
122
+ decoded: vtables.decoded
123
+ });
124
+ };
125
+ formatIssue = ({ code, location, message }) => `${code}${location === undefined ? "" : ` at ${location}`}: ${message}`;
126
+ })))();
127
+ }
128
+
129
+ //#endregion
130
+ //#region dist/native/AppleDispatchDecodeFacts.js
131
+ var issue;
132
+ function init_AppleDispatchDecodeFacts() {
133
+ return (init_AppleDispatchDecodeFacts = __esmMin((() => {
134
+ issue = (facet, code, message, location) => ({
135
+ facet,
136
+ code,
137
+ message,
138
+ ...location === undefined ? {} : { location }
139
+ });
140
+ })))();
141
+ }
142
+
143
+ //#endregion
144
+ //#region dist/native/AppleMachoFixups.js
145
+ var POINTER_FORMATS, bits, signed, libraryName, cString, readImport, decodeChainedPointer, readChainedPage, chainedFixups, uleb, sleb, setBindRegister, readBindStream, parsePointerFixups;
146
+ function init_AppleMachoFixups() {
147
+ return (init_AppleMachoFixups = __esmMin((() => {
148
+ init_AppleDispatchDecodeFacts();
149
+ POINTER_FORMATS = {
150
+ 1: "DYLD_CHAINED_PTR_ARM64E",
151
+ 2: "DYLD_CHAINED_PTR_64",
152
+ 6: "DYLD_CHAINED_PTR_64_OFFSET",
153
+ 9: "DYLD_CHAINED_PTR_ARM64E_USERLAND",
154
+ 12: "DYLD_CHAINED_PTR_ARM64E_USERLAND24"
155
+ };
156
+ bits = (value, from, width) => value >> BigInt(from) & (1n << BigInt(width)) - 1n;
157
+ signed = (value, width) => value >= 1n << BigInt(width - 1) ? value - (1n << BigInt(width)) : value;
158
+ libraryName = (ordinal, dylibs) => {
159
+ if (ordinal > 0) return dylibs[ordinal - 1] ?? null;
160
+ return null;
161
+ };
162
+ cString = (bytes, offset, end) => {
163
+ const stop = bytes.indexOf(0, offset);
164
+ if (offset < 0 || offset >= end || stop < 0 || stop >= end) throw new RangeError("Fixup symbol name is outside the symbol pool");
165
+ return bytes.toString("utf8", offset, stop);
166
+ };
167
+ readImport = (data, header, index) => {
168
+ const { bytes, base, end, dylibs } = data;
169
+ const size = header.format === 3 ? 16 : header.format === 2 ? 8 : 4;
170
+ if (header.format < 1 || header.format > 3) throw new RangeError(`Unsupported chained import format ${header.format}`);
171
+ if (!Number.isSafeInteger(header.count) || base + header.offset + header.count * size > end) throw new RangeError("Chained import table exceeds the fixup data");
172
+ if (index < 0 || index >= header.count) throw new RangeError("Chained import index is outside the table");
173
+ const at = base + header.offset + index * size;
174
+ if (header.format === 3) {
175
+ const word = bytes.readBigUInt64LE(at);
176
+ const encodedOrdinal = Number(bits(word, 0, 16));
177
+ const ordinal = encodedOrdinal > 65520 ? encodedOrdinal - 65536 : encodedOrdinal;
178
+ return {
179
+ symbol: cString(bytes, base + header.symbols + Number(bits(word, 32, 32)), end),
180
+ library: libraryName(ordinal, dylibs),
181
+ weak: bits(word, 16, 1) === 1n,
182
+ addend: bytes.readBigInt64LE(at + 8)
183
+ };
184
+ }
185
+ const word = bytes.readUInt32LE(at);
186
+ const encodedOrdinal = word & 255;
187
+ const ordinal = encodedOrdinal > 240 ? encodedOrdinal - 256 : encodedOrdinal;
188
+ return {
189
+ symbol: cString(bytes, base + header.symbols + (word >>> 9), end),
190
+ library: libraryName(ordinal, dylibs),
191
+ weak: (word >>> 8 & 1) === 1,
192
+ addend: header.format === 2 ? BigInt(bytes.readInt32LE(at + 4)) : 0n
193
+ };
194
+ };
195
+ decodeChainedPointer = (raw, format, baseAddress, imports) => {
196
+ const bind = (ordinal, addend) => {
197
+ const target = typeof imports === "function" ? imports(Number(ordinal)) : imports[Number(ordinal)];
198
+ if (target === undefined) throw new RangeError(`Chained bind ordinal ${ordinal} has no import`);
199
+ return {
200
+ kind: "bind",
201
+ ...target,
202
+ addend: target.addend + addend
203
+ };
204
+ };
205
+ if (format === 2 || format === 6) {
206
+ if (bits(raw, 63, 1) === 1n) return bind(bits(raw, 0, 24), bits(raw, 24, 8));
207
+ const target = bits(raw, 0, 36) | bits(raw, 36, 8) << 56n;
208
+ return {
209
+ kind: "rebase",
210
+ target: format === 6 ? target + baseAddress : target
211
+ };
212
+ }
213
+ if (format === 1 || format === 9 || format === 12) {
214
+ const auth = bits(raw, 63, 1) === 1n;
215
+ if (bits(raw, 62, 1) === 1n) return bind(bits(raw, 0, format === 12 ? 24 : 16), auth ? 0n : signed(bits(raw, 32, 19), 19));
216
+ if (auth) return {
217
+ kind: "rebase",
218
+ target: bits(raw, 0, 32) + baseAddress
219
+ };
220
+ const target = bits(raw, 0, 43) | bits(raw, 43, 8) << 56n;
221
+ return {
222
+ kind: "rebase",
223
+ target: format === 1 ? target : target + baseAddress
224
+ };
225
+ }
226
+ throw new RangeError(`Unsupported chained pointer format ${format}`);
227
+ };
228
+ readChainedPage = (bytes, source) => {
229
+ let locations = new Uint8Array(0);
230
+ let lastOffset;
231
+ let failure;
232
+ try {
233
+ if ((source.start & 32768) !== 0) throw new RangeError("Multiple chained starts are not valid for 64-bit pointers");
234
+ if (source.start + 8 > source.size) throw new RangeError("Chained pointer leaves its file-backed page");
235
+ locations = new Uint8Array(Math.ceil(source.size / 8));
236
+ const generic = source.format === 2 || source.format === 6;
237
+ let at = source.start;
238
+ while (true) {
239
+ locations[at >>> 3] = (locations[at >>> 3] ?? 0) | 1 << (at & 7);
240
+ lastOffset = at;
241
+ const raw = bytes.readBigUInt64LE(source.offset + at);
242
+ const next = Number(bits(raw, 51, generic ? 12 : 11)) * (generic ? 4 : 8);
243
+ if (next === 0) break;
244
+ if (at + next + 8 > source.size) throw new RangeError("Chained pointer link leaves its file-backed page");
245
+ at += next;
246
+ }
247
+ } catch (cause) {
248
+ failure = cause instanceof Error ? cause.message : String(cause);
249
+ }
250
+ return {
251
+ locations,
252
+ lastOffset,
253
+ failure
254
+ };
255
+ };
256
+ chainedFixups = (image, range, unreadRebaseBytes) => {
257
+ const { bytes, segments, dylibs, baseAddress } = image;
258
+ const base = range.offset;
259
+ const end = range.offset + range.size;
260
+ if (!Number.isSafeInteger(base) || base < 0 || !Number.isSafeInteger(range.size) || range.size < 28 || end > bytes.length) throw new RangeError("Chained fixup header exceeds the target");
261
+ if (bytes.readUInt32LE(base) !== 0) throw new RangeError("Unsupported chained fixup header version");
262
+ const startsOffset = bytes.readUInt32LE(base + 4);
263
+ const importHeader = {
264
+ offset: bytes.readUInt32LE(base + 8),
265
+ symbols: bytes.readUInt32LE(base + 12),
266
+ count: bytes.readUInt32LE(base + 16),
267
+ format: bytes.readUInt32LE(base + 20)
268
+ };
269
+ const importSize = importHeader.format === 3 ? 16 : importHeader.format === 2 ? 8 : 4;
270
+ const importTableEnd = base + importHeader.offset + importHeader.count * importSize;
271
+ if (importHeader.format < 1 || importHeader.format > 3) throw new RangeError(`Unsupported chained import format ${importHeader.format}`);
272
+ if (importHeader.offset < 28 || importHeader.symbols < importHeader.offset || importTableEnd > base + importHeader.symbols || base + importHeader.symbols > end) throw new RangeError("Chained import table exceeds the fixup data");
273
+ const imports = (index) => readImport({
274
+ bytes,
275
+ base,
276
+ end,
277
+ dylibs
278
+ }, importHeader, index);
279
+ if (bytes.readUInt32LE(base + 24) !== 0) throw new RangeError("Compressed chained-fixup symbol names are not supported");
280
+ const starts = base + startsOffset;
281
+ const startsEnd = base + importHeader.offset;
282
+ const requireStartsRange = (at, size) => {
283
+ if (at < base + 28 || at > startsEnd - size) throw new RangeError("Chained starts table exceeds its fixup data");
284
+ };
285
+ requireStartsRange(starts, 4);
286
+ const segmentCount = bytes.readUInt32LE(starts);
287
+ if (segmentCount > segments.length) throw new RangeError("Chained starts segment count exceeds the Mach-O layout");
288
+ requireStartsRange(starts, 4 + segmentCount * 4);
289
+ const ranges = [];
290
+ const maximumCachedPages = Math.ceil(bytes.length / 4096) + 2 * segmentCount;
291
+ let remainingLocationBytes = Math.ceil(bytes.length / 8);
292
+ const cachedPages = new Map();
293
+ const pageFacts = (chain, page, start) => {
294
+ const pageOffset = page * chain.pageSize;
295
+ const source = {
296
+ offset: chain.segment.offset + pageOffset,
297
+ size: Math.min(chain.pageSize, Number(chain.segment.size) - pageOffset, bytes.length - chain.segment.offset - pageOffset),
298
+ format: chain.format,
299
+ start
300
+ };
301
+ const key = `${source.offset}:${source.size}:${source.format}:${source.start}`;
302
+ const cached = cachedPages.get(key);
303
+ if (cached !== undefined) return cached;
304
+ const retain = cachedPages.size < maximumCachedPages && Math.ceil(Math.max(source.size, 0) / 8) <= remainingLocationBytes;
305
+ const facts = readChainedPage(bytes, source);
306
+ if (retain) {
307
+ remainingLocationBytes -= facts.locations.byteLength;
308
+ cachedPages.set(key, facts);
309
+ }
310
+ return facts;
311
+ };
312
+ for (let index = 0; index < segmentCount; index++) {
313
+ const infoOffset = bytes.readUInt32LE(starts + 4 + index * 4);
314
+ if (infoOffset === 0) continue;
315
+ const segment = segments[index];
316
+ if (segment === undefined) throw new RangeError("Chained fixup segment table is out of range");
317
+ const info = starts + infoOffset;
318
+ requireStartsRange(info, 22);
319
+ const infoSize = bytes.readUInt32LE(info);
320
+ const pageSize = bytes.readUInt16LE(info + 4);
321
+ const pageCount = bytes.readUInt16LE(info + 20);
322
+ if (infoSize < 22 + pageCount * 2) throw new RangeError("Chained page starts exceed the segment table size");
323
+ requireStartsRange(info, infoSize);
324
+ if (pageSize !== 4096 && pageSize !== 16384) throw new RangeError("Chained page size must be 4096 or 16384 bytes");
325
+ if (bytes.readBigUInt64LE(info + 8) !== segment.address - baseAddress) throw new RangeError("Chained segment offset disagrees with its Mach-O layout");
326
+ ranges.push({
327
+ segment,
328
+ format: bytes.readUInt16LE(info + 6),
329
+ pageSize,
330
+ pageCount,
331
+ pageStarts: info + 22
332
+ });
333
+ }
334
+ const formats = [...new Set(ranges.map(({ format }) => POINTER_FORMATS[format] ?? `format-${format}`))];
335
+ const issues = ranges.flatMap(({ format, segment }) => POINTER_FORMATS[format] === undefined ? [issue("pointer_fixups", "unsupported_pointer_format", `Unsupported chained pointer format ${format}`, `0x${segment.address.toString(16)}`)] : []);
336
+ const examinedViews = new Map();
337
+ const decodedRanges = new Set();
338
+ for (const [chainIndex, chain] of ranges.entries()) {
339
+ if (POINTER_FORMATS[chain.format] === undefined) continue;
340
+ const view = `${chain.pageStarts}:${chain.segment.offset}:${chain.segment.size}:${chain.segment.address}:${chain.format}:${chain.pageSize}:${chain.pageCount}`;
341
+ const prior = examinedViews.get(view);
342
+ if (prior !== undefined) {
343
+ if (prior) decodedRanges.add(chainIndex);
344
+ continue;
345
+ }
346
+ let complete = true;
347
+ for (let page = 0; page < chain.pageCount; page++) {
348
+ const start = bytes.readUInt16LE(chain.pageStarts + page * 2);
349
+ if (start === 65535) continue;
350
+ const facts = pageFacts(chain, page, start);
351
+ if (facts.failure !== undefined) {
352
+ complete = false;
353
+ issues.push(issue("pointer_fixups", "chained_pointer_walk_failed", facts.failure, `0x${(chain.segment.address + BigInt(page * chain.pageSize)).toString(16)}`));
354
+ break;
355
+ }
356
+ }
357
+ examinedViews.set(view, complete);
358
+ if (complete) decodedRanges.add(chainIndex);
359
+ }
360
+ const failures = issues.map(({ message }) => message);
361
+ return {
362
+ kind: "chained",
363
+ formats,
364
+ failures,
365
+ issues,
366
+ examined: Math.max(ranges.length, 1),
367
+ get decoded() {
368
+ return ranges.length === 0 ? 1 : decodedRanges.size;
369
+ },
370
+ unreadRebaseBytes,
371
+ decode(address, raw) {
372
+ const chainIndex = ranges.findIndex(({ segment }) => address >= segment.address && address < segment.address + segment.size);
373
+ const chain = ranges[chainIndex];
374
+ if (chain === undefined) return {
375
+ kind: "rebase",
376
+ target: raw
377
+ };
378
+ const within = Number(address - chain.segment.address);
379
+ const page = Math.floor(within / chain.pageSize);
380
+ if (page >= chain.pageCount) return {
381
+ kind: "rebase",
382
+ target: raw
383
+ };
384
+ const start = bytes.readUInt16LE(chain.pageStarts + page * 2);
385
+ if (start === 65535) return {
386
+ kind: "rebase",
387
+ target: raw
388
+ };
389
+ if (POINTER_FORMATS[chain.format] === undefined) return {
390
+ kind: "unsupported",
391
+ reason: `Unsupported chained pointer format ${chain.format}`
392
+ };
393
+ try {
394
+ const facts = pageFacts(chain, page, start);
395
+ const at = within % chain.pageSize;
396
+ const locations = facts.locations;
397
+ if (((locations[at >>> 3] ?? 0) & 1 << (at & 7)) !== 0) return decodeChainedPointer(raw, chain.format, baseAddress, imports);
398
+ if (facts.failure !== undefined && (facts.lastOffset === undefined || at > facts.lastOffset)) throw new RangeError(facts.failure);
399
+ return {
400
+ kind: "rebase",
401
+ target: raw
402
+ };
403
+ } catch (cause) {
404
+ const reason = cause instanceof Error ? cause.message : String(cause);
405
+ const location = `0x${address.toString(16)}`;
406
+ if (!issues.some((entry) => entry.code === "chained_pointer_decode_failed" && entry.location === location)) {
407
+ issues.push(issue("pointer_fixups", "chained_pointer_decode_failed", reason, location));
408
+ failures.push(reason);
409
+ }
410
+ decodedRanges.delete(chainIndex);
411
+ return {
412
+ kind: "unsupported",
413
+ reason
414
+ };
415
+ }
416
+ }
417
+ };
418
+ };
419
+ uleb = (bytes, cursor, end) => {
420
+ let value = 0n;
421
+ let shift = 0n;
422
+ for (;;) {
423
+ if (cursor.at >= end) throw new RangeError("Truncated bind opcode operand");
424
+ const byte = bytes[cursor.at++] ?? 0;
425
+ value |= BigInt(byte & 127) << shift;
426
+ shift += 7n;
427
+ if ((byte & 128) === 0) return value;
428
+ if (shift > 63n) throw new RangeError("Oversized bind opcode operand");
429
+ }
430
+ };
431
+ sleb = (bytes, cursor, end) => {
432
+ let value = 0n;
433
+ let shift = 0n;
434
+ let byte = 0;
435
+ do {
436
+ if (cursor.at >= end) throw new RangeError("Truncated bind opcode operand");
437
+ byte = bytes[cursor.at++] ?? 0;
438
+ value |= BigInt(byte & 127) << shift;
439
+ shift += 7n;
440
+ } while ((byte & 128) !== 0 && shift <= 63n);
441
+ return (byte & 64) !== 0 ? value - (1n << shift) : value;
442
+ };
443
+ setBindRegister = (image, stream, state, byte) => {
444
+ const { bytes } = image;
445
+ const { cursor, end } = stream;
446
+ const immediate = byte & 15;
447
+ switch (byte & 240) {
448
+ case 16:
449
+ state.ordinal = immediate;
450
+ return true;
451
+ case 32:
452
+ state.ordinal = Number(uleb(bytes, cursor, end));
453
+ return true;
454
+ case 48:
455
+ state.ordinal = immediate === 0 ? 0 : immediate - 16;
456
+ return true;
457
+ case 64: {
458
+ const stop = bytes.indexOf(0, cursor.at);
459
+ if (stop < 0 || stop >= end) throw new RangeError("Unterminated bind symbol");
460
+ state.symbol = bytes.toString("utf8", cursor.at, stop);
461
+ state.weak = (immediate & 1) !== 0;
462
+ cursor.at = stop + 1;
463
+ return true;
464
+ }
465
+ case 80: return true;
466
+ case 96:
467
+ state.addend = sleb(bytes, cursor, end);
468
+ return true;
469
+ case 112: {
470
+ const segment = image.segments[immediate];
471
+ if (segment === undefined) throw new RangeError("Bind segment index is out of range");
472
+ state.segmentIndex = immediate;
473
+ state.address = segment.address + uleb(bytes, cursor, end);
474
+ return true;
475
+ }
476
+ case 128:
477
+ state.address = state.address + uleb(bytes, cursor, end) & 18446744073709551615n;
478
+ return true;
479
+ default: return false;
480
+ }
481
+ };
482
+ readBindStream = (image, range, binds) => {
483
+ const { bytes } = image;
484
+ const end = range.offset + range.size;
485
+ if (end > bytes.length) throw new RangeError("Bind opcodes exceed the target");
486
+ const cursor = { at: range.offset };
487
+ const state = {
488
+ ordinal: 0,
489
+ segmentIndex: -1,
490
+ symbol: "",
491
+ weak: false,
492
+ addend: 0n,
493
+ address: 0n
494
+ };
495
+ const preflightRun = (count, skip) => {
496
+ if (count === 0n) return;
497
+ const segment = image.segments[state.segmentIndex];
498
+ if (segment === undefined) throw new RangeError("Bind location has no selected segment");
499
+ const stride = 8n + skip;
500
+ const end = state.address + (count - 1n) * stride + 8n;
501
+ if (state.address < segment.address || end > segment.address + segment.size) throw new RangeError("Bind expansion leaves its file-backed segment");
502
+ };
503
+ const bind = (count, skip) => {
504
+ if (count === 0n) return;
505
+ preflightRun(count, skip);
506
+ const stride = 8n + skip;
507
+ const binding = {
508
+ symbol: state.symbol,
509
+ library: range.stream === "weak" ? null : libraryName(state.ordinal, image.dylibs),
510
+ weak: state.weak,
511
+ addend: state.addend
512
+ };
513
+ const previous = binds.at(-1);
514
+ if (previous !== undefined && previous.stride === stride && previous.start + previous.count * stride === state.address && previous.binding.symbol === binding.symbol && previous.binding.library === binding.library && previous.binding.weak === binding.weak && previous.binding.addend === binding.addend) {
515
+ previous.count += count;
516
+ } else {
517
+ binds.push({
518
+ start: state.address,
519
+ count,
520
+ stride,
521
+ binding
522
+ });
523
+ }
524
+ state.address = state.address + count * stride & 18446744073709551615n;
525
+ };
526
+ while (cursor.at < end) {
527
+ const byte = bytes[cursor.at++] ?? 0;
528
+ if (setBindRegister(image, {
529
+ cursor,
530
+ end
531
+ }, state, byte)) continue;
532
+ switch (byte & 240) {
533
+ case 0:
534
+ if (range.stream !== "lazy") return;
535
+ break;
536
+ case 144:
537
+ bind(1n, 0n);
538
+ break;
539
+ case 160:
540
+ bind(1n, uleb(bytes, cursor, end));
541
+ break;
542
+ case 176:
543
+ bind(1n, BigInt(byte & 15) * 8n);
544
+ break;
545
+ case 192: {
546
+ if (range.stream === "lazy") throw new RangeError("Lazy bind streams do not support repeated bind opcodes");
547
+ const count = uleb(bytes, cursor, end);
548
+ const skip = uleb(bytes, cursor, end);
549
+ bind(count, skip);
550
+ break;
551
+ }
552
+ default: throw new RangeError(`Unsupported bind opcode 0x${byte.toString(16)}`);
553
+ }
554
+ }
555
+ };
556
+ parsePointerFixups = (bytes, commands, segments, baseAddress) => {
557
+ const image = {
558
+ bytes,
559
+ segments,
560
+ dylibs: commands.dylibs,
561
+ baseAddress
562
+ };
563
+ const unreadRebaseBytes = commands.rebases.reduce((total, rebase) => total + rebase.size, 0);
564
+ if (commands.chained !== null) {
565
+ return chainedFixups(image, commands.chained, unreadRebaseBytes);
566
+ }
567
+ if (commands.binds.length === 0) return {
568
+ kind: "none",
569
+ formats: [],
570
+ failures: [],
571
+ issues: [],
572
+ examined: 0,
573
+ decoded: 0,
574
+ unreadRebaseBytes,
575
+ decode: (_address, raw) => ({
576
+ kind: "rebase",
577
+ target: raw
578
+ })
579
+ };
580
+ const binds = [];
581
+ const failures = [];
582
+ let decoded = 0;
583
+ for (const stream of commands.binds) try {
584
+ readBindStream(image, stream, binds);
585
+ decoded++;
586
+ } catch (cause) {
587
+ failures.push(`${stream.stream} bind opcodes: ${cause instanceof Error ? cause.message : String(cause)}`);
588
+ }
589
+ return {
590
+ kind: "dyld-info",
591
+ formats: [],
592
+ failures,
593
+ issues: failures.map((message) => issue("pointer_fixups", "bind_stream_decode_failed", message)),
594
+ examined: commands.binds.length,
595
+ decoded,
596
+ unreadRebaseBytes,
597
+ decode(address, raw) {
598
+ let match;
599
+ for (const run of binds) {
600
+ const { start, count, stride } = run;
601
+ const distance = address - start;
602
+ if (distance >= 0n && distance % stride === 0n && distance / stride < count) {
603
+ if (match !== undefined) return {
604
+ kind: "unsupported",
605
+ reason: `Ambiguous bind records target pointer location 0x${address.toString(16)}`
606
+ };
607
+ match = run;
608
+ }
609
+ }
610
+ return match === undefined ? {
611
+ kind: "rebase",
612
+ target: raw
613
+ } : {
614
+ kind: "bind",
615
+ ...match.binding
616
+ };
617
+ }
618
+ };
619
+ };
620
+ })))();
621
+ }
622
+
623
+ //#endregion
624
+ //#region dist/native/MachoArchitectureSelection.js
625
+ var MACHO_ARCHITECTURE_POLICIES, machoSubtypeRank, selectMachoArchitectureName;
626
+ function init_MachoArchitectureSelection() {
627
+ return (init_MachoArchitectureSelection = __esmMin((() => {
628
+ init_machoCpuIdentity();
629
+ MACHO_ARCHITECTURE_POLICIES = {
630
+ x86: {
631
+ cpuType: 7,
632
+ subtypes: [{
633
+ subtype: 3,
634
+ name: "i386"
635
+ }]
636
+ },
637
+ x86_64: {
638
+ cpuType: 16777223,
639
+ subtypes: [{
640
+ subtype: 3,
641
+ name: "x86_64"
642
+ }]
643
+ },
644
+ arm: {
645
+ cpuType: 12,
646
+ subtypes: [],
647
+ variantName: /^arm$/u
648
+ },
649
+ arm64: {
650
+ cpuType: 16777228,
651
+ subtypes: [
652
+ {
653
+ subtype: 0,
654
+ name: "arm64"
655
+ },
656
+ {
657
+ subtype: 2,
658
+ name: "arm64e"
659
+ },
660
+ {
661
+ subtype: 1,
662
+ name: "arm64v8"
663
+ }
664
+ ],
665
+ variantName: /^arm64e\.[A-Za-z0-9_]+$/u
666
+ }
667
+ };
668
+ machoSubtypeRank = (policy, subtype) => {
669
+ const rank = policy.subtypes.findIndex((candidate) => candidate.subtype === machoCpuSubtypeBase(subtype));
670
+ return rank < 0 ? policy.subtypes.length : rank;
671
+ };
672
+ selectMachoArchitectureName = (policy, available) => {
673
+ let selected;
674
+ let bestRank = Number.POSITIVE_INFINITY;
675
+ for (const architecture of available) {
676
+ if (architecture.cpu_type_code !== null && architecture.cpu_type_code !== policy.cpuType) continue;
677
+ const namedSubtype = policy.subtypes.find(({ name }) => name === architecture.name);
678
+ const recognizedName = namedSubtype !== undefined || policy.variantName?.test(architecture.name);
679
+ if (!recognizedName && (architecture.cpu_type_code === null || architecture.cpu_subtype_base === null)) continue;
680
+ const subtype = architecture.cpu_subtype_base ?? namedSubtype?.subtype;
681
+ const rank = subtype === undefined ? policy.subtypes.length : machoSubtypeRank(policy, subtype);
682
+ if (rank >= bestRank) continue;
683
+ selected = architecture.name;
684
+ bestRank = rank;
685
+ }
686
+ return selected;
687
+ };
688
+ })))();
689
+ }
690
+
691
+ //#endregion
692
+ //#region dist/native/AppleMachoSelection.js
693
+ var hex$2, fatHeaderFormat, selectMachoSlice, MH_MAGIC, MH_CIGAM, parseMachoLayout, collectSegment$1, LC_DYLD_INFO, LC_DYLD_INFO_ONLY, LC_DYLD_CHAINED_FIXUPS, DYLIB_COMMANDS$1, collectFixupCommand;
694
+ function init_AppleMachoSelection() {
695
+ return (init_AppleMachoSelection = __esmMin((() => {
696
+ init_MachoArchitectureSelection();
697
+ init_machoCpuIdentity();
698
+ init_machoContainer();
699
+ hex$2 = (value) => `0x${value.toString(16)}`;
700
+ fatHeaderFormat = (magic) => {
701
+ switch (magic) {
702
+ case 3405691582: return {
703
+ littleEndian: false,
704
+ fat64: false
705
+ };
706
+ case 3405691583: return {
707
+ littleEndian: false,
708
+ fat64: true
709
+ };
710
+ case 3199925962: return {
711
+ littleEndian: true,
712
+ fat64: false
713
+ };
714
+ case 3216703178: return {
715
+ littleEndian: true,
716
+ fat64: true
717
+ };
718
+ default: return null;
719
+ }
720
+ };
721
+ selectMachoSlice = (bytes, architecture) => {
722
+ const magic = bytes.readUInt32BE(0);
723
+ const header = fatHeaderFormat(magic);
724
+ if (header === null) return {
725
+ slice: 0,
726
+ sliceEnd: bytes.length
727
+ };
728
+ const { littleEndian, fat64 } = header;
729
+ const stride = fat64 ? 32 : 20;
730
+ const readUInt32 = littleEndian ? (offset) => bytes.readUInt32LE(offset) : (offset) => bytes.readUInt32BE(offset);
731
+ const byteOrder = littleEndian ? "little-endian" : "big-endian";
732
+ const malformed = (reason) => new RangeError(`${reason} (FAT header byte order: ${byteOrder})`);
733
+ const invalid = (reason) => new TypeError(`${reason} (FAT header byte order: ${byteOrder})`);
734
+ if (bytes.length < 8) throw malformed("Malformed FAT architecture table");
735
+ const count = readUInt32(4);
736
+ const headerEnd = 8 + count * stride;
737
+ if (count > 128 || headerEnd > bytes.length) throw malformed("Malformed FAT architecture table");
738
+ const policy = MACHO_ARCHITECTURE_POLICIES[architecture];
739
+ if (policy === undefined) throw invalid("Requested FAT architecture is absent");
740
+ const declarations = readFatSliceDeclarations(bytes.subarray(8, headerEnd), {
741
+ count,
742
+ wide: fat64,
743
+ littleEndian
744
+ });
745
+ if (declarations.status !== "parsed") throw malformed(declarations.reason);
746
+ let best;
747
+ let bestRank = Number.POSITIVE_INFINITY;
748
+ let ambiguous = false;
749
+ for (const declaration of declarations.slices) {
750
+ const issue = validateFatSlice(declaration, bytes.length, headerEnd);
751
+ if (issue !== null) throw malformed(issue);
752
+ if (declaration.cpuType !== policy.cpuType) continue;
753
+ const rank = machoSubtypeRank(policy, declaration.cpuSubtype);
754
+ if (best !== undefined && rank >= bestRank) {
755
+ if (rank === bestRank && machoCpuSubtypeBase(declaration.cpuSubtype) === machoCpuSubtypeBase(best.cpuSubtype)) ambiguous = true;
756
+ continue;
757
+ }
758
+ best = declaration;
759
+ bestRank = rank;
760
+ ambiguous = false;
761
+ }
762
+ if (best === undefined) throw invalid("Requested FAT architecture is absent");
763
+ if (ambiguous) throw invalid("Ambiguous FAT architecture slice");
764
+ const selected = {
765
+ slice: best.offset,
766
+ sliceEnd: best.offset + best.size,
767
+ fatDeclaration: {
768
+ ...best,
769
+ tableEnd: headerEnd
770
+ }
771
+ };
772
+ if (selected.slice + 4 > bytes.length) throw malformed("Truncated Mach-O header");
773
+ const sliceMagic = bytes.readUInt32LE(selected.slice);
774
+ if (sliceMagic === MH_MAGIC || sliceMagic === MH_CIGAM) throw invalid(`Unsupported 32-bit Mach-O metadata for requested CPU type ${architecture}`);
775
+ return selected;
776
+ };
777
+ MH_MAGIC = 4277009102;
778
+ MH_CIGAM = 3472551422;
779
+ parseMachoLayout = (bytes, architecture) => {
780
+ if (bytes.length < 4) throw new RangeError("Truncated Mach-O header");
781
+ const selection = selectMachoSlice(bytes, architecture);
782
+ const { slice, sliceEnd } = selection;
783
+ if (slice === 0 && sliceEnd === bytes.length && bytes.length < 32) throw new RangeError("Truncated Mach-O header");
784
+ if (slice + 32 > sliceEnd || bytes.readUInt32LE(slice) !== 4277009103) throw new TypeError("Only little-endian 64-bit Mach-O metadata is supported");
785
+ const fat = selection.fatDeclaration;
786
+ if (fat !== undefined) {
787
+ const issue = validateFatSlice(fat, bytes.length, fat.tableEnd, {
788
+ cpuType: bytes.readUInt32LE(slice + 4),
789
+ cpuSubtype: bytes.readUInt32LE(slice + 8)
790
+ });
791
+ if (issue !== null) throw new TypeError(issue);
792
+ }
793
+ const commands = bytes.readUInt32LE(slice + 16);
794
+ const commandEnd = slice + 32 + bytes.readUInt32LE(slice + 20);
795
+ if (commands > 4096 || commandEnd > sliceEnd) throw new RangeError("Malformed Mach-O command bounds");
796
+ const state = {
797
+ slice,
798
+ sliceEnd,
799
+ segments: [],
800
+ sections: [],
801
+ dylibs: [],
802
+ binds: [],
803
+ rebases: [],
804
+ chained: null,
805
+ baseAddress: undefined
806
+ };
807
+ let cursor = slice + 32;
808
+ for (let index = 0; index < commands; index++) {
809
+ if (cursor + 8 > commandEnd) throw new RangeError("Truncated load command");
810
+ const command = {
811
+ cursor,
812
+ kind: bytes.readUInt32LE(cursor),
813
+ size: bytes.readUInt32LE(cursor + 4)
814
+ };
815
+ if (command.size < 8 || cursor + command.size > commandEnd) throw new RangeError("Invalid load command size");
816
+ if (command.kind === 25) collectSegment$1(bytes, command, state);
817
+ else collectFixupCommand(bytes, command, state);
818
+ cursor += command.size;
819
+ }
820
+ const { segments, sections, chained, binds, rebases, dylibs } = state;
821
+ const offset = (address, size = 1) => {
822
+ const matches = segments.filter((segment) => address >= segment.address && address + BigInt(size) <= segment.address + segment.size);
823
+ if (matches.length !== 1) throw new RangeError(`Unmapped or ambiguous metadata pointer ${hex$2(address)}`);
824
+ const segment = matches[0];
825
+ if (segment === undefined) throw new RangeError("Missing metadata segment");
826
+ return segment.offset + Number(address - segment.address);
827
+ };
828
+ return {
829
+ segments,
830
+ sections,
831
+ offset,
832
+ fixups: {
833
+ chained,
834
+ binds,
835
+ rebases,
836
+ dylibs
837
+ },
838
+ baseAddress: state.baseAddress ?? 0n
839
+ };
840
+ };
841
+ collectSegment$1 = (bytes, { cursor, size }, state) => {
842
+ if (size < 72) throw new RangeError("Truncated segment command");
843
+ const address = bytes.readBigUInt64LE(cursor + 24), fileSize = bytes.readBigUInt64LE(cursor + 48), fileOffset = bytes.readBigUInt64LE(cursor + 40);
844
+ if (fileOffset + fileSize > BigInt(state.sliceEnd - state.slice)) throw new RangeError("Segment file range exceeds target bytes");
845
+ state.segments.push({
846
+ address,
847
+ size: fileSize,
848
+ offset: state.slice + Number(fileOffset),
849
+ executable: (bytes.readUInt32LE(cursor + 60) & 4) !== 0
850
+ });
851
+ if (fileOffset === 0n && fileSize > 0n) state.baseAddress ??= address;
852
+ const count = bytes.readUInt32LE(cursor + 64);
853
+ if (72 + count * 80 > size) throw new RangeError("Truncated section table");
854
+ for (let section = 0; section < count; section++) {
855
+ const position = cursor + 72 + section * 80;
856
+ const sectionSize = bytes.readBigUInt64LE(position + 40);
857
+ if (sectionSize > BigInt(Number.MAX_SAFE_INTEGER)) throw new RangeError("Section size exceeds exact numeric range");
858
+ state.sections.push({
859
+ name: bytes.subarray(position, position + 16).toString("latin1").replace(/\0.*$/u, ""),
860
+ address: bytes.readBigUInt64LE(position + 32),
861
+ size: Number(sectionSize)
862
+ });
863
+ }
864
+ };
865
+ LC_DYLD_INFO = 34;
866
+ LC_DYLD_INFO_ONLY = 2147483682;
867
+ LC_DYLD_CHAINED_FIXUPS = 2147483700;
868
+ DYLIB_COMMANDS$1 = [
869
+ 12,
870
+ 2147483672,
871
+ 2147483679,
872
+ 32,
873
+ 2147483683
874
+ ];
875
+ collectFixupCommand = (bytes, { cursor, kind, size }, state) => {
876
+ const range = (at) => {
877
+ const offset = state.slice + bytes.readUInt32LE(at);
878
+ const length = bytes.readUInt32LE(at + 4);
879
+ if (offset + length > state.sliceEnd) throw new RangeError("Fixup data exceeds the Mach-O slice");
880
+ return {
881
+ offset,
882
+ size: length
883
+ };
884
+ };
885
+ if (kind === LC_DYLD_CHAINED_FIXUPS) {
886
+ if (size < 16) throw new RangeError("Truncated chained-fixups command");
887
+ state.chained = range(cursor + 8);
888
+ } else if (kind === LC_DYLD_INFO || kind === LC_DYLD_INFO_ONLY) {
889
+ if (size < 48) throw new RangeError("Truncated dyld-info command");
890
+ const rebase = range(cursor + 8);
891
+ if (rebase.size > 0) state.rebases.push(rebase);
892
+ for (const [at, stream] of [
893
+ [cursor + 16, "bind"],
894
+ [cursor + 24, "weak"],
895
+ [cursor + 32, "lazy"]
896
+ ]) {
897
+ const bound = range(at);
898
+ if (bound.size > 0) state.binds.push({
899
+ ...bound,
900
+ stream
901
+ });
902
+ }
903
+ } else if (DYLIB_COMMANDS$1.includes(kind)) {
904
+ if (size < 24) throw new RangeError("Truncated dylib command");
905
+ const nameOffset = bytes.readUInt32LE(cursor + 8);
906
+ if (nameOffset < 24 || nameOffset >= size) throw new RangeError("Dylib install name is outside its load command");
907
+ const end = bytes.indexOf(0, cursor + nameOffset);
908
+ if (end < 0 || end >= cursor + size) throw new RangeError("Unterminated dylib install name");
909
+ state.dylibs.push(bytes.toString("utf8", cursor + nameOffset, end));
910
+ }
911
+ };
912
+ })))();
913
+ }
914
+
915
+ //#endregion
916
+ //#region dist/native/AppleObjcProperties.js
917
+ var parsePropertyAttributes, splitAttributes, readObjcPropertyList, readObjcPropertiesOf;
918
+ function init_AppleObjcProperties() {
919
+ return (init_AppleObjcProperties = __esmMin((() => {
920
+ init_AppleDispatchDecodeFacts();
921
+ parsePropertyAttributes = (name, attributes) => {
922
+ const tokens = attributes.length === 0 ? [] : splitAttributes(attributes);
923
+ const typeAttributes = tokens.filter((token) => token[0] === "T");
924
+ const typeAttribute = typeAttributes.length === 1 ? typeAttributes[0] : undefined;
925
+ const typeEncoding = typeAttribute !== undefined && typeAttribute.length > 1 ? typeAttribute.slice(1) : null;
926
+ const value = (code) => tokens.find((token) => token[0] === code)?.slice(1) ?? null;
927
+ return {
928
+ name,
929
+ type_encoding: typeEncoding,
930
+ attributes: tokens.map((token) => ({
931
+ name: token.slice(0, 1),
932
+ value: token.slice(1)
933
+ })),
934
+ atomicity: tokens.includes("N") ? "nonatomic" : typeEncoding === null ? null : "atomic",
935
+ is_readonly: tokens.includes("R") ? true : typeEncoding === null ? null : false,
936
+ getter: value("G"),
937
+ setter: value("S")
938
+ };
939
+ };
940
+ splitAttributes = (attributes) => {
941
+ const tokens = [];
942
+ let current = "";
943
+ let quoted = false;
944
+ for (const character of attributes) {
945
+ if (character === "\"") quoted = !quoted;
946
+ if (character === "," && !quoted) {
947
+ tokens.push(current);
948
+ current = "";
949
+ } else current += character;
950
+ }
951
+ tokens.push(current);
952
+ return tokens.filter((token) => token.length > 0);
953
+ };
954
+ readObjcPropertyList = (read, list, admit) => {
955
+ if (list === 0n) return [];
956
+ const entrySize = read.u32(list) & ~3;
957
+ const count = read.u32(list + 4n);
958
+ if (entrySize !== 16) throw new TypeError(`Unsupported Objective-C property entry size ${entrySize}`);
959
+ const properties = [];
960
+ for (let index = 0; index < count; index++) {
961
+ if (!admit()) break;
962
+ const entry = list + 8n + BigInt(index * entrySize);
963
+ properties.push(parsePropertyAttributes(read.string(read.pointer(entry)), read.string(read.pointer(entry + 8n))));
964
+ }
965
+ return properties;
966
+ };
967
+ readObjcPropertiesOf = (read, list, context) => {
968
+ try {
969
+ return readObjcPropertyList(read, list, context.admit);
970
+ } catch (cause) {
971
+ context.issues.push(issue("objc_properties_categories", "property_decode_failed", `${context.owner}: ${cause instanceof Error ? cause.message : String(cause)}`, context.location));
972
+ return [];
973
+ }
974
+ };
975
+ })))();
976
+ }
977
+
978
+ //#endregion
979
+ //#region dist/native/AppleObjcCategories.js
980
+ var CLASS_SYMBOL, boundClassName, decodeObjcCategories;
981
+ function init_AppleObjcCategories() {
982
+ return (init_AppleObjcCategories = __esmMin((() => {
983
+ init_AppleObjcProperties();
984
+ init_AppleDispatchDecodeFacts();
985
+ CLASS_SYMBOL = /^_OBJC_(?:META)?CLASS_\$_(.+)$/u;
986
+ boundClassName = (read, field) => {
987
+ const bound = read.bound(field);
988
+ return bound === undefined ? undefined : CLASS_SYMBOL.exec(bound.symbol)?.[1];
989
+ };
990
+ decodeObjcCategories = (input) => {
991
+ const { read, result } = input;
992
+ let examined = 0;
993
+ for (const section of input.sections.filter(({ name }) => name === "__objc_catlist")) {
994
+ if (section.size % 8 !== 0) throw new RangeError("Misaligned Objective-C category list");
995
+ for (let index = 0; index < section.size / 8; index++) {
996
+ if (!input.admit()) break;
997
+ examined++;
998
+ const field = section.address + BigInt(index * 8);
999
+ try {
1000
+ const category = read.pointer(field);
1001
+ const name = read.string(read.pointer(category));
1002
+ const external = boundClassName(read, category + 8n);
1003
+ const local = read.pointer(category + 8n);
1004
+ const className = external ?? (local === 0n ? null : input.localClassName(local));
1005
+ const owner = className ?? `(${name})`;
1006
+ result.objc_categories.push({
1007
+ name,
1008
+ class_name: className,
1009
+ class_source: external !== undefined ? "external" : className === null ? "unresolved" : "local",
1010
+ instance_methods: input.methods(read.pointer(category + 16n), owner, "instance", name),
1011
+ class_methods: input.methods(read.pointer(category + 24n), owner, "class", name),
1012
+ protocols: input.protocols(read.pointer(category + 32n)),
1013
+ properties: readObjcPropertiesOf(read, read.pointer(category + 40n), {
1014
+ owner: `category ${name}`,
1015
+ admit: input.admit,
1016
+ issues: input.issues,
1017
+ location: `0x${read.pointer(category + 40n).toString(16)}`
1018
+ }),
1019
+ location: read.location(category),
1020
+ decode: className === null ? {
1021
+ status: "partial",
1022
+ reason: "category_class_unresolved"
1023
+ } : {
1024
+ status: "decoded",
1025
+ reason: null
1026
+ },
1027
+ evidence: read.evidence(category, "Objective-C category_t record")
1028
+ });
1029
+ } catch (cause) {
1030
+ const message = cause instanceof Error ? cause.message : String(cause);
1031
+ input.issues.push(issue("objc_properties_categories", "category_decode_failed", message, `0x${field.toString(16)}`));
1032
+ }
1033
+ }
1034
+ }
1035
+ return examined;
1036
+ };
1037
+ })))();
1038
+ }
1039
+
1040
+ //#endregion
1041
+ //#region dist/native/AppleObjcProtocols.js
1042
+ var createObjcProtocolReader;
1043
+ function init_AppleObjcProtocols() {
1044
+ return (init_AppleObjcProtocols = __esmMin((() => {
1045
+ createObjcProtocolReader = (input) => {
1046
+ const { readers: read, result, failures } = input;
1047
+ const visited = new Set();
1048
+ const name = (address) => read.string(read.pointer(address + 8n));
1049
+ const list = (address) => {
1050
+ if (address === 0n) return [];
1051
+ const count = read.u64(address);
1052
+ if (count > 20000n) throw new RangeError("Protocol list exceeds 20000 entries");
1053
+ const names = [];
1054
+ for (let index = 0n; index < count; index++) {
1055
+ if (!read.admit()) break;
1056
+ const protocol = read.pointer(address + 8n + index * 8n);
1057
+ names.push(name(protocol));
1058
+ record(protocol);
1059
+ }
1060
+ return names;
1061
+ };
1062
+ const methods = (address, required, instance) => {
1063
+ const output = [];
1064
+ if (address === 0n) return output;
1065
+ const flags = read.u32(address), count = read.u32(address + 4n);
1066
+ const relative = (flags & 2147483648) !== 0;
1067
+ const stride = flags & 65532;
1068
+ if (stride !== (relative ? 12 : 24)) throw new TypeError("Unsupported Objective-C protocol method entry size");
1069
+ for (let index = 0; index < count; index++) {
1070
+ if (!read.admit()) break;
1071
+ const entry = address + 8n + BigInt(index * stride);
1072
+ let selector = relative ? entry + BigInt(read.i32(entry)) : read.pointer(entry);
1073
+ if (relative && (flags & 1073741824) === 0) selector = read.pointer(selector);
1074
+ output.push({
1075
+ selector: read.string(selector),
1076
+ method_type: instance ? "instance" : "class",
1077
+ address: null,
1078
+ is_required: required,
1079
+ is_optional: !required
1080
+ });
1081
+ }
1082
+ return output;
1083
+ };
1084
+ const record = (address) => {
1085
+ if (address === 0n || visited.has(address) || !read.admit()) return;
1086
+ visited.add(address);
1087
+ try {
1088
+ if (read.u32(address + 64n) < 72) throw new RangeError("Truncated Objective-C protocol declaration");
1089
+ const protocolName = name(address);
1090
+ const adopted = list(read.pointer(address + 16n));
1091
+ const required = [...methods(read.pointer(address + 24n), true, true), ...methods(read.pointer(address + 32n), true, false)];
1092
+ const optional = [...methods(read.pointer(address + 40n), false, true), ...methods(read.pointer(address + 48n), false, false)];
1093
+ result.objc_protocols.push({
1094
+ name: protocolName,
1095
+ methods: required,
1096
+ optional_methods: optional,
1097
+ properties: []
1098
+ });
1099
+ result.objc_protocol_records.push({
1100
+ name: protocolName,
1101
+ adopted_protocols: adopted,
1102
+ methods: required,
1103
+ optional_methods: optional,
1104
+ location: read.location(address),
1105
+ decode: {
1106
+ status: "decoded",
1107
+ reason: null
1108
+ },
1109
+ evidence: read.evidence(address, "Objective-C protocol declaration and encoded method lists; IMP fields are not handler targets")
1110
+ });
1111
+ } catch (cause) {
1112
+ failures.push(`Protocol 0x${address.toString(16)}: ${cause instanceof Error ? cause.message : String(cause)}`);
1113
+ }
1114
+ };
1115
+ return {
1116
+ list,
1117
+ record
1118
+ };
1119
+ };
1120
+ })))();
1121
+ }
1122
+
1123
+ //#endregion
1124
+ //#region dist/native/AppleObjcDispatchFacets.js
1125
+ var hex$1, decoded$1, localClassName, resolveSuperclass, decodeObjcDispatchFacets;
1126
+ function init_AppleObjcDispatchFacets() {
1127
+ return (init_AppleObjcDispatchFacets = __esmMin((() => {
1128
+ init_result();
1129
+ init_AppleObjcCategories();
1130
+ init_AppleObjcProperties();
1131
+ init_AppleObjcProtocols();
1132
+ hex$1 = (value) => `0x${value.toString(16)}`;
1133
+ decoded$1 = {
1134
+ status: "decoded",
1135
+ reason: null
1136
+ };
1137
+ localClassName = (read, address) => read.string(read.pointer((read.pointer(address + 32n) & ~7n) + 24n));
1138
+ resolveSuperclass = (read, address, className, failures) => {
1139
+ const external = boundClassName(read, address + 8n);
1140
+ if (external !== undefined) return {
1141
+ name: external,
1142
+ address: null
1143
+ };
1144
+ const superclass = read.pointer(address + 8n);
1145
+ if (superclass === 0n) return {
1146
+ name: null,
1147
+ address: null
1148
+ };
1149
+ try {
1150
+ return {
1151
+ name: localClassName(read, superclass),
1152
+ address: hex$1(superclass)
1153
+ };
1154
+ } catch (cause) {
1155
+ void cause;
1156
+ failures.push(`Superclass pointer ${hex$1(superclass)} of ${className} requires unsupported binding/fixup resolution`);
1157
+ return {
1158
+ name: null,
1159
+ address: hex$1(superclass)
1160
+ };
1161
+ }
1162
+ };
1163
+ decodeObjcDispatchFacets = (input) => {
1164
+ const { bytes, sections, segments, readers: read, budget, maxListSlots, result } = input;
1165
+ const failures = [];
1166
+ const categoryIssues = [];
1167
+ let examined = 0;
1168
+ const methods = (list, className, methodType, category) => {
1169
+ const selectors = [];
1170
+ if (list === 0n) return selectors;
1171
+ const flags = read.u32(list), count = read.u32(list + 4n), relative = (flags & 2147483648) !== 0;
1172
+ const stride = flags & 65532;
1173
+ if (stride !== (relative ? 12 : 24)) throw new TypeError(`Unsupported method stride/flags at ${hex$1(list)}`);
1174
+ for (let index = 0; index < count; index++) {
1175
+ if (!budget.admit()) break;
1176
+ const entry = list + 8n + BigInt(index * stride);
1177
+ const rel = (field) => {
1178
+ const displacement = bytes.readInt32LE(read.offset(field, 4));
1179
+ const target = field + BigInt(displacement);
1180
+ let fileOffset = null;
1181
+ try {
1182
+ fileOffset = read.offset(target);
1183
+ } catch (cause) {
1184
+ void cause;
1185
+ }
1186
+ if (budget.admit()) result.relative_pointers.push({
1187
+ field: read.location(field),
1188
+ target: {
1189
+ address: hex$1(target),
1190
+ file_offset: fileOffset
1191
+ },
1192
+ displacement,
1193
+ indirectable: false,
1194
+ indirect: false,
1195
+ decode: fileOffset === null ? {
1196
+ status: "partial",
1197
+ reason: "relative_target_unmapped"
1198
+ } : decoded$1,
1199
+ evidence: read.evidence(field, "Signed-relative Objective-C method-list pointer")
1200
+ });
1201
+ return target;
1202
+ };
1203
+ let selectorAddress = relative ? rel(entry) : read.pointer(entry);
1204
+ if (relative && (flags & 1073741824) === 0) selectorAddress = read.pointer(selectorAddress);
1205
+ const implementation = relative ? rel(entry + 8n) : read.pointer(entry + 16n);
1206
+ let implementationLocation = null;
1207
+ try {
1208
+ if (!segments.some((segment) => segment.executable && implementation >= segment.address && implementation < segment.address + segment.size)) throw new RangeError("Method implementation is not in an executable segment");
1209
+ implementationLocation = read.location(implementation);
1210
+ } catch (cause) {
1211
+ void cause;
1212
+ }
1213
+ const selector = read.string(selectorAddress);
1214
+ selectors.push(selector);
1215
+ result.objc_dispatch_implementations.push({
1216
+ class_name: className,
1217
+ selector,
1218
+ method_type: methodType,
1219
+ ...category === undefined ? {} : { category },
1220
+ implementation_address: implementationLocation?.address ?? null,
1221
+ location: read.location(entry),
1222
+ decode: implementationLocation === null ? {
1223
+ status: "partial",
1224
+ reason: "implementation_pointer_unmapped_or_encoded"
1225
+ } : decoded$1,
1226
+ evidence: read.evidence(entry, relative ? "Encoded relative Objective-C method entry" : "Encoded absolute Objective-C method entry")
1227
+ });
1228
+ }
1229
+ return selectors;
1230
+ };
1231
+ const protocolReader = createObjcProtocolReader({
1232
+ readers: {
1233
+ u32: read.u32,
1234
+ pointer: read.pointer,
1235
+ string: read.string,
1236
+ location: read.location,
1237
+ evidence: read.evidence,
1238
+ admit: () => budget.admit(),
1239
+ i32: read.i32,
1240
+ u64: read.u64
1241
+ },
1242
+ result,
1243
+ failures
1244
+ });
1245
+ let objcListScanTruncated = false;
1246
+ let objcClassListScanTruncated = false;
1247
+ const createListSlotReader = () => {
1248
+ let listSlotsExamined = 0;
1249
+ return (field) => {
1250
+ if (listSlotsExamined >= maxListSlots) {
1251
+ objcListScanTruncated = true;
1252
+ return err("exhausted");
1253
+ }
1254
+ listSlotsExamined++;
1255
+ try {
1256
+ return ok(read.pointer(field));
1257
+ } catch (cause) {
1258
+ const admitted = budget.admit();
1259
+ failures.push(`${hex$1(field)}: ${cause instanceof Error ? cause.message : String(cause)}`);
1260
+ return err(admitted ? "unmapped" : "exhausted");
1261
+ }
1262
+ };
1263
+ };
1264
+ const readProtocolListSlot = createListSlotReader();
1265
+ const readClassListSlot = createListSlotReader();
1266
+ for (const section of sections.filter(({ name }) => name === "__objc_protolist")) {
1267
+ if (section.size % 8 !== 0) throw new RangeError("Misaligned Objective-C protocol list");
1268
+ for (let index = 0; index < section.size / 8; index++) {
1269
+ if (budget.isFull()) {
1270
+ budget.markTruncated();
1271
+ break;
1272
+ }
1273
+ const field = section.address + BigInt(index * 8);
1274
+ const pointer = readProtocolListSlot(field);
1275
+ if (!pointer.ok) {
1276
+ if (pointer.error === "exhausted") break;
1277
+ continue;
1278
+ }
1279
+ try {
1280
+ protocolReader.record(pointer.value);
1281
+ } catch (cause) {
1282
+ failures.push(`${hex$1(field)}: ${cause instanceof Error ? cause.message : String(cause)}`);
1283
+ }
1284
+ }
1285
+ }
1286
+ const visited = new Set();
1287
+ const readClass = (address, meta = false) => {
1288
+ if (address === 0n || visited.has(hex$1(address)) || !budget.admit()) return;
1289
+ visited.add(hex$1(address));
1290
+ const ro = read.pointer(address + 32n) & ~7n;
1291
+ const name = read.string(read.pointer(ro + 24n));
1292
+ if (name.length === 0) throw new TypeError(`Objective-C class at ${hex$1(address)} has an empty name`);
1293
+ const root = (read.u32(ro) & 2) !== 0;
1294
+ const superclass = resolveSuperclass(read, address, name, failures);
1295
+ if (superclass.name === null && superclass.address === null && !root) failures.push(`Superclass of ${name} requires external binding resolution`);
1296
+ const ivarList = read.pointer(ro + 48n);
1297
+ let ivarCount = meta ? null : 0;
1298
+ if (ivarList !== 0n && !meta) {
1299
+ const stride = read.u32(ivarList), count = read.u32(ivarList + 4n);
1300
+ if (stride !== 32) throw new TypeError("Unsupported Objective-C ivar entry size");
1301
+ ivarCount = count;
1302
+ for (let index = 0; index < count; index++) {
1303
+ if (!budget.admit()) break;
1304
+ const entry = ivarList + 8n + BigInt(index * stride);
1305
+ const encodedOffset = read.pointer(entry);
1306
+ let value = null;
1307
+ try {
1308
+ value = read.u32(encodedOffset);
1309
+ } catch (cause) {
1310
+ void cause;
1311
+ failures.push(`Unresolved ivar offset pointer ${hex$1(encodedOffset)}`);
1312
+ }
1313
+ const alignment = read.u32(entry + 24n);
1314
+ result.objc_ivars.push({
1315
+ class_name: name,
1316
+ name: read.string(read.pointer(entry + 8n)),
1317
+ type_encoding: read.string(read.pointer(entry + 16n)),
1318
+ offset: value,
1319
+ size: read.u32(entry + 28n),
1320
+ alignment: alignment === 4294967295 ? 8 : alignment < 31 ? 2 ** alignment : null,
1321
+ location: read.location(entry),
1322
+ decode: value === null ? {
1323
+ status: "partial",
1324
+ reason: "ivar_offset_pointer_unresolved"
1325
+ } : decoded$1,
1326
+ evidence: read.evidence(entry, "Objective-C ivar entry and encoded offset storage")
1327
+ });
1328
+ }
1329
+ }
1330
+ methods(read.pointer(ro + 32n), name, meta ? "class" : "instance");
1331
+ result.objc_classes.push({
1332
+ name,
1333
+ super_class: superclass.name,
1334
+ is_meta_class: meta,
1335
+ is_root_class: root,
1336
+ methods: result.objc_dispatch_implementations.filter((item) => item.class_name === name && item.method_type === (meta ? "class" : "instance")).map((item) => ({
1337
+ selector: item.selector,
1338
+ method_type: item.method_type,
1339
+ address: item.implementation_address !== null && BigInt(item.implementation_address) <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(BigInt(item.implementation_address)) : null,
1340
+ is_required: null,
1341
+ is_optional: null
1342
+ })),
1343
+ properties: readObjcPropertiesOf(read, read.pointer(ro + 64n), {
1344
+ owner: name,
1345
+ admit: () => budget.admit(),
1346
+ issues: categoryIssues,
1347
+ location: hex$1(read.pointer(ro + 64n))
1348
+ }),
1349
+ protocols: protocolReader.list(read.pointer(ro + 40n)),
1350
+ ivar_count: ivarCount,
1351
+ instance_size: read.u32(ro + 8n),
1352
+ location: read.location(address),
1353
+ superclass_address: superclass.address,
1354
+ metaclass_address: meta ? null : hex$1(read.pointer(address)),
1355
+ decode: superclass.name === null && !root ? {
1356
+ status: "partial",
1357
+ reason: "superclass_binding_unresolved"
1358
+ } : decoded$1,
1359
+ evidence: read.evidence(address, "Objective-C class and class_ro_t records")
1360
+ });
1361
+ if (!meta) {
1362
+ try {
1363
+ readClass(read.pointer(address), true);
1364
+ } catch (cause) {
1365
+ failures.push(`Metaclass of ${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
1366
+ }
1367
+ }
1368
+ };
1369
+ for (const section of sections.filter(({ name }) => name === "__objc_classlist")) {
1370
+ if (section.size % 8 !== 0) throw new RangeError("Misaligned Objective-C class-list size");
1371
+ for (let index = 0; index < section.size / 8; index++) {
1372
+ if (budget.isFull()) {
1373
+ budget.markTruncated();
1374
+ break;
1375
+ }
1376
+ const field = section.address + BigInt(index * 8);
1377
+ const pointer = readClassListSlot(field);
1378
+ if (pointer.ok || pointer.error === "unmapped") examined++;
1379
+ if (!pointer.ok) {
1380
+ if (pointer.error === "exhausted") {
1381
+ objcClassListScanTruncated = true;
1382
+ break;
1383
+ }
1384
+ continue;
1385
+ }
1386
+ try {
1387
+ readClass(pointer.value);
1388
+ } catch (cause) {
1389
+ failures.push(`${hex$1(field)}: ${cause instanceof Error ? cause.message : String(cause)}`);
1390
+ }
1391
+ }
1392
+ }
1393
+ const categoriesExamined = decodeObjcCategories({
1394
+ sections,
1395
+ read,
1396
+ result,
1397
+ issues: categoryIssues,
1398
+ admit: () => budget.admit(),
1399
+ methods,
1400
+ protocols: (list) => protocolReader.list(list),
1401
+ localClassName: (address) => localClassName(read, address)
1402
+ });
1403
+ return {
1404
+ failures,
1405
+ categoryIssues,
1406
+ examined,
1407
+ categoriesExamined,
1408
+ objcListScanTruncated,
1409
+ objcClassListScanTruncated
1410
+ };
1411
+ };
1412
+ })))();
1413
+ }
1414
+
1415
+ //#endregion
1416
+ //#region dist/native/AppleSwiftDispatchFacets.js
1417
+ var hex, decoded, createSwiftRelativeReader, decodeSwiftDispatchFacets;
1418
+ function init_AppleSwiftDispatchFacets() {
1419
+ return (init_AppleSwiftDispatchFacets = __esmMin((() => {
1420
+ init_AppleDispatchDecodeFacts();
1421
+ hex = (value) => `0x${value.toString(16)}`;
1422
+ decoded = {
1423
+ status: "decoded",
1424
+ reason: null
1425
+ };
1426
+ createSwiftRelativeReader = (input) => {
1427
+ const { bytes, readers: read, budget, result } = input;
1428
+ return (field, indirectable = false) => {
1429
+ const displacement = bytes.readInt32LE(read.offset(field, 4));
1430
+ const indirect = indirectable && (displacement & 1) !== 0;
1431
+ let target = displacement === 0 ? 0n : field + BigInt(indirectable ? displacement & ~1 : displacement);
1432
+ let fileOffset = null;
1433
+ let reason = null;
1434
+ try {
1435
+ if (indirect && target !== 0n) target = read.pointer(target);
1436
+ if (target !== 0n) fileOffset = read.offset(target);
1437
+ } catch (cause) {
1438
+ reason = cause instanceof Error ? cause.message : String(cause);
1439
+ }
1440
+ if (budget.admit()) result.relative_pointers.push({
1441
+ field: read.location(field),
1442
+ target: {
1443
+ address: target === 0n ? null : hex(target),
1444
+ file_offset: fileOffset
1445
+ },
1446
+ displacement,
1447
+ indirectable,
1448
+ indirect,
1449
+ decode: reason === null ? decoded : {
1450
+ status: "partial",
1451
+ reason
1452
+ },
1453
+ evidence: read.evidence(field, "Swift ABI signed-relative metadata pointer")
1454
+ });
1455
+ if (reason !== null) throw new RangeError(reason);
1456
+ return target;
1457
+ };
1458
+ };
1459
+ decodeSwiftDispatchFacets = (input) => {
1460
+ const { sections, segments, readers: read, relative, budget, result } = input;
1461
+ const swiftFailures = [];
1462
+ const issues = [];
1463
+ let swiftExamined = 0;
1464
+ let decodedRecords = 0;
1465
+ for (const section of sections.filter(({ name }) => name === "__swift5_proto")) {
1466
+ if (section.size % 4 !== 0) throw new RangeError("Misaligned Swift conformance section");
1467
+ for (let index = 0; index < section.size / 4; index++) {
1468
+ if (!budget.admit()) break;
1469
+ swiftExamined++;
1470
+ const field = section.address + BigInt(index * 4);
1471
+ try {
1472
+ const descriptor = relative(field);
1473
+ const flags = read.u32(descriptor + 12n);
1474
+ const protocol = relative(descriptor, true);
1475
+ if ((read.u32(protocol) & 31) !== 3) throw new TypeError("Unsupported Swift protocol descriptor kind");
1476
+ const protocolName = read.string(relative(protocol + 8n));
1477
+ const typeKind = flags >>> 3 & 7;
1478
+ if (typeKind !== 0 && typeKind !== 1) throw new TypeError("Unsupported Swift conformance type-reference kind");
1479
+ let type = relative(descriptor + 4n);
1480
+ if (typeKind === 1) type = read.pointer(type);
1481
+ if (![
1482
+ 16,
1483
+ 17,
1484
+ 18
1485
+ ].includes(read.u32(type) & 31)) throw new TypeError("Unsupported Swift type descriptor kind");
1486
+ const typeName = read.string(relative(type + 8n));
1487
+ const witness = relative(descriptor + 8n);
1488
+ const staticWitness = witness !== 0n && (flags & ~56) === 0 && (read.u32(type) & 128) === 0;
1489
+ let witnessReason = staticWitness ? null : "Conditional, generic, resilient or missing static witness table is not decoded";
1490
+ if (staticWitness && read.pointer(witness) !== descriptor) witnessReason = "Witness-table conformance header is unresolved or encoded";
1491
+ const conformanceDecode = witnessReason === null ? {
1492
+ status: "decoded",
1493
+ reason: null
1494
+ } : {
1495
+ status: "partial",
1496
+ reason: witnessReason
1497
+ };
1498
+ result.swift_conformances.push({
1499
+ type_name: typeName,
1500
+ protocol_name: protocolName,
1501
+ module: null,
1502
+ witness_table: witness === 0n ? {
1503
+ address: null,
1504
+ file_offset: null
1505
+ } : read.location(witness),
1506
+ location: read.location(descriptor),
1507
+ decode: conformanceDecode,
1508
+ evidence: read.evidence(descriptor, "Swift protocol conformance descriptor and directly encoded type/protocol names")
1509
+ });
1510
+ if (conformanceDecode.status === "decoded") decodedRecords++;
1511
+ if (witnessReason !== null) {
1512
+ swiftFailures.push(`${typeName}: ${witnessReason}`);
1513
+ issues.push(issue("swift_conformances_static_witness_slots", "conformance_decode_partial", witnessReason, hex(descriptor)));
1514
+ continue;
1515
+ }
1516
+ const count = read.u32(protocol + 16n);
1517
+ const signatureCount = read.u32(protocol + 12n);
1518
+ if (count > 2e4 || signatureCount > 2e4) throw new RangeError("Swift witness requirement count exceeds 20000");
1519
+ for (let slot = 0; slot < count; slot++) {
1520
+ if (!budget.admit()) break;
1521
+ const entry = witness + BigInt((slot + 1) * 8);
1522
+ const implementation = read.pointer(entry);
1523
+ const requirementFlags = read.u32(protocol + 24n + BigInt(signatureCount * 12 + slot * 8));
1524
+ const kind = requirementFlags & 15;
1525
+ const synchronousFunction = kind >= 1 && kind <= 4 && (requirementFlags & 32) === 0;
1526
+ const executable = synchronousFunction && segments.some((segment) => segment.executable && implementation >= segment.address && implementation < segment.address + segment.size);
1527
+ const slotDecode = executable ? {
1528
+ status: "decoded",
1529
+ reason: null
1530
+ } : {
1531
+ status: "partial",
1532
+ reason: "Witness slot is non-function, async, nil, external, authenticated or encoded; implementation target is unresolved"
1533
+ };
1534
+ result.swift_dispatch_slots.push({
1535
+ owner: `${typeName}: ${protocolName}`,
1536
+ table_kind: "witness_table",
1537
+ slot_index: slot + 1,
1538
+ requirement: null,
1539
+ implementation: null,
1540
+ implementation_address: executable ? hex(implementation) : null,
1541
+ thunk_address: null,
1542
+ location: read.location(entry),
1543
+ decode: slotDecode,
1544
+ evidence: read.evidence(entry, "Static Swift witness slot, indexed after the conformance-descriptor header")
1545
+ });
1546
+ if (slotDecode.status !== "decoded") issues.push(issue("swift_conformances_static_witness_slots", "witness_slot_unresolved", slotDecode.reason, hex(entry)));
1547
+ }
1548
+ } catch (cause) {
1549
+ const message = cause instanceof Error ? cause.message : String(cause);
1550
+ swiftFailures.push(`${hex(field)}: ${message}`);
1551
+ issues.push(issue("swift_conformances_static_witness_slots", "conformance_decode_failed", message, hex(field)));
1552
+ }
1553
+ }
1554
+ }
1555
+ return {
1556
+ facet: "swift_conformances_static_witness_slots",
1557
+ examined: swiftExamined,
1558
+ decoded: decodedRecords,
1559
+ exhaustive: !budget.truncated && issues.length === 0,
1560
+ issues
1561
+ };
1562
+ };
1563
+ })))();
1564
+ }
1565
+
1566
+ //#endregion
1567
+ //#region dist/native/AppleSwiftVtables.js
1568
+ var decodeSwiftClassVtables;
1569
+ function init_AppleSwiftVtables() {
1570
+ return (init_AppleSwiftVtables = __esmMin((() => {
1571
+ init_AppleDispatchDecodeFacts();
1572
+ decodeSwiftClassVtables = (input) => {
1573
+ const { readers: read, result } = input;
1574
+ const failures = [];
1575
+ const issues = [];
1576
+ let examined = 0;
1577
+ let decoded = 0;
1578
+ for (const field of input.entries) {
1579
+ if (!read.admit()) {
1580
+ failures.push("max_records_reached");
1581
+ issues.push(issue("swift_class_vtable_descriptors", "record_budget_exhausted", "max_records_reached", `0x${field.toString(16)}`));
1582
+ break;
1583
+ }
1584
+ examined++;
1585
+ try {
1586
+ const descriptor = read.relative(field);
1587
+ const flags = read.u32(descriptor);
1588
+ if ((flags & 31) !== 16) continue;
1589
+ const specific = flags >>> 16;
1590
+ if ((flags & 128) !== 0 || (specific & 8192) !== 0) throw new TypeError("Generic class or resilient superclass metadata is unsupported");
1591
+ if ((specific & 32768) === 0) continue;
1592
+ const initialization = specific & 3;
1593
+ if (initialization === 3) throw new TypeError("Unknown metadata initialization kind");
1594
+ const header = descriptor + 44n + BigInt(initialization === 1 ? 12 : initialization === 2 ? 4 : 0);
1595
+ const tableOffset = read.u32(header);
1596
+ const count = read.u32(header + 4n);
1597
+ const positiveWords = read.u32(descriptor + 28n);
1598
+ if (count > 2e4 || tableOffset + count > positiveWords) throw new RangeError("Swift vtable count or offset exceeds declared metadata bounds");
1599
+ const owner = read.string(read.relative(descriptor + 8n));
1600
+ for (let index = 0; index < count; index++) {
1601
+ const entry = header + 8n + BigInt(index * 8);
1602
+ if (!read.admit()) {
1603
+ failures.push("max_records_reached");
1604
+ issues.push(issue("swift_class_vtable_descriptors", "record_budget_exhausted", "max_records_reached", `0x${entry.toString(16)}`));
1605
+ break;
1606
+ }
1607
+ const methodFlags = read.u32(entry);
1608
+ const synchronous = (methodFlags & 64) === 0 && (methodFlags & 15) <= 3;
1609
+ const implementation = read.relative(entry + 4n);
1610
+ const resolved = synchronous && read.executable(implementation);
1611
+ result.swift_dispatch_slots.push({
1612
+ owner,
1613
+ table_kind: "class_vtable",
1614
+ slot_index: tableOffset + index,
1615
+ requirement: null,
1616
+ implementation: null,
1617
+ implementation_address: resolved ? `0x${implementation.toString(16)}` : null,
1618
+ thunk_address: null,
1619
+ location: read.location(entry),
1620
+ decode: resolved ? {
1621
+ status: "decoded",
1622
+ reason: null
1623
+ } : {
1624
+ status: "partial",
1625
+ reason: "Async, coroutine, external or unmapped vtable implementation is unresolved"
1626
+ },
1627
+ evidence: read.evidence(entry, "Swift class vtable method descriptor; slot index is a metadata word offset, not a source method ordinal")
1628
+ });
1629
+ if (resolved) decoded++;
1630
+ else issues.push(issue("swift_class_vtable_descriptors", "vtable_implementation_unresolved", "Async, coroutine, external or unmapped vtable implementation is unresolved", `0x${entry.toString(16)}`));
1631
+ }
1632
+ if ((specific & 16384) !== 0) {
1633
+ failures.push(`${owner}: inherited override descriptors are unsupported`);
1634
+ issues.push(issue("swift_class_vtable_descriptors", "inherited_override_descriptors_unsupported", "Inherited override descriptors are unsupported", `0x${descriptor.toString(16)}`));
1635
+ }
1636
+ } catch (cause) {
1637
+ const message = cause instanceof Error ? cause.message : String(cause);
1638
+ failures.push(`0x${field.toString(16)}: ${message}`);
1639
+ issues.push(issue("swift_class_vtable_descriptors", "vtable_decode_failed", message, `0x${field.toString(16)}`));
1640
+ }
1641
+ }
1642
+ return {
1643
+ facet: "swift_class_vtable_descriptors",
1644
+ examined,
1645
+ decoded,
1646
+ exhaustive: issues.length === 0,
1647
+ issues
1648
+ };
1649
+ };
1650
+ })))();
1651
+ }
1652
+
1653
+ //#endregion
1654
+ //#region dist/native/AppleDispatchMetadata.js
1655
+ var decodeAppleDispatchMetadata, inspectAppleDispatchMetadata;
1656
+ function init_AppleDispatchMetadata() {
1657
+ return (init_AppleDispatchMetadata = __esmMin((() => {
1658
+ init_objcSwiftMetadata();
1659
+ init_binaryTargetTypes();
1660
+ init_analysisErrorCore();
1661
+ init_RegularFile();
1662
+ init_BoundedFileBytes();
1663
+ init_evidenceErrors();
1664
+ init_AppleDispatchCoverage();
1665
+ init_AppleMachoFixups();
1666
+ init_AppleMachoSelection();
1667
+ init_AppleObjcDispatchFacets();
1668
+ init_AppleSwiftDispatchFacets();
1669
+ init_AppleSwiftVtables();
1670
+ decodeAppleDispatchMetadata = (bytes, maxRecords, provenance, architecture = "arm64") => {
1671
+ const layout = parseMachoLayout(bytes, architecture);
1672
+ const { segments, sections, offset } = layout;
1673
+ const fixups = parsePointerFixups(bytes, layout.fixups, segments, layout.baseAddress);
1674
+ const u32 = (address) => bytes.readUInt32LE(offset(address, 4));
1675
+ const decodePointer = (address) => fixups.decode(address, bytes.readBigUInt64LE(offset(address, 8)));
1676
+ /** Rebased target of a pointer; a bind to another image reads as 0. */
1677
+ const pointer = (address) => {
1678
+ const decodedPointer = decodePointer(address);
1679
+ return decodedPointer.kind === "rebase" ? decodedPointer.target : 0n;
1680
+ };
1681
+ const bound = (address) => {
1682
+ const decodedPointer = decodePointer(address);
1683
+ return decodedPointer.kind === "bind" ? decodedPointer : undefined;
1684
+ };
1685
+ const location = (address) => ({
1686
+ address: `0x${address.toString(16)}`,
1687
+ file_offset: offset(address)
1688
+ });
1689
+ const evidence = (address, description) => [{
1690
+ kind: "binary_metadata",
1691
+ description,
1692
+ location: location(address),
1693
+ artifact_path: provenance.path,
1694
+ artifact_sha256: provenance.sha256
1695
+ }];
1696
+ const string = (address) => {
1697
+ const start = offset(address);
1698
+ let end = start;
1699
+ while (end < bytes.length && end - start < 4096 && bytes[end] !== 0) end++;
1700
+ if (end === bytes.length || end - start >= 4096) throw new RangeError("Unterminated or oversized metadata string");
1701
+ offset(address, end - start + 1);
1702
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(start, end));
1703
+ };
1704
+ const result = objcSwiftMetadataSchema.parse({ db_save_result: null });
1705
+ let records = 0;
1706
+ const budget = {
1707
+ truncated: false,
1708
+ isFull: () => records >= maxRecords,
1709
+ markTruncated: () => {
1710
+ budget.truncated = true;
1711
+ },
1712
+ admit: () => {
1713
+ if (records >= maxRecords) {
1714
+ budget.truncated = true;
1715
+ return false;
1716
+ }
1717
+ records++;
1718
+ return true;
1719
+ }
1720
+ };
1721
+ const readers = {
1722
+ u32,
1723
+ i32: (address) => bytes.readInt32LE(offset(address, 4)),
1724
+ u64: (address) => bytes.readBigUInt64LE(offset(address, 8)),
1725
+ pointer,
1726
+ bound,
1727
+ string,
1728
+ location,
1729
+ evidence,
1730
+ offset
1731
+ };
1732
+ const { failures, categoryIssues, examined, categoriesExamined, objcListScanTruncated, objcClassListScanTruncated } = decodeObjcDispatchFacets({
1733
+ bytes,
1734
+ sections,
1735
+ segments,
1736
+ readers,
1737
+ budget,
1738
+ maxListSlots: maxRecords,
1739
+ result
1740
+ });
1741
+ const swiftRelative = createSwiftRelativeReader({
1742
+ bytes,
1743
+ readers,
1744
+ budget,
1745
+ result
1746
+ });
1747
+ const swift = decodeSwiftDispatchFacets({
1748
+ sections,
1749
+ segments,
1750
+ readers,
1751
+ relative: swiftRelative,
1752
+ budget,
1753
+ result
1754
+ });
1755
+ const typeEntries = [];
1756
+ for (const section of sections.filter(({ name }) => name === "__swift5_types")) {
1757
+ if (section.size % 4 !== 0) throw new RangeError("Misaligned Swift type section");
1758
+ for (let index = 0; index < section.size / 4 && index < maxRecords; index++) typeEntries.push(section.address + BigInt(index * 4));
1759
+ if (section.size / 4 > maxRecords) budget.truncated = true;
1760
+ }
1761
+ const vtables = decodeSwiftClassVtables({
1762
+ entries: typeEntries,
1763
+ result,
1764
+ readers: {
1765
+ u32,
1766
+ relative: swiftRelative,
1767
+ string,
1768
+ location,
1769
+ evidence,
1770
+ admit: () => budget.admit(),
1771
+ executable: (address) => segments.some((segment) => segment.executable && address >= segment.address && address < segment.address + segment.size)
1772
+ }
1773
+ });
1774
+ pushDispatchCoverage({
1775
+ result,
1776
+ failures,
1777
+ categoryIssues,
1778
+ examined,
1779
+ categoriesExamined,
1780
+ objcListScanTruncated,
1781
+ objcClassListScanTruncated,
1782
+ truncated: budget.truncated,
1783
+ fixups,
1784
+ vtables,
1785
+ swift
1786
+ });
1787
+ return objcSwiftMetadataSchema.parse(result);
1788
+ };
1789
+ inspectAppleDispatchMetadata = async (target, maxRecords, signal) => {
1790
+ if (target.kind !== "executable" || !isMachOFormat(target.format)) throw new TypeError("Apple dispatch metadata requires a Mach-O target");
1791
+ const maximumBytes = 64 * 1024 * 1024;
1792
+ const capacityError = () => new AnalysisResourceConstraintError("inspect_native_dispatch_metadata", "memory", "Apple static metadata input exceeds its 64 MiB snapshot budget", { input_bytes: maximumBytes });
1793
+ const handle = await openRegularFile(target.path, {
1794
+ symlinks: "reject",
1795
+ signal
1796
+ });
1797
+ try {
1798
+ const before = await handle.stat();
1799
+ if (before.size > maximumBytes) throw capacityError();
1800
+ if (signal?.aborted) throw new AnalysisCancelledError("inspect_native_dispatch_metadata");
1801
+ const bytes = await readBoundedFileBytes(handle, maximumBytes, signal);
1802
+ if (bytes === undefined) throw capacityError();
1803
+ const digest = createHash("sha256").update(bytes).digest("hex");
1804
+ if (digest !== target.sha256) throw new EvidenceIntegrityError("Apple metadata target digest changed after session binding");
1805
+ return nativeDispatchMetadataResultSchema.parse({
1806
+ target_sha256: target.sha256,
1807
+ provider: {
1808
+ id: "native-macos",
1809
+ name: "macOS native inspection utilities",
1810
+ version: "apple-metadata-reader-1"
1811
+ },
1812
+ analysis_profile_digest: null,
1813
+ result: decodeAppleDispatchMetadata(bytes, maxRecords, {
1814
+ path: target.path,
1815
+ sha256: digest
1816
+ }, target.architecture)
1817
+ });
1818
+ } finally {
1819
+ await handle.close();
1820
+ }
1821
+ };
1822
+ })))();
1823
+ }
1824
+
1825
+ //#endregion
1826
+ //#region dist/native/NativeUiOutputBudget.js
1827
+ var HELPER_SUCCESS_WRAPPER, NATIVE_UI_OUTPUT_BUDGET_BYTES, NATIVE_UI_OUTPUT_WEIGHT, NATIVE_UI_HELPER_ENVELOPE_BYTES, NATIVE_UI_HELPER_MAX_BUFFER;
1828
+ function init_NativeUiOutputBudget() {
1829
+ return (init_NativeUiOutputBudget = __esmMin((() => {
1830
+ HELPER_SUCCESS_WRAPPER = Buffer.from(JSON.stringify({
1831
+ ok: true,
1832
+ result: {}
1833
+ }));
1834
+ NATIVE_UI_OUTPUT_BUDGET_BYTES = 64 * 1024 * 1024;
1835
+ NATIVE_UI_OUTPUT_WEIGHT = 2;
1836
+ NATIVE_UI_HELPER_ENVELOPE_BYTES = HELPER_SUCCESS_WRAPPER.byteLength - Buffer.byteLength("{}");
1837
+ NATIVE_UI_HELPER_MAX_BUFFER = NATIVE_UI_OUTPUT_BUDGET_BYTES + NATIVE_UI_HELPER_ENVELOPE_BYTES;
1838
+ })))();
1839
+ }
1840
+
1841
+ //#endregion
1842
+ //#region dist/native/NativeUiHelperRuntime.js
1843
+ var createNativeUiHelperRuntime;
1844
+ function init_NativeUiHelperRuntime() {
1845
+ return (init_NativeUiHelperRuntime = __esmMin((() => {
1846
+ init_snapshotEnvironment();
1847
+ init_DarwinProcessRunTokenReader();
1848
+ init_ExecFileOutput();
1849
+ init_safeJson();
1850
+ init_NativeUiOutputBudget();
1851
+ createNativeUiHelperRuntime = (environment) => {
1852
+ const selectedEnvironment = snapshotEnvironment(environment);
1853
+ let root;
1854
+ let executable;
1855
+ const invoke = async (parameters, signal) => {
1856
+ if (executable === undefined) {
1857
+ root = await mkdtemp(join(tmpdir(), "rea-native-ui-"));
1858
+ const output = join(root, "observer");
1859
+ const main = join(root, "main.swift");
1860
+ await symlink(fileURLToPath(new URL("../../bridge/native/ReaNativeUI.swift", new URL("../native/NativeUiHelperRuntime.js", import.meta.url).href)), main);
1861
+ const compilerTemporary = join(root, "tmp");
1862
+ await mkdir(compilerTemporary);
1863
+ await execFileOutput("/usr/bin/xcrun", [
1864
+ "swiftc",
1865
+ "-module-cache-path",
1866
+ join(root, "modules"),
1867
+ fileURLToPath(new URL("../../bridge/native/NativeUIChildren.swift", new URL("../native/NativeUiHelperRuntime.js", import.meta.url).href)),
1868
+ main,
1869
+ "-o",
1870
+ output
1871
+ ], {
1872
+ timeout: 6e4,
1873
+ maxBuffer: 1024 * 1024,
1874
+ stopSignal: SWIFTC_INTERRUPT,
1875
+ env: {
1876
+ ...selectedEnvironment,
1877
+ TMPDIR: compilerTemporary
1878
+ },
1879
+ ...signal === undefined ? {} : { signal }
1880
+ });
1881
+ executable = output;
1882
+ }
1883
+ const output = await execFileOutput(executable, [JSON.stringify(parameters)], {
1884
+ timeout: 3e4,
1885
+ maxBuffer: NATIVE_UI_HELPER_MAX_BUFFER,
1886
+ stopSignal: "SIGTERM",
1887
+ env: selectedEnvironment,
1888
+ ...signal === undefined ? {} : { signal }
1889
+ });
1890
+ const parsed = safeParseJson(output.stdout);
1891
+ if (!parsed.ok) throw new Error(`Native helper returned invalid JSON: ${parsed.error}`, { cause: parsed.cause });
1892
+ return parsed.value;
1893
+ };
1894
+ return {
1895
+ invoke,
1896
+ close: async () => {
1897
+ if (root !== undefined) {
1898
+ await rm(root, {
1899
+ recursive: true,
1900
+ force: true
1901
+ });
1902
+ root = undefined;
1903
+ executable = undefined;
1904
+ }
1905
+ },
1906
+ resources: () => root === undefined ? [] : [root]
1907
+ };
1908
+ };
1909
+ })))();
1910
+ }
1911
+
1912
+ //#endregion
1913
+ //#region dist/native/NativeUiObservation.js
1914
+ var helper, responseSchema, observeNativeUi, observeWithHelper;
1915
+ function init_NativeUiObservation() {
1916
+ return (init_NativeUiObservation = __esmMin((() => {
1917
+ init_binaryTargetTypes();
1918
+ init_nativeUiObservation();
1919
+ init_analysisErrorCore();
1920
+ init_providerAdapterError();
1921
+ init_result();
1922
+ init_NativeUiHelperRuntime();
1923
+ init_NativeUiOutputBudget();
1924
+ helper = fileURLToPath(new URL("../../bridge/native/ReaNativeUI.swift", new URL("../native/NativeUiObservation.js", import.meta.url).href));
1925
+ responseSchema = z.discriminatedUnion("ok", [z.strictObject({
1926
+ ok: z.literal(true),
1927
+ result: nativeUiSnapshotSchema
1928
+ }), z.strictObject({
1929
+ ok: z.literal(false),
1930
+ code: z.string(),
1931
+ message: z.string()
1932
+ })]);
1933
+ observeNativeUi = async (target, operation, parameters, options) => {
1934
+ const runtime = options.runtime ?? createNativeUiHelperRuntime(options.environment);
1935
+ try {
1936
+ return await observeWithHelper(target, operation, parameters, {
1937
+ ...options,
1938
+ invoke: options.invoke ?? runtime.invoke
1939
+ });
1940
+ } finally {
1941
+ if (options.runtime === undefined) await runtime.close();
1942
+ }
1943
+ };
1944
+ observeWithHelper = async (target, operation, parameters, options) => {
1945
+ const parsed = (operation === "observe_native_ui" ? nativeUiObservationInputSchema : nativeUiScenarioInputSchema).safeParse(parameters);
1946
+ if (!parsed.success) return err(new AnalysisInputError(operation, { cause: parsed.error }));
1947
+ if (target.kind !== "executable" || !isMachOFormat(target.format)) return err(new AnalysisCapabilityUnavailableError("native-macos", operation, "Native UI observation requires an active Mach-O executable or app target"));
1948
+ const input = parsed.data;
1949
+ if (!input.screenshot && !input.accessibility) return err(new AnalysisInputError(operation, { cause: new Error("Enable screenshot or accessibility capture") }));
1950
+ const steps = operation === "capture_native_ui_scenario" ? nativeUiScenarioInputSchema.parse(parameters).steps : [];
1951
+ const signal = options.signal === undefined ? AbortSignal.timeout(18e4) : AbortSignal.any([options.signal, AbortSignal.timeout(18e4)]);
1952
+ const invoke = options.invoke;
1953
+ let launchTime;
1954
+ let outputBytes = 0;
1955
+ const take = async (action) => {
1956
+ if (signal.aborted) return err(new AnalysisCancelledError(operation));
1957
+ try {
1958
+ const response = responseSchema.parse(await invoke({
1959
+ pid: input.pid,
1960
+ window_id: input.window_id,
1961
+ executable: target.path,
1962
+ sha256: target.sha256,
1963
+ ...launchTime === undefined ? {} : { launch_time: launchTime },
1964
+ screenshot: input.screenshot,
1965
+ accessibility: input.accessibility,
1966
+ max_nodes: input.max_nodes,
1967
+ ...action === undefined ? {} : { action }
1968
+ }, signal));
1969
+ if (!response.ok) return err(new AnalysisCapabilityUnavailableError("native-macos", operation, `${response.code}: ${response.message}`));
1970
+ if (response.result.window.pid !== input.pid || response.result.window.window_id !== input.window_id || response.result.window.executable !== target.path || launchTime !== undefined && response.result.window.launch_time !== launchTime) return err(new AnalysisCapabilityUnavailableError("native-macos", operation, "Native helper returned a different target process or window"));
1971
+ launchTime = response.result.window.launch_time;
1972
+ outputBytes += 2 * Buffer.byteLength(JSON.stringify(response.result));
1973
+ if (outputBytes > 67108864) return err(new AnalysisCapabilityUnavailableError("native-macos", operation, "Scenario captures exceeded the 64 MiB output budget"));
1974
+ return ok(response.result);
1975
+ } catch (cause) {
1976
+ return err(signal.aborted ? new AnalysisCancelledError(operation) : new ProviderAdapterError("native-macos", operation, {
1977
+ cause,
1978
+ diagnostics: {
1979
+ helper_path: helper,
1980
+ reason: cause instanceof Error ? cause.message : String(cause),
1981
+ remediation: "Native helper failed, timed out, or returned malformed capture data; install compatible Xcode command-line tools and inspect local OS permissions"
1982
+ }
1983
+ }));
1984
+ }
1985
+ };
1986
+ const initial = await take();
1987
+ if (!initial.ok) return initial;
1988
+ const results = [];
1989
+ let before = initial.value;
1990
+ for (const [index, step] of steps.entries()) {
1991
+ if (signal.aborted) {
1992
+ results.push({
1993
+ index,
1994
+ kind: step.kind,
1995
+ before,
1996
+ after: null,
1997
+ outcome: "cancelled",
1998
+ reason: "Scenario cancelled before action"
1999
+ });
2000
+ break;
2001
+ }
2002
+ if (step.kind === "wait") {
2003
+ try {
2004
+ await new Promise((resolve, reject) => {
2005
+ const abort = () => {
2006
+ clearTimeout(timer);
2007
+ reject(new Error("cancelled"));
2008
+ };
2009
+ const timer = setTimeout(() => {
2010
+ signal.removeEventListener("abort", abort);
2011
+ resolve();
2012
+ }, step.milliseconds);
2013
+ signal.addEventListener("abort", abort, { once: true });
2014
+ if (signal.aborted) abort();
2015
+ });
2016
+ } catch (cause) {
2017
+ void cause;
2018
+ results.push({
2019
+ index,
2020
+ kind: step.kind,
2021
+ before,
2022
+ after: null,
2023
+ outcome: "cancelled",
2024
+ reason: "Scenario cancelled during wait"
2025
+ });
2026
+ break;
2027
+ }
2028
+ }
2029
+ const after = await take(step.kind === "wait" ? undefined : step);
2030
+ if (!after.ok) {
2031
+ results.push({
2032
+ index,
2033
+ kind: step.kind,
2034
+ before,
2035
+ after: null,
2036
+ outcome: after.error._tag === "AnalysisCancelledError" ? "cancelled" : "failed",
2037
+ reason: after.error.message
2038
+ });
2039
+ break;
2040
+ }
2041
+ results.push({
2042
+ index,
2043
+ kind: step.kind,
2044
+ before,
2045
+ after: after.value,
2046
+ outcome: "completed",
2047
+ reason: null
2048
+ });
2049
+ before = after.value;
2050
+ }
2051
+ return ok(nativeUiResultSchema.parse({
2052
+ target_sha256: target.sha256,
2053
+ initial: initial.value,
2054
+ steps: results,
2055
+ restore: "leave-as-is",
2056
+ limitations: [
2057
+ "Only the explicitly selected already-running process/window is admitted. REA starts no target process and does not change permissions, foreground applications, or restore application data.",
2058
+ "Click uses AXPress; scroll uses AXIncrement/AXDecrement; key-entry sets the selected element's AXValue. Unsupported elements fail without global event fallback.",
2059
+ "Each completed action is followed immediately by capture; delayed UI changes require explicit wait steps. A failed after-capture can follow a completed action, so failure does not prove absence of application effects.",
2060
+ "Scenarios can change app data, cause app network activity and persist changes. The caller explicitly chooses leave-as-is; automatic restoration is unsupported.",
2061
+ "Window matching uses exact PID and window ID for screenshots and unique accessibility geometry. Accessibility paths can change as the UI changes; stale or ambiguous paths fail. Screenshots are scaled to at most 2048 pixels; scenario output is budgeted at 64 MiB and execution is cancelled after 180 seconds."
2062
+ ]
2063
+ }));
2064
+ };
2065
+ })))();
2066
+ }
2067
+
2068
+ //#endregion
2069
+ //#region dist/native/LldbRetainedObservations.js
2070
+ var LLDB_OBSERVATION_JOURNAL_MAX_BYTES, MAX_CAPTURE_BYTES, projectLldbPartialObservation, parseLldbObservationJournal, readBoundedPrefix, readPrefix, readLldbObservationJournal, readPartialCapture;
2071
+ function init_LldbRetainedObservations() {
2072
+ return (init_LldbRetainedObservations = __esmMin((() => {
2073
+ init_nativeCallObservation();
2074
+ LLDB_OBSERVATION_JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
2075
+ MAX_CAPTURE_BYTES = 1024 * 1024;
2076
+ projectLldbPartialObservation = (input) => ({
2077
+ kind: "native-call-observation",
2078
+ target: input.target,
2079
+ process: {
2080
+ pid: input.pid ?? null,
2081
+ stdout: input.stdout,
2082
+ stderr: input.stderr,
2083
+ other_stops: input.journal.otherStops
2084
+ },
2085
+ debugger: { version: input.version },
2086
+ events: input.journal.events,
2087
+ coverage: {
2088
+ status: "partial",
2089
+ reason: input.reason
2090
+ },
2091
+ limitations: [
2092
+ "The LLDB run did not produce a complete native call observation result.",
2093
+ "The target SHA-256 identifies the selected artifact; LLDB did not verify the bytes loaded into the process.",
2094
+ "Captured output byte counts are observed lower bounds because LLDB did not report final stream counters.",
2095
+ ...input.journal.limitations,
2096
+ ...input.journalLimitations ?? [],
2097
+ ...input.limitations ?? [],
2098
+ ...input.pid === undefined ? ["The target PID was unavailable."] : [],
2099
+ ...input.stdout === null ? ["The target stdout capture was unavailable."] : [],
2100
+ ...input.stderr === null ? ["The target stderr capture was unavailable."] : []
2101
+ ]
2102
+ });
2103
+ parseLldbObservationJournal = (bytes) => {
2104
+ const completeText = Buffer.from(bytes).toString("utf8");
2105
+ const newline = completeText.lastIndexOf("\n");
2106
+ const hasTornTail = newline !== completeText.length - 1;
2107
+ const events = [];
2108
+ const otherStops = [];
2109
+ const limitations = [];
2110
+ let malformedCount = 0;
2111
+ let firstMalformedRow;
2112
+ let start = 0;
2113
+ let rowNumber = 0;
2114
+ while (start <= newline && newline >= 0) {
2115
+ const end = completeText.indexOf("\n", start);
2116
+ if (end < 0 || end > newline) break;
2117
+ const line = completeText.slice(start, end);
2118
+ start = end + 1;
2119
+ if (line.length === 0) continue;
2120
+ rowNumber += 1;
2121
+ const markMalformed = () => {
2122
+ malformedCount += 1;
2123
+ firstMalformedRow ??= rowNumber;
2124
+ };
2125
+ let row;
2126
+ try {
2127
+ row = JSON.parse(line);
2128
+ } catch {
2129
+ markMalformed();
2130
+ continue;
2131
+ }
2132
+ if (typeof row !== "object" || row === null || !("kind" in row) || typeof row.kind !== "string") {
2133
+ markMalformed();
2134
+ continue;
2135
+ }
2136
+ if (row.kind === "event" && "event" in row) {
2137
+ const event = nativeCallEventSchema.safeParse(row.event);
2138
+ if (event.success) events.push(event.data);
2139
+ else markMalformed();
2140
+ } else if (row.kind === "other-stop" && "reason" in row && typeof row.reason === "string") {
2141
+ otherStops.push(row.reason);
2142
+ } else {
2143
+ markMalformed();
2144
+ }
2145
+ }
2146
+ if (malformedCount > 0) limitations.push(`${malformedCount} observation journal row(s) were malformed or invalid and ignored (first at row ${String(firstMalformedRow)}).`);
2147
+ if (hasTornTail) limitations.push("The final observation journal record was incomplete and was ignored.");
2148
+ return {
2149
+ events,
2150
+ otherStops,
2151
+ limitations
2152
+ };
2153
+ };
2154
+ readBoundedPrefix = async (requestedBytes, readChunk) => {
2155
+ const buffer = Buffer.alloc(requestedBytes);
2156
+ let bytesRead = 0;
2157
+ while (bytesRead < requestedBytes) {
2158
+ const count = await readChunk(buffer, bytesRead, requestedBytes - bytesRead, bytesRead);
2159
+ if (count === 0) break;
2160
+ if (count > requestedBytes - bytesRead) throw new Error("The bounded read returned more bytes than requested");
2161
+ bytesRead += count;
2162
+ }
2163
+ return {
2164
+ buffer,
2165
+ bytesRead
2166
+ };
2167
+ };
2168
+ readPrefix = (handle, requestedBytes) => readBoundedPrefix(requestedBytes, async (buffer, offset, length, position) => (await handle.read(buffer, offset, length, position)).bytesRead);
2169
+ readLldbObservationJournal = async (path) => {
2170
+ let handle;
2171
+ try {
2172
+ handle = await open(path, "r");
2173
+ const { size } = await handle.stat();
2174
+ const length = Math.min(size, LLDB_OBSERVATION_JOURNAL_MAX_BYTES);
2175
+ const { buffer, bytesRead } = await readPrefix(handle, length);
2176
+ const parsed = parseLldbObservationJournal(buffer.subarray(0, bytesRead));
2177
+ const limitations = [...size > 8388608 ? ["The observation journal exceeded 8 MiB; only its bounded prefix was read."] : [], ...bytesRead < length ? ["The observation journal became shorter while being read; the available prefix was parsed."] : []];
2178
+ return {
2179
+ parsed,
2180
+ limitations
2181
+ };
2182
+ } catch (cause) {
2183
+ return {
2184
+ parsed: {
2185
+ events: [],
2186
+ otherStops: [],
2187
+ limitations: []
2188
+ },
2189
+ limitations: [`The observation journal could not be read: ${cause instanceof Error ? cause.message : String(cause)}`]
2190
+ };
2191
+ } finally {
2192
+ await handle?.close().catch(() => undefined);
2193
+ }
2194
+ };
2195
+ readPartialCapture = async (path) => {
2196
+ let handle;
2197
+ try {
2198
+ handle = await open(path, "r");
2199
+ const { size } = await handle.stat();
2200
+ const length = Math.min(size, MAX_CAPTURE_BYTES);
2201
+ const { buffer, bytesRead } = await readPrefix(handle, length);
2202
+ return {
2203
+ capture: {
2204
+ text: buffer.subarray(0, bytesRead).toString("utf8"),
2205
+ bytes: Math.max(size, bytesRead),
2206
+ truncated: true,
2207
+ complete: false
2208
+ },
2209
+ limitations: bytesRead < length ? ["A target output capture became shorter while being read; its retained prefix may be incomplete."] : []
2210
+ };
2211
+ } catch {
2212
+ return null;
2213
+ } finally {
2214
+ await handle?.close().catch(() => undefined);
2215
+ }
2216
+ };
2217
+ })))();
2218
+ }
2219
+
2220
+ //#endregion
2221
+ //#region dist/native/LldbCallTracer.js
2222
+ var OPERATION$1, PROVIDER, LLDB_REQUIREMENT, MAX_OUTPUT_BYTES, DEADLINE_GRACE_MS, DIAGNOSTIC_BYTES, BRIDGE, tracedSchema, tracerOutputSchema, ATTACH_REMEDIATION, LldbCallTracer, quote, tracerFailure, partialNativeObservation, partialObservationFromTrace, lldbRuntimePaths, readTracerOutput, capturedOutput, lldbCleanupResources, runLldb, readTargetPid, ensureTerminated, targetTerminationReason, alive;
2223
+ function init_LldbCallTracer() {
2224
+ return (init_LldbCallTracer = __esmMin((() => {
2225
+ init_snapshotEnvironment();
2226
+ init_analysisErrorCore();
2227
+ init_evidenceErrors();
2228
+ init_analysisErrorProjection();
2229
+ init_nativeCallObservation();
2230
+ init_providerAdapterError();
2231
+ init_providerCleanupError();
2232
+ init_result();
2233
+ init_safeJson();
2234
+ init_ProviderProcess();
2235
+ init_ProcessOwnership();
2236
+ init_ProcessOwnershipObservation();
2237
+ init_ProviderDeadline();
2238
+ init_PrivateRuntimeRoot();
2239
+ init_CommandRunner();
2240
+ init_LldbRetainedObservations();
2241
+ OPERATION$1 = "observe_native_calls";
2242
+ PROVIDER = "native-macos";
2243
+ LLDB_REQUIREMENT = "LLDB from Xcode or the Command Line Tools is not available";
2244
+ MAX_OUTPUT_BYTES = 1024 * 1024;
2245
+ DEADLINE_GRACE_MS = 6e4;
2246
+ DIAGNOSTIC_BYTES = 16 * 1024;
2247
+ BRIDGE = fileURLToPath(new URL("../../bridge/native/rea_lldb_tracer.py", new URL("../native/LldbCallTracer.js", import.meta.url).href));
2248
+ tracedSchema = z.strictObject({
2249
+ status: z.literal("traced"),
2250
+ version: z.string(),
2251
+ pid: z.number().int().positive(),
2252
+ outcome: z.enum([
2253
+ "exited",
2254
+ "duration-elapsed",
2255
+ "event-limit",
2256
+ "stop-limit",
2257
+ "resource-limit"
2258
+ ]),
2259
+ exit_status: z.number().int().nullable(),
2260
+ exit_description: z.string().nullable(),
2261
+ killed: z.boolean(),
2262
+ terminated: z.boolean(),
2263
+ target_identity: z.strictObject({
2264
+ loaded_image_sha256: z.null(),
2265
+ selected_file_sha256: z.string().regex(/^[0-9a-f]{64}$/u).nullable(),
2266
+ file_device: z.string().nullable(),
2267
+ file_inode: z.string().nullable(),
2268
+ module_path: z.string().nullable(),
2269
+ module_uuid: z.string().nullable(),
2270
+ stable: z.boolean()
2271
+ }),
2272
+ resource_limit_reached: z.boolean(),
2273
+ breakpoint_locations_truncated: z.boolean().optional(),
2274
+ target_output: z.strictObject({
2275
+ stdout_bytes: z.number().int().nonnegative(),
2276
+ stderr_bytes: z.number().int().nonnegative(),
2277
+ stdout_truncated: z.boolean(),
2278
+ stderr_truncated: z.boolean(),
2279
+ stdout_complete: z.boolean(),
2280
+ stderr_complete: z.boolean()
2281
+ }),
2282
+ elapsed_ms: z.number().nonnegative(),
2283
+ breakpoints: z.array(z.strictObject({
2284
+ index: z.number().int().nonnegative(),
2285
+ location_count: z.number().int().nonnegative(),
2286
+ locations: z.array(nativeCodeLocationSchema)
2287
+ })),
2288
+ events: z.array(nativeCallEventSchema),
2289
+ other_stops: z.array(z.string())
2290
+ });
2291
+ tracerOutputSchema = z.discriminatedUnion("status", [tracedSchema, z.strictObject({
2292
+ status: z.enum([
2293
+ "target-error",
2294
+ "target-integrity-error",
2295
+ "target-identity-unavailable",
2296
+ "launch-error",
2297
+ "tracer-error"
2298
+ ]),
2299
+ error: z.string().nullable(),
2300
+ target_process_created: z.boolean().optional()
2301
+ })]);
2302
+ ATTACH_REMEDIATION = "Allow debugging for this user (Developer Tools access: `DevToolsSecurity -enable`, or membership in the _developer group). A hardened-runtime target is debuggable only with the com.apple.security.get-task-allow entitlement; see inspect_signature's debugger-attach facet.";
2303
+ LldbCallTracer = class {
2304
+ launch;
2305
+ resolveTool;
2306
+ environment;
2307
+ #tail = Promise.resolve();
2308
+ #pendingCleanup;
2309
+ constructor(environment, launch = runLldb, resolveTool = (tool, signal) => resolveXcrunTool(tool, this.environment, signal)) {
2310
+ this.launch = launch;
2311
+ this.resolveTool = resolveTool;
2312
+ this.environment = snapshotEnvironment(environment);
2313
+ }
2314
+ async trace(request, signal) {
2315
+ return this.#serialize(() => this.#trace(request, signal));
2316
+ }
2317
+ async #trace(request, signal) {
2318
+ const pendingCleanup = await this.#retryPendingCleanup();
2319
+ if (pendingCleanup !== undefined) return err(pendingCleanup);
2320
+ const lldb = await this.resolveTool("lldb", signal);
2321
+ if (!lldb.ok) return err(lldb.error.reason === "cancelled" ? new AnalysisCancelledError(OPERATION$1) : new AnalysisCapabilityUnavailableError(PROVIDER, OPERATION$1, LLDB_REQUIREMENT, { userMessage: LLDB_REQUIREMENT }));
2322
+ const root = await PrivateRuntimeRoot.create({ prefix: "rea-lldb-" });
2323
+ const paths = lldbRuntimePaths(root.path);
2324
+ let result;
2325
+ try {
2326
+ result = await this.#run(lldb.value, root, request, signal);
2327
+ } catch (cause) {
2328
+ const partialObservation = await partialNativeObservation({
2329
+ request,
2330
+ pidPath: paths.pid,
2331
+ stdoutPath: paths.stdoutCapture,
2332
+ stderrPath: paths.stderrCapture,
2333
+ observationPath: paths.observations,
2334
+ version: null,
2335
+ reason: "tracer-failure"
2336
+ });
2337
+ const retained = this.#pendingCleanup;
2338
+ const resources = retained === undefined ? [] : await lldbCleanupResources(retained);
2339
+ result = err(new ProviderAdapterError(PROVIDER, OPERATION$1, {
2340
+ cause,
2341
+ diagnostics: { reason: cause instanceof Error ? cause.message : String(cause) },
2342
+ partialObservation,
2343
+ ...retained === undefined ? {} : { cleanup: {
2344
+ reason: "LLDB trace failed while owned resources remain",
2345
+ resources
2346
+ } }
2347
+ }));
2348
+ }
2349
+ if (this.#pendingCleanup?.root === root) return result;
2350
+ try {
2351
+ await root.close();
2352
+ } catch (cause) {
2353
+ this.#pendingCleanup = {
2354
+ root,
2355
+ supervisor: undefined,
2356
+ pidPath: paths.pid,
2357
+ targetIdentity: undefined,
2358
+ processStopped: true,
2359
+ targetStopped: true
2360
+ };
2361
+ const partialObservation = result.ok ? partialObservationFromTrace(request, result.value) : result.error.partialObservation;
2362
+ return err(new ProviderCleanupError(PROVIDER, [root.path], {
2363
+ reason: cause instanceof Error ? cause.message : String(cause),
2364
+ ...result.ok ? {} : {
2365
+ execution_failure: projectAnalysisError(result.error).code,
2366
+ primary_failure: result.error.message
2367
+ }
2368
+ }, {
2369
+ operation: OPERATION$1,
2370
+ cause: result.ok ? cause : new AggregateError([result.error, cause], "LLDB trace and runtime cleanup both failed"),
2371
+ ...partialObservation === undefined ? {} : { partialObservation }
2372
+ }));
2373
+ }
2374
+ return result;
2375
+ }
2376
+ /** Retry retained LLDB cleanup without abandoning its process or runtime owner. */
2377
+ async close() {
2378
+ return this.#serialize(() => this.#close());
2379
+ }
2380
+ async #close() {
2381
+ const failure = await this.#retryPendingCleanup();
2382
+ return failure === undefined ? ok(null) : err(failure);
2383
+ }
2384
+ #serialize(operation) {
2385
+ const call = this.#tail.then(operation, operation);
2386
+ this.#tail = call.then(() => undefined, () => undefined);
2387
+ return call;
2388
+ }
2389
+ async #retryPendingCleanup() {
2390
+ const owner = this.#pendingCleanup;
2391
+ if (owner === undefined) return undefined;
2392
+ let firstFailure;
2393
+ if (!owner.processStopped) {
2394
+ const stopped = await owner.supervisor?.stop();
2395
+ if (stopped?.status === "incomplete") firstFailure = stopped.reason;
2396
+ else {
2397
+ owner.supervisor?.dispose();
2398
+ owner.processStopped = true;
2399
+ }
2400
+ }
2401
+ if (firstFailure === undefined && !owner.targetStopped) {
2402
+ const targetTermination = await ensureTerminated(owner.pidPath, owner.targetIdentity, true);
2403
+ if (targetTermination !== "terminated") firstFailure = targetTerminationReason(targetTermination);
2404
+ else owner.targetStopped = true;
2405
+ }
2406
+ if (firstFailure === undefined) {
2407
+ try {
2408
+ await owner.root.close();
2409
+ this.#pendingCleanup = undefined;
2410
+ return undefined;
2411
+ } catch (cause) {
2412
+ firstFailure = cause instanceof Error ? cause.message : String(cause);
2413
+ }
2414
+ }
2415
+ const resources = await lldbCleanupResources(owner);
2416
+ return new ProviderCleanupError(PROVIDER, resources, {
2417
+ reason: firstFailure ?? "LLDB cleanup remains incomplete",
2418
+ resources
2419
+ }, { operation: OPERATION$1 });
2420
+ }
2421
+ async #run(lldb, root, request, signal) {
2422
+ const directory = root.path;
2423
+ const paths = lldbRuntimePaths(directory);
2424
+ const { input } = request;
2425
+ await writeFile(paths.config, JSON.stringify({
2426
+ executable: request.executable,
2427
+ architecture: request.architecture,
2428
+ expected_sha256: request.expectedSha256,
2429
+ arguments: input.arguments,
2430
+ environment: input.environment,
2431
+ working_directory: input.working_directory ?? null,
2432
+ breakpoints: input.breakpoints.map((breakpoint) => breakpoint.kind === "function" ? {
2433
+ ...breakpoint,
2434
+ module: breakpoint.module ?? null
2435
+ } : {
2436
+ ...breakpoint,
2437
+ class_name: breakpoint.class_name ?? null
2438
+ }),
2439
+ duration_ms: input.duration_ms,
2440
+ max_events: input.max_events,
2441
+ argument_registers: input.argument_registers,
2442
+ backtrace_frames: input.backtrace_frames,
2443
+ max_output_bytes: MAX_OUTPUT_BYTES,
2444
+ stdout_path: paths.stdout,
2445
+ stderr_path: paths.stderr,
2446
+ stdout_capture_path: paths.stdoutCapture,
2447
+ stderr_capture_path: paths.stderrCapture,
2448
+ result_path: paths.result,
2449
+ pid_path: paths.pid,
2450
+ identity_ack_path: paths.identityAck,
2451
+ observation_path: paths.observations
2452
+ }), { mode: 384 });
2453
+ const exited = await this.launch(lldb.path, [
2454
+ "--batch",
2455
+ "--no-lldbinit",
2456
+ "--no-use-colors",
2457
+ "-o",
2458
+ `command script import ${quote(BRIDGE)}`,
2459
+ "-o",
2460
+ `rea_trace ${paths.config}`
2461
+ ], {
2462
+ deadlineMs: input.duration_ms + DEADLINE_GRACE_MS,
2463
+ pidPath: paths.pid,
2464
+ identityAckPath: paths.identityAck,
2465
+ environment: this.environment,
2466
+ ...signal === undefined ? {} : { signal }
2467
+ });
2468
+ const retained = {
2469
+ root,
2470
+ supervisor: exited.cleanupOwner,
2471
+ pidPath: paths.pid,
2472
+ targetIdentity: exited.targetIdentity,
2473
+ processStopped: exited.cleanupOwner === undefined,
2474
+ targetStopped: !exited.targetLaunched
2475
+ };
2476
+ this.#pendingCleanup = retained;
2477
+ const output = exited.kind === "exited" ? await readTracerOutput(paths.result) : undefined;
2478
+ let targetTermination = exited.targetLaunched ? await ensureTerminated(paths.pid, exited.targetIdentity, true) : "terminated";
2479
+ if (output !== undefined && output.status !== "traced" && output.target_process_created === false && await readTargetPid(paths.pid) === undefined) targetTermination = "terminated";
2480
+ retained.targetStopped = targetTermination === "terminated";
2481
+ if (retained.processStopped && retained.targetStopped) this.#pendingCleanup = undefined;
2482
+ const terminated = targetTermination === "terminated";
2483
+ const cleanupDetails = [exited.cleanupFailure, ...terminated ? [] : [targetTerminationReason(targetTermination)]].filter((detail) => detail !== undefined);
2484
+ const lifecycleCleanup = cleanupDetails.length === 0 ? undefined : {
2485
+ reason: cleanupDetails.join("; "),
2486
+ resources: await lldbCleanupResources(retained)
2487
+ };
2488
+ const partialReason = exited.kind === "cancelled" ? "cancelled" : exited.kind === "timeout" ? "timeout" : exited.cleanupFailure !== undefined ? "cleanup-failure" : "tracer-failure";
2489
+ const getPartialObservation = (reason = partialReason) => partialNativeObservation({
2490
+ request,
2491
+ pidPath: paths.pid,
2492
+ stdoutPath: paths.stdoutCapture,
2493
+ stderrPath: paths.stderrCapture,
2494
+ observationPath: paths.observations,
2495
+ version: output?.status === "traced" ? output.version : null,
2496
+ reason
2497
+ });
2498
+ if (exited.kind === "cancelled") return err(new AnalysisCancelledError(OPERATION$1, {
2499
+ ...lifecycleCleanup === undefined ? {} : { cleanup: lifecycleCleanup },
2500
+ partialObservation: await getPartialObservation()
2501
+ }));
2502
+ if (exited.kind === "timeout") return err(new AnalysisTimeoutError(OPERATION$1, input.duration_ms + DEADLINE_GRACE_MS, {
2503
+ ...lifecycleCleanup === undefined ? {} : { cleanup: lifecycleCleanup },
2504
+ partialObservation: await getPartialObservation()
2505
+ }));
2506
+ if (output !== undefined && output.status !== "traced") return err(tracerFailure(output, lifecycleCleanup, await getPartialObservation()));
2507
+ if (exited.cleanupFailure !== undefined) return err(new ProviderCleanupError(PROVIDER, await lldbCleanupResources(retained), {
2508
+ reason: "LLDB process-group cleanup could not be verified",
2509
+ cleanup_failure: exited.cleanupFailure,
2510
+ ...lifecycleCleanup === undefined ? {} : { target_cleanup: lifecycleCleanup }
2511
+ }, {
2512
+ operation: OPERATION$1,
2513
+ partialObservation: await getPartialObservation()
2514
+ }));
2515
+ if (!terminated) return err(new ProviderCleanupError(PROVIDER, await lldbCleanupResources(retained), {
2516
+ reason: "LLDB target process termination could not be verified",
2517
+ ...lifecycleCleanup === undefined ? {} : { target_cleanup: lifecycleCleanup }
2518
+ }, {
2519
+ operation: OPERATION$1,
2520
+ partialObservation: await getPartialObservation()
2521
+ }));
2522
+ if (output === undefined) return err(new ProviderAdapterError(PROVIDER, OPERATION$1, {
2523
+ diagnostics: {
2524
+ reason: "LLDB exited without a tracer result",
2525
+ exit_code: exited.exitCode,
2526
+ lldb_output: exited.output,
2527
+ ...lifecycleCleanup === undefined ? {} : { target_cleanup: lifecycleCleanup }
2528
+ },
2529
+ partialObservation: await getPartialObservation(),
2530
+ ...lifecycleCleanup === undefined ? {} : { cleanup: lifecycleCleanup }
2531
+ }));
2532
+ const stdout = await capturedOutput(paths.stdoutCapture, output.target_output.stdout_bytes, output.target_output.stdout_truncated, output.target_output.stdout_complete);
2533
+ const stderr = await capturedOutput(paths.stderrCapture, output.target_output.stderr_bytes, output.target_output.stderr_truncated, output.target_output.stderr_complete);
2534
+ if (!stdout.ok || !stderr.ok) {
2535
+ const partial = await getPartialObservation("capture-failure");
2536
+ return err(new ProviderAdapterError(PROVIDER, OPERATION$1, {
2537
+ partialObservation: partial,
2538
+ diagnostics: {
2539
+ reason: "LLDB target output capture could not be read",
2540
+ ...stdout.ok ? {} : { stdout_capture_error: stdout.error },
2541
+ ...stderr.ok ? {} : { stderr_capture_error: stderr.error },
2542
+ ...lifecycleCleanup === undefined ? {} : { target_cleanup: lifecycleCleanup }
2543
+ },
2544
+ ...lifecycleCleanup === undefined ? {} : { cleanup: lifecycleCleanup }
2545
+ }));
2546
+ }
2547
+ return ok({
2548
+ debugger: {
2549
+ ...lldb,
2550
+ version: output.version
2551
+ },
2552
+ run: output,
2553
+ stdout: stdout.value,
2554
+ stderr: stderr.value,
2555
+ terminated
2556
+ });
2557
+ }
2558
+ };
2559
+ quote = (value) => `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
2560
+ tracerFailure = (output, cleanup, partialObservation) => {
2561
+ const options = {
2562
+ ...cleanup === undefined ? {} : { cleanup },
2563
+ ...partialObservation === undefined ? {} : { partialObservation }
2564
+ };
2565
+ const message = output.error ?? "no LLDB error text";
2566
+ if (output.status === "target-integrity-error") return new EvidenceIntegrityError(message || "The launched native target did not match its session digest", options);
2567
+ if (output.status === "target-identity-unavailable") return new ProviderAdapterError(PROVIDER, OPERATION$1, {
2568
+ ...options,
2569
+ diagnostics: {
2570
+ reason: message,
2571
+ constraint: "target process start identity could not be verified"
2572
+ }
2573
+ });
2574
+ if (output.status === "tracer-error") return new ProviderAdapterError(PROVIDER, OPERATION$1, {
2575
+ ...options,
2576
+ diagnostics: { reason: `LLDB bridge failed: ${message}` }
2577
+ });
2578
+ if (output.status === "target-error") return new AnalysisCapabilityUnavailableError(PROVIDER, OPERATION$1, `lldb-target-unloadable: ${message}`, options);
2579
+ return /attach|not allowed|permission|denied|debugserver/iu.test(message) ? new AnalysisCapabilityUnavailableError(PROVIDER, OPERATION$1, `debugger-attach-denied: ${message}`, {
2580
+ userMessage: ATTACH_REMEDIATION,
2581
+ ...options
2582
+ }) : new AnalysisCapabilityUnavailableError(PROVIDER, OPERATION$1, `launch-failed: ${message}`, options);
2583
+ };
2584
+ partialNativeObservation = async (options) => {
2585
+ const [journal, pid, stdout, stderr] = await Promise.all([
2586
+ readLldbObservationJournal(options.observationPath),
2587
+ readTargetPid(options.pidPath),
2588
+ readPartialCapture(options.stdoutPath),
2589
+ readPartialCapture(options.stderrPath)
2590
+ ]);
2591
+ return projectLldbPartialObservation({
2592
+ target: {
2593
+ path: options.request.executable,
2594
+ sha256: options.request.expectedSha256,
2595
+ architecture: options.request.architecture,
2596
+ arguments: options.request.input.arguments,
2597
+ environment: options.request.input.environment,
2598
+ working_directory: options.request.input.working_directory ?? null
2599
+ },
2600
+ pid,
2601
+ stdout: stdout?.capture ?? null,
2602
+ stderr: stderr?.capture ?? null,
2603
+ version: options.version,
2604
+ journal: journal.parsed,
2605
+ journalLimitations: journal.limitations,
2606
+ limitations: [...stdout?.limitations ?? [], ...stderr?.limitations ?? []],
2607
+ reason: options.reason
2608
+ });
2609
+ };
2610
+ partialObservationFromTrace = (request, trace) => projectLldbPartialObservation({
2611
+ target: {
2612
+ path: request.executable,
2613
+ sha256: request.expectedSha256,
2614
+ architecture: request.architecture,
2615
+ arguments: request.input.arguments,
2616
+ environment: request.input.environment,
2617
+ working_directory: request.input.working_directory ?? null
2618
+ },
2619
+ pid: trace.run.pid,
2620
+ stdout: trace.stdout,
2621
+ stderr: trace.stderr,
2622
+ version: trace.run.version,
2623
+ journal: {
2624
+ events: trace.run.events,
2625
+ otherStops: trace.run.other_stops,
2626
+ limitations: []
2627
+ },
2628
+ reason: "cleanup-failure"
2629
+ });
2630
+ lldbRuntimePaths = (directory) => ({
2631
+ config: join(directory, "config.json"),
2632
+ result: join(directory, "result.json"),
2633
+ pid: join(directory, "pid"),
2634
+ identityAck: join(directory, "identity.ack"),
2635
+ stdout: join(directory, "stdout"),
2636
+ stderr: join(directory, "stderr"),
2637
+ stdoutCapture: join(directory, "stdout.capture"),
2638
+ stderrCapture: join(directory, "stderr.capture"),
2639
+ observations: join(directory, "observations.jsonl")
2640
+ });
2641
+ readTracerOutput = async (path) => {
2642
+ let text;
2643
+ try {
2644
+ text = await readFile(path, "utf8");
2645
+ } catch {
2646
+ return undefined;
2647
+ }
2648
+ const parsed = safeParseJson(text);
2649
+ if (!parsed.ok) return undefined;
2650
+ const output = tracerOutputSchema.safeParse(parsed.value);
2651
+ return output.success ? output.data : undefined;
2652
+ };
2653
+ capturedOutput = async (path, observedBytes, truncated, complete) => {
2654
+ let handle;
2655
+ try {
2656
+ handle = await open(path, "r");
2657
+ const { size } = await handle.stat();
2658
+ const captureHandle = handle;
2659
+ const { buffer, bytesRead } = await readBoundedPrefix(Math.min(size, MAX_OUTPUT_BYTES), async (target, offset, length, position) => (await captureHandle.read(target, offset, length, position)).bytesRead);
2660
+ const captured = {
2661
+ text: buffer.subarray(0, bytesRead).toString("utf8"),
2662
+ bytes: observedBytes,
2663
+ truncated: truncated || size > MAX_OUTPUT_BYTES,
2664
+ complete: complete && bytesRead >= Math.min(observedBytes, MAX_OUTPUT_BYTES)
2665
+ };
2666
+ await handle.close();
2667
+ handle = undefined;
2668
+ return ok(captured);
2669
+ } catch (cause) {
2670
+ const failure = cause instanceof Error ? cause.message : String(cause);
2671
+ if (handle !== undefined) {
2672
+ try {
2673
+ await handle.close();
2674
+ } catch (closeCause) {
2675
+ return err(`${failure}; closing capture file failed: ${closeCause instanceof Error ? closeCause.message : String(closeCause)}`);
2676
+ }
2677
+ }
2678
+ return err(failure);
2679
+ }
2680
+ };
2681
+ lldbCleanupResources = async (owner) => [
2682
+ ...owner.processStopped ? [] : ["lldb-process-group"],
2683
+ ...owner.targetStopped ? [] : [`native-target:${String(await readTargetPid(owner.pidPath) ?? "unknown")}`],
2684
+ owner.root.path
2685
+ ];
2686
+ runLldb = async (executable, arguments_, options) => {
2687
+ if (options.signal?.aborted === true) return {
2688
+ kind: "cancelled",
2689
+ targetLaunched: false,
2690
+ targetIdentity: undefined,
2691
+ cleanupFailure: undefined
2692
+ };
2693
+ const deadline = new ProviderStartupDeadline(options.deadlineMs, options.signal);
2694
+ let targetIdentity;
2695
+ let supervisor;
2696
+ let retained = false;
2697
+ const finish = async (outcome) => {
2698
+ const stopped = await supervisor?.stop();
2699
+ retained = stopped?.status === "incomplete";
2700
+ return {
2701
+ ...deadline.interruption === undefined ? outcome : { kind: deadline.interruption },
2702
+ targetLaunched: supervisor !== undefined,
2703
+ targetIdentity,
2704
+ cleanupFailure: stopped?.status === "incomplete" ? stopped.reason : undefined,
2705
+ ...retained && supervisor !== undefined ? { cleanupOwner: supervisor } : {}
2706
+ };
2707
+ };
2708
+ try {
2709
+ const launched = await spawnOwnedProviderProcess({
2710
+ command: executable,
2711
+ arguments: arguments_,
2712
+ runId: randomUUID(),
2713
+ expectedCommand: executable,
2714
+ signal: deadline.signal,
2715
+ hostEnvironment: options.environment
2716
+ });
2717
+ supervisor = new ProviderProcessSupervisor({
2718
+ ...launched,
2719
+ ownsProcessLifetime: true,
2720
+ cleanup: () => cleanupOwnedProcessGroup(launched.ownership)
2721
+ }, { maxDiagnosticBytes: DIAGNOSTIC_BYTES });
2722
+ let identityAckWritten = false;
2723
+ while (!await supervisor.waitForOutputClose(20)) {
2724
+ const pid = await readTargetPid(options.pidPath);
2725
+ if (pid !== undefined && !identityAckWritten) {
2726
+ let observation;
2727
+ try {
2728
+ observation = await observeProcessStartIdentity(pid);
2729
+ } catch {
2730
+ observation = undefined;
2731
+ }
2732
+ if (observation?.state === "readable") targetIdentity = observation.identity;
2733
+ await writeFile(options.identityAckPath, observation?.state === "readable" ? "readable" : "unavailable", { mode: 384 });
2734
+ identityAckWritten = true;
2735
+ }
2736
+ const interruption = deadline.interruption;
2737
+ if (interruption !== undefined) return await finish({ kind: interruption });
2738
+ await waitForAbortableDelay(20, deadline.signal);
2739
+ }
2740
+ const snapshot = supervisor.snapshot();
2741
+ const interruption = deadline.interruption;
2742
+ return await finish(interruption === undefined ? {
2743
+ kind: "exited",
2744
+ exitCode: snapshot.exitCode ?? null,
2745
+ output: `${snapshot.stdout.text}${snapshot.stderr.text}`.slice(-DIAGNOSTIC_BYTES)
2746
+ } : { kind: interruption });
2747
+ } catch (cause) {
2748
+ const interruption = deadline.interruption;
2749
+ return await finish(interruption === undefined ? {
2750
+ kind: "exited",
2751
+ exitCode: null,
2752
+ output: cause instanceof Error ? cause.message : String(cause)
2753
+ } : { kind: interruption });
2754
+ } finally {
2755
+ if (!retained) supervisor?.dispose();
2756
+ deadline.dispose();
2757
+ }
2758
+ };
2759
+ readTargetPid = async (pidPath) => {
2760
+ try {
2761
+ const contents = (await readFile(pidPath, "utf8")).trim();
2762
+ if (!/^[1-9]\d*$/u.test(contents)) return undefined;
2763
+ const pid = Number(contents);
2764
+ return Number.isSafeInteger(pid) ? pid : undefined;
2765
+ } catch {
2766
+ return undefined;
2767
+ }
2768
+ };
2769
+ ensureTerminated = async (pidPath, identity, missingPidIsUnknown) => {
2770
+ const pid = await readTargetPid(pidPath);
2771
+ if (pid === undefined) return missingPidIsUnknown ? "identity-unavailable" : "terminated";
2772
+ if (!Number.isSafeInteger(pid) || pid <= 0) return "identity-unavailable";
2773
+ let signalDisposition;
2774
+ for (let attempt = 0; attempt < 20; attempt++) {
2775
+ if (!alive(pid)) return "terminated";
2776
+ if (attempt === 10) {
2777
+ if (identity === undefined) signalDisposition = "identity-unavailable";
2778
+ else {
2779
+ const result = await signalProcessWithStartIdentity(pid, identity, "SIGKILL");
2780
+ if (result === "gone") return "terminated";
2781
+ if (result === "identity-changed") signalDisposition = "identity-changed";
2782
+ else if (result === "unverified") signalDisposition = "identity-unavailable";
2783
+ else if (result === "signaled") signalDisposition = "signal-did-not-stop";
2784
+ }
2785
+ }
2786
+ await new Promise((resolve) => setTimeout(resolve, 100));
2787
+ }
2788
+ return !alive(pid) ? "terminated" : signalDisposition ?? "identity-unavailable";
2789
+ };
2790
+ targetTerminationReason = (termination) => {
2791
+ switch (termination) {
2792
+ case "terminated": return "target process terminated";
2793
+ case "identity-unavailable": return "target process start identity was unavailable; survivor was left untouched";
2794
+ case "identity-changed": return "target PID start identity changed; replacement process was left untouched";
2795
+ case "signal-did-not-stop": return "verified target did not exit after SIGKILL";
2796
+ }
2797
+ };
2798
+ alive = (pid) => {
2799
+ try {
2800
+ process.kill(pid, 0);
2801
+ return true;
2802
+ } catch (cause) {
2803
+ return !(cause instanceof Error && "code" in cause && cause.code === "ESRCH");
2804
+ }
2805
+ };
2806
+ })))();
2807
+ }
2808
+
2809
+ //#endregion
2810
+ //#region dist/native/NativeCallObservation.js
2811
+ var OPERATION, NATIVE_CALL_OBSERVATION_LIMITATIONS, observeNativeCalls, isAbortError, projectNativeCalls, fileSha256;
2812
+ function init_NativeCallObservation() {
2813
+ return (init_NativeCallObservation = __esmMin((() => {
2814
+ init_analysisErrorCore();
2815
+ init_binaryTargetTypes();
2816
+ init_evidenceErrors();
2817
+ init_providerAdapterError();
2818
+ init_nativeCallObservation();
2819
+ init_result();
2820
+ OPERATION = "observe_native_calls";
2821
+ NATIVE_CALL_OBSERVATION_LIMITATIONS = [
2822
+ "Only entries are observed; return values, floating-point and stack-passed arguments are not captured.",
2823
+ "Registers are the raw integer argument registers at entry. For Objective-C methods the first two hold the receiver and the selector.",
2824
+ "Receiver classes come from LLDB's Objective-C runtime reader without running target code; they are null for class methods and for receivers LLDB cannot classify.",
2825
+ "Calls that never reach a symbol's entry, such as inlined code or objc_direct methods called directly, are not observed.",
2826
+ "The target is launched directly under LLDB, not through LaunchServices; LLDB disables ASLR for it, so load addresses can equal file addresses.",
2827
+ "The observation window is checked about once a second, and recording pauses the process at every entry, which slows it."
2828
+ ];
2829
+ observeNativeCalls = async (target, parameters, tracer, signal, readTargetDigest = fileSha256) => {
2830
+ if (target.kind !== "executable" || !isMachOFormat(target.format)) return err(new AnalysisCapabilityUnavailableError("native-macos", OPERATION, "Native call observation launches a Mach-O executable; the active target is not one"));
2831
+ const parsed = nativeCallObservationInputSchema.safeParse(parameters);
2832
+ if (!parsed.success) return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
2833
+ let digest;
2834
+ try {
2835
+ digest = await readTargetDigest(target.path, signal);
2836
+ } catch (cause) {
2837
+ if (signal?.aborted === true || isAbortError(cause)) return err(new AnalysisCancelledError(OPERATION));
2838
+ return err(new ProviderAdapterError("native-macos", OPERATION, { diagnostics: {
2839
+ reason: "Unable to verify the selected target digest",
2840
+ detail: cause instanceof Error ? cause.message : String(cause)
2841
+ } }));
2842
+ }
2843
+ if (digest !== target.sha256) return err(new EvidenceIntegrityError("Native call observation target digest changed after session binding"));
2844
+ if (signal?.aborted === true) return err(new AnalysisCancelledError(OPERATION));
2845
+ const traced = await tracer.trace({
2846
+ executable: target.path,
2847
+ architecture: target.architecture,
2848
+ expectedSha256: target.sha256,
2849
+ input: parsed.data
2850
+ }, signal);
2851
+ if (!traced.ok) return traced;
2852
+ return ok(projectNativeCalls(target, parsed.data, traced.value));
2853
+ };
2854
+ isAbortError = (cause) => cause instanceof Error && cause.name === "AbortError";
2855
+ projectNativeCalls = (target, input, trace) => {
2856
+ const { run } = trace;
2857
+ const unresolved = run.breakpoints.filter(({ location_count: count }) => count === 0).map(({ index }) => index);
2858
+ const eventLimit = run.outcome === "event-limit";
2859
+ const resourceLimit = run.outcome === "resource-limit";
2860
+ const breakpointLocationLimit = run.breakpoint_locations_truncated === true;
2861
+ const partial = eventLimit || resourceLimit || breakpointLocationLimit || run.outcome === "duration-elapsed" || run.outcome === "stop-limit" || unresolved.length > 0;
2862
+ return nativeCallObservationResultSchema.parse({
2863
+ target: {
2864
+ path: target.path,
2865
+ sha256: target.sha256,
2866
+ architecture: target.architecture,
2867
+ arguments: input.arguments,
2868
+ environment: input.environment,
2869
+ working_directory: input.working_directory ?? null,
2870
+ launch_identity: {
2871
+ loaded_image_sha256: run.target_identity.loaded_image_sha256,
2872
+ file_device: run.target_identity.file_device,
2873
+ file_inode: run.target_identity.file_inode,
2874
+ selected_file_sha256: run.target_identity.selected_file_sha256,
2875
+ module_path: run.target_identity.module_path,
2876
+ module_uuid: run.target_identity.module_uuid,
2877
+ stable: run.target_identity.stable
2878
+ }
2879
+ },
2880
+ debugger: trace.debugger,
2881
+ process: {
2882
+ pid: run.pid,
2883
+ outcome: run.outcome,
2884
+ exit_status: run.exit_status,
2885
+ exit_description: run.exit_description,
2886
+ terminated: run.terminated && trace.terminated,
2887
+ elapsed_ms: run.elapsed_ms,
2888
+ stdout: trace.stdout,
2889
+ stderr: trace.stderr,
2890
+ other_stops: run.other_stops
2891
+ },
2892
+ breakpoints: input.breakpoints.map((request, index) => ({
2893
+ index,
2894
+ request: request.kind === "function" ? {
2895
+ ...request,
2896
+ module: request.module ?? null
2897
+ } : {
2898
+ ...request,
2899
+ class_name: request.class_name ?? null
2900
+ },
2901
+ location_count: run.breakpoints[index]?.location_count ?? 0,
2902
+ locations: run.breakpoints[index]?.locations ?? []
2903
+ })),
2904
+ events: run.events,
2905
+ coverage: {
2906
+ status: partial ? "partial" : "complete",
2907
+ event_limit_reached: eventLimit,
2908
+ resource_limit_reached: resourceLimit,
2909
+ ...breakpointLocationLimit ? { breakpoint_locations_truncated: true } : {},
2910
+ unresolved_breakpoints: unresolved
2911
+ },
2912
+ limitations: [
2913
+ ...NATIVE_CALL_OBSERVATION_LIMITATIONS,
2914
+ "The selected pathname digest and LLDB module identity are checked around launch. No immutable executable snapshot is used; concurrent in-place mutation or replacement and restoration cannot be ruled out, so the loaded-image digest remains unknown.",
2915
+ ...eventLimit ? [`Observation stopped at max_events (${input.max_events}); later calls were not recorded and the process was killed.`] : [],
2916
+ ...resourceLimit ? ["Observation stopped before retaining the next complete event because the estimated 8 MiB trace-payload or 65,536-frame aggregate budget was reached; the process was killed."] : [],
2917
+ ...run.outcome === "duration-elapsed" ? [`The process was still running after duration_ms (${input.duration_ms}) and was killed.`] : [],
2918
+ ...run.target_identity.stable ? [] : ["LLDB did not provide enough module identity evidence to confirm pathname and module continuity around launch."],
2919
+ ...run.outcome === "stop-limit" ? ["Observation stopped after repeated signal or exception stops; the process was killed."] : [],
2920
+ ...unresolved.length === 0 ? [] : [`Breakpoints ${unresolved.join(", ")} matched no code in any image loaded while observing; their calls could not be observed.`],
2921
+ ...run.breakpoints.some(({ location_count: count, locations }) => locations.length < count) ? ["Breakpoints with many matching locations list only the first 64; location_count gives the total."] : [],
2922
+ ...breakpointLocationLimit ? ["Resolved breakpoint locations exceeded the aggregate 8 MiB metadata budget; omitted locations are counted in location_count. This metadata limit does not change the process outcome."] : [],
2923
+ ...trace.stdout.truncated || trace.stderr.truncated ? ["Target output beyond 1 MiB per stream is counted but not kept."] : [],
2924
+ ...!trace.stdout.complete || !trace.stderr.complete ? ["Target output draining did not complete; reported byte counts are observed lower bounds, not stream totals."] : [],
2925
+ ...run.terminated && trace.terminated ? [] : [`REA could not confirm that process ${run.pid} exited; check for it before relying on host state.`]
2926
+ ]
2927
+ });
2928
+ };
2929
+ fileSha256 = async (path, signal) => {
2930
+ const handle = await open(path, "r");
2931
+ try {
2932
+ const hash = createHash("sha256");
2933
+ const buffer = new Uint8Array(1024 * 1024);
2934
+ for (;;) {
2935
+ signal?.throwIfAborted();
2936
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
2937
+ if (bytesRead === 0) break;
2938
+ hash.update(buffer.subarray(0, bytesRead));
2939
+ }
2940
+ return hash.digest("hex");
2941
+ } finally {
2942
+ await handle.close();
2943
+ }
2944
+ };
2945
+ })))();
2946
+ }
2947
+
2948
+ //#endregion
2949
+ //#region dist/native/SignatureTargetBinding.js
2950
+ var identity, changedTarget, signatureReadFailure, withSignatureTarget, combineCleanupFailure, snapshotFailure, snapshotIO, copySignatureBytes, bindSignatureTarget, verifySignatureTarget;
2951
+ function init_SignatureTargetBinding() {
2952
+ return (init_SignatureTargetBinding = __esmMin((() => {
2953
+ init_analysisErrorBase();
2954
+ init_analysisErrorCore();
2955
+ init_providerAdapterError();
2956
+ init_providerCleanupError();
2957
+ init_analysisErrorCleanup();
2958
+ init_result();
2959
+ init_OwnedFileHandle();
2960
+ init_ArtifactResourceScope();
2961
+ init_PrivateRuntimeRoot();
2962
+ init_ArtifactReader();
2963
+ init_NativeMacOSProviderMetadata();
2964
+ identity = (stat) => [
2965
+ stat.dev,
2966
+ stat.ino,
2967
+ stat.size,
2968
+ stat.mtimeNs,
2969
+ stat.ctimeNs
2970
+ ].join(":");
2971
+ changedTarget = (target, reason) => err(new AnalysisArtifactChangedError("inspect_signature", target.path, reason));
2972
+ signatureReadFailure = (target, cause) => {
2973
+ if (cause instanceof AnalysisError) return cause;
2974
+ const code = cause instanceof Error && "code" in cause ? cause.code : undefined;
2975
+ if (code === "EACCES" || code === "EPERM") return new AnalysisAccessDeniedError("inspect_signature", target.path, code, { cause });
2976
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP") return new AnalysisArtifactChangedError("inspect_signature", target.path, `Registered signature target is no longer readable (${code}): ${target.path}`, { cause });
2977
+ return new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_signature", {
2978
+ cause,
2979
+ diagnostics: {
2980
+ path: target.path,
2981
+ phase: "target-version-binding",
2982
+ system_code: typeof code === "string" ? code : null,
2983
+ reason: cause instanceof Error ? cause.message : String(cause)
2984
+ }
2985
+ });
2986
+ };
2987
+ withSignatureTarget = async (target, resources, inspect, signal, createRoot = () => PrivateRuntimeRoot.create({ prefix: "rea-signature-" })) => {
2988
+ try {
2989
+ return await resources.run(async () => {
2990
+ let root;
2991
+ try {
2992
+ signal?.throwIfAborted();
2993
+ root = await createRoot();
2994
+ } catch (cause) {
2995
+ return err(signal?.aborted ? new AnalysisCancelledError("inspect_signature") : snapshotFailure(target, "create", cause));
2996
+ }
2997
+ const owner = {
2998
+ kind: "private-runtime-root",
2999
+ root,
3000
+ resource: root.path
3001
+ };
3002
+ let result;
3003
+ try {
3004
+ const binding = await bindSignatureTarget(target, join(root.path, basename(target.path)), resources, signal);
3005
+ if (!binding.ok) result = binding;
3006
+ else {
3007
+ try {
3008
+ result = await inspect(binding.value);
3009
+ } catch (cause) {
3010
+ result = err(cause instanceof AnalysisError ? cause : new AnalysisOutputError("inspect_signature", "Native output parsing failed", { cause }));
3011
+ }
3012
+ }
3013
+ } catch (cause) {
3014
+ result = err(cause instanceof AnalysisError ? cause : signatureReadFailure(target, cause));
3015
+ }
3016
+ const cleanup = await resources.release(owner);
3017
+ if (cleanup.kind === "failed") return combineCleanupFailure(target, result, [root.path], cleanup.cause, "cleanup");
3018
+ return result;
3019
+ });
3020
+ } catch (cause) {
3021
+ if (cause instanceof AnalysisError) return err(cause);
3022
+ const retained = cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined ? cause.cleanup : undefined;
3023
+ if (retained !== undefined) return combineCleanupFailure(target, err(signal?.aborted ? new AnalysisCancelledError("inspect_signature") : signatureReadFailure(target, cause)), retained.resources, cause, "retry");
3024
+ return err(signal?.aborted ? new AnalysisCancelledError("inspect_signature") : signatureReadFailure(target, cause));
3025
+ }
3026
+ };
3027
+ combineCleanupFailure = (target, primary, resources, cause, phase) => {
3028
+ const cleanup = new ProviderCleanupError(NATIVE_MACOS_PROVIDER_IDENTITY.id, resources, {
3029
+ reason: cause instanceof Error ? cause.message : String(cause),
3030
+ phase: `signature-snapshot-${phase}`,
3031
+ path: target.path
3032
+ }, {
3033
+ operation: "inspect_signature",
3034
+ cause
3035
+ });
3036
+ return primary.ok ? err(cleanup) : err(analysisErrorWithCleanupFailure(primary.error, cleanup, "inspect_signature"));
3037
+ };
3038
+ snapshotFailure = (target, phase, cause) => new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_signature", {
3039
+ cause,
3040
+ diagnostics: {
3041
+ path: target.path,
3042
+ phase: `signature-snapshot-${phase}`,
3043
+ reason: cause instanceof Error ? cause.message : String(cause)
3044
+ }
3045
+ });
3046
+ snapshotIO = async (target, phase, operation) => {
3047
+ try {
3048
+ return await operation();
3049
+ } catch (cause) {
3050
+ throw snapshotFailure(target, phase, cause);
3051
+ }
3052
+ };
3053
+ copySignatureBytes = async (target, source, snapshot, signal) => {
3054
+ const size = Number(source.stat.size);
3055
+ if (!Number.isSafeInteger(size)) throw new AnalysisResourceConstraintError("inspect_signature", "file-size", `Signature target size is not exactly representable: ${target.path}`, null);
3056
+ const hash = createHash("sha256");
3057
+ const chunk = Buffer.alloc(64 * 1024);
3058
+ let position = 0;
3059
+ while (position < size) {
3060
+ signal?.throwIfAborted();
3061
+ const { bytesRead } = await source.file.read(chunk, 0, Math.min(chunk.length, size - position), position);
3062
+ signal?.throwIfAborted();
3063
+ if (bytesRead === 0) throw new AnalysisArtifactChangedError("inspect_signature", target.path, `Signature target was truncated while hashing: ${target.path}`);
3064
+ const bytes = chunk.subarray(0, bytesRead);
3065
+ hash.update(bytes);
3066
+ await snapshotIO(target, "write", () => snapshot.writeFile(bytes));
3067
+ position += bytesRead;
3068
+ }
3069
+ return hash.digest("hex");
3070
+ };
3071
+ bindSignatureTarget = async (target, snapshotPath, resources, signal) => {
3072
+ let sourceOwner;
3073
+ let snapshotOwner;
3074
+ const perform = async () => {
3075
+ try {
3076
+ signal?.throwIfAborted();
3077
+ const before = await lstat(target.path, { bigint: true });
3078
+ signal?.throwIfAborted();
3079
+ if (!before.isFile() || before.isSymbolicLink()) return changedTarget(target, `Signature target is no longer a regular file: ${target.path}`);
3080
+ const file = await open(target.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
3081
+ sourceOwner = new OwnedFileHandle(file);
3082
+ const opened = await file.stat({ bigint: true });
3083
+ signal?.throwIfAborted();
3084
+ if (identity(opened) !== identity(before)) return changedTarget(target, `Signature target changed before open: ${target.path}`);
3085
+ const snapshot = await snapshotIO(target, "create-file", () => open(snapshotPath, "wx", 384));
3086
+ snapshotOwner = new OwnedFileHandle(snapshot);
3087
+ const observed = await copySignatureBytes(target, {
3088
+ file,
3089
+ stat: opened
3090
+ }, snapshot, signal);
3091
+ if (observed !== target.sha256) return changedTarget(target, `Signature target digest changed: ${target.path}; expected ${target.sha256}, observed ${observed}`);
3092
+ const after = await file.stat({ bigint: true });
3093
+ const current = await lstat(target.path, { bigint: true });
3094
+ signal?.throwIfAborted();
3095
+ if (identity(after) !== identity(opened) || identity(current) !== identity(opened)) return changedTarget(target, `Signature target changed while establishing its version: ${target.path}`);
3096
+ await snapshotIO(target, "seal", () => snapshot.chmod(256));
3097
+ return ok({
3098
+ identity: identity(opened),
3099
+ snapshotPath
3100
+ });
3101
+ } catch (cause) {
3102
+ return err(signal?.aborted ? new AnalysisCancelledError("inspect_signature") : signatureReadFailure(target, cause));
3103
+ }
3104
+ };
3105
+ let result = await perform();
3106
+ const cleanupFailures = [];
3107
+ for (const [owner, path] of [[snapshotOwner, snapshotPath], [sourceOwner, target.path]]) {
3108
+ if (owner === undefined) continue;
3109
+ const cleanup = await resources.release({
3110
+ kind: "file-handle",
3111
+ handle: owner,
3112
+ resource: path
3113
+ });
3114
+ if (cleanup.kind === "failed") cleanupFailures.push({
3115
+ path,
3116
+ cause: cleanup.cause
3117
+ });
3118
+ }
3119
+ if (cleanupFailures.length > 0) {
3120
+ const cause = new AggregateError(cleanupFailures.map(({ cause: failure }) => failure), "Signature snapshot file handles could not be closed");
3121
+ result = combineCleanupFailure(target, result, cleanupFailures.map(({ path }) => path), cause, "close");
3122
+ }
3123
+ return result;
3124
+ };
3125
+ verifySignatureTarget = async (target, binding, signal) => {
3126
+ try {
3127
+ signal?.throwIfAborted();
3128
+ const current = await lstat(target.path, { bigint: true });
3129
+ signal?.throwIfAborted();
3130
+ return current.isFile() && identity(current) === binding.identity ? ok(undefined) : changedTarget(target, `Signature target changed during inspection: ${target.path}`);
3131
+ } catch (cause) {
3132
+ return err(signal?.aborted ? new AnalysisCancelledError("inspect_signature") : signatureReadFailure(target, cause));
3133
+ }
3134
+ };
3135
+ })))();
3136
+ }
3137
+
3138
+ //#endregion
3139
+ //#region dist/native/parsers/codesign.js
3140
+ var parseCodeSignature, splitEchoedValues, nullableCodeSignValue, splitAlgorithms, parseRuntime;
3141
+ function init_codesign() {
3142
+ return (init_codesign = __esmMin((() => {
3143
+ init_nativeInspection();
3144
+ parseCodeSignature = (output, unsigned, executablePaths = []) => {
3145
+ const { identifier, fields } = splitEchoedValues(output, executablePaths);
3146
+ const values = new Map();
3147
+ const authorities = [];
3148
+ const cdhashes = [];
3149
+ for (const line of fields.split(/\r?\n/u)) {
3150
+ if (line.startsWith("CodeDirectory ")) {
3151
+ values.set("CodeDirectory", line.slice("CodeDirectory ".length));
3152
+ continue;
3153
+ }
3154
+ const separator = line.indexOf("=");
3155
+ if (separator < 1) continue;
3156
+ const key = line.slice(0, separator).trim();
3157
+ const value = line.slice(separator + 1).trim();
3158
+ if (key === "Authority") authorities.push(value);
3159
+ else if (key === "CDHash") cdhashes.push(value);
3160
+ else values.set(key, value);
3161
+ }
3162
+ const parsed = inspectSignatureSchema.omit({ provenance: true }).parse({
3163
+ signed: !unsigned,
3164
+ identifier: identifier ?? null,
3165
+ team_identifier: nullableCodeSignValue(values.get("TeamIdentifier")),
3166
+ format: values.get("Format") ?? null,
3167
+ cdhashes,
3168
+ hash_algorithms: splitAlgorithms(values.get("Hash choices")),
3169
+ authorities,
3170
+ designated_requirement: values.get("designated") ?? null,
3171
+ entitlements: null,
3172
+ timestamp: values.get("Timestamp") ?? null,
3173
+ hardened_runtime: parseRuntime(values.get("CodeDirectory")),
3174
+ limitations: unsigned ? ["Artifact is not signed."] : ["Entitlements and designated requirements require separate bounded commands."]
3175
+ });
3176
+ return parsed;
3177
+ };
3178
+ splitEchoedValues = (text, executablePaths) => {
3179
+ let rest = text;
3180
+ let newline;
3181
+ for (const path of executablePaths) {
3182
+ const prefix = `Executable=${path}`;
3183
+ if (!text.startsWith(prefix)) continue;
3184
+ const separator = /^\r?\n/u.exec(text.slice(prefix.length))?.[0];
3185
+ if (separator === undefined) continue;
3186
+ newline = separator;
3187
+ rest = text.slice(prefix.length + separator.length);
3188
+ break;
3189
+ }
3190
+ if (rest === text && text.startsWith("Executable=")) {
3191
+ const identifierLine = text.indexOf("\nIdentifier=");
3192
+ rest = identifierLine < 0 ? text : text.slice(identifierLine + 1);
3193
+ }
3194
+ if (!rest.startsWith("Identifier=")) return {
3195
+ identifier: undefined,
3196
+ fields: rest
3197
+ };
3198
+ const format = rest.lastIndexOf("\nFormat=");
3199
+ if (newline === undefined && format >= 0) newline = /\r?\n/u.exec(rest.slice(format + 1))?.[0];
3200
+ const boundary = format >= 0 ? format : rest.indexOf("\n");
3201
+ const crlf = newline === undefined || newline === "\r\n";
3202
+ const end = boundary < 0 ? rest.length : boundary - (crlf && rest[boundary - 1] === "\r" ? 1 : 0);
3203
+ return {
3204
+ identifier: rest.slice("Identifier=".length, end),
3205
+ fields: rest.slice(end)
3206
+ };
3207
+ };
3208
+ nullableCodeSignValue = (value) => value === undefined || value === "not set" ? null : value;
3209
+ splitAlgorithms = (value) => value === undefined ? [] : value.split(/[,+\s]+/u).map((part) => part.trim()).filter((part) => part.length > 0);
3210
+ parseRuntime = (value) => {
3211
+ if (value === undefined) return null;
3212
+ const flags = /(?:^|\s)flags=[^(]*\(([^)]*)\)/u.exec(value)?.[1];
3213
+ if (flags === undefined) return null;
3214
+ return flags.split(",").some((flag) => flag.trim() === "runtime");
3215
+ };
3216
+ })))();
3217
+ }
3218
+
3219
+ //#endregion
3220
+ //#region dist/native/parsers/demangle.js
3221
+ var resultSchema, parseDemangledSymbols;
3222
+ function init_demangle() {
3223
+ return (init_demangle = __esmMin((() => {
3224
+ init_swiftSymbolClassification();
3225
+ resultSchema = z.object({
3226
+ input: z.string(),
3227
+ output: z.string(),
3228
+ status: z.enum([
3229
+ "demangled",
3230
+ "unchanged",
3231
+ "invalid"
3232
+ ])
3233
+ });
3234
+ parseDemangledSymbols = (inputs, output) => {
3235
+ if (inputs.length === 0) {
3236
+ if (output === "" || output === "\n") return [];
3237
+ throw new TypeError("swift-demangle emitted output for an empty input");
3238
+ }
3239
+ const lines = output.replace(/\n$/u, "").split("\n");
3240
+ if (lines.length !== inputs.length) throw new TypeError("swift-demangle output count does not match input");
3241
+ return inputs.map((input, index) => {
3242
+ const value = lines[index];
3243
+ if (value === undefined) throw new TypeError("swift-demangle omitted an output line");
3244
+ return resultSchema.parse({
3245
+ input,
3246
+ output: value,
3247
+ status: value === input ? isSwiftMangledSymbolName(input) ? "invalid" : "unchanged" : "demangled"
3248
+ });
3249
+ });
3250
+ };
3251
+ })))();
3252
+ }
3253
+
3254
+ //#endregion
3255
+ //#region dist/native/parsers/plist.js
3256
+ var plistObject, INTEGRAL_LITERAL, decodePlistJson, plistJsonNeedsNumberTypes, parsePlistJson, parsePlistXml, xmlNumberLiterals, prototypeKeyLimitations, numberLimitations, mapJsonNumbers, projectPlistBundle;
3257
+ function init_plist() {
3258
+ return (init_plist = __esmMin((() => {
3259
+ init_analysisErrorCore();
3260
+ init_plistValue();
3261
+ init_propertyListKeys();
3262
+ init_result();
3263
+ plistObject = z.record(z.string(), z.unknown());
3264
+ INTEGRAL_LITERAL = /^-?\d+$/u;
3265
+ decodePlistJson = (output, unsafe) => {
3266
+ const text = output.replace(/^\uFEFF/u, "");
3267
+ return JSON.parse(text, (_key, item, context) => {
3268
+ const source = context?.source;
3269
+ return typeof item !== "number" || Number.isSafeInteger(item) || source === undefined || !INTEGRAL_LITERAL.test(source) ? item : unsafe(item, source);
3270
+ });
3271
+ };
3272
+ plistJsonNeedsNumberTypes = (output) => {
3273
+ let found = false;
3274
+ try {
3275
+ decodePlistJson(output, (item) => {
3276
+ found = true;
3277
+ return item;
3278
+ });
3279
+ } catch {}
3280
+ return found;
3281
+ };
3282
+ parsePlistJson = (output, xmlConversion) => {
3283
+ const literals = xmlConversion === undefined ? undefined : xmlNumberLiterals(xmlConversion);
3284
+ let exactIntegerCount = 0;
3285
+ let ambiguousNumberCount = 0;
3286
+ const classify = (item, digits) => {
3287
+ const exact = BigInt(digits).toString();
3288
+ const integer = literals?.integers.get(item)?.has(exact) === true;
3289
+ const real = literals?.reals.has(item) === true;
3290
+ if (integer && !real) {
3291
+ exactIntegerCount += 1;
3292
+ return {
3293
+ $plist_type: "integer",
3294
+ decimal: digits
3295
+ };
3296
+ }
3297
+ if (real && !integer) return item;
3298
+ ambiguousNumberCount += 1;
3299
+ return item;
3300
+ };
3301
+ let decoded;
3302
+ try {
3303
+ decoded = omitPrototypeKeys(decodePlistJson(output, classify));
3304
+ } catch (cause) {
3305
+ return err(new AnalysisOutputError("inspect_plist", cause instanceof Error ? cause.message : String(cause), { cause }));
3306
+ }
3307
+ const { value } = decoded;
3308
+ return ok({
3309
+ value,
3310
+ bundle: projectPlistBundle(value),
3311
+ limitations: [...numberLimitations(exactIntegerCount, ambiguousNumberCount), ...prototypeKeyLimitations(decoded.omittedPrototypeKeys)]
3312
+ });
3313
+ };
3314
+ parsePlistXml = (output) => {
3315
+ let projected;
3316
+ let omittedPrototypeKeys;
3317
+ try {
3318
+ const decoded = parseXmlPropertyList(output);
3319
+ omittedPrototypeKeys = decoded.omittedPrototypeKeys;
3320
+ projected = projectPlistValue(decoded.value);
3321
+ } catch (cause) {
3322
+ return err(new AnalysisOutputError("inspect_plist", "plutil XML conversion was not a readable plist", { cause }));
3323
+ }
3324
+ const literals = xmlNumberLiterals(output);
3325
+ let exactIntegerCount = 0;
3326
+ let ambiguousNumberCount = 0;
3327
+ const value = mapJsonNumbers(projected.value, (item) => {
3328
+ const decimals = literals.integers.get(item);
3329
+ if (decimals === undefined) return item;
3330
+ const [decimal] = decimals;
3331
+ if (decimals.size !== 1 || decimal === undefined || literals.reals.has(item)) {
3332
+ ambiguousNumberCount += 1;
3333
+ return item;
3334
+ }
3335
+ exactIntegerCount += 1;
3336
+ return {
3337
+ $plist_type: "integer",
3338
+ decimal
3339
+ };
3340
+ });
3341
+ return ok({
3342
+ value,
3343
+ bundle: projectPlistBundle(value),
3344
+ limitations: [
3345
+ "plutil cannot express this plist as JSON, so it was decoded from plutil's XML conversion; data and date values are typed objects such as { \"$plist_type\": \"data\", \"base64\": ... }.",
3346
+ ...projected.unknownRealCount === 0 ? [] : [`${String(projected.unknownRealCount)} non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because the XML decoder does not distinguish NaN from infinity.`],
3347
+ ...numberLimitations(exactIntegerCount, ambiguousNumberCount),
3348
+ ...prototypeKeyLimitations(omittedPrototypeKeys)
3349
+ ]
3350
+ });
3351
+ };
3352
+ xmlNumberLiterals = (xml) => {
3353
+ const integers = new Map();
3354
+ for (const [, decimal = ""] of xml.matchAll(/<integer>\s*([+-]?\d+)\s*<\/integer>/gu)) {
3355
+ const rounded = Number(decimal);
3356
+ if (Number.isSafeInteger(rounded)) continue;
3357
+ integers.set(rounded, (integers.get(rounded) ?? new Set()).add(BigInt(decimal).toString()));
3358
+ }
3359
+ const reals = new Set([...xml.matchAll(/<real>([^<]*)<\/real>/gu)].map(([, text = ""]) => Number.parseFloat(text)));
3360
+ return {
3361
+ integers,
3362
+ reals
3363
+ };
3364
+ };
3365
+ prototypeKeyLimitations = (count) => count === 0 ? [] : [omittedPrototypeKeysLimitation(count)];
3366
+ numberLimitations = (exactIntegerCount, ambiguousNumberCount) => [...exactIntegerCount === 0 ? [] : [`${String(exactIntegerCount)} integer value(s) exceed the exact range of a JSON number and are reported as { "$plist_type": "integer", "decimal": "<exact digits>" }.`], ...ambiguousNumberCount === 0 ? [] : [`${String(ambiguousNumberCount)} number(s) beyond the exact range of a JSON number are reported as decoded because the XML literal they came from, a rounded <integer> or a <real>, cannot be identified.`]];
3367
+ mapJsonNumbers = (value, map) => {
3368
+ if (typeof value === "number") return map(value);
3369
+ if (Array.isArray(value)) return value.map((item) => mapJsonNumbers(item, map));
3370
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapJsonNumbers(item, map)]));
3371
+ return value;
3372
+ };
3373
+ projectPlistBundle = (value) => {
3374
+ const object = plistObject.safeParse(value);
3375
+ const field = (name) => {
3376
+ if (!object.success) return null;
3377
+ const candidate = object.data[name];
3378
+ return typeof candidate === "string" ? candidate : null;
3379
+ };
3380
+ return {
3381
+ identifier: field("CFBundleIdentifier"),
3382
+ executable: field("CFBundleExecutable"),
3383
+ name: field("CFBundleName"),
3384
+ version: field("CFBundleVersion"),
3385
+ short_version: field("CFBundleShortVersionString")
3386
+ };
3387
+ };
3388
+ })))();
3389
+ }
3390
+
3391
+ //#endregion
3392
+ //#region dist/native/parsers/dyldInfo.js
3393
+ var parseDyldSymbols, canonicalHex, parseReexportRow, reexportSuffix;
3394
+ function init_dyldInfo() {
3395
+ return (init_dyldInfo = __esmMin((() => {
3396
+ parseDyldSymbols = (output, mode, imageBase = null, knownExportNames = new Set()) => {
3397
+ const offsets = /^\s*offset\s+symbol\s*$/mu.test(output);
3398
+ return output.split(/\r?\n/u).flatMap((rawLine) => {
3399
+ const line = rawLine.trim();
3400
+ if (mode === "imports") {
3401
+ const imported = /^(?:0x[\da-f]+\s+)?(.+?)(?:\s+\[([^\]]+)\])?\s+\(from (.+)\)$/iu.exec(line);
3402
+ if (imported?.[1] !== undefined) return [{
3403
+ name: imported[1],
3404
+ address: null,
3405
+ weak: /\bweak-import\b/u.test(imported[2] ?? "") ? true : null,
3406
+ reexport: null,
3407
+ source: imported[3] ?? null
3408
+ }];
3409
+ return [];
3410
+ }
3411
+ const reexport = parseReexportRow(line, knownExportNames);
3412
+ if (reexport !== null) return [{
3413
+ name: reexport.name,
3414
+ address: null,
3415
+ weak: null,
3416
+ reexport: true,
3417
+ source: reexport.source,
3418
+ ...reexport.sourceSymbol === undefined ? {} : { sourceSymbol: reexport.sourceSymbol }
3419
+ }];
3420
+ const exported = /^(0x[\da-f]+)\s+(.+?)(?:\s+\[([^\]]+)\])?$/iu.exec(line);
3421
+ if (exported?.[1] === undefined || exported[2] === undefined) return [];
3422
+ const rawName = /^0x[\da-f]+\s+(.+)$/iu.exec(line)?.[1];
3423
+ const literalName = rawName !== undefined && knownExportNames.has(rawName);
3424
+ if (literalName && exported[3] !== undefined && knownExportNames.has(exported[2])) return [];
3425
+ const annotation = literalName ? undefined : exported[3];
3426
+ const absolute = /\babsolute\b/u.test(annotation ?? "");
3427
+ const address = offsets && !absolute ? imageBase === null ? null : `0x${(BigInt(imageBase) + BigInt(exported[1])).toString(16)}` : canonicalHex(exported[1]);
3428
+ return [{
3429
+ name: literalName ? rawName : exported[2],
3430
+ address,
3431
+ weak: /\bweak-def\b/u.test(annotation ?? "") ? true : null,
3432
+ reexport: false,
3433
+ source: null
3434
+ }];
3435
+ });
3436
+ };
3437
+ canonicalHex = (value) => value === undefined ? null : `0x${BigInt(value).toString(16)}`;
3438
+ parseReexportRow = (line, knownNames) => {
3439
+ const prefix = /^\[re-export\]\s+/u.exec(line);
3440
+ if (prefix === null) return null;
3441
+ const rest = line.slice(prefix[0].length);
3442
+ if (rest.length === 0) return null;
3443
+ if (!rest.endsWith(")")) return {
3444
+ name: rest,
3445
+ source: null
3446
+ };
3447
+ const candidates = [];
3448
+ for (const match of rest.matchAll(/\s+\(/gu)) {
3449
+ const name = rest.slice(0, match.index);
3450
+ if (!knownNames.has(name)) continue;
3451
+ const parsed = reexportSuffix(name, rest.slice(match.index + match[0].length, -1));
3452
+ if (parsed !== null) candidates.push(parsed);
3453
+ }
3454
+ if (candidates.length > 0) return candidates.length === 1 ? candidates[0] : null;
3455
+ if (knownNames.has(rest)) return {
3456
+ name: rest,
3457
+ source: null
3458
+ };
3459
+ let depth = 0;
3460
+ for (let index = rest.length - 1; index >= 0; index--) {
3461
+ if (rest[index] === ")") depth++;
3462
+ else if (rest[index] === "(" && --depth === 0) {
3463
+ if (index === 0 || !/\s/u.test(rest[index - 1])) break;
3464
+ const name = rest.slice(0, index).trimEnd();
3465
+ return reexportSuffix(name, rest.slice(index + 1, -1)) ?? {
3466
+ name: rest,
3467
+ source: null
3468
+ };
3469
+ }
3470
+ }
3471
+ return {
3472
+ name: rest,
3473
+ source: null
3474
+ };
3475
+ };
3476
+ reexportSuffix = (name, inner) => {
3477
+ if (name.length === 0) return null;
3478
+ if (inner.startsWith("from ") && inner.length > 5) return {
3479
+ name,
3480
+ source: inner.slice(5)
3481
+ };
3482
+ const separator = /\s+from /u.exec(inner);
3483
+ if (separator === null) return null;
3484
+ const sourceSymbol = inner.slice(0, separator.index);
3485
+ const source = inner.slice(separator.index + separator[0].length);
3486
+ return sourceSymbol.length > 0 && source.length > 0 ? {
3487
+ name,
3488
+ source,
3489
+ sourceSymbol
3490
+ } : null;
3491
+ };
3492
+ })))();
3493
+ }
3494
+
3495
+ //#endregion
3496
+ //#region dist/native/parsers/echoedPath.js
3497
+ var withoutEchoedPathHeader;
3498
+ function init_echoedPath() {
3499
+ return (init_echoedPath = __esmMin((() => {
3500
+ withoutEchoedPathHeader = (output, path) => {
3501
+ if (path === undefined || !output.startsWith(path)) return output;
3502
+ const header = /^(?: \(architecture [^)\n]*\)| \[[^\]\n]*\])?:\r?\n/u.exec(output.slice(path.length));
3503
+ return header === null ? output : output.slice(path.length + header[0].length);
3504
+ };
3505
+ })))();
3506
+ }
3507
+
3508
+ //#endregion
3509
+ //#region dist/native/parsers/otool.js
3510
+ var DYLIB_COMMANDS, DYLIB_FIELDS, DYLIB_ENCODING_FIELDS, EMPTY_VALUE_FIELDS, BUILD_PLATFORM_NAMES, BUILD_TOOL_NAMES, buildCodeName, normalizeLineEndings, parseOtoolLoadCommands, WORD_SIZES, cpuEndian, parseHeader, headerValue, validateLoadCommandFraming, createLoadCommandState, parseLoadCommand, validateDylibCommandLines, scalarFields, collectUuid, collectEntrypoint, collectBuild, collectDependency, collectSegment, parseFields, parseField, requireUniqueField, parseSegment, parseSections, parseBuildTools, permissions, NUMERIC_PATTERN, numeric, nonEmptyName, stringField, numberField, hexField, stripOffsetSuffix, sectionAlignment;
3511
+ function init_otool() {
3512
+ return (init_otool = __esmMin((() => {
3513
+ DYLIB_COMMANDS = new Set([
3514
+ "LC_ID_DYLIB",
3515
+ "LC_LOAD_DYLIB",
3516
+ "LC_LOAD_WEAK_DYLIB",
3517
+ "LC_REEXPORT_DYLIB",
3518
+ "LC_LAZY_LOAD_DYLIB",
3519
+ "LC_LOAD_UPWARD_DYLIB"
3520
+ ]);
3521
+ DYLIB_FIELDS = [
3522
+ "cmd",
3523
+ "cmdsize",
3524
+ "name",
3525
+ "current version",
3526
+ "compatibility version"
3527
+ ];
3528
+ DYLIB_ENCODING_FIELDS = ["time stamp", "options"];
3529
+ EMPTY_VALUE_FIELDS = new Set([
3530
+ "options",
3531
+ "segname",
3532
+ "sectname"
3533
+ ]);
3534
+ BUILD_PLATFORM_NAMES = new Map([
3535
+ ["1", "MACOS"],
3536
+ ["2", "IOS"],
3537
+ ["3", "TVOS"],
3538
+ ["4", "WATCHOS"],
3539
+ ["5", "BRIDGEOS"],
3540
+ ["6", "MACCATALYST"],
3541
+ ["7", "IOSSIMULATOR"],
3542
+ ["8", "TVOSSIMULATOR"],
3543
+ ["9", "WATCHOSSIMULATOR"],
3544
+ ["10", "DRIVERKIT"],
3545
+ ["11", "VISIONOS"],
3546
+ ["12", "VISIONOSSIMULATOR"],
3547
+ ["13", "FIRMWARE"],
3548
+ ["14", "SEPOS"],
3549
+ ["15", "MACOS_EXCLAVECORE"],
3550
+ ["16", "MACOS_EXCLAVEKIT"],
3551
+ ["17", "IOS_EXCLAVECORE"],
3552
+ ["18", "IOS_EXCLAVEKIT"],
3553
+ ["19", "TVOS_EXCLAVECORE"],
3554
+ ["20", "TVOS_EXCLAVEKIT"],
3555
+ ["21", "WATCHOS_EXCLAVECORE"],
3556
+ ["22", "WATCHOS_EXCLAVEKIT"],
3557
+ ["23", "VISIONOS_EXCLAVECORE"],
3558
+ ["24", "VISIONOS_EXCLAVEKIT"]
3559
+ ]);
3560
+ BUILD_TOOL_NAMES = new Map([
3561
+ ["1", "CLANG"],
3562
+ ["2", "SWIFT"],
3563
+ ["3", "LD"],
3564
+ ["4", "LLD"],
3565
+ ["1024", "METAL"],
3566
+ ["1025", "AIRLLD"],
3567
+ ["1026", "AIRNT"],
3568
+ ["1027", "AIRNT_PLUGIN"],
3569
+ ["1028", "AIRPACK"],
3570
+ ["1031", "GPUARCHIVER"],
3571
+ ["1032", "METAL_FRAMEWORK"]
3572
+ ]);
3573
+ buildCodeName = (names, value) => value === null ? null : names.get(value) ?? value;
3574
+ normalizeLineEndings = (output) => output.replaceAll("\r\n", "\n");
3575
+ parseOtoolLoadCommands = (raw) => {
3576
+ const output = normalizeLineEndings(raw);
3577
+ const header = parseHeader(output);
3578
+ if (header === undefined) throw new TypeError("otool output is missing the Mach header");
3579
+ const state = createLoadCommandState(header.flags);
3580
+ for (const block of output.split(/(?=^Load command \d+$)/mu)) parseLoadCommand(block, state);
3581
+ validateLoadCommandFraming(header, state.commands);
3582
+ return {
3583
+ wordSize: WORD_SIZES.get(header.magic ?? "") ?? null,
3584
+ endian: header.cpuType === null ? null : cpuEndian(header.cpuType),
3585
+ fileType: header.fileType,
3586
+ flags: [...state.flags].sort(),
3587
+ uuid: state.uuid,
3588
+ commands: state.commands,
3589
+ segments: state.segments,
3590
+ dependencies: state.dependencies,
3591
+ entrypoints: state.entrypoints,
3592
+ builds: state.builds
3593
+ };
3594
+ };
3595
+ WORD_SIZES = new Map([
3596
+ ["0xfeedface", 32],
3597
+ ["0xfeedfacf", 64],
3598
+ ["MH_MAGIC", 32],
3599
+ ["MH_MAGIC_64", 64]
3600
+ ]);
3601
+ cpuEndian = (cpuType) => {
3602
+ const family = cpuType & 16777215;
3603
+ if (family === 7 || family === 12) return "little";
3604
+ return family === 18 ? "big" : null;
3605
+ };
3606
+ parseHeader = (output) => {
3607
+ const lines = output.split(/\r?\n/u).map((line) => line.trim());
3608
+ const columnsLine = lines.findIndex((line) => /(?:^|\s)magic\s/u.test(line));
3609
+ if (columnsLine < 0) return undefined;
3610
+ const columns = lines[columnsLine]?.split(/\s+/u);
3611
+ const dataLine = lines.slice(columnsLine + 1).find((line) => line.length > 0);
3612
+ const values = dataLine?.split(/\s+/u);
3613
+ if (columns === undefined || values === undefined) return undefined;
3614
+ const commandCount = headerValue(columns, values, "ncmds");
3615
+ const commandBytes = headerValue(columns, values, "sizeofcmds");
3616
+ if (commandCount === null || commandBytes === null) throw new TypeError("otool Mach header is missing valid command framing");
3617
+ const fileTypeIndex = columns.indexOf("filetype");
3618
+ const flagsIndex = columns.indexOf("flags");
3619
+ const complete = values.length >= columns.length;
3620
+ const fileTypeValueIndex = flagsIndex >= 0 && fileTypeIndex > flagsIndex ? values.length - (columns.length - fileTypeIndex) : fileTypeIndex;
3621
+ const flagsEnd = flagsIndex >= 0 ? values.length - (columns.length - flagsIndex - 1) : 0;
3622
+ const magicIndex = columns.indexOf("magic");
3623
+ return {
3624
+ magic: magicIndex < 0 ? null : values[magicIndex] ?? null,
3625
+ cpuType: headerValue(columns, values, "cputype"),
3626
+ commandCount,
3627
+ commandBytes,
3628
+ fileType: complete && fileTypeValueIndex >= 0 && fileTypeValueIndex < values.length ? values[fileTypeValueIndex] ?? null : null,
3629
+ flags: !complete || flagsIndex < 0 || flagsIndex >= flagsEnd ? [] : values.slice(flagsIndex, flagsEnd).filter((value) => value.length > 0)
3630
+ };
3631
+ };
3632
+ headerValue = (columns, values, name) => {
3633
+ const index = columns.indexOf(name);
3634
+ if (index < 0) return null;
3635
+ const flagsIndex = columns.indexOf("flags");
3636
+ const valueIndex = flagsIndex >= 0 && index > flagsIndex ? values.length - (columns.length - index) : index;
3637
+ const value = values[valueIndex];
3638
+ return value === undefined ? null : numeric(value);
3639
+ };
3640
+ validateLoadCommandFraming = (header, commands) => {
3641
+ if (commands.length !== header.commandCount) throw new TypeError("otool load-command count does not match the Mach header");
3642
+ let totalBytes = 0;
3643
+ for (const [expectedIndex, command] of commands.entries()) {
3644
+ const size = numberField(command.fields, "cmdsize");
3645
+ if (command.index !== expectedIndex || size === null || size < 8) throw new TypeError("otool load-command sequence or size is invalid");
3646
+ totalBytes += size;
3647
+ if (!Number.isSafeInteger(totalBytes)) throw new TypeError("otool load-command byte count is unsafe");
3648
+ }
3649
+ if (totalBytes !== header.commandBytes) throw new TypeError("otool load-command sizes do not match the Mach header");
3650
+ };
3651
+ createLoadCommandState = (headerFlags) => ({
3652
+ commands: [],
3653
+ segments: [],
3654
+ dependencies: [],
3655
+ entrypoints: [],
3656
+ builds: [],
3657
+ uuid: null,
3658
+ flags: new Set(headerFlags ?? [])
3659
+ });
3660
+ parseLoadCommand = (block, state) => {
3661
+ const indexText = /^Load command (\d+)/u.exec(block)?.[1];
3662
+ if (indexText === undefined) return;
3663
+ const index = Number(indexText);
3664
+ if (!Number.isSafeInteger(index)) throw new TypeError("otool load-command index is unsafe");
3665
+ const header = block.split(/\n\s*Section\n/u)[0] ?? block;
3666
+ const parsed = parseFields(header);
3667
+ const fields = parsed.values;
3668
+ const kind = stringField(fields, "cmd");
3669
+ if (kind === null) throw new TypeError("otool load command is missing cmd");
3670
+ for (const key of scalarFields(kind)) requireUniqueField(parsed, key);
3671
+ if (DYLIB_COMMANDS.has(kind)) validateDylibCommandLines(parsed);
3672
+ state.commands.push({
3673
+ index,
3674
+ kind,
3675
+ fields
3676
+ });
3677
+ collectUuid(kind, fields, state);
3678
+ collectEntrypoint(kind, fields, state);
3679
+ collectBuild(kind, block, fields, state);
3680
+ collectDependency(kind, fields, state);
3681
+ collectSegment(kind, block, fields, state);
3682
+ };
3683
+ validateDylibCommandLines = (parsed) => {
3684
+ const encodingFields = DYLIB_ENCODING_FIELDS.filter((key) => Object.hasOwn(parsed.values, key));
3685
+ if (encodingFields.length !== 1) throw new TypeError("otool dylib command must contain timestamp or options");
3686
+ for (const key of encodingFields) requireUniqueField(parsed, key);
3687
+ const allowed = new Set([...DYLIB_FIELDS, ...DYLIB_ENCODING_FIELDS]);
3688
+ for (const field of parsed.rows) {
3689
+ const key = field?.[0];
3690
+ if (key === undefined || !allowed.has(key)) throw new TypeError("otool dylib command contains ambiguous multiline text");
3691
+ }
3692
+ };
3693
+ scalarFields = (kind) => {
3694
+ const common = ["cmd", "cmdsize"];
3695
+ if (DYLIB_COMMANDS.has(kind)) return DYLIB_FIELDS;
3696
+ if (kind === "LC_LOAD_DYLINKER" || kind === "LC_ID_DYLINKER") return [...common, "name"];
3697
+ if (kind === "LC_UUID") return [...common, "uuid"];
3698
+ if (kind === "LC_MAIN") return [...common, "entryoff"];
3699
+ if (kind === "LC_BUILD_VERSION") return [
3700
+ ...common,
3701
+ "platform",
3702
+ "minos",
3703
+ "sdk",
3704
+ "ntools"
3705
+ ];
3706
+ if (kind.startsWith("LC_VERSION_MIN_")) return [
3707
+ ...common,
3708
+ "version",
3709
+ "sdk"
3710
+ ];
3711
+ if (kind === "LC_SEGMENT" || kind === "LC_SEGMENT_64") return [
3712
+ ...common,
3713
+ "segname",
3714
+ "vmaddr",
3715
+ "vmsize",
3716
+ "fileoff",
3717
+ "filesize",
3718
+ "maxprot",
3719
+ "initprot",
3720
+ "nsects",
3721
+ "flags"
3722
+ ];
3723
+ return common;
3724
+ };
3725
+ collectUuid = (kind, fields, state) => {
3726
+ if (kind === "LC_UUID") state.uuid = stringField(fields, "uuid") ?? state.uuid;
3727
+ };
3728
+ collectEntrypoint = (kind, fields, state) => {
3729
+ if (kind !== "LC_MAIN") return;
3730
+ const entry = numberField(fields, "entryoff");
3731
+ if (entry !== null) state.entrypoints.push({ file_offset: entry });
3732
+ };
3733
+ collectBuild = (kind, block, fields, state) => {
3734
+ if (kind === "LC_BUILD_VERSION") {
3735
+ const tools = parseBuildTools(block);
3736
+ if (numberField(fields, "ntools") !== tools.length) throw new TypeError("otool build-tool count does not match ntools");
3737
+ state.builds.push({
3738
+ platform: buildCodeName(BUILD_PLATFORM_NAMES, stringField(fields, "platform")),
3739
+ minimum_os: stringField(fields, "minos"),
3740
+ sdk: stringField(fields, "sdk"),
3741
+ tools
3742
+ });
3743
+ return;
3744
+ }
3745
+ if (kind.startsWith("LC_VERSION_MIN_")) state.builds.push({
3746
+ platform: kind.slice("LC_VERSION_MIN_".length) || null,
3747
+ minimum_os: stringField(fields, "version"),
3748
+ sdk: stringField(fields, "sdk"),
3749
+ tools: []
3750
+ });
3751
+ };
3752
+ collectDependency = (kind, fields, state) => {
3753
+ if (!DYLIB_COMMANDS.has(kind)) return;
3754
+ state.dependencies.push({
3755
+ path: stripOffsetSuffix(stringField(fields, "name")),
3756
+ kind,
3757
+ current_version: stringField(fields, "current version"),
3758
+ compatibility_version: stringField(fields, "compatibility version")
3759
+ });
3760
+ };
3761
+ collectSegment = (kind, block, fields, state) => {
3762
+ if (kind !== "LC_SEGMENT" && kind !== "LC_SEGMENT_64") return;
3763
+ const segment = parseSegment(block, fields);
3764
+ if (numberField(fields, "nsects") !== segment.sections.length) throw new TypeError("otool segment section count does not match its sections");
3765
+ state.segments.push(segment);
3766
+ };
3767
+ parseFields = (block) => {
3768
+ const fields = {};
3769
+ const rows = [];
3770
+ for (const rawLine of block.split(/\r?\n/u).slice(1)) {
3771
+ if (rawLine.trim().length === 0) continue;
3772
+ const field = parseField(rawLine);
3773
+ rows.push(field);
3774
+ if (field === undefined) continue;
3775
+ const [key, value] = field;
3776
+ fields[key] = key === "segname" || key === "sectname" ? value : numeric(value) ?? value;
3777
+ }
3778
+ return {
3779
+ values: fields,
3780
+ rows
3781
+ };
3782
+ };
3783
+ parseField = (rawLine) => {
3784
+ const line = rawLine.trim();
3785
+ const match = /^((?:time stamp)|\S+(?:\s+version)?)(?:\s+(.+))?$/u.exec(line);
3786
+ return match?.[1] === undefined ? undefined : [match[1], match[2]?.trim() ?? ""];
3787
+ };
3788
+ requireUniqueField = (parsed, key) => {
3789
+ const matches = parsed.rows.filter((field) => field?.[0] === key);
3790
+ const field = matches[0];
3791
+ if (matches.length !== 1 || field === undefined) throw new TypeError(`otool field ${key} is missing or repeated`);
3792
+ if (field[1] === "" && !EMPTY_VALUE_FIELDS.has(key)) throw new TypeError(`otool field ${key} has no value`);
3793
+ };
3794
+ parseSegment = (block, fields) => ({
3795
+ name: nonEmptyName(stringField(fields, "segname")),
3796
+ vm_address: hexField(fields, "vmaddr"),
3797
+ vm_size: numberField(fields, "vmsize"),
3798
+ file_offset: numberField(fields, "fileoff"),
3799
+ file_size: numberField(fields, "filesize"),
3800
+ maximum_permissions: permissions(stringField(fields, "maxprot")),
3801
+ initial_permissions: permissions(stringField(fields, "initprot")),
3802
+ sections: parseSections(block)
3803
+ });
3804
+ parseSections = (block) => block.split(/(?=\n\s*Section\n)/u).slice(1).map((sectionBlock) => {
3805
+ const parsed = parseFields(`Section${sectionBlock}`);
3806
+ const fields = parsed.values;
3807
+ for (const key of [
3808
+ "sectname",
3809
+ "segname",
3810
+ "addr",
3811
+ "size",
3812
+ "offset",
3813
+ "align",
3814
+ "flags"
3815
+ ]) requireUniqueField(parsed, key);
3816
+ return {
3817
+ segment: nonEmptyName(stringField(fields, "segname")),
3818
+ name: nonEmptyName(stringField(fields, "sectname")),
3819
+ address: hexField(fields, "addr"),
3820
+ size: numberField(fields, "size"),
3821
+ file_offset: numberField(fields, "offset"),
3822
+ alignment: sectionAlignment(stringField(fields, "align")),
3823
+ flags: (stringField(fields, "flags") ?? "").split(/\s+/u).filter((flag) => flag.length > 0)
3824
+ };
3825
+ });
3826
+ parseBuildTools = (block) => {
3827
+ const tools = [];
3828
+ const lines = block.split(/\r?\n/u).map((line) => line.trim());
3829
+ for (let index = 0; index < lines.length - 1; index += 1) {
3830
+ const tool = /^tool\s+(.+)$/u.exec(lines[index] ?? "")?.[1];
3831
+ const version = /^version\s+(.+)$/u.exec(lines[index + 1] ?? "")?.[1];
3832
+ if (tool !== undefined && version !== undefined) tools.push({
3833
+ name: BUILD_TOOL_NAMES.get(tool) ?? tool,
3834
+ version
3835
+ });
3836
+ }
3837
+ return tools;
3838
+ };
3839
+ permissions = (raw) => {
3840
+ if (raw === null) return {
3841
+ read: null,
3842
+ write: null,
3843
+ execute: null,
3844
+ raw: null
3845
+ };
3846
+ const numericValue = numeric(raw);
3847
+ if (numericValue !== null) return {
3848
+ read: (numericValue & 1) !== 0,
3849
+ write: (numericValue & 2) !== 0,
3850
+ execute: (numericValue & 4) !== 0,
3851
+ raw
3852
+ };
3853
+ if (/^[r-][w-][x-]$/u.test(raw)) return {
3854
+ read: raw[0] === "r",
3855
+ write: raw[1] === "w",
3856
+ execute: raw[2] === "x",
3857
+ raw
3858
+ };
3859
+ return {
3860
+ read: null,
3861
+ write: null,
3862
+ execute: null,
3863
+ raw
3864
+ };
3865
+ };
3866
+ NUMERIC_PATTERN = /^(?:0x[a-fA-F0-9]+|\d+)$/u;
3867
+ numeric = (value) => {
3868
+ if (!NUMERIC_PATTERN.test(value)) return null;
3869
+ const parsed = Number.parseInt(value, value.startsWith("0x") ? 16 : 10);
3870
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
3871
+ };
3872
+ nonEmptyName = (name) => name === null || name.length === 0 ? "unknown" : name;
3873
+ stringField = (fields, name) => {
3874
+ const value = fields[name];
3875
+ return typeof value === "string" ? value : value === undefined || value === null ? null : String(value);
3876
+ };
3877
+ numberField = (fields, name) => {
3878
+ const value = fields[name];
3879
+ return typeof value === "number" ? value : typeof value === "string" ? numeric(value) : null;
3880
+ };
3881
+ hexField = (fields, name) => {
3882
+ const value = stringField(fields, name);
3883
+ if (value === null || !NUMERIC_PATTERN.test(value)) return null;
3884
+ return `0x${BigInt(value).toString(16)}`;
3885
+ };
3886
+ stripOffsetSuffix = (value) => value?.replace(/\s+\(offset\s+\d+\)$/u, "") ?? "unknown";
3887
+ sectionAlignment = (raw) => {
3888
+ if (raw === null) return null;
3889
+ const exponent = numeric(/^2\^(\d+)(?:\s+\(\d+\))?$/u.exec(raw)?.[1] ?? raw);
3890
+ return exponent === null || exponent > 52 ? null : 2 ** exponent;
3891
+ };
3892
+ })))();
3893
+ }
3894
+
3895
+ //#endregion
3896
+ //#region dist/native/parsers/machoUuid.js
3897
+ var MACHO_UUID, reconcileMachoUuid, parseDwarfdumpUuid, parseDwarfdumpRows, selectDwarfdumpRow, loadCommandUuid, reconcileObservations;
3898
+ function init_machoUuid() {
3899
+ return (init_machoUuid = __esmMin((() => {
3900
+ MACHO_UUID = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu;
3901
+ reconcileMachoUuid = (commands, dwarfdumpOutput, artifactPath, selectedArchitecture) => reconcileObservations(loadCommandUuid(commands), parseDwarfdumpUuid(dwarfdumpOutput, artifactPath, selectedArchitecture));
3902
+ parseDwarfdumpUuid = (output, artifactPath, selectedArchitecture) => {
3903
+ const parsed = parseDwarfdumpRows(output, artifactPath);
3904
+ return parsed.kind === "invalid" ? parsed : selectDwarfdumpRow(parsed.rows, selectedArchitecture);
3905
+ };
3906
+ parseDwarfdumpRows = (output, artifactPath) => {
3907
+ if (output.trim().length === 0) return {
3908
+ kind: "rows",
3909
+ rows: []
3910
+ };
3911
+ const header = /UUID:[ \t]*([^\s]+)[ \t]+\(([^)\r\n]+)\) /uy;
3912
+ const rows = [];
3913
+ let offset = 0;
3914
+ while (offset < output.length) {
3915
+ if (output.startsWith("\r\n", offset)) {
3916
+ offset += 2;
3917
+ continue;
3918
+ }
3919
+ if (output[offset] === "\n") {
3920
+ offset += 1;
3921
+ continue;
3922
+ }
3923
+ header.lastIndex = offset;
3924
+ const match = header.exec(output);
3925
+ if (match === null) return {
3926
+ kind: "invalid",
3927
+ reason: "dwarfdump --uuid output contains an unrecognized row"
3928
+ };
3929
+ const value = match[1] ?? "";
3930
+ const architecture = match[2] ?? "";
3931
+ offset = header.lastIndex;
3932
+ if (!output.startsWith(artifactPath, offset)) return {
3933
+ kind: "invalid",
3934
+ reason: `dwarfdump --uuid row does not match the selected artifact path (UUID ${JSON.stringify(value)})`
3935
+ };
3936
+ offset += artifactPath.length;
3937
+ if (offset < output.length && output.startsWith("\r\n", offset)) offset += 2;
3938
+ else if (output[offset] === "\n") offset += 1;
3939
+ else if (offset !== output.length) return {
3940
+ kind: "invalid",
3941
+ reason: `dwarfdump --uuid returned malformed UUID row ${JSON.stringify(value)}`
3942
+ };
3943
+ rows.push({
3944
+ value,
3945
+ architecture
3946
+ });
3947
+ }
3948
+ return {
3949
+ kind: "rows",
3950
+ rows
3951
+ };
3952
+ };
3953
+ selectDwarfdumpRow = (rows, selectedArchitecture) => {
3954
+ if (rows.length === 0) return { kind: "absent" };
3955
+ const selectedRows = selectedArchitecture === null ? rows : rows.filter(({ architecture }) => architecture === selectedArchitecture);
3956
+ const validRows = selectedRows.filter(({ value }) => MACHO_UUID.test(value));
3957
+ const distinctValid = new Set(validRows.map(({ value }) => value.toLowerCase()));
3958
+ if (distinctValid.size > 1) return {
3959
+ kind: "conflict",
3960
+ reason: `dwarfdump --uuid returned conflicting UUIDs for selected architecture ${selectedArchitecture ?? "unknown"}`
3961
+ };
3962
+ if (selectedRows.length !== 1) return {
3963
+ kind: "invalid",
3964
+ reason: selectedRows.length > 1 ? `dwarfdump --uuid returned multiple rows for selected architecture ${selectedArchitecture}` : `dwarfdump --uuid returned no row for selected architecture ${selectedArchitecture}`
3965
+ };
3966
+ const [row] = selectedRows;
3967
+ if (row === undefined) return { kind: "absent" };
3968
+ if (!MACHO_UUID.test(row.value)) return {
3969
+ kind: "invalid",
3970
+ reason: `dwarfdump --uuid returned malformed UUID ${JSON.stringify(row.value)}`
3971
+ };
3972
+ return {
3973
+ kind: "valid",
3974
+ value: row.value
3975
+ };
3976
+ };
3977
+ loadCommandUuid = (commands) => {
3978
+ const loadCommands = commands.filter(({ kind }) => kind === "LC_UUID");
3979
+ if (loadCommands.length === 0) return { kind: "absent" };
3980
+ if (loadCommands.length > 1) {
3981
+ const observed = loadCommands.map(({ fields }) => fields.uuid).filter((value) => typeof value === "string" && MACHO_UUID.test(value));
3982
+ const distinct = new Set(observed.map((value) => value.toLowerCase()));
3983
+ return {
3984
+ kind: distinct.size > 1 ? "conflict" : "invalid",
3985
+ reason: distinct.size > 1 ? `otool returned conflicting LC_UUID values ${observed.map((value) => JSON.stringify(value)).join(" and ")}` : `otool returned ${String(loadCommands.length)} LC_UUID commands`
3986
+ };
3987
+ }
3988
+ const value = loadCommands[0]?.fields.uuid;
3989
+ return typeof value === "string" && MACHO_UUID.test(value) ? {
3990
+ kind: "valid",
3991
+ value
3992
+ } : {
3993
+ kind: "invalid",
3994
+ reason: `otool LC_UUID contains malformed UUID ${JSON.stringify(value ?? null)}`
3995
+ };
3996
+ };
3997
+ reconcileObservations = (loadUuid, dwarfdump) => {
3998
+ if (dwarfdump.kind === "valid" && loadUuid.kind === "valid") {
3999
+ if (dwarfdump.value.toLowerCase() === loadUuid.value.toLowerCase()) return {
4000
+ value: dwarfdump.value,
4001
+ limitations: []
4002
+ };
4003
+ return {
4004
+ value: null,
4005
+ limitations: [`dwarfdump --uuid (${dwarfdump.value}) conflicts with otool LC_UUID (${loadUuid.value}); the image UUID is unknown.`]
4006
+ };
4007
+ }
4008
+ if (dwarfdump.kind === "valid" && loadUuid.kind === "conflict") return {
4009
+ value: null,
4010
+ limitations: [loadUuid.reason]
4011
+ };
4012
+ if (loadUuid.kind === "valid" && dwarfdump.kind === "conflict") return {
4013
+ value: null,
4014
+ limitations: [dwarfdump.reason]
4015
+ };
4016
+ if (dwarfdump.kind === "valid") return {
4017
+ value: dwarfdump.value,
4018
+ limitations: loadUuid.kind === "invalid" ? [`${loadUuid.reason}; using the unambiguous dwarfdump UUID.`] : []
4019
+ };
4020
+ if (loadUuid.kind === "valid") return {
4021
+ value: loadUuid.value,
4022
+ limitations: dwarfdump.kind === "invalid" ? [`${dwarfdump.reason}; using the unambiguous otool LC_UUID.`] : []
4023
+ };
4024
+ return {
4025
+ value: null,
4026
+ limitations: [...dwarfdump.kind === "invalid" || dwarfdump.kind === "conflict" ? [dwarfdump.reason] : [], ...loadUuid.kind === "invalid" || loadUuid.kind === "conflict" ? [loadUuid.reason] : []]
4027
+ };
4028
+ };
4029
+ })))();
4030
+ }
4031
+
4032
+ //#endregion
4033
+ //#region dist/native/NativeMachoInspection.js
4034
+ var DISCOVERY_COMMANDS, SYMBOL_TABLE_EXPORTS, DYLD_INFO_EXPORTS, REQUIRED_SLICE_COMMANDS, OPTIONAL_VTOOL_COMMAND, VTOOL_UNAVAILABLE_LIMITATION, inspectNativeMacho, normalizeMacho, sliceOutput, captureLookup, namesEveryExport, parseNmExports, covered, uniqueSymbols, fileOffsetLocations, architectureLocations, selectedArchitectureArguments, selectArchitecture;
4035
+ function init_NativeMachoInspection() {
4036
+ return (init_NativeMachoInspection = __esmMin((() => {
4037
+ init_analysisErrorCore();
4038
+ init_nativeInspection();
4039
+ init_jsonValue();
4040
+ init_result();
4041
+ init_MachoArchitectureSelection();
4042
+ init_dyldInfo();
4043
+ init_lipo();
4044
+ init_echoedPath();
4045
+ init_otool();
4046
+ init_machoUuid();
4047
+ init_unicodeCodePointOrder();
4048
+ DISCOVERY_COMMANDS = [["lipo", ["-detailed_info"]]];
4049
+ SYMBOL_TABLE_EXPORTS = ["nm", ["-gjU", "--no-dyldinfo"]];
4050
+ DYLD_INFO_EXPORTS = ["nm", ["-gjU"]];
4051
+ REQUIRED_SLICE_COMMANDS = [
4052
+ ["otool", ["-h", "-l"]],
4053
+ SYMBOL_TABLE_EXPORTS,
4054
+ ["dyld_info", ["-imports"]],
4055
+ ["dyld_info", ["-exports"]],
4056
+ ["dwarfdump", ["--uuid"]]
4057
+ ];
4058
+ OPTIONAL_VTOOL_COMMAND = ["vtool", ["-show-build"]];
4059
+ VTOOL_UNAVAILABLE_LIMITATION = "vtool is unavailable; build metadata is normalized from otool only.";
4060
+ inspectNativeMacho = async (context) => {
4061
+ const captures = [];
4062
+ for (const [tool, prefix] of DISCOVERY_COMMANDS) {
4063
+ const captured = await context.run(tool, [...prefix, context.target.path], context.signal);
4064
+ if (!captured.ok) return err(captured.error);
4065
+ captures.push(captured.value);
4066
+ }
4067
+ const lipo = captures.find(({ tool }) => tool === "lipo");
4068
+ if (lipo === undefined) throw new TypeError("Missing lipo capture");
4069
+ const { format, architectures } = parseLipoOutput(lipo.stdout, context.target.path);
4070
+ const selection = selectArchitecture(context.target, architectures);
4071
+ if (selection.status === "absent") return err(new AnalysisOutputError("inspect_macho", `lipo did not list ${selection.architecture}; refusing to read another slice`));
4072
+ const selectedArchitecture = selection.status === "selected" ? selection.architecture : null;
4073
+ const runSliceCommand = ([tool, prefix]) => context.run(tool, [
4074
+ ...prefix,
4075
+ ...selectedArchitectureArguments(tool, selectedArchitecture),
4076
+ context.target.path
4077
+ ], context.signal);
4078
+ const [required, optional] = await Promise.all([Promise.all(REQUIRED_SLICE_COMMANDS.map(runSliceCommand)), runSliceCommand(OPTIONAL_VTOOL_COMMAND)]);
4079
+ for (const captured of required) {
4080
+ if (!captured.ok) return err(captured.error);
4081
+ captures.push(captured.value);
4082
+ }
4083
+ const limitations = [];
4084
+ if (optional.ok) captures.push(optional.value);
4085
+ else if (optional.error._tag === "AnalysisCapabilityUnavailableError") limitations.push(VTOOL_UNAVAILABLE_LIMITATION);
4086
+ else return err(optional.error);
4087
+ const nmIndex = captures.findIndex(({ tool }) => tool === "nm");
4088
+ const dyldExports = captures.filter(({ tool }) => tool === "dyld_info")[1];
4089
+ if (nmIndex < 0 || dyldExports === undefined) throw new TypeError("Missing nm or dyld_info export capture");
4090
+ if (!namesEveryExport(captures[nmIndex].stdout, dyldExports)) {
4091
+ const withDyldInfo = await runSliceCommand(DYLD_INFO_EXPORTS);
4092
+ if (!withDyldInfo.ok) return err(withDyldInfo.error);
4093
+ captures[nmIndex] = withDyldInfo.value;
4094
+ }
4095
+ const otool = captures.find(({ tool }) => tool === "otool");
4096
+ if (otool === undefined) throw new TypeError("Missing otool capture");
4097
+ let load;
4098
+ try {
4099
+ load = parseOtoolLoadCommands(sliceOutput(otool));
4100
+ } catch (cause) {
4101
+ return err(new AnalysisOutputError("inspect_macho", "Malformed otool load-command output", {
4102
+ cause,
4103
+ capturedOutput: {
4104
+ stdout: otool.stdout,
4105
+ stderr: otool.stderr,
4106
+ truncated: false,
4107
+ stdout_bytes: otool.stdoutBytes,
4108
+ stderr_bytes: otool.stderrBytes,
4109
+ exit_code: otool.exitCode,
4110
+ signal: otool.signal
4111
+ }
4112
+ }));
4113
+ }
4114
+ const selectedArchitectureName = selectedArchitecture ?? (architectures.length === 1 ? architectures[0]?.name ?? null : null);
4115
+ const containerOffset = selectedArchitectureName === null ? undefined : format === "thin" ? 0 : architectures.find(({ name }) => name === selectedArchitectureName)?.file_offset ?? undefined;
4116
+ const normalized = normalizeMacho(captures, context.invocation, limitations, load, architectures, context.target.path, {
4117
+ name: selectedArchitectureName,
4118
+ container_file_offset: containerOffset ?? null
4119
+ });
4120
+ const result = containerOffset === undefined ? inspectMachoSchema.parse({
4121
+ ...normalized,
4122
+ limitations: [...normalized.limitations, selectedArchitectureName === null ? "The selected Mach-O slice is unknown; slice-based evidence locations are unavailable." : "The selected Mach-O slice's container file offset was not observed; slice-based evidence locations are unavailable."]
4123
+ }) : normalized;
4124
+ return ok({
4125
+ result: jsonValueSchema.parse(result),
4126
+ limitations: result.limitations,
4127
+ locations: fileOffsetLocations(result, containerOffset)
4128
+ });
4129
+ };
4130
+ normalizeMacho = (captures, toInvocation, additionalLimitations, load, architectures, artifactPath, selectedArchitecture) => {
4131
+ const byTool = captureLookup(captures);
4132
+ const imports = parseDyldSymbols(sliceOutput(byTool("dyld_info", 0)), "imports");
4133
+ const imageBase = load.segments.find((segment) => segment.file_offset === 0 && (segment.file_size ?? 0) > 0)?.vm_address ?? null;
4134
+ const nmExports = parseNmExports(byTool("nm").stdout);
4135
+ const dyldExports = parseDyldSymbols(sliceOutput(byTool("dyld_info", 1)), "exports", imageBase, new Set(nmExports.map(({ name }) => name)));
4136
+ const exports = uniqueSymbols([...dyldExports, ...nmExports]);
4137
+ const dwarfdump = byTool("dwarfdump");
4138
+ const uuid = reconcileMachoUuid(load.commands, dwarfdump.stdout, artifactPath, selectedArchitecture.name);
4139
+ const provenance = captures.map(toInvocation);
4140
+ const threadEntrypoint = load.entrypoints.length === 0 && load.commands.some((command) => command.kind === "LC_UNIXTHREAD" || command.kind === "LC_THREAD");
4141
+ const threadEntrypointLimitation = "Thread-state entrypoints (LC_UNIXTHREAD/LC_THREAD) are retained as raw load commands; file offsets are not derived.";
4142
+ const limitations = [
4143
+ "Imports and exports combine dyld_info and nm; stripped or toolchain-hidden symbols may be absent.",
4144
+ ...captures.some(({ tool }) => tool === "vtool") ? ["vtool output is retained as provenance but only otool build metadata is normalized."] : [],
4145
+ ...additionalLimitations,
4146
+ ...uuid.limitations,
4147
+ ...threadEntrypoint ? [threadEntrypointLimitation] : [],
4148
+ ...imageBase === null && /^\s*offset\s+symbol\s*$/mu.test(sliceOutput(byTool("dyld_info", 1))) ? ["Export virtual addresses are unavailable because no file-backed image base was observed."] : []
4149
+ ];
4150
+ return inspectMachoSchema.parse({
4151
+ format: "mach-o",
4152
+ selected_architecture: selectedArchitecture,
4153
+ endian: load.endian,
4154
+ word_size: load.wordSize,
4155
+ file_type: load.fileType,
4156
+ flags: load.flags,
4157
+ uuid: uuid.value,
4158
+ entrypoints: covered(load.entrypoints, !threadEntrypoint, threadEntrypoint ? [threadEntrypointLimitation] : []),
4159
+ architectures: covered(architectures, true),
4160
+ build_metadata: covered(load.builds, true),
4161
+ load_commands: covered(load.commands, true),
4162
+ dependencies: covered(load.dependencies, true),
4163
+ imports: covered(imports, false, ["dyld_info textual imports may omit chained or toolchain-unsupported metadata."]),
4164
+ exports: covered(exports, false, ["Merged nm/dyld_info results may be incomplete for stripped binaries.", ...dyldExports.some(({ sourceSymbol }) => sourceSymbol !== undefined) ? ["Renamed re-exports are listed under their exported name; the source library's symbol name is not reported."] : []]),
4165
+ segments: covered(load.segments.map((segment) => ({
4166
+ ...segment,
4167
+ sections: covered(segment.sections, true)
4168
+ })), true),
4169
+ provenance,
4170
+ limitations
4171
+ });
4172
+ };
4173
+ sliceOutput = (capture) => withoutEchoedPathHeader(capture.stdout, capture.arguments.at(-1));
4174
+ captureLookup = (captures) => (tool, occurrence = 0) => {
4175
+ const capture = captures.filter((item) => item.tool === tool)[occurrence];
4176
+ if (capture === undefined) throw new TypeError(`Missing ${tool} capture`);
4177
+ return capture;
4178
+ };
4179
+ namesEveryExport = (nmOutput, dyldExports) => {
4180
+ const names = new Set(parseNmExports(nmOutput).map(({ name }) => name));
4181
+ return sliceOutput(dyldExports).split(/\r?\n/u).every((rawLine, index) => {
4182
+ const line = rawLine.trim();
4183
+ if (line.length === 0 || index === 0 && line.endsWith(":") || /^-?exports:$/u.test(line) || /^offset\s+symbol$/u.test(line)) return true;
4184
+ const rows = parseDyldSymbols(line, "exports", null, names);
4185
+ if (rows.length === 0) return names.has(/^0x[\da-f]+\s+(.+)$/iu.exec(line)?.[1] ?? "");
4186
+ return rows.length === 1 && names.has(rows[0].name);
4187
+ });
4188
+ };
4189
+ parseNmExports = (output) => output.split(/\r?\n/u).filter((name) => name.length > 0).map((name) => ({
4190
+ name,
4191
+ address: null,
4192
+ weak: null,
4193
+ reexport: null,
4194
+ source: "nm"
4195
+ }));
4196
+ covered = (items, exhaustive, limitations = []) => ({
4197
+ items: [...items],
4198
+ total: exhaustive ? items.length : null,
4199
+ exhaustive,
4200
+ limitations: [...limitations]
4201
+ });
4202
+ uniqueSymbols = (items) => {
4203
+ const unique = new Map();
4204
+ for (const item of items) if (!unique.has(item.name)) unique.set(item.name, item);
4205
+ return [...unique.values()].sort((left, right) => compareUnicodeCodePoints(left.name, right.name));
4206
+ };
4207
+ fileOffsetLocations = (macho, containerOffset) => {
4208
+ const locations = architectureLocations(macho.architectures.items);
4209
+ if (containerOffset === undefined) return locations;
4210
+ for (const entrypoint of macho.entrypoints.items) locations.push({
4211
+ kind: "file-offset",
4212
+ offset: containerOffset + entrypoint.file_offset
4213
+ });
4214
+ for (const segment of macho.segments.items) {
4215
+ if (segment.file_offset === null || segment.file_size === null || segment.file_size === 0) continue;
4216
+ locations.push({
4217
+ kind: "file-offset-range",
4218
+ start: containerOffset + segment.file_offset,
4219
+ end: containerOffset + segment.file_offset + segment.file_size
4220
+ });
4221
+ }
4222
+ return locations;
4223
+ };
4224
+ architectureLocations = (architectures) => {
4225
+ const locations = [];
4226
+ for (const { file_offset: offset, size } of architectures) {
4227
+ if (offset === null) continue;
4228
+ locations.push(size === null ? {
4229
+ kind: "file-offset",
4230
+ offset
4231
+ } : {
4232
+ kind: "file-offset-range",
4233
+ start: offset,
4234
+ end: offset + size
4235
+ });
4236
+ }
4237
+ return locations;
4238
+ };
4239
+ selectedArchitectureArguments = (tool, architecture) => {
4240
+ if (architecture === null) return [];
4241
+ const baseArchitecture = architecture.split(".")[0] ?? architecture;
4242
+ const toolArchitecture = tool === "dyld_info" ? architecture : baseArchitecture;
4243
+ return tool === "dwarfdump" ? [`--arch=${toolArchitecture}`] : ["-arch", toolArchitecture];
4244
+ };
4245
+ selectArchitecture = (target, available) => {
4246
+ if (target.kind !== "executable" || target.availableArchitectures.length < 2 && available.length < 2) return { status: "unfiltered" };
4247
+ const normalized = target.architecture === "x86" ? "i386" : target.architecture;
4248
+ const policy = MACHO_ARCHITECTURE_POLICIES[target.architecture];
4249
+ const selected = policy === undefined ? available.find(({ name }) => name === normalized)?.name : selectMachoArchitectureName(policy, available);
4250
+ if (selected !== undefined) return {
4251
+ status: "selected",
4252
+ architecture: selected
4253
+ };
4254
+ return {
4255
+ status: "absent",
4256
+ architecture: normalized
4257
+ };
4258
+ };
4259
+ })))();
4260
+ }
4261
+
4262
+ //#endregion
4263
+ //#region dist/native/NativeMacOSProvider.js
4264
+ var NativeMacOSProvider, NativeMacOSClient, nativeCommandCleanupFailure, isNativeOperation, translateCommandFailure, translateCodeSignExitFailure, commandOutput, isNonzeroUnsignedObservation, canonicalPath, codeSignCaptureFailure, codeSignArchitectures, invocation, parseEntitlements, unreadablePlist, plutilDiagnostic, requireRegularPlist, resolvePlistPath;
4265
+ function init_NativeMacOSProvider() {
4266
+ return (init_NativeMacOSProvider = __esmMin((() => {
4267
+ init_snapshotEnvironment();
4268
+ init_NativeMacOSProviderMetadata();
4269
+ init_AppleDispatchMetadata();
4270
+ init_NativeUiObservation();
4271
+ init_LldbCallTracer();
4272
+ init_NativeCallObservation();
4273
+ init_AnalysisProvider();
4274
+ init_nativeToolContracts();
4275
+ init_binaryTargetTypes();
4276
+ init_toolContracts();
4277
+ init_inputIssueProjection();
4278
+ init_analysisErrorCore();
4279
+ init_configurationErrors();
4280
+ init_providerAdapterError();
4281
+ init_providerCleanupError();
4282
+ init_analysisErrorBase();
4283
+ init_jsonValue();
4284
+ init_propertyListKeys();
4285
+ init_nativeInspection();
4286
+ init_result();
4287
+ init_CommandRunner();
4288
+ init_SignatureTargetBinding();
4289
+ init_codesign();
4290
+ init_demangle();
4291
+ init_lipo();
4292
+ init_plist();
4293
+ init_NativeMachoInspection();
4294
+ init_analysisErrorCleanup();
4295
+ init_ArtifactResourceScope();
4296
+ init_ArtifactReader();
4297
+ init_NativeUiHelperRuntime();
4298
+ NativeMacOSProvider = class {
4299
+ runner;
4300
+ #capabilities;
4301
+ #environment;
4302
+ #tracerFactory;
4303
+ #privateRuntimeRootFactory;
4304
+ constructor(environment, runner = new XcrunCommandRunner(environment), platform = process.platform, tracerFactory, privateRuntimeRootFactory) {
4305
+ this.runner = runner;
4306
+ this.#environment = snapshotEnvironment(environment, platform);
4307
+ this.#tracerFactory = tracerFactory ?? (() => new LldbCallTracer(this.#environment));
4308
+ this.#privateRuntimeRootFactory = privateRuntimeRootFactory;
4309
+ this.#capabilities = nativeMacOSCapabilities(platform);
4310
+ }
4311
+ identity() {
4312
+ return NATIVE_MACOS_PROVIDER_IDENTITY;
4313
+ }
4314
+ capabilities() {
4315
+ return this.#capabilities;
4316
+ }
4317
+ createClient(target) {
4318
+ return new NativeMacOSClient(target, this.runner, this.#tracerFactory(), this.#environment, this.#privateRuntimeRootFactory);
4319
+ }
4320
+ };
4321
+ NativeMacOSClient = class {
4322
+ target;
4323
+ runner;
4324
+ tracer;
4325
+ environment;
4326
+ privateRuntimeRootFactory;
4327
+ #pendingNativeUiRuntimes = new Set();
4328
+ #pendingCommands = new Set();
4329
+ #signatureResources = new ArtifactResourceScope();
4330
+ #nativeUiTail = Promise.resolve();
4331
+ #closed = false;
4332
+ constructor(target, runner, tracer, environment, privateRuntimeRootFactory) {
4333
+ this.target = target;
4334
+ this.runner = runner;
4335
+ this.tracer = tracer;
4336
+ this.environment = environment;
4337
+ this.privateRuntimeRootFactory = privateRuntimeRootFactory;
4338
+ }
4339
+ async execute(operation, parameters, options) {
4340
+ if (this.#closed) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, "Native provider client is closed"));
4341
+ if (options?.signal?.aborted === true) return err(new AnalysisCancelledError(operation));
4342
+ if (operation === "health") return ok(createAnalysisExecution(null, NATIVE_MACOS_PROVIDER_IDENTITY));
4343
+ if (operation === "inspect_native_dispatch_metadata") {
4344
+ const input = toolContract(operation).inputSchema.safeParse(parameters);
4345
+ if (!input.success) return err(analysisInputErrorFromIssues(operation, input.error.issues, parameters, { cause: input.error }));
4346
+ if (this.target.kind !== "executable" || !isMachOFormat(this.target.format)) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, "Binary Apple metadata requires Mach-O; other providers can report symbol-only metadata"));
4347
+ try {
4348
+ const result = await inspectAppleDispatchMetadata(this.target, input.data.max_records, options?.signal);
4349
+ return ok(createAnalysisExecution(result, result.provider, {
4350
+ locations: [{
4351
+ kind: "artifact-path",
4352
+ path: this.target.path
4353
+ }],
4354
+ limitations: result.result.coverage.flatMap(({ reason }) => reason === null ? [] : [reason])
4355
+ }));
4356
+ } catch (cause) {
4357
+ if (cause instanceof AnalysisError) return err(cause);
4358
+ return err(options?.signal?.aborted ? new AnalysisCancelledError(operation) : new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, {
4359
+ cause,
4360
+ diagnostics: {
4361
+ target_path: this.target.path,
4362
+ reason: cause instanceof Error ? cause.message : String(cause)
4363
+ }
4364
+ }));
4365
+ }
4366
+ }
4367
+ if (!isNativeOperation(operation)) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, "Operation is not implemented by native macOS tools."));
4368
+ if (operation === "observe_native_calls") {
4369
+ const result = await observeNativeCalls(this.target, parameters, this.tracer, options?.signal);
4370
+ return result.ok ? ok(createAnalysisExecution(result.value, NATIVE_MACOS_PROVIDER_IDENTITY, {
4371
+ limitations: result.value.limitations,
4372
+ locations: [{
4373
+ kind: "artifact-path",
4374
+ path: this.target.path
4375
+ }]
4376
+ })) : result;
4377
+ }
4378
+ if (operation === "observe_native_ui" || operation === "capture_native_ui_scenario") {
4379
+ return this.#observeNativeUi(operation, parameters, options?.signal);
4380
+ }
4381
+ try {
4382
+ const observation = await this.#dispatch(operation, parameters, options?.signal);
4383
+ return observation.ok ? ok(createAnalysisExecution(observation.value.result, NATIVE_MACOS_PROVIDER_IDENTITY, {
4384
+ limitations: observation.value.limitations,
4385
+ locations: observation.value.locations
4386
+ })) : observation;
4387
+ } catch (cause) {
4388
+ return err(new AnalysisOutputError(operation, "Native output parsing failed", { cause }));
4389
+ }
4390
+ }
4391
+ async close() {
4392
+ this.#closed = true;
4393
+ await Promise.allSettled(this.#pendingCommands);
4394
+ const uiCleanupFailures = await this.#serializeNativeUi(() => this.#retryNativeUiCleanup());
4395
+ let signatureCleanup;
4396
+ try {
4397
+ await this.#signatureResources.close();
4398
+ } catch (cause) {
4399
+ const observation = ArtifactReaderFailure.cleanupObservation(cause, "signature-snapshot");
4400
+ signatureCleanup = new ProviderCleanupError(NATIVE_MACOS_PROVIDER_IDENTITY.id, observation.resources, { reason: observation.reason }, {
4401
+ operation: "close_binary",
4402
+ cause
4403
+ });
4404
+ }
4405
+ const commandCleanup = await this.#retryNativeCommandCleanup();
4406
+ let result = await this.tracer.close();
4407
+ const cleanupErrors = [
4408
+ ...uiCleanupFailures.length === 0 ? [] : [this.#nativeUiCleanupFailure(uiCleanupFailures, "close_binary")],
4409
+ ...commandCleanup === undefined ? [] : [commandCleanup],
4410
+ ...signatureCleanup === undefined ? [] : [signatureCleanup]
4411
+ ];
4412
+ for (const cleanupError of cleanupErrors) result = result.ok ? err(cleanupError) : err(analysisErrorWithCleanupFailure(result.error, cleanupError));
4413
+ return result;
4414
+ }
4415
+ #observeNativeUi(operation, parameters, signal) {
4416
+ return this.#serializeNativeUi(async () => {
4417
+ if (this.#closed) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, "Native provider client is closed"));
4418
+ const earlierCleanupFailures = await this.#retryNativeUiCleanup();
4419
+ if (earlierCleanupFailures.length > 0) return err(this.#nativeUiCleanupFailure(earlierCleanupFailures, operation));
4420
+ const runtime = createNativeUiHelperRuntime(this.environment);
4421
+ this.#pendingNativeUiRuntimes.add(runtime);
4422
+ let result;
4423
+ try {
4424
+ result = await observeNativeUi(this.target, operation, parameters, {
4425
+ environment: this.environment,
4426
+ signal,
4427
+ runtime
4428
+ });
4429
+ } catch (cause) {
4430
+ result = err(cause instanceof AnalysisError ? cause : new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, { cause }));
4431
+ }
4432
+ try {
4433
+ await runtime.close();
4434
+ this.#pendingNativeUiRuntimes.delete(runtime);
4435
+ } catch (cause) {
4436
+ const cleanup = this.#nativeUiCleanupFailure([{
4437
+ runtime,
4438
+ cause
4439
+ }], operation, result.ok ? result.value : undefined);
4440
+ return err(result.ok ? cleanup : analysisErrorWithCleanupFailure(result.error, cleanup, operation));
4441
+ }
4442
+ return result.ok ? ok(createAnalysisExecution(result.value, NATIVE_MACOS_PROVIDER_IDENTITY, { limitations: result.value.limitations })) : result;
4443
+ });
4444
+ }
4445
+ #serializeNativeUi(operation) {
4446
+ const call = this.#nativeUiTail.then(operation, operation);
4447
+ this.#nativeUiTail = call.then(() => undefined, () => undefined);
4448
+ return call;
4449
+ }
4450
+ async #retryNativeUiCleanup() {
4451
+ const failures = [];
4452
+ for (const runtime of this.#pendingNativeUiRuntimes) {
4453
+ try {
4454
+ await runtime.close();
4455
+ this.#pendingNativeUiRuntimes.delete(runtime);
4456
+ } catch (cause) {
4457
+ failures.push({
4458
+ runtime,
4459
+ cause
4460
+ });
4461
+ }
4462
+ }
4463
+ return failures;
4464
+ }
4465
+ async #retryNativeCommandCleanup() {
4466
+ if (this.runner.retryCleanup === undefined) return undefined;
4467
+ try {
4468
+ const failures = await this.runner.retryCleanup();
4469
+ return failures.length === 0 ? undefined : nativeCommandCleanupFailure(failures);
4470
+ } catch (cause) {
4471
+ return new ProviderCleanupError(NATIVE_MACOS_PROVIDER_IDENTITY.id, ["native-command-process-cleanup"], { reason: cause instanceof Error ? cause.message || cause.name : String(cause) || "native command cleanup failed unexpectedly" }, { cause });
4472
+ }
4473
+ }
4474
+ #nativeUiCleanupFailure(failures, operation, partialObservation) {
4475
+ const resources = failures.flatMap(({ runtime }) => runtime.resources());
4476
+ return new ProviderCleanupError(NATIVE_MACOS_PROVIDER_IDENTITY.id, resources.length === 0 ? ["native-ui-runtime"] : resources, {
4477
+ reason: "Native UI runtime cleanup remains incomplete",
4478
+ failures: failures.map(({ runtime, cause }) => ({
4479
+ resources: [...runtime.resources()],
4480
+ reason: cause instanceof Error ? cause.message : String(cause)
4481
+ }))
4482
+ }, {
4483
+ operation,
4484
+ cause: new AggregateError(failures.map(({ cause }) => cause), "Native UI runtime cleanup failed"),
4485
+ ...partialObservation === undefined ? {} : { partialObservation }
4486
+ });
4487
+ }
4488
+ #dispatch(operation, parameters, signal) {
4489
+ switch (operation) {
4490
+ case "observe_native_ui":
4491
+ case "capture_native_ui_scenario":
4492
+ case "observe_native_calls": return Promise.resolve(err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, "UI observation uses its explicit authority boundary")));
4493
+ case "inspect_macho": return this.#inspectMacho(signal);
4494
+ case "inspect_signature": return this.#inspectSignature(signal);
4495
+ case "inspect_plist": return this.#inspectPlist(parameters, signal);
4496
+ case "list_architectures": return this.#listArchitectures(signal);
4497
+ case "demangle_swift": return this.#demangle(parameters, signal);
4498
+ }
4499
+ }
4500
+ async #listArchitectures(signal) {
4501
+ if (!isMachOFormat(this.target.format)) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "list_architectures", "Active artifact is not Mach-O."));
4502
+ const capture = await this.#run("list_architectures", "lipo", ["-detailed_info", this.target.path], { signal });
4503
+ if (!capture.ok) return capture;
4504
+ const provenance = [invocation(capture.value, this.target.path)];
4505
+ const { architectures } = parseLipoOutput(capture.value.stdout, this.target.path);
4506
+ const result = listArchitecturesSchema.parse({
4507
+ architectures: {
4508
+ items: architectures,
4509
+ total: architectures.length,
4510
+ exhaustive: true,
4511
+ limitations: []
4512
+ },
4513
+ provenance,
4514
+ limitations: []
4515
+ });
4516
+ return ok({
4517
+ result: jsonValueSchema.parse(result),
4518
+ limitations: [],
4519
+ locations: architectureLocations(result.architectures.items)
4520
+ });
4521
+ }
4522
+ async #demangle(parameters, signal) {
4523
+ const symbols = z.array(z.string()).safeParse(parameters.symbols);
4524
+ if (!symbols.success) return err(new AnalysisOutputError("demangle_swift", "symbols were not parsed strings"));
4525
+ const capture = await this.#run("demangle_swift", "swift-demangle", [
4526
+ "--compact",
4527
+ "--",
4528
+ ...symbols.data
4529
+ ], { signal });
4530
+ if (!capture.ok) return capture;
4531
+ const provenance = [invocation(capture.value, this.target.path)];
4532
+ const result = demangleSwiftSchema.parse({
4533
+ symbols: parseDemangledSymbols(symbols.data, capture.value.stdout),
4534
+ provenance,
4535
+ limitations: []
4536
+ });
4537
+ return ok({
4538
+ result: jsonValueSchema.parse(result),
4539
+ limitations: [],
4540
+ locations: []
4541
+ });
4542
+ }
4543
+ async #inspectSignature(signal) {
4544
+ if (this.target.kind !== "executable" || !isMachOFormat(this.target.format)) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_signature", "Active artifact is not Mach-O; its container-level signature layer is not evaluated by codesign."));
4545
+ return withSignatureTarget(this.target, this.#signatureResources, (binding) => this.#inspectBoundSignature(binding, signal), signal, this.privateRuntimeRootFactory);
4546
+ }
4547
+ async #inspectBoundSignature(binding, signal) {
4548
+ const display = await this.#captureSignature(binding, ["-d", "--verbose=4"], signal);
4549
+ if (!display.ok) return display;
4550
+ const unsigned = isNonzeroUnsignedObservation(display.value);
4551
+ const displayFailure = codeSignCaptureFailure(display.value);
4552
+ if (displayFailure !== null) return err(displayFailure);
4553
+ const requirements = await this.#captureSignature(binding, ["-d", "-r-"], signal);
4554
+ if (!requirements.ok) return requirements;
4555
+ const requirementsFailure = codeSignCaptureFailure(requirements.value);
4556
+ if (requirementsFailure !== null) return err(requirementsFailure);
4557
+ const entitlements = await this.#captureSignature(binding, [
4558
+ "-d",
4559
+ "--entitlements",
4560
+ ":-"
4561
+ ], signal);
4562
+ if (!entitlements.ok) return entitlements;
4563
+ const entitlementsFailure = codeSignCaptureFailure(entitlements.value);
4564
+ if (entitlementsFailure !== null) return err(entitlementsFailure);
4565
+ const parsed = parseCodeSignature(display.value.stderr, unsigned, [binding.snapshotPath, ...await canonicalPath(binding.snapshotPath)]);
4566
+ const requirementText = /designated\s*=>\s*(.+)$/mu.exec(requirements.value.stdout)?.[1] ?? null;
4567
+ const entitlementValue = parseEntitlements(entitlements.value.stdout);
4568
+ const captures = [
4569
+ display.value,
4570
+ requirements.value,
4571
+ entitlements.value
4572
+ ];
4573
+ const limitations = [
4574
+ ...parsed.limitations,
4575
+ "Inspected a digest-verified Mach-O byte snapshot; filesystem-bound signing context and trust validation are not examined.",
4576
+ ...entitlementValue.omittedPrototypeKeys === 0 ? [] : [`Entitlements: ${omittedPrototypeKeysLimitation(entitlementValue.omittedPrototypeKeys)}`]
4577
+ ];
4578
+ const mixedSigning = !unsigned && (isNonzeroUnsignedObservation(requirements.value) || isNonzeroUnsignedObservation(entitlements.value));
4579
+ if (mixedSigning) {
4580
+ const slices = await this.#inspectMixedSignatureSlices(binding, parsed.format, {
4581
+ requirements: requirements.value.exitCode,
4582
+ entitlements: entitlements.value.exitCode
4583
+ }, signal);
4584
+ if (!slices.ok) return slices;
4585
+ captures.push(...slices.value.captures);
4586
+ limitations.push(...slices.value.limitations);
4587
+ }
4588
+ const provenance = captures.map((capture) => invocation(capture, binding.snapshotPath));
4589
+ const version = await verifySignatureTarget(this.target, binding, signal);
4590
+ if (!version.ok) return version;
4591
+ const result = inspectSignatureSchema.parse({
4592
+ ...parsed,
4593
+ designated_requirement: requirementText,
4594
+ entitlements: entitlementValue.value,
4595
+ provenance,
4596
+ limitations
4597
+ });
4598
+ return ok({
4599
+ result: jsonValueSchema.parse(result),
4600
+ limitations: result.limitations,
4601
+ locations: []
4602
+ });
4603
+ }
4604
+ async #inspectMixedSignatureSlices(binding, format, aggregateExits, signal) {
4605
+ const captures = [];
4606
+ const unsigned = [];
4607
+ const unclassified = [];
4608
+ for (const architecture of codeSignArchitectures(format, this.target)) {
4609
+ const slice = await this.#captureSignature(binding, [
4610
+ "-d",
4611
+ "-a",
4612
+ architecture,
4613
+ "--verbose=4"
4614
+ ], signal);
4615
+ if (!slice.ok) return slice;
4616
+ captures.push(slice.value);
4617
+ if (slice.value.exitCode === 0) continue;
4618
+ if (isNonzeroUnsignedObservation(slice.value)) unsigned.push(architecture);
4619
+ else unclassified.push(architecture);
4620
+ }
4621
+ const limitations = [unsigned.length > 0 ? `Unsigned Mach-O slices: ${unsigned.join(", ")}.` : "One or more Mach-O slices are unsigned, but their architectures could not be classified."];
4622
+ if (unclassified.length > 0) limitations.push(`Signature state could not be classified for Mach-O slices: ${unclassified.join(", ")}.`);
4623
+ if (aggregateExits.requirements !== 0) limitations.push("The aggregate designated requirement is unavailable because Mach-O slices have mixed signing states.");
4624
+ if (aggregateExits.entitlements !== 0) limitations.push("The aggregate entitlements are unavailable because Mach-O slices have mixed signing states.");
4625
+ return ok({
4626
+ captures,
4627
+ limitations
4628
+ });
4629
+ }
4630
+ async #captureSignature(binding, args, signal) {
4631
+ const before = await verifySignatureTarget(this.target, binding, signal);
4632
+ if (!before.ok) return before;
4633
+ let capture;
4634
+ try {
4635
+ capture = await this.#run("inspect_signature", "codesign", [...args, binding.snapshotPath], {
4636
+ signal,
4637
+ acceptNonZero: true
4638
+ });
4639
+ } catch (cause) {
4640
+ capture = err(new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_signature", {
4641
+ cause,
4642
+ diagnostics: {
4643
+ phase: "codesign-capture",
4644
+ path: this.target.path,
4645
+ reason: cause instanceof Error ? cause.message : String(cause)
4646
+ }
4647
+ }));
4648
+ }
4649
+ const after = await verifySignatureTarget(this.target, binding, signal);
4650
+ return after.ok ? capture : after;
4651
+ }
4652
+ async #inspectPlist(parameters, signal) {
4653
+ const requested = parameters.path;
4654
+ if (requested !== undefined && typeof requested !== "string") return err(new AnalysisOutputError("inspect_plist", "path was not a string"));
4655
+ const plist = await resolvePlistPath(this.target, requested);
4656
+ if (!plist.ok) return plist;
4657
+ const selected = await requireRegularPlist(plist.value, requested);
4658
+ if (!selected.ok) return selected;
4659
+ const classified = await this.#run("inspect_plist", "file", ["-b", plist.value], { signal });
4660
+ if (!classified.ok) return classified;
4661
+ const json = await this.#run("inspect_plist", "plutil", [
4662
+ "-convert",
4663
+ "json",
4664
+ "-o",
4665
+ "-",
4666
+ "--",
4667
+ plist.value
4668
+ ], {
4669
+ signal,
4670
+ acceptNonZero: true
4671
+ });
4672
+ if (!json.ok) return json;
4673
+ const jsonDecoded = json.value.exitCode === 0;
4674
+ const xml = jsonDecoded && !plistJsonNeedsNumberTypes(json.value.stdout) ? undefined : await this.#run("inspect_plist", "plutil", [
4675
+ "-convert",
4676
+ "xml1",
4677
+ "-o",
4678
+ "-",
4679
+ "--",
4680
+ plist.value
4681
+ ], {
4682
+ signal,
4683
+ acceptNonZero: !jsonDecoded
4684
+ });
4685
+ if (xml !== undefined && !xml.ok) return xml;
4686
+ if (xml !== undefined && xml.value.exitCode !== 0) return err(unreadablePlist(plist.value, requested, `plutil could not decode it as a property list (${plutilDiagnostic(xml.value.stderr, plist.value)})`));
4687
+ const parsed = xml === undefined ? parsePlistJson(json.value.stdout) : jsonDecoded ? parsePlistJson(json.value.stdout, xml.value.stdout) : parsePlistXml(xml.value.stdout);
4688
+ if (!parsed.ok) return parsed;
4689
+ const provenance = [
4690
+ classified.value,
4691
+ json.value,
4692
+ ...xml === undefined ? [] : [xml.value]
4693
+ ].map((item) => invocation(item, plist.value, "$PLIST"));
4694
+ const result = inspectPlistSchema.parse({
4695
+ format: /binary property list/iu.test(classified.value.stdout) ? "binary" : /XML|text/iu.test(classified.value.stdout) ? "xml" : "unknown",
4696
+ value: parsed.value.value,
4697
+ bundle: parsed.value.bundle,
4698
+ source_path: plist.value,
4699
+ provenance,
4700
+ limitations: parsed.value.limitations
4701
+ });
4702
+ return ok({
4703
+ result: jsonValueSchema.parse(result),
4704
+ limitations: parsed.value.limitations,
4705
+ locations: [{
4706
+ kind: "artifact-path",
4707
+ path: plist.value
4708
+ }]
4709
+ });
4710
+ }
4711
+ async #inspectMacho(signal) {
4712
+ if (!isMachOFormat(this.target.format)) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_macho", "Active artifact is not Mach-O."));
4713
+ return inspectNativeMacho({
4714
+ target: this.target,
4715
+ ...signal === undefined ? {} : { signal },
4716
+ run: (tool, arguments_, commandSignal) => this.#run("inspect_macho", tool, arguments_, { signal: commandSignal }),
4717
+ invocation: (capture) => invocation(capture, this.target.path)
4718
+ });
4719
+ }
4720
+ async #run(operation, tool, arguments_, options = {}) {
4721
+ if (this.#closed) return err(new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, "Native provider client is closed"));
4722
+ const command = this.runner.run(tool, arguments_, {
4723
+ ...options.signal === undefined ? {} : { signal: options.signal },
4724
+ acceptNonZero: options.acceptNonZero ?? false
4725
+ });
4726
+ this.#pendingCommands.add(command);
4727
+ let captured;
4728
+ try {
4729
+ captured = await command;
4730
+ } finally {
4731
+ this.#pendingCommands.delete(command);
4732
+ }
4733
+ if (captured.ok) return captured;
4734
+ return err(translateCommandFailure(operation, captured.error));
4735
+ }
4736
+ };
4737
+ nativeCommandCleanupFailure = (failures) => new ProviderCleanupError(NATIVE_MACOS_PROVIDER_IDENTITY.id, [...new Set(failures.flatMap(({ resources }) => resources))], {
4738
+ reason: "Native command process cleanup remains incomplete",
4739
+ failures: failures.map(({ reason, resources }) => ({
4740
+ reason,
4741
+ resources: [...resources]
4742
+ }))
4743
+ });
4744
+ isNativeOperation = (operation) => NATIVE_TOOL_CONTRACTS.some(({ name }) => name === operation);
4745
+ translateCommandFailure = (operation, failure) => {
4746
+ const capturedOutput = failure.capture === null ? undefined : {
4747
+ stdout: failure.capture.stdout,
4748
+ stderr: failure.capture.stderr,
4749
+ truncated: failure.capture.truncated,
4750
+ stdout_bytes: failure.capture.stdoutBytes,
4751
+ stderr_bytes: failure.capture.stderrBytes,
4752
+ exit_code: failure.capture.exitCode,
4753
+ signal: failure.capture.signal
4754
+ };
4755
+ const cleanup = failure.cleanupFailure === null ? undefined : {
4756
+ reason: failure.cleanupFailure,
4757
+ resources: [...failure.cleanupResources]
4758
+ };
4759
+ const errorOptions = {
4760
+ ...capturedOutput === undefined ? {} : { capturedOutput },
4761
+ ...cleanup === undefined ? {} : { cleanup }
4762
+ };
4763
+ if (failure.reason === "unavailable") {
4764
+ const reason = `${failure.tool} is unavailable through xcrun.`;
4765
+ return new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, reason, {
4766
+ ...errorOptions,
4767
+ userMessage: reason
4768
+ });
4769
+ }
4770
+ if (failure.reason === "cancelled") return new AnalysisCancelledError(operation, errorOptions);
4771
+ if (failure.reason === "timeout") return new AnalysisTimeoutError(operation, NATIVE_COMMAND_TIMEOUT_MS, errorOptions);
4772
+ if (failure.reason === "output-limit") return new AnalysisResourceConstraintError(operation, "memory", `Native command output exceeded ${String(NATIVE_COMMAND_OUTPUT_BUDGET_BYTES)} bytes; complete output is required for analysis.`, { max_output_bytes: NATIVE_COMMAND_OUTPUT_BUDGET_BYTES }, errorOptions);
4773
+ return new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, operation, {
4774
+ cause: failure,
4775
+ ...errorOptions,
4776
+ diagnostics: {
4777
+ tool: failure.tool,
4778
+ reason: failure.reason,
4779
+ exit_code: failure.capture?.exitCode ?? failure.exitCode,
4780
+ signal: failure.capture?.signal ?? null,
4781
+ stdout_bytes: failure.capture?.stdoutBytes ?? 0,
4782
+ stderr_bytes: failure.capture?.stderrBytes ?? 0,
4783
+ ...failure.detail === null ? {} : { detail: failure.detail }
4784
+ }
4785
+ });
4786
+ };
4787
+ translateCodeSignExitFailure = (capture) => translateCommandFailure("inspect_signature", new NativeCommandFailure("codesign", "nonzero-exit", capture.exitCode, undefined, failureCapture(capture, false)));
4788
+ commandOutput = (capture) => `${capture.stdout}\n${capture.stderr}`;
4789
+ isNonzeroUnsignedObservation = (capture) => capture.exitCode !== null && capture.exitCode !== 0 && /not signed at all|code object is not signed/iu.test(commandOutput(capture));
4790
+ canonicalPath = async (path) => {
4791
+ try {
4792
+ return [await realpath(path)];
4793
+ } catch {
4794
+ return [];
4795
+ }
4796
+ };
4797
+ codeSignCaptureFailure = (capture) => capture.exitCode === 0 || isNonzeroUnsignedObservation(capture) ? null : translateCodeSignExitFailure(capture);
4798
+ codeSignArchitectures = (format, target) => {
4799
+ const universal = /^Mach-O universal \(([^)\r\n]+)\)$/u.exec(format ?? "")?.[1];
4800
+ if (universal !== undefined) {
4801
+ const architectures = universal.split(/\s+/u).filter((architecture) => /^(?:i386|x86_64|armv7|arm64|arm64e)$/u.test(architecture));
4802
+ if (architectures.length > 0) return [...new Set(architectures)];
4803
+ }
4804
+ if (target.kind !== "executable" || !isMachOFormat(target.format)) return [];
4805
+ return target.availableArchitectures.map((architecture) => architecture === "x86" ? "i386" : architecture);
4806
+ };
4807
+ invocation = (capture, artifactPath, alias = "$ARTIFACT") => ({
4808
+ tool: capture.tool,
4809
+ command: [capture.executable, ...capture.arguments.map((argument) => argument === artifactPath ? alias : argument)],
4810
+ tool_version: capture.toolVersion,
4811
+ version_reason: capture.versionReason,
4812
+ executable_sha256: capture.executableSha256,
4813
+ exit: {
4814
+ code: capture.exitCode,
4815
+ signal: capture.signal
4816
+ },
4817
+ stdout_bytes: capture.stdoutBytes,
4818
+ stderr_bytes: capture.stderrBytes
4819
+ });
4820
+ parseEntitlements = (output) => {
4821
+ const start = output.indexOf("<?xml");
4822
+ const end = output.lastIndexOf("</plist>");
4823
+ if (start < 0 || end < start) return {
4824
+ value: null,
4825
+ omittedPrototypeKeys: 0
4826
+ };
4827
+ const { value, omittedPrototypeKeys } = parseXmlPropertyList(output.slice(start, end + "</plist>".length));
4828
+ return {
4829
+ value: jsonValueSchema.parse(value),
4830
+ omittedPrototypeKeys
4831
+ };
4832
+ };
4833
+ unreadablePlist = (path, requested, reason) => {
4834
+ const sentence = reason.endsWith(".") ? reason : `${reason}.`;
4835
+ const missingDefault = `The target has no readable Contents/Info.plist at ${path}: ${sentence} Select another plist in the target with the path input (CLI: --relative-path).`;
4836
+ return requested === undefined ? new AnalysisCapabilityUnavailableError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_plist", missingDefault, { userMessage: missingDefault }) : new AnalysisInputError("inspect_plist", undefined, [{
4837
+ path: ["path"],
4838
+ reason: "invalid_value",
4839
+ message: `Cannot inspect ${path}: ${sentence}`
4840
+ }]);
4841
+ };
4842
+ plutilDiagnostic = (stderr, path) => {
4843
+ const text = stderr.trim();
4844
+ return text.startsWith(`${path}: `) ? text.slice(path.length + 2) : text;
4845
+ };
4846
+ requireRegularPlist = async (path, requested) => {
4847
+ try {
4848
+ if (!(await stat(path)).isFile()) return err(unreadablePlist(path, requested, "it is not a regular file"));
4849
+ await (await open(path, "r")).close();
4850
+ return ok(null);
4851
+ } catch (cause) {
4852
+ const code = cause instanceof Error && "code" in cause ? cause.code : undefined;
4853
+ if (code === "ENOENT" || code === "ENOTDIR") return err(unreadablePlist(path, requested, "no file exists there"));
4854
+ if (code === "EACCES" || code === "EPERM") return err(new BinaryTargetError(path, `permission denied while reading plist (${code})`, { cause }));
4855
+ return err(new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_plist", { cause }));
4856
+ }
4857
+ };
4858
+ resolvePlistPath = async (target, requested) => {
4859
+ try {
4860
+ const source = target.sourcePath ?? target.path;
4861
+ if (requested !== undefined && isAbsolute(requested)) return ok(resolve(requested));
4862
+ const sourceMetadata = await stat(source);
4863
+ const root = sourceMetadata.isDirectory() ? source : dirname(target.path);
4864
+ if (requested !== undefined) return ok(resolve(root, requested));
4865
+ return ok(target.bundleInfoPlist ?? resolve(root, "Contents/Info.plist"));
4866
+ } catch (cause) {
4867
+ return err(new ProviderAdapterError(NATIVE_MACOS_PROVIDER_IDENTITY.id, "inspect_plist", { cause }));
4868
+ }
4869
+ };
4870
+ })))();
4871
+ }
4872
+
4873
+ //#endregion
4874
+ init_NativeMacOSProvider();
4875
+ export { NativeMacOSProvider };