@jshookmcp/jshook 0.3.2 → 0.3.3
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.
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/dist/{AntiCheatDetector-B6d4Qe9D.mjs → AntiCheatDetector-CUpZBh5O.mjs} +1 -1
- package/dist/{BrowserSessionCoordinator-BJ-HOxo0.mjs → BrowserSessionCoordinator-QIt3tetp.mjs} +1 -1
- package/dist/CodeInjector-Btj9upnf.mjs +1 -0
- package/dist/{ConsoleMonitor-CxDJV15E.mjs → ConsoleMonitor-DIjN5Afa.mjs} +5 -5
- package/dist/{DarwinAPI-ZfQdpLNI.mjs → DarwinAPI-BuMPGzHm.mjs} +1 -1
- package/dist/DetailedDataManager-Z77fDl9Z.mjs +5 -0
- package/dist/ExtensionManager.tools-CIGOWViz.mjs +1 -0
- package/dist/{FingerprintManager-DT0EAUEo.mjs → FingerprintManager-BkDSsjjP.mjs} +1 -1
- package/dist/{HardwareBreakpoint-BUfPdp0f.mjs → HardwareBreakpoint-DMAMcPyB.mjs} +1 -1
- package/dist/{HeapAnalyzer-B_aqY8oj.mjs → HeapAnalyzer-Yj348FYt.mjs} +1 -1
- package/dist/{ExtensionManager.tools-oVMJgPcN.mjs → MCPServer.activation.ttl-CEGNBycZ.mjs} +1 -1
- package/dist/MCPServer.search.helpers-Cs1JpKbu.mjs +1 -0
- package/dist/MCPServer.search.validation-DnifPCCv.mjs +1 -0
- package/dist/{MemoryController-X1XNSn1n.mjs → MemoryController-DjtgiING.mjs} +1 -1
- package/dist/{MemoryScanSession-DG_F-PjE.mjs → MemoryScanSession-zfoVZJB0.mjs} +1 -1
- package/dist/MemoryScanner-Dxd657li.mjs +1 -0
- package/dist/{NativeMemoryManager.utils-BHy1P_jM.mjs → NativeMemoryManager.utils-Bu8srMEF.mjs} +1 -1
- package/dist/{PEAnalyzer-yWQaGrcx.mjs → PEAnalyzer-CMu9Ua9T.mjs} +1 -1
- package/dist/PointerChainEngine-CaSC1Mry.mjs +1 -0
- package/dist/{ProcessRegistry-C-bN48oR.mjs → ProcessRegistry-D5y1yuP2.mjs} +1 -1
- package/dist/{ReverseEvidenceGraph-BhSYYdiI.mjs → ReverseEvidenceGraph-BksOpsPs.mjs} +1 -1
- package/dist/ServerRuntimeState-CgqBBwfd.mjs +1 -0
- package/dist/{Speedhack-yseDPSZ9.mjs → Speedhack-pwXTHxOY.mjs} +1 -1
- package/dist/{StructureAnalyzer-C5lpuZkg.mjs → StructureAnalyzer-BseGzsSl.mjs} +2 -2
- package/dist/ToolCatalog-DgmQXdsm.mjs +1 -0
- package/dist/ToolHandlerMap-7HWoIgQO.mjs +1 -0
- package/dist/{ToolProbe-C7ZU2x7M.mjs → ToolProbe-DQiREmNp.mjs} +1 -1
- package/dist/{ToolRegistry-C5oB8KP8.mjs → ToolRegistry-eMZEBiR1.mjs} +1 -1
- package/dist/ToolRouter.policy-UKBlFlbh.mjs +4 -0
- package/dist/{TraceRecorder-BiJWBXHX.mjs → TraceRecorder-B5ktv3nP.mjs} +2 -2
- package/dist/VersionDetector-CmPJmaJg.mjs +1 -0
- package/dist/{Win32API-eUCF57l_.mjs → Win32API-DoP3MMHS.mjs} +1 -1
- package/dist/{Win32Debug-CYrIQBvr.mjs → Win32Debug-DwF8mQGm.mjs} +1 -1
- package/dist/{WorkflowEngine-D876meOO.mjs → WorkflowEngine-CldHG5b4.mjs} +1 -1
- package/dist/{analysis-D4swdMvq.mjs → analysis-C-ln0Brh.mjs} +3 -3
- package/dist/antidebug-CsnpOR9z.mjs +1 -0
- package/dist/{artifactRetention-BCPQASm7.mjs → artifactRetention-DkYKLOvi.mjs} +1 -1
- package/dist/{artifacts-CkodUM4j.mjs → artifacts-D-4pSS_N.mjs} +1 -1
- package/dist/{betterSqlite3-Brtq-SIQ.mjs → betterSqlite3-Bdo_ifuJ.mjs} +1 -1
- package/dist/binary-instrument-BeZ224mZ.mjs +9 -0
- package/dist/{boringssl-inspector-BBaJwwkU.mjs → boringssl-inspector-ZOCkaipa.mjs} +2 -2
- package/dist/browser-BUaB25bk.mjs +11 -0
- package/dist/{handlers-yo_xYzT8.mjs → canvas-396ieNv5.mjs} +22 -22
- package/dist/collector-CB2syQEg.mjs +1 -0
- package/dist/constants-DMv3svps.mjs +2 -0
- package/dist/coordination-Dbohmj6D.mjs +1 -0
- package/dist/dart-inspector-LhEqRITQ.mjs +0 -0
- package/dist/debugger-CLzkObIO.mjs +1 -0
- package/dist/{definitions-OeLvmlQy.mjs → definitions-0hxnrDU72.mjs} +1 -1
- package/dist/definitions-B3a9QC2t.mjs +1 -0
- package/dist/{definitions-Ibci7e_L.mjs → definitions-BOvju5t2.mjs} +1 -1
- package/dist/{definitions-D4g-MS10.mjs → definitions-CXj_cEVt.mjs} +1 -1
- package/dist/{definitions-C3qNgSn1.mjs → definitions-Co6AvTjH.mjs} +1 -1
- package/dist/{definitions-DxFNRQNK2.mjs → definitions-Cv5r8xwq.mjs} +1 -1
- package/dist/definitions-DBYSxChX.mjs +1 -0
- package/dist/{definitions-CQd7yCQH.mjs → definitions-D_dTDX9B.mjs} +1 -1
- package/dist/{definitions-l7TjdE6V.mjs → definitions-Db9t2ddh.mjs} +1 -1
- package/dist/{definitions-BWxBke3r.mjs → definitions-DbN2CjI2.mjs} +1 -1
- package/dist/{definitions-DAQm1Xar.mjs → definitions-DlmmHmZc.mjs} +1 -1
- package/dist/{definitions-Bf3H1EwV.mjs → definitions-DnYpoGig.mjs} +1 -1
- package/dist/{definitions-BYwATKc-.mjs → definitions-DtZ6Ktx2.mjs} +1 -1
- package/dist/{definitions-D5wl_8HN.mjs → definitions-DuIPS8gq.mjs} +1 -1
- package/dist/{definitions-RZYGD_Ey.mjs → definitions-DywfwPMb.mjs} +1 -1
- package/dist/definitions-EGmqr85H.mjs +1 -0
- package/dist/{definitions-bybDvnG0.mjs → definitions-Fetw_Cge.mjs} +3 -3
- package/dist/{definitions-CB6vmOer.mjs → definitions-LdkeuOeA.mjs} +1 -1
- package/dist/{definitions-B_83XfNQ.mjs → definitions-Ym8niHDb.mjs} +1 -1
- package/dist/{definitions-Cenu6mxo.mjs → definitions-aeRd5DAR.mjs} +1 -1
- package/dist/{definitions-CT8ln6GQ.mjs → definitions-cnG6tj17.mjs} +1 -1
- package/dist/{encoding-ycOaz8Vr.mjs → encoding-B4xZWErf.mjs} +2 -2
- package/dist/ensure-browser-core-JHwDo5ql.mjs +285 -0
- package/dist/{factory-CKr4fAE1.mjs → factory-BxNdBiZa.mjs} +1 -1
- package/dist/{graphql-B2TiPEow.mjs → graphql-GBWsZ9xC.mjs} +4 -4
- package/dist/{handlers-D5E40ssn.mjs → handlers-5nzR8B0a.mjs} +2 -2
- package/dist/handlers-6iNsXOVT.mjs +7 -0
- package/dist/{handlers-BpDlVVVU.mjs → handlers-BZ8n6Hvf.mjs} +1 -1
- package/dist/{handlers-0yKLRIfo.mjs → handlers-BbLxNbbT.mjs} +1 -1
- package/dist/{handlers-DGbdQAgD.mjs → handlers-BbS4hssc.mjs} +2 -2
- package/dist/{handlers-l8QIKqBj.mjs → handlers-CIKOP4aI.mjs} +2 -2
- package/dist/handlers-CWKBBjai.mjs +1 -0
- package/dist/{handlers-B62K4FTc.mjs → handlers-Cmb6SoRC.mjs} +1 -1
- package/dist/handlers-CrJsKnEI.mjs +1 -0
- package/dist/{antidebug-7L3ygj_9.mjs → handlers-DB6xVVWq.mjs} +2 -2
- package/dist/{handlers-CMJK7m1c.mjs → handlers-DOOCWUNR.mjs} +3 -3
- package/dist/{handlers-D2ZOul9p.mjs → handlers-Z_B5aVaU.mjs} +2 -2
- package/dist/handlers-gVscChvl.mjs +1 -0
- package/dist/handlers-xFvI9P_y.mjs +1 -0
- package/dist/{handlers.impl-D9Hh8Bgl.mjs → handlers.impl-BsFTW6SD.mjs} +1 -1
- package/dist/{hooks-D4XLfgtV.mjs → hooks-DPouiS7I.mjs} +9 -9
- package/dist/index.mjs +11 -11
- package/dist/macro-p8kuJVcm.mjs +2 -0
- package/dist/maintenance-DAqADb6Z.mjs +302 -0
- package/dist/manifest-4lmM6MZR.mjs +1 -0
- package/dist/{manifest-DujQqEQR.mjs → manifest-AxaxRSt6.mjs} +2 -2
- package/dist/{manifest-DYpn8w_h.mjs → manifest-BIqRE1Qz.mjs} +1 -1
- package/dist/manifest-Box-jWfr.mjs +1 -0
- package/dist/manifest-Bp33di0Q.mjs +1 -0
- package/dist/{manifest-CQH9FhwI.mjs → manifest-BvRX4nRP.mjs} +1 -1
- package/dist/{manifest-0Jpt_AQa.mjs → manifest-C6KoB1XE.mjs} +1 -1
- package/dist/manifest-C7TdXCWY.mjs +1 -0
- package/dist/manifest-CM-n64K0.mjs +1 -0
- package/dist/{manifest-nXHmtMSp2.mjs → manifest-CUokxCUN.mjs} +1 -1
- package/dist/manifest-CWJS45iO.mjs +1 -0
- package/dist/{manifest-LLdI5m4T.mjs → manifest-Cdxdgo-D.mjs} +1 -1
- package/dist/{manifest-D_obs5F4.mjs → manifest-Cf6SmamD.mjs} +1 -1
- package/dist/manifest-Cgxu2qdv.mjs +1 -0
- package/dist/{manifest-ztWJoXy4.mjs → manifest-CowGSURa2.mjs} +1 -1
- package/dist/{manifest-DYzWI8Xs.mjs → manifest-CsGIrh34.mjs} +1 -1
- package/dist/manifest-CvDpVToN.mjs +1 -0
- package/dist/manifest-D8TL9RLE.mjs +1 -0
- package/dist/{manifest-DCx6w2XV.mjs → manifest-DIhtCBe6.mjs} +1 -1
- package/dist/{manifest-D9jUUJAu.mjs → manifest-DJbruNOg.mjs} +1 -1
- package/dist/manifest-DLGtZH-0.mjs +1 -0
- package/dist/manifest-DXHdPt2T.mjs +1 -0
- package/dist/{manifest-B3fZbSWR.mjs → manifest-Dg5ScOyW.mjs} +1 -1
- package/dist/{manifest-xWfu6iLo.mjs → manifest-DzGoTS0R.mjs} +1 -1
- package/dist/manifest-G2H52LKz.mjs +131 -0
- package/dist/{manifest-CctIumog.mjs → manifest-P0Futrgb.mjs} +1 -1
- package/dist/{manifest-YgVd8Sgz.mjs → manifest-Qw7xgvjv.mjs} +1 -1
- package/dist/{manifest-QYbQXJn0.mjs → manifest-W3qvVrP2.mjs} +1 -1
- package/dist/manifest-dG6MuR1U.mjs +1 -0
- package/dist/manifest-nWXtgq5Y2.mjs +1 -0
- package/dist/{manifest-LG42zPLY2.mjs → manifest-vp1upSSq.mjs} +1 -1
- package/dist/{modules-BPBcSaM-.mjs → modules-DO3jXCgj.mjs} +10 -10
- package/dist/{mojo-ipc-BhwsdVUW.mjs → mojo-ipc-Be-ccWrc.mjs} +1 -1
- package/dist/native-g095qhpK.mjs +961 -0
- package/dist/network-Dvxm7eEI.mjs +7 -0
- package/dist/outputPaths-D2ddHrOJ.mjs +2 -0
- package/dist/{parse-args-Bw413PlW.mjs → parse-args-ngRrvF9e.mjs} +1 -1
- package/dist/platform-DjWbuiF8.mjs +93 -0
- package/dist/process-Dq5I-KZW.mjs +2 -0
- package/dist/proxy-DPNgM7TE.mjs +2 -0
- package/dist/{registry-DH4sc1dt.mjs → registry-xB8Wgmyj.mjs} +1 -1
- package/dist/{renderer-pid-9tJnZ_9N.mjs → renderer-pid-7jbTR8f5.mjs} +1 -1
- package/dist/search-defaults-CJik67or.mjs +1 -0
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/sourcemap-DqEW15Ao.mjs +1 -0
- package/dist/streaming-Dbk4eStJ.mjs +1 -0
- package/dist/{transform-DOxzeWPB.mjs → transform-D-peM3aO.mjs} +2 -2
- package/dist/{wasm-CZ_HTfKR.mjs → wasm-CZajRaad.mjs} +6 -6
- package/dist/{webcrack-C1iYG_EX.mjs → webcrack-phEfVt5y.mjs} +3 -3
- package/dist/{workflow-BdwQmARn.mjs → workflow-wkXb3x-U.mjs} +3 -3
- package/package.json +2 -2
- package/dist/CodeInjector-Cll_7bLJ.mjs +0 -1
- package/dist/DOMInspector-C19J4zeq.mjs +0 -95
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +0 -1
- package/dist/ExtensionManager-BD724zkO.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +0 -1
- package/dist/MemoryScanner-g1_L1ub5.mjs +0 -1
- package/dist/NativeMemoryManager.impl-DniBe2wf.mjs +0 -1
- package/dist/NetworkMonitor-B_-au6aV.mjs +0 -185
- package/dist/PageController-Dfsm1_o7.mjs +0 -1
- package/dist/PointerChainEngine-BhCUkmxY.mjs +0 -1
- package/dist/PrerequisiteError-BjCQA-gK.mjs +0 -1
- package/dist/ScriptManager-LWGPTdvD.mjs +0 -7
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +0 -1
- package/dist/ToolCatalog-CYdD9F5f.mjs +0 -1
- package/dist/ToolRouter.policy-CfhJczkt.mjs +0 -4
- package/dist/VersionDetector-CHT36Az0.mjs +0 -9
- package/dist/apk-packer-BqXcInnX.mjs +0 -1
- package/dist/binary-instrument-DU7V6TUM.mjs +0 -7
- package/dist/binary-secrets-PdMVoyt0.mjs +0 -1
- package/dist/browser-Qqco2rOT.mjs +0 -11
- package/dist/collector-Bpl6qy2L.mjs +0 -1
- package/dist/constants-BYj8Xek8.mjs +0 -1
- package/dist/coordination-CWXW1o8K.mjs +0 -1
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/debugger-DyALjYMk.mjs +0 -1
- package/dist/definitions-BftdXgXI.mjs +0 -1
- package/dist/definitions-Bio5XJYy.mjs +0 -1
- package/dist/definitions-CMZRSy3k.mjs +0 -1
- package/dist/definitions-DP1vgxEY.mjs +0 -1
- package/dist/definitions-Tls8c0A0.mjs +0 -1
- package/dist/ensure-browser-core-DxWC-NTp.mjs +0 -1
- package/dist/flat-target-session-DvcQX7J5.mjs +0 -1
- package/dist/handlers-8zN_vBIz.mjs +0 -1
- package/dist/handlers-DHO3rjsW.mjs +0 -1
- package/dist/handlers-FJ80VzUI.mjs +0 -2
- package/dist/handlers-VHWrxbM_.mjs +0 -1
- package/dist/handlers-mPFiNPe8.mjs +0 -302
- package/dist/jadx-search-B_Yse0Zh.mjs +0 -5
- package/dist/maintenance-BUpIukhg.mjs +0 -1
- package/dist/manifest-B7NB2rh2.mjs +0 -1
- package/dist/manifest-BDi4nbH1.mjs +0 -1
- package/dist/manifest-BLDfkE7n.mjs +0 -1
- package/dist/manifest-BcXbB4gf.mjs +0 -1
- package/dist/manifest-Bdnc_vrc.mjs +0 -1
- package/dist/manifest-BuYKgCnp.mjs +0 -1
- package/dist/manifest-CBfNnGPV.mjs +0 -1
- package/dist/manifest-CPS1Xv69.mjs +0 -1
- package/dist/manifest-CRryuZF4.mjs +0 -1
- package/dist/manifest-CvTe5ZGV2.mjs +0 -1
- package/dist/manifest-D-5GH0DV.mjs +0 -1
- package/dist/manifest-D3Ssf3IC.mjs +0 -1
- package/dist/manifest-D5ck3NvC.mjs +0 -1
- package/dist/manifest-DG19q-Ld.mjs +0 -1
- package/dist/manifest-DLMlD0Zc.mjs +0 -1
- package/dist/manifest-DwL2ik8P.mjs +0 -1
- package/dist/manifest-ItF5P8A12.mjs +0 -1
- package/dist/manifest-KZphqIyX.mjs +0 -1
- package/dist/manifest-RcpX_MyZ.mjs +0 -123
- package/dist/manifest-Zy7Odg5J.mjs +0 -1
- package/dist/manifest-ff1H7Pdp.mjs +0 -1
- package/dist/manifest-iuhF6pTL2.mjs +0 -1
- package/dist/manifest-yC16OhL2.mjs +0 -1
- package/dist/matchesWildcardPattern-BAG6LvX5.mjs +0 -1
- package/dist/native-j8l473zn.mjs +0 -961
- package/dist/network-T0VRwNPd.mjs +0 -7
- package/dist/outputPaths-B4Ic4RZh.mjs +0 -2
- package/dist/platform-CzaQtISh.mjs +0 -93
- package/dist/playwright-cdp-fallback-DqFdx9-s.mjs +0 -1
- package/dist/process-CWhsCWrf.mjs +0 -2
- package/dist/proxy-DZFlDsG3.mjs +0 -2
- package/dist/search-defaults-lYBVn_3L.mjs +0 -1
- package/dist/shared-state-board-BSjXLUV1.mjs +0 -1
- package/dist/sourcemap-Dh3Ai_ur.mjs +0 -1
- package/dist/streaming-BcJ0B6ao.mjs +0 -1
- package/dist/types-D9EiE5o9.mjs +0 -1
- /package/dist/{CacheAdapters-CsNtQIR8.mjs → CacheAdapters-BlDrQg8f.mjs} +0 -0
- /package/dist/{EventBus-DL8iLA09.mjs → EventBus-Cm-t-B65.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BtbwXsLC.mjs → EvidenceGraphBridge-DBDc0wUA.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs → HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs} +0 -0
- /package/dist/{InstrumentationSession-D_G1ZPyd.mjs → InstrumentationSession-c5qZyp7d.mjs} +0 -0
- /package/dist/{ResponseBuilder-BfWP-uaT.mjs → ResponseBuilder-nPXl_khE.mjs} +0 -0
- /package/dist/{RingBuffer-Dm54ELKT.mjs → RingBuffer-B6RTHmij.mjs} +0 -0
- /package/dist/{StealthVerifier-BmcxfwSF.mjs → StealthVerifier-DMBrtkhN.mjs} +0 -0
- /package/dist/{ToolError-DWU_z7gp.mjs → ToolError-g3rjWzhx.mjs} +0 -0
- /package/dist/{authorization-schema-BOFwSXUN.mjs → authorization-schema-Jtikc5Yt.mjs} +0 -0
- /package/dist/{bind-helpers-m2U8glkF.mjs → bind-helpers-D0mGAOof.mjs} +0 -0
- /package/dist/{capabilities-CyXuKUl1.mjs → capabilities-L1ax5EHS.mjs} +0 -0
- /package/dist/{chunk-C_pMuVsO.mjs → chunk-88NL7fhV.mjs} +0 -0
- /package/dist/{concurrency-DCr8WQ2M.mjs → concurrency-Dehnw4JC.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-CV_UdYqj.mjs → evidence-graph-bridge-eT9icP6a.mjs} +0 -0
- /package/dist/{formatAddress-vLA_hOJt.mjs → formatAddress-DAcw4Ckg.mjs} +0 -0
- /package/dist/{logger-sBC6IdRT.mjs → logger-CCikqqvj.mjs} +0 -0
- /package/dist/{response-C7rKQst4.mjs → response-B1RuVVfD.mjs} +0 -0
- /package/dist/{ssrf-policy-CsIJGkpd.mjs → ssrf-policy-B72vdy23.mjs} +0 -0
- /package/dist/{tool-builder-qif8M9-K.mjs → tool-builder-CpLh-UQd.mjs} +0 -0
- /package/dist/{types-Fz69RzbZ.mjs → types-BzPBzmVB.mjs} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-88NL7fhV.mjs";import{t}from"./logger-CCikqqvj.mjs";import{Dt as n,Ht as r,Ut as i,Wt as a,qt as o,ra as s}from"./constants-DMv3svps.mjs";import{i as c,n as l}from"./outputPaths-D2ddHrOJ.mjs";import{i as u}from"./artifacts-D-4pSS_N.mjs";import{t as d}from"./ProcessRegistry-D5y1yuP2.mjs";import{a as f,c as p,i as m,n as h,o as g,r as _,s as v,t as y}from"./HookGeneratorBuilders.core.generators.storage-CWaWpOHa.mjs";import{c as b,d as x,l as S,o as C,s as ee,v as w}from"./ensure-browser-core-JHwDo5ql.mjs";import{r as te,t as T}from"./concurrency-Dehnw4JC.mjs";import{n as ne,t as E}from"./webcrack-phEfVt5y.mjs";import"./ToolRegistry-eMZEBiR1.mjs";import*as D from"path";import{join as re}from"path";import O from"crypto";import{tmpdir as ie}from"node:os";import{isAbsolute as ae,relative as oe,resolve as k,sep as se}from"node:path";import{stat as ce,writeFile as A}from"node:fs/promises";import{spawn as le}from"node:child_process";import"rebrowser-puppeteer-core";import*as j from"fs/promises";import{mkdir as ue,writeFile as de}from"fs/promises";import*as fe from"os";import{setImmediate as pe}from"node:timers/promises";import*as M from"@babel/parser";import N from"@babel/traverse";import*as P from"@babel/types";import"@babel/generator";function me(e,t,n,r=!1){return`
|
|
2
2
|
(function() {
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
@@ -108,7 +108,7 @@ XHR.send = function(data) {
|
|
|
108
108
|
|
|
109
109
|
console.log('[Hook] XHR hooked successfully');
|
|
110
110
|
})();
|
|
111
|
-
`.trim()}function
|
|
111
|
+
`.trim()}function he(e,t,n,r=!1){return`
|
|
112
112
|
(function() {
|
|
113
113
|
'use strict';
|
|
114
114
|
|
|
@@ -203,7 +203,7 @@ window.fetch = new Proxy(originalFetch, {
|
|
|
203
203
|
|
|
204
204
|
console.log('[Fetch Hook] Successfully hooked window.fetch');
|
|
205
205
|
})();
|
|
206
|
-
`.trim()}function
|
|
206
|
+
`.trim()}function ge(e,t,n,r=!1){return`
|
|
207
207
|
(function() {
|
|
208
208
|
'use strict';
|
|
209
209
|
|
|
@@ -309,18 +309,18 @@ window.WebSocket.CLOSED = OriginalWebSocket.CLOSED;
|
|
|
309
309
|
|
|
310
310
|
console.log('[WebSocket Hook] Successfully hooked window.WebSocket');
|
|
311
311
|
})();
|
|
312
|
-
`.trim()}function
|
|
312
|
+
`.trim()}function _e(e){return`
|
|
313
313
|
|
|
314
314
|
${e.map(e=>e.script).join(`
|
|
315
315
|
|
|
316
316
|
`)}
|
|
317
317
|
|
|
318
318
|
console.log('[Hook Chain] All ${e.length} hooks initialized');
|
|
319
|
-
`.trim()}function F(e){let t=[],n=e;for(;
|
|
320
|
-
`).length,v=Math.max(0,171-5.2*Math.log(g||1)-.23*n-16.2*Math.log(_));return{cyclomaticComplexity:n,cognitiveComplexity:r,maintainabilityIndex:Math.round(v),halsteadMetrics:{vocabulary:f,length:p,difficulty:Math.round(m*100)/100,effort:Math.round(h)}}}function Se(e){let n=[],r=[];try{M(e,{FunctionDeclaration(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},FunctionExpression(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},ArrowFunctionExpression(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},ClassMethod(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})}});for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){let i=r[e],a=r[t];if(i.hash===a.hash){n.push({location:i.location,duplicateLocation:a.location,similarity:1});continue}let o=Ce(i.normalizedCode,a.normalizedCode);o>=.85&&n.push({location:i.location,duplicateLocation:a.location,similarity:o})}}catch(e){t.debug(`Duplicate code detection failed`,e)}return n}function L(e){let t=JSON.stringify(e,(e,t)=>{if(![`loc`,`start`,`end`,`range`].includes(e)&&!(e===`comments`||e===`leadingComments`||e===`trailingComments`))return t}),n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return n.toString(36)}function R(e){let t=0,n=new Map,r=N.cloneNode(e,!0,!1);return M(N.file(N.program([r])),{Identifier(e){let r=e.node.name;[`console`,`window`,`document`,`Math`,`JSON`,`Array`,`Object`,`String`,`Number`].includes(r)||(n.has(r)||n.set(r,`VAR_${t++}`),e.node.name=n.get(r))},StringLiteral(e){e.node.value=`STRING`},NumericLiteral(e){e.node.value=0}}),JSON.stringify(r)}function Ce(e,t){let n=e.length,r=t.length;if(Math.abs(n-r)>Math.max(n,r)*.3)return 0;let i=Array.from({length:n+1},()=>Array.from({length:r+1},()=>0));for(let e=0;e<=n;e++)i[e][0]=e;for(let e=0;e<=r;e++)i[0][e]=e;for(let a=1;a<=n;a++)for(let n=1;n<=r;n++){let r=e[a-1]===t[n-1]?0:1;i[a][n]=Math.min(i[a-1][n]+1,i[a][n-1]+1,i[a-1][n-1]+r)}return 1-i[n][r]/Math.max(n,r)}async function we(e){let n={nodes:[],edges:[]},r=[],i=[],a=[],o=new Map,s=new Set(`encodeURIComponent,encodeURI,escape,decodeURIComponent,decodeURI,htmlentities,htmlspecialchars,escapeHtml,escapeHTML,he.encode,he.escape,validator.escape,validator.unescape,validator.stripLow,validator.blacklist,validator.whitelist,validator.trim,validator.isEmail,validator.isURL,validator.isInt,DOMPurify.sanitize,DOMPurify.addHook,crypto.encrypt,crypto.hash,crypto.createHash,crypto.createHmac,CryptoJS.AES.encrypt,CryptoJS.SHA256,CryptoJS.MD5,bcrypt.hash,bcrypt.compare,btoa,atob,Buffer.from,db.prepare,db.query,mysql.escape,pg.query,xss,sanitizeHtml,parseInt,parseFloat,Number,String,JSON.stringify,JSON.parse,String.prototype.replace,String.prototype.trim,Array.prototype.filter,Array.prototype.map`.split(`,`));try{let c=j.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]});M(c,{CallExpression(e){let t=e.node.callee,s=e.node.loc?.start.line||0;if(N.isMemberExpression(t)&&N.isIdentifier(t.property)){let i=t.property.name;if([`fetch`,`ajax`,`get`,`post`,`request`,`axios`].includes(i)){let t=`source-network-${s}`;r.push({type:`network`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${i}()`,type:`source`,location:{file:`current`,line:s}});let a=e.parent;N.isVariableDeclarator(a)&&N.isIdentifier(a.id)&&o.set(a.id.name,{sourceType:`network`,sourceLine:s})}else if([`querySelector`,`getElementById`,`getElementsByClassName`,`getElementsByTagName`].includes(i)){let e=`source-dom-${s}`;r.push({type:`user_input`,location:{file:`current`,line:s}}),n.nodes.push({id:e,name:`${i}()`,type:`source`,location:{file:`current`,line:s}})}}if(N.isIdentifier(t)){let r=t.name;if([`eval`,`Function`,`setTimeout`,`setInterval`].includes(r)){let t=`sink-eval-${s}`;i.push({type:`eval`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}()`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}}if(N.isMemberExpression(t)&&N.isIdentifier(t.property)){let r=t.property.name;if([`write`,`writeln`].includes(r)&&N.isIdentifier(t.object)&&t.object.name===`document`){let t=`sink-document-write-${s}`;i.push({type:`xss`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`document.${r}()`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`query`,`execute`,`exec`,`run`].includes(r)){let t=`sink-sql-${s}`;i.push({type:`sql-injection`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (SQL)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`exec`,`spawn`,`execSync`,`spawnSync`].includes(r)){let t=`sink-command-${s}`;i.push({type:`other`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (Command)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`readFile`,`writeFile`,`readFileSync`,`writeFileSync`,`open`].includes(r)){let t=`sink-file-${s}`;i.push({type:`other`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (File)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}}},MemberExpression(e){let t=e.node.object,i=e.node.property,a=e.node.loc?.start.line||0;if(N.isIdentifier(t)&&t.name===`location`&&N.isIdentifier(i)&&[`href`,`search`,`hash`,`pathname`].includes(i.name)){let t=`source-url-${a}`;r.push({type:`user_input`,location:{file:`current`,line:a}}),n.nodes.push({id:t,name:`location.${i.name}`,type:`source`,location:{file:`current`,line:a}});let s=e.parent;N.isVariableDeclarator(s)&&N.isIdentifier(s.id)&&o.set(s.id.name,{sourceType:`url`,sourceLine:a})}if(N.isIdentifier(t)&&t.name===`document`&&N.isIdentifier(i)&&i.name===`cookie`){let e=`source-cookie-${a}`;r.push({type:`storage`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`document.cookie`,type:`source`,location:{file:`current`,line:a}})}if(N.isIdentifier(t)&&[`localStorage`,`sessionStorage`].includes(t.name)){let e=`source-storage-${a}`;r.push({type:`storage`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`${t.name}.getItem()`,type:`source`,location:{file:`current`,line:a}})}if(N.isIdentifier(t)&&t.name===`window`&&N.isIdentifier(i)&&i.name===`name`){let e=`source-window-name-${a}`;r.push({type:`user_input`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`window.name`,type:`source`,location:{file:`current`,line:a}})}if(N.isIdentifier(t)&&t.name===`event`&&N.isIdentifier(i)&&i.name===`data`){let e=`source-postmessage-${a}`;r.push({type:`network`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`event.data (postMessage)`,type:`source`,location:{file:`current`,line:a}})}if(N.isIdentifier(t)&&t.name===`message`&&N.isIdentifier(i)&&i.name===`data`){let e=`source-websocket-${a}`;r.push({type:`network`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`WebSocket message.data`,type:`source`,location:{file:`current`,line:a}})}},AssignmentExpression(e){let t=e.node.left,r=e.node.right,s=e.node.loc?.start.line||0;if(N.isMemberExpression(t)&&N.isIdentifier(t.property)){let e=t.property.name;if([`innerHTML`,`outerHTML`].includes(e)){let t=`sink-dom-${s}`;if(i.push({type:`xss`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:e,type:`sink`,location:{file:`current`,line:s}}),N.isIdentifier(r)&&o.has(r.name)){let e=o.get(r.name);a.push({source:{type:e.sourceType,location:{file:`current`,line:e.sourceLine}},sink:{type:`xss`,location:{file:`current`,line:s}},path:[{file:`current`,line:e.sourceLine},{file:`current`,line:s}]})}}}}}),M(c,{VariableDeclarator(e){let n=e.node.id,r=e.node.init;if(N.isIdentifier(n)&&r){if(N.isCallExpression(r)&&I(r,s)){let e=r.arguments[0];if(N.isIdentifier(e)&&o.has(e.name)){t.debug(`Taint cleaned by sanitizer: ${e.name} -> ${n.name}`);return}}if(N.isIdentifier(r)&&o.has(r.name)){let e=o.get(r.name);o.set(n.name,e)}else if(N.isBinaryExpression(r)){let e=N.isIdentifier(r.left)&&o.has(r.left.name),t=N.isIdentifier(r.right)&&o.has(r.right.name);if(e||t){let t=e?o.get(r.left.name):o.get(r.right.name);o.set(n.name,t)}}else if(N.isCallExpression(r)){let e=r.arguments[0];if(N.isIdentifier(e)&&o.has(e.name)){let t=o.get(e.name);o.set(n.name,t)}}}},AssignmentExpression(e){let t=e.node.left,n=e.node.right;if(N.isIdentifier(t)&&N.isIdentifier(n)&&o.has(n.name)){let e=o.get(n.name);o.set(t.name,e)}}})}catch(e){t.warn(`Data flow analysis failed`,e)}return{graph:n,sources:r,sinks:i,taintPaths:a}}function z(e,t,n,r,i){e.forEach(e=>{if(N.isIdentifier(e)&&t.has(e.name)){let r=t.get(e.name);n.push({source:{type:r.sourceType,location:{file:`current`,line:r.sourceLine}},sink:{type:`eval`,location:{file:`current`,line:i}},path:[{file:`current`,line:r.sourceLine},{file:`current`,line:i}]})}})}const Te=e=>typeof e==`object`&&!!e&&`traverse`in e&&typeof e.traverse==`function`;var Ee=class{constructor(e){}async understand(e){t.info(`Starting code understanding...`);let n=Date.now();try{let{code:r,context:i,focus:a=`all`}=e,o=await this.analyzeStructure(r);t.debug(`Code structure analyzed`);let s=await this.aiAnalyze(r,a);t.debug(`AI analysis completed`);let c=this.detectTechStack(r,s);t.debug(`Tech stack detected`);let l=this.extractBusinessLogic(s,i);t.debug(`Business logic extracted`);let u=await this.analyzeDataFlow(r);t.debug(`Data flow analyzed`);let d=ve(r,s);t.debug(`Security risks identified`);let{patterns:f,antiPatterns:p}=be(r);t.debug(`Detected ${f.length} patterns and ${p.length} anti-patterns`);let m=xe(r);t.debug(`Complexity metrics calculated`);let h=ye(o,d,s,m,p),g=Date.now()-n;return t.success(`Code understanding completed in ${g}ms`),{structure:o,techStack:c,businessLogic:l,dataFlow:u,securityRisks:d,qualityScore:h,codePatterns:f,antiPatterns:p,complexityMetrics:m}}catch(e){throw t.error(`Code understanding failed`,e),e}}async analyzeStructure(e){let n=[],r=[];try{M(j.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),{FunctionDeclaration:e=>{let t=e.node;n.push({name:t.id?.name||`anonymous`,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},FunctionExpression:e=>{let t=e.node,r=e.parent,i=`anonymous`;r.type===`VariableDeclarator`&&r.id.type===`Identifier`?i=r.id.name:r.type===`AssignmentExpression`&&r.left.type===`Identifier`&&(i=r.left.name),n.push({name:i,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},ArrowFunctionExpression:e=>{let t=e.node,r=e.parent,i=`arrow`;r.type===`VariableDeclarator`&&r.id.type===`Identifier`&&(i=r.id.name),n.push({name:i,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},ClassDeclaration(e){let t=e.node,n=[],i=[];e.traverse({ClassMethod(e){let t=e.node;n.push({name:t.key.type===`Identifier`?t.key.name:`unknown`,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:1})},ClassProperty(e){let t=e.node;t.key.type===`Identifier`&&i.push({name:t.key.name,type:void 0,value:void 0})}}),r.push({name:t.id?.name||`anonymous`,methods:n,properties:i,location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column}})}})}catch(e){t.warn(`Failed to parse code structure`,e)}return{functions:n,classes:r,modules:this.analyzeModules(e),callGraph:this.buildCallGraph(n,e)}}async aiAnalyze(e,t){return{}}detectTechStack(e,t){let n={other:[]};if(t.techStack&&typeof t.techStack==`object`){let e=t.techStack;n.framework=e.framework,n.bundler=e.bundler,Array.isArray(e.libraries)&&(n.other=e.libraries)}e.includes(`React.`)||e.includes(`useState`)||e.includes(`useEffect`)?n.framework=`React`:e.includes(`Vue.`)||e.includes(`createApp`)?n.framework=`Vue`:e.includes(`@angular/`)&&(n.framework=`Angular`),e.includes(`__webpack_require__`)&&(n.bundler=`Webpack`);let r=[];return e.includes(`CryptoJS`)&&r.push(`CryptoJS`),e.includes(`JSEncrypt`)&&r.push(`JSEncrypt`),e.includes(`crypto-js`)&&r.push(`crypto-js`),r.length>0&&(n.cryptoLibrary=r),n}extractBusinessLogic(e,t){let n={mainFeatures:[],entities:[],rules:[],dataModel:{}};if(e.businessLogic&&typeof e.businessLogic==`object`){let t=e.businessLogic;Array.isArray(t.mainFeatures)&&(n.mainFeatures=t.mainFeatures),typeof t.dataFlow==`string`&&n.rules.push(t.dataFlow)}return t&&(n.dataModel={...n.dataModel,...t}),n}analyzeModules(e){let n=[];try{let t=j.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=[],i=[];M(t,{ImportDeclaration(e){r.push(e.node.source.value)},ExportNamedDeclaration(e){e.node.source&&i.push(e.node.source.value)},ExportDefaultDeclaration(){i.push(`default`)}}),(r.length>0||i.length>0)&&n.push({name:`current`,imports:r,exports:i})}catch(e){t.warn(`Module analysis failed`,e)}return n}buildCallGraph(e,n){let r=e.map(e=>({id:e.name,name:e.name,type:`function`})),i=[];try{let t=j.parse(n,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=``;M(t,{FunctionDeclaration(e){r=e.node.id?.name||``},FunctionExpression(e){let t=e.parent;t.type===`VariableDeclarator`&&t.id.type===`Identifier`&&(r=t.id.name)},CallExpression(t){if(r){let n=t.node.callee,a=``;n.type===`Identifier`?a=n.name:n.type===`MemberExpression`&&n.property.type===`Identifier`&&(a=n.property.name),a&&e.some(e=>e.name===a)&&i.push({from:r,to:a})}}})}catch(e){t.warn(`Call graph construction failed`,e)}return{nodes:r,edges:i}}calculateComplexity(e){let t=1;return Te(e)&&e.traverse({IfStatement(){t++},SwitchCase(){t++},ForStatement(){t++},WhileStatement(){t++},DoWhileStatement(){t++},ConditionalExpression(){t++},LogicalExpression(e){(e.node.operator===`&&`||e.node.operator===`||`)&&t++},CatchClause(){t++}}),t}async analyzeDataFlow(e){return we(e)}};function B(e){return{os:e.os,headless:e.headless,geoip:e.geoip,humanize:e.humanize,proxy:e.proxy,block_images:e.blockImages,block_webrtc:e.blockWebrtc,block_webgl:e.blockWebgl,locale:e.locale,addons:e.addons,fonts:e.fonts,exclude_addons:e.excludeAddons,custom_fonts_only:e.customFontsOnly,screen:e.screen,window:e.window,fingerprint:e.fingerprint,webgl_config:e.webglConfig,firefox_user_prefs:e.firefoxUserPrefs,main_world_eval:e.mainWorldEval,enable_cache:e.enableCache}}var De=class e{browser=null;browserServer=null;config;isClosing=!1;launchPromise;constructor(e={}){this.config={os:e.os??`windows`,headless:e.headless??!0,geoip:e.geoip??!1,humanize:e.humanize??!1,blockImages:e.blockImages??!1,blockWebrtc:e.blockWebrtc??!1,proxy:e.proxy,blockWebgl:e.blockWebgl,locale:e.locale,addons:e.addons,fonts:e.fonts,excludeAddons:e.excludeAddons,customFontsOnly:e.customFontsOnly,screen:e.screen,window:e.window,fingerprint:e.fingerprint,webglConfig:e.webglConfig,firefoxUserPrefs:e.firefoxUserPrefs,mainWorldEval:e.mainWorldEval,enableCache:e.enableCache}}async launch(){if(this.browser?.isConnected())return this.browser;if(this.isClosing)throw Error(`Cannot launch browser while closing`);if(this.launchPromise)return this.launchPromise;this.launchPromise=this.doLaunch();try{return await this.launchPromise}finally{this.launchPromise=void 0}}async doLaunch(){this.browser&&=(t.info(`Closing existing Camoufox browser before relaunch`),await this.browser.close().catch(e=>t.warn(`Failed to close previous browser:`,e)),null),t.info(`Launching Camoufox (Firefox) [os=${this.config.os}, headless=${this.config.headless}]...`);let e;try{({Camoufox:e}=await import(`camoufox-js`))}catch(e){throw new b(`camoufox-js is not installed or its binaries are missing. Run \`pnpm run install:full\` or \`pnpm exec camoufox-js fetch\` before using the Camoufox driver. Root cause: ${e instanceof Error?e.message:String(e)}`)}this.browser=await e(B(this.config));let n=this.browser;if(typeof n.process==`function`){let e=n.process.call(this.browser);e&&typeof e.unref==`function`&&c.register(e)}if(this.isClosing)throw await this.browser.close().catch(e=>{t.warn(`Failed to close Camoufox browser launched during shutdown:`,e)}),this.browser=null,Error(`Camoufox launch aborted because close was requested`);return t.info(`Camoufox browser launched`),this.browser}async newPage(){this.browser||await this.launch();let e=await this.browser.newPage();return t.info(`New Camoufox page created`),e}async goto(e,n){let r=n??await this.newPage();return t.info(`Navigating to: ${e}`),await r.goto(e,{waitUntil:`networkidle`}),r}async close(){this.isClosing=!0;let e=this.launchPromise;if(e){e.catch(()=>void 0).finally(()=>{this.finalizeClose()});return}await this.finalizeClose()}static BROWSER_CLOSE_TIMEOUT_MS=5e3;async finalizeClose(){try{let n=this.browser;this.browser=null,n&&(await Promise.race([n.close(),new Promise((t,n)=>setTimeout(()=>n(Error(`camoufox browser.close() timed out`)),e.BROWSER_CLOSE_TIMEOUT_MS))]),t.info(`Camoufox browser closed`))}finally{this.isClosing=!1}}async launchAsServer(e,n){t.info(`Launching Camoufox server [os=${this.config.os}, port=${e??`auto`}]...`);let r;try{({launchServer:r}=await import(`camoufox-js`))}catch(e){throw new b(`camoufox-js server support is unavailable. Run \`pnpm run install:full\` or \`pnpm exec camoufox-js fetch\` before launching a Camoufox WebSocket server. Root cause: ${e instanceof Error?e.message:String(e)}`)}let i={...B(this.config),port:e,ws_path:n};this.browserServer&&=(t.info(`Closing existing Camoufox server before relaunch`),await this.browserServer.close().catch(e=>t.warn(`Failed to close previous server:`,e)),null);let a=await r(i);this.browserServer=a;let o=this.browserServer;if(typeof o.process==`function`){let e=o.process.call(this.browserServer);e&&typeof e.unref==`function`&&c.register(e)}let s=a.wsEndpoint();return t.info(`Camoufox server listening on: ${s}`),s}async connectToServer(e){t.info(`Connecting to Camoufox server: ${e}`),this.browser&&=(t.info(`Disconnecting existing browser before new connection`),await this.browser.close().catch(e=>t.warn(`Failed to close previous browser:`,e)),null);let n=(await import(`playwright-core`)).firefox;return this.browser=await n.connect(e),t.info(`Connected to Camoufox server`),this.browser}async closeBrowserServer(){this.browserServer&&(await this.browserServer.close(),this.browserServer=null,t.info(`Camoufox server closed`))}getBrowserServerEndpoint(){return this.browserServer?this.browserServer.wsEndpoint():null}getBrowser(){return this.browser}async getCDPSession(e){return t.warn(`CDP sessions on camoufox (Firefox) have limited support — consider using Chrome driver for CDP-heavy operations`),e.context().newCDPSession(e)}};function V(e){return[...new Set(e)]}const Oe=[`captcha`,`challenge`,`verify`,`verification`,`robot`,`human`,`security check`,`bot check`,`anti-bot`],ke=[`browser check`,`security challenge`,`human check`,`verification widget`,`widget challenge`],Ae=[`验证码`,`安全验证`,`人机验证`,`滑动验证`,`身份验证`,`安全检测`],je=[`captcha`,`challenge`,`verify`,`verification`,`robot-check`,`security-check`,`bot-check`],Me=[`cdn-cgi/challenge`,`challenge-platform`,`browser-check`,`security-check`,`interstitial`],Ne=[`captcha-frame`,`challenge-frame`,`widget-challenge`,`siteverify`,`sitekey`],Pe=[`slider-verify`,`drag-verify`,`slide-check`],Fe=[`Please verify`,`Verify you are human`,`Complete the security check`,`Slide to verify`,`Click to verify`,`Drag the slider`,`Prove you are human`,`I am not a robot`,`Checking your browser`,`Just a moment`,`Checking if the site connection is secure`,`This process is automatic`,`Protected by`,`Powered by`,`Are you a robot`,`Confirm you are human`,`Security verification required`],Ie=[`请完成安全验证`,`请滑动验证`,`拖动滑块`,`点击验证`,`人机验证`,`安全检测中`,`请证明您是人类`,`正在检查您的浏览器`,`请稍候`,`验证您的身份`,`请完成验证`,`滑动滑块`,`请拖动滑块完成验证`];V([...Oe,...ke,...Ae]),V([...je,...Me,...Ne,...Pe]),V([...Fe,...Ie]);const H={slider:[`.captcha-slider`,`.verify-slider`,`#captcha-slider`,`.slide-verify`,`[class*="captcha"][class*="slider"]`,`[class*="verify"][class*="slider"]`,`[id*="captcha"][id*="slider"]`,`[id*="verify"][id*="slider"]`,`[aria-label*="slider" i]`],image:[`[class*="captcha-image"]`,`[id*="captcha-image"]`,`.verify-img`,`.captcha-img`,`img[src*="captcha"]`,`img[alt*=""]`,`img[alt*="captcha"]`],widget:[`iframe[src*="captcha" i]`,`iframe[src*="challenge" i]`,`iframe[title*="captcha" i]`,`iframe[title*="verification" i]`,`[data-sitekey]`,`[class*="captcha"][class*="widget"]`,`[class*="challenge"][class*="widget"]`,`[class*="human"][class*="check"]`],browserCheck:[`#challenge-form`,`[id*="challenge-form"]`,`[class*="browser-check"]`,`[class*="security-check"]`,`[class*="challenge-page"]`,`[class*="challenge-container"]`],generic:[`[class*="captcha"]`,`[id*="captcha"]`,`[class*="verify"]`,`[id*="verify"]`,`[class*="challenge"]`,`[id*="challenge"]`,`iframe[src*="captcha"]`,`iframe[src*="verify"]`]};H.slider,H.widget,H.browserCheck;const Le=[`verification code`,`enter code`,`sms code`,`email verification`,`phone verification`,`verify your email`,`verify your phone`],Re=[`verify-email`,`verify-phone`,`email-verification`,`account-verification`,`verify-account`,`phone-verification`,`sms-verification`,`reset-password`,`forgot-password`],ze=[`Enter verification code`,`Get code`,`Send code`,`Enter the code`,`We sent a code`,`verification code sent`,`Enter your authenticator code`,`Two-factor authentication`],Be=[`短信验证`,`邮箱验证`,`输入验证码`,`手机验证`,`登录验证`,`双重验证`],Ve=[`验证邮箱`,`验证手机`,`重置密码`],He=[`输入验证码`,`获取验证码`,`发送验证码`,`已发送验证码`,`双因素认证`],Ue=[`two-factor`,`2fa`,`two-factor authentication`];V([...Le,...Be,...Ue]),V([...Re,...Ve]),V([...ze,...He]);const We=[`captcha`,`verification challenge`,`security check`,`human verification`,`slide to verify`,`drag the slider`,`select all images`,`i am not a robot`,`protected by security verification`,`checking your browser`],Ge=[`验证码`,`人机验证`,`安全验证`,`滑动验证`,`拖动滑块`,`请完成验证`,`请完成安全验证`,`请证明您是人类`,`正在检查您的浏览器`],Ke=[`verification code`,`enter verification code`,`sms code`,`email verification`,`phone verification`,`two-factor authentication`,`authenticator code`],qe=[`输入验证码`,`短信验证码`,`邮箱验证码`,`获取验证码`,`发送验证码`,`双因素认证`],U=V([...We,...Ge]),Je=V([...Ke,...qe]),Ye=[`slider`,`image`,`widget`,`browser_check`,`page_redirect`,`url_redirect`,`text_input`,`none`,`unknown`],Xe=[`regional_service`,`embedded_widget`,`edge_service`,`managed_service`,`external_review`,`unknown`],Ze={checkbox:`widget`,challenge_widget:`widget`,browsercheck:`browser_check`,"browser-check":`browser_check`,redirect:`page_redirect`},Qe={regional:`regional_service`,embedded:`embedded_widget`,widget:`embedded_widget`,edge:`edge_service`,managed:`managed_service`,"external-ai-required":`external_review`,unknown:`unknown`},$e=U,et=[`captcha`,`challenge`,`slider`,`widget`,`checkbox`,`sitekey`,`browser-check`,`security-check`];var tt=class{screenshotDir;constructor(e=`./screenshots`){this.screenshotDir=e}async saveScreenshot(e){try{await de(this.screenshotDir,{recursive:!0});let n=`captcha-${Date.now()}.png`,r=ie(this.screenshotDir,n);return await fe(r,Buffer.from(e,`base64`)),t.info(`Screenshot saved: ${r}`),r}catch(e){throw t.error(`Failed to persist CAPTCHA screenshot`,e),e}}async detect(e){try{t.info(`Running rule-based captcha detection...`);let n=await this.getPageInfo(e),r=this.applyLocalGuardrails(n,this.evaluateFallbackTextAnalysis(n));return t.info(`CAPTCHA detection result: ${r.detected?`detected`:`not_detected`} (confidence: ${r.confidence}%)`),r}catch(e){return t.error(`CAPTCHA detection failed`,e),{detected:!1,type:`none`,confidence:0,reasoning:`Detection error: ${e instanceof Error?e.message:String(e)}`}}}async getPageInfo(e){return{url:e.url(),title:await e.title(),...await e.evaluate(()=>{let e=document.body.innerText.substring(0,1e3),t=document.querySelectorAll(`iframe`).length>0,n=[];for(let e of[`[class*="captcha"]`,`[id*="captcha"]`,`[class*="verify"]`,`[id*="verify"]`,`[class*="challenge"]`,`iframe[src*="captcha" i]`,`iframe[src*="challenge" i]`,`[data-sitekey]`,`[class*="browser-check"]`]){let t=document.querySelectorAll(e);t.length>0&&n.push(`${e} (${t.length})`)}return{bodyText:e,hasIframes:t,suspiciousElements:n}})}}normalizeCaptchaType(e,t){if(!t)return`none`;if(typeof e==`string`){if(Ye.includes(e))return e;let t=Ze[e.toLowerCase()];if(t)return t}return`unknown`}normalizeProviderHint(e,t){if(typeof e==`string`){if(Xe.includes(e))return e;let t=Qe[e.toLowerCase()];if(t)return t}return t?`unknown`:void 0}normalizeDetected(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return!1}normalizeConfidence(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}applyLocalGuardrails(e,t){return t.detected||!this.hasStrongOverrideSignals(e)?t:{...this.evaluateFallbackTextAnalysis(e),reasoning:`AI reported no CAPTCHA, but local heuristics found strong CAPTCHA signals in the page context. / AI 判定为无验证码,但本地启发式在页面上下文中发现强信号。`,screenshotPath:t.screenshotPath}}hasStrongCaptchaElementSignals(e){return e.some(e=>{let t=e.toLowerCase();return et.some(e=>t.includes(e))})}hasStrongOverrideSignals(e){let t=`${e.title}\n${e.bodyText}`.toLowerCase();return this.hasStrongCaptchaElementSignals(e.suspiciousElements)?$e.some(e=>t.includes(e)):!1}evaluateFallbackTextAnalysis(e){let t=`${e.url}\n${e.title}\n${e.bodyText}`.toLowerCase(),n=this.hasStrongCaptchaElementSignals(e.suspiciousElements),r=U.some(e=>t.includes(e)),i=n&&r,a=Je.some(e=>t.includes(e));if(a&&!i)return{detected:!1,type:`none`,confidence:95,reasoning:`Fallback heuristics matched OTP or account verification text, not a CAPTCHA. / 后备启发式匹配到一次性验证码或账户校验文本,不视为 CAPTCHA。`,suggestions:[`Continue the login or verification flow normally / 继续正常登录或验证流程`]};let o=i;return{detected:o,type:o?`unknown`:`none`,confidence:o?a?55:60:90,reasoning:o?a?`Fallback heuristics found strong CAPTCHA signals despite OTP-like wording on the page. / 后备启发式发现了强 CAPTCHA 信号,优先于页面上的一次性验证码类文案。`:`Fallback heuristics matched both suspicious elements and CAPTCHA keywords. / 后备启发式匹配到可疑元素和验证码关键词。`:`Fallback heuristics did not find strong CAPTCHA signals. / 后备启发式未找到强验证码信号。`,suggestions:o?[`Switch to headed mode if needed / 如需要切换到有头模式`,`Wait for manual completion before continuing / 等待手动完成后继续`]:[`Solve the CAPTCHA manually if one is visible / 如有可见验证码请手动解决`]}}async waitForCompletion(e,n=3e5){t.info(`Waiting for CAPTCHA to be solved...`);let r=Date.now();for(;Date.now()-r<n;){let n=await this.detect(e);if(!n.detected||n.confidence<50)return t.info(`CAPTCHA is no longer detected; continuing workflow`),!0;await new Promise(e=>setTimeout(e,3e3))}return t.error(`Timed out while waiting for CAPTCHA completion`),!1}},nt=class{keywordRules=new Map;libraryRules=new Map;constantRules=new Map;patternRules=new Map;securityRules=new Map;constructor(){this.loadDefaultRules()}loadDefaultRules(){this.addKeywordRule({category:`symmetric`,keywords:[`AES`,`DES`,`3DES`,`TripleDES`,`RC4`,`RC2`,`Blowfish`,`Twofish`,`ChaCha20`,`Camellia`,`SEED`,`ARIA`,`SM4`],confidence:.6,description:`Symmetric encryption algorithms`}),this.addKeywordRule({category:`asymmetric`,keywords:[`RSA`,`ECC`,`ECDSA`,`ECDH`,`DSA`,`ElGamal`,`Ed25519`,`X25519`,`Curve25519`,`secp256k1`,`SM2`],confidence:.6,description:`Asymmetric encryption algorithms`}),this.addKeywordRule({category:`hash`,keywords:[`MD5`,`SHA1`,`SHA-1`,`SHA256`,`SHA-256`,`SHA512`,`SHA-512`,`SHA3`,`BLAKE2`,`BLAKE3`,`RIPEMD`,`Whirlpool`,`SM3`,`Keccak`],confidence:.6,description:`Hash algorithms`}),this.addKeywordRule({category:`encoding`,keywords:[`Base64`,`Base32`,`Base58`,`Hex`,`UTF8`,`UTF-8`,`Latin1`,`ASCII`],confidence:.5,description:`Encoding methods`}),this.addKeywordRule({category:`mode`,keywords:[`CBC`,`ECB`,`CTR`,`GCM`,`CFB`,`OFB`,`XTS`,`CCM`],confidence:.7,description:`Block cipher modes`}),this.addKeywordRule({category:`padding`,keywords:[`PKCS7`,`PKCS5`,`PKCS1`,`ISO10126`,`ZeroPadding`,`NoPadding`,`OAEP`,`PSS`],confidence:.7,description:`Padding schemes`}),this.addLibraryRule({name:`CryptoJS`,patterns:[`CryptoJS`,`crypto-js`],versionPattern:/CryptoJS\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`AES`,`DES`,`TripleDES`,`RC4`,`Rabbit`,`MD5`,`SHA1`,`SHA256`,`SHA512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`JSEncrypt`,patterns:[`JSEncrypt`,`jsencrypt`],versionPattern:/version:\s*['"]([^'"]+)['"]/,confidence:.9,features:[`RSA`]}),this.addLibraryRule({name:`forge`,patterns:[`forge.`,`node-forge`],versionPattern:/forge\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`RSA`,`AES`,`DES`,`3DES`,`MD5`,`SHA1`,`SHA256`,`SHA512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`sjcl`,patterns:[`sjcl.`],versionPattern:/sjcl\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`AES`,`SHA256`,`HMAC`,`PBKDF2`,`CCM`,`GCM`]}),this.addLibraryRule({name:`Web Crypto API`,patterns:[`crypto.subtle`,`window.crypto.subtle`,`self.crypto.subtle`],confidence:.95,features:[`AES-CBC`,`AES-CTR`,`AES-GCM`,`RSA-OAEP`,`RSA-PSS`,`ECDSA`,`ECDH`,`SHA-1`,`SHA-256`,`SHA-384`,`SHA-512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`asmCrypto`,patterns:[`asmCrypto`],confidence:.9,features:[`AES`,`RSA`,`SHA256`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`TweetNaCl`,patterns:[`nacl.`,`tweetnacl`],confidence:.9,features:[`Curve25519`,`Ed25519`,`Salsa20`,`Poly1305`]}),this.addLibraryRule({name:`elliptic`,patterns:[`elliptic`,`ec.keyFromPrivate`,`ec.keyFromPublic`],confidence:.9,features:[`ECDSA`,`ECDH`,`secp256k1`]}),this.addConstantRule({name:`MD5`,type:`hash`,values:[1732584193,4023233417,2562383102,271733878],confidence:.95,description:`MD5 initialization vector`}),this.addConstantRule({name:`SHA1`,type:`hash`,values:[1732584193,4023233417,2562383102,271733878,3285377520],confidence:.95,description:`SHA-1 initialization vector`}),this.addConstantRule({name:`SHA256`,type:`hash`,values:[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],confidence:.95,description:`SHA-256 initialization vector`}),this.addConstantRule({name:`AES S-box`,type:`symmetric`,values:[99,124,119,123,242,107,111,197],confidence:.9,description:`AES S-box first 8 values`}),this.addSecurityRule({name:`weak-md5`,severity:`high`,check:e=>e.algorithm===`MD5`,message:`MD5 is cryptographically broken and should not be used`,recommendation:`Use SHA-256 or SHA-3 instead`}),this.addSecurityRule({name:`weak-sha1`,severity:`high`,check:e=>e.algorithm===`SHA1`||e.algorithm===`SHA-1`,message:`SHA-1 is deprecated and vulnerable to collision attacks`,recommendation:`Use SHA-256 or SHA-3 instead`}),this.addSecurityRule({name:`weak-des`,severity:`critical`,check:e=>e.algorithm===`DES`,message:`DES has a very small key size (56 bits) and is easily broken`,recommendation:`Use AES-256 instead`}),this.addSecurityRule({name:`weak-rc4`,severity:`critical`,check:e=>e.algorithm===`RC4`,message:`RC4 has known vulnerabilities and should not be used`,recommendation:`Use AES-GCM or ChaCha20-Poly1305 instead`}),this.addSecurityRule({name:`ecb-mode`,severity:`high`,check:e=>e.mode===`ECB`,message:`ECB mode is insecure as it does not provide semantic security`,recommendation:`Use CBC, CTR, or GCM mode instead`}),this.addSecurityRule({name:`no-padding`,severity:`medium`,check:e=>e.padding===`NoPadding`&&e.mode!==`CTR`&&e.mode!==`GCM`,message:`Using no padding with non-streaming modes can be insecure`,recommendation:`Use PKCS7 padding or switch to CTR/GCM mode`}),this.addSecurityRule({name:`short-key`,severity:`high`,check:e=>!!(e.keySize&&e.keySize<128),message:`Key size is too short and vulnerable to brute force attacks`,recommendation:`Use at least 128-bit keys, preferably 256-bit`})}addKeywordRule(e){this.keywordRules.set(e.category,e)}addLibraryRule(e){this.libraryRules.set(e.name,e)}addConstantRule(e){this.constantRules.set(e.name,e)}addPatternRule(e){this.patternRules.set(e.name,e)}addSecurityRule(e){this.securityRules.set(e.name,e)}getKeywordRules(){return Array.from(this.keywordRules.values())}getLibraryRules(){return Array.from(this.libraryRules.values())}getConstantRules(){return Array.from(this.constantRules.values())}getPatternRules(){return Array.from(this.patternRules.values())}getSecurityRules(){return Array.from(this.securityRules.values())}loadFromJSON(e){try{let t=JSON.parse(e);t.keywords&&t.keywords.forEach(e=>this.addKeywordRule(e)),t.libraries&&t.libraries.forEach(e=>this.addLibraryRule(e)),t.constants&&t.constants.forEach(e=>this.addConstantRule(e))}catch(e){throw Error(`Failed to load rules from JSON: ${e}`,{cause:e})}}exportToJSON(){return JSON.stringify({keywords:this.getKeywordRules(),libraries:this.getLibraryRules(),constants:this.getConstantRules(),patterns:this.getPatternRules(),security:this.getSecurityRules()},null,2)}},rt=class{rulesManager;constructor(e,t){this.rulesManager=t||new nt}loadCustomRules(e){this.rulesManager.loadFromJSON(e)}exportRules(){return this.rulesManager.exportToJSON()}async detect(e){t.info(`Starting crypto detection...`);let n=Date.now();try{let{code:r}=e,i=[],a=[],o=[],s=this.detectByKeywords(r);i.push(...s);let c=this.detectLibraries(r);a.push(...c);let l=this.detectByAST(r);i.push(...l.algorithms),l.parameters&&this.mergeParameters(i,l.parameters);let u=this.mergeResults(i),d=this.evaluateSecurity(u,r);o.push(...d);let f=this.analyzeStrength(u,o),p=u.length>0?u.reduce((e,t)=>e+t.confidence,0)/u.length:0;return t.info(`Crypto detection completed in ${Date.now()-n}ms, found ${u.length} algorithms`),{algorithms:u,libraries:a,confidence:p,securityIssues:o,strength:f}}catch(e){throw t.error(`Crypto detection failed`,e),e}}detectByKeywords(e){let t=[];return this.rulesManager.getKeywordRules().forEach(n=>{n.keywords.forEach(r=>{let i=RegExp(`\\b${this.escapeRegex(r)}\\b`,`gi`),a=e.match(i);if(a){if(n.category===`mode`||n.category===`padding`)return;t.push({name:r,type:n.category,confidence:n.confidence,location:{file:`current`,line:this.findLineNumber(e,r)},usage:`Found ${a.length} occurrence(s) of ${r}${n.description?` (${n.description})`:``}`})}})}),t}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}detectLibraries(e){let t=[];return this.rulesManager.getLibraryRules().forEach(n=>{if(n.patterns.some(t=>e.includes(t))){let r;n.versionPattern&&(r=e.match(n.versionPattern)?.[1]),t.push({name:n.name,version:r,confidence:n.confidence})}}),t}detectByAST(e){let n=[],r=new Map;try{let t=j.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),i=this.rulesManager.getConstantRules();M(t,{VariableDeclarator(e){let t=e.node;t.init?.type===`ArrayExpression`&&t.init.elements.length===256&&t.id.type===`Identifier`&&(t.id.name.toLowerCase().includes(`sbox`)||t.id.name.toLowerCase().includes(`box`)||t.id.name.toLowerCase().includes(`table`))&&n.push({name:`Custom Symmetric Cipher`,type:`symmetric`,confidence:.8,location:{file:`current`,line:t.loc?.start.line||0},usage:`S-box array detected (${t.id.name})`})},CallExpression(e){let t=e.node;if(N.isMemberExpression(t.callee)&&N.isIdentifier(t.callee.property)){let e=t.callee.property.name;[`modPow`,`modInverse`,`gcd`,`isProbablePrime`].includes(e)&&n.push({name:`Asymmetric Encryption`,type:`asymmetric`,confidence:.75,location:{file:`current`,line:t.loc?.start.line||0},usage:`Big number operation detected: ${e}`}),it(t,r)}},FunctionDeclaration(t){let r=t.node,i=r.id?.name.toLowerCase()||``;if(i.includes(`hash`)||i.includes(`digest`)||i.includes(`checksum`)){let t=e.substring(r.start||0,r.end||0),a=t.includes(`for`)||t.includes(`while`),o=/>>>|<<|&|\||\^/.test(t);a&&o&&n.push({name:`Custom Hash Function`,type:`hash`,confidence:.7,location:{file:`current`,line:r.loc?.start.line||0},usage:`Hash function detected: ${i}`})}},ArrayExpression(e){let t=e.node.elements;if(t.length<4)return;let r=[];t.forEach(e=>{N.isNumericLiteral(e)&&r.push(e.value)}),i.forEach(t=>{if(t.values.every((e,t)=>r[t]===e)){let r=t.type===`other`?`encoding`:t.type;n.push({name:t.name,type:r,confidence:t.confidence,location:{file:`current`,line:e.node.loc?.start.line||0},usage:`${t.name} initialization constants detected`})}})}})}catch(e){t.warn(`AST detection failed`,e)}return{algorithms:n,parameters:r}}mergeParameters(e,t){e.forEach(e=>{let n=t.get(e.name);n&&(e.parameters={...e.parameters,...n})})}evaluateSecurity(e,t){let n=[],r=this.rulesManager.getSecurityRules();return e.forEach(e=>{let t={algorithm:e.name,mode:e.parameters?.mode,padding:e.parameters?.padding,keySize:e.parameters?.keySize};r.forEach(r=>{r.check(t)&&n.push({severity:r.severity,algorithm:e.name,issue:r.message,recommendation:r.recommendation||``,location:e.location})})}),n}analyzeStrength(e,t){let n=100,r=100,i=100,a=100;t.forEach(e=>{let t={critical:40,high:25,medium:15,low:5}[e.severity];e.issue.includes(`algorithm`)||e.issue.includes(`broken`)?n-=t:e.issue.includes(`key`)?r-=t:e.issue.includes(`mode`)?i-=t:a-=t}),n=Math.max(0,n),r=Math.max(0,r),i=Math.max(0,i),a=Math.max(0,a);let o=(n+r+i+a)/4,s;return s=o>=80?`strong`:o>=60?`moderate`:o>=40?`weak`:`broken`,{overall:s,score:Math.round(o),factors:{algorithm:Math.round(n),keySize:Math.round(r),mode:Math.round(i),implementation:Math.round(a)}}}mergeResults(e){let t=new Map;return e.forEach(e=>{let n=`${e.name}-${e.type}`,r=t.get(n);(!r||e.confidence>r.confidence)&&t.set(n,e)}),Array.from(t.values()).toSorted((e,t)=>t.confidence-e.confidence)}findLineNumber(e,t){let n=e.split(`
|
|
321
|
-
`);for(let e=0;e<n.length;e++)if(n[e]?.includes(t))return e+1;return 0}};function it(e,t){if(!
|
|
319
|
+
`.trim()}function F(e){let t=[],n=e;for(;P.isMemberExpression(n);)P.isIdentifier(n.property)&&t.unshift(n.property.name),n=n.object;return P.isIdentifier(n)&&t.unshift(n.name),t.join(`.`)}function I(e,t){let{callee:n}=e;if(P.isIdentifier(n))return t.has(n.name);if(P.isMemberExpression(n)){let e=F(n);return t.has(e)}return!1}function ve(e,n){let r=[];Array.isArray(n.securityRisks)&&n.securityRisks.forEach(e=>{if(typeof e==`object`&&e){let t=e;r.push({type:t.type||`other`,severity:t.severity||`low`,location:{file:`current`,line:t.location?.line||0},description:t.description||``,recommendation:t.recommendation||``})}});try{N(M.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),{AssignmentExpression(e){let t=e.node.left,n=e.node.loc?.start.line||0;if(P.isMemberExpression(t)&&P.isIdentifier(t.property)){let e=t.property.name;[`innerHTML`,`outerHTML`,`insertAdjacentHTML`].includes(e)&&r.push({type:`xss`,severity:`high`,location:{file:`current`,line:n},description:`Potential XSS vulnerability: Direct assignment to ${e} without sanitization`,recommendation:`Use textContent for plain text, or DOMPurify.sanitize() for HTML content`}),e===`write`&&P.isIdentifier(t.object)&&t.object.name===`document`&&r.push({type:`xss`,severity:`high`,location:{file:`current`,line:n},description:`Dangerous use of document.write() which can lead to XSS`,recommendation:`Use modern DOM manipulation methods instead`})}},CallExpression(e){let t=e.node.callee,n=e.node.loc?.start.line||0;if(P.isIdentifier(t)&&(t.name===`eval`&&r.push({type:`other`,severity:`critical`,location:{file:`current`,line:n},description:`Critical: Use of eval() allows arbitrary code execution`,recommendation:`Refactor to avoid eval(). Use JSON.parse() for data, or proper function calls`}),t.name===`Function`&&r.push({type:`other`,severity:`critical`,location:{file:`current`,line:n},description:`Critical: Function constructor allows code injection`,recommendation:`Use regular function declarations or arrow functions`}),[`setTimeout`,`setInterval`].includes(t.name))){let i=e.node.arguments[0];(P.isStringLiteral(i)||P.isIdentifier(i)&&i.name!==`function`)&&r.push({type:`other`,severity:`medium`,location:{file:`current`,line:n},description:`${t.name}() with string argument can lead to code injection`,recommendation:`Use ${t.name}() with function reference instead of string`})}if(P.isMemberExpression(t)&&P.isIdentifier(t.property)){let i=t.property.name;if([`query`,`execute`,`exec`,`run`].includes(i)){let t=e.node.arguments[0];(P.isBinaryExpression(t)||P.isTemplateLiteral(t))&&r.push({type:`sql-injection`,severity:`critical`,location:{file:`current`,line:n},description:`Potential SQL injection: Query built with string concatenation`,recommendation:`Use parameterized queries or prepared statements`})}}},MemberExpression(e){let t=e.node.object,n=e.node.property,i=e.node.loc?.start.line||0;if(P.isIdentifier(t)&&t.name===`Math`&&P.isIdentifier(n)&&n.name===`random`){let t=e.parent;(P.isCallExpression(t)||P.isBinaryExpression(t))&&r.push({type:`other`,severity:`medium`,location:{file:`current`,line:i},description:`Math.random() is not cryptographically secure`,recommendation:`Use crypto.getRandomValues() or crypto.randomBytes() for security-sensitive operations`})}},VariableDeclarator(e){let t=e.node.id,n=e.node.init,i=e.node.loc?.start.line||0;if(P.isIdentifier(t)&&P.isStringLiteral(n)){let e=t.name.toLowerCase(),a=n.value;for(let{pattern:t,type:n}of[{pattern:/(password|passwd|pwd)/i,type:`password`},{pattern:/(api[_-]?key|apikey)/i,type:`API key`},{pattern:/(secret|token|auth)/i,type:`secret`},{pattern:/(private[_-]?key|privatekey)/i,type:`private key`}])if(t.test(e)&&a.length>8){r.push({type:`other`,severity:`critical`,location:{file:`current`,line:i},description:`Hardcoded ${n} detected in source code`,recommendation:`Store ${n} in environment variables or secure configuration`});break}}}})}catch(e){t.warn(`Static security analysis failed`,e)}return r.filter((e,t,n)=>t===n.findIndex(t=>t.type===e.type&&t.location.line===e.location.line))}function ye(e,t,n,r,i){let a=100,o=100;t.forEach(e=>{e.severity===`critical`?o-=20:e.severity===`high`?o-=10:e.severity===`medium`?o-=5:o-=2}),o=Math.max(0,o);let s=100;if(r)r.cyclomaticComplexity>20?s-=30:r.cyclomaticComplexity>10?s-=15:r.cyclomaticComplexity>5&&(s-=5),r.cognitiveComplexity>15?s-=20:r.cognitiveComplexity>10&&(s-=10);else{let t=e.functions.reduce((e,t)=>e+t.complexity,0)/(e.functions.length||1);t>10?s-=20:t>5&&(s-=10)}s=Math.max(0,s);let c=r?.maintainabilityIndex||70,l=100;i&&i.forEach(e=>{e.severity===`high`?l-=10:e.severity===`medium`?l-=5:l-=2}),l=Math.max(0,l);let u=70;return typeof n.qualityScore==`number`&&(u=n.qualityScore),a=o*.4+s*.25+c*.2+l*.15,typeof n.qualityScore==`number`&&(a=(a+u)/2),Math.round(Math.max(0,Math.min(100,a)))}function be(e){let n=[],r=[];try{let t=M.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]});N(t,{VariableDeclarator(e){let t=e.node.init;P.isCallExpression(t)&&P.isFunctionExpression(t.callee)&&t.callee.body.body.some(e=>P.isReturnStatement(e)&&P.isObjectExpression(e.argument))&&n.push({name:`Singleton Pattern`,location:e.node.loc?.start.line||0,description:`IIFE returning object (Singleton pattern)`})},ClassDeclaration(e){let t=e.node.body.body.filter(e=>P.isClassMethod(e)).map(e=>P.isClassMethod(e)&&P.isIdentifier(e.key)?e.key.name:``);t.includes(`subscribe`)&&t.includes(`unsubscribe`)&&t.includes(`notify`)&&n.push({name:`Observer Pattern`,location:e.node.loc?.start.line||0,description:`Class with subscribe/unsubscribe/notify methods`})},FunctionDeclaration(e){let t=e.node.loc;if(t){let e=t.end.line-t.start.line;e>50&&r.push({name:`Long Function`,location:t.start.line,severity:`medium`,recommendation:`Function is ${e} lines long. Consider breaking it into smaller functions (max 50 lines)`})}},IfStatement(e){let t=0,n=e.parentPath;for(;n;)(n.isIfStatement()||n.isForStatement()||n.isWhileStatement())&&t++,n=n.parentPath;t>3&&r.push({name:`Deep Nesting`,location:e.node.loc?.start.line||0,severity:`medium`,recommendation:`Nesting depth is ${t}. Consider extracting to separate functions or using early returns`})},NumericLiteral(e){let t=e.node.value,n=e.parent;[0,1,-1,2,10,100,1e3].includes(t)||P.isMemberExpression(n)&&n.property===e.node||P.isAssignmentPattern(n)||r.push({name:`Magic Number`,location:e.node.loc?.start.line||0,severity:`low`,recommendation:`Replace magic number ${t} with a named constant`})},CatchClause(e){e.node.body.body.length===0&&r.push({name:`Empty Catch Block`,location:e.node.loc?.start.line||0,severity:`high`,recommendation:`Empty catch block swallows errors. Add proper error handling or logging`})},VariableDeclaration(e){e.node.kind===`var`&&r.push({name:`Use of var`,location:e.node.loc?.start.line||0,severity:`low`,recommendation:`Use let or const instead of var for better scoping`})}}),Se(t).forEach(e=>{r.push({name:`Duplicate Code`,location:e.location,severity:`medium`,recommendation:`Duplicate code found at lines ${e.location} and ${e.duplicateLocation}. Extract into a reusable function.`})})}catch(e){t.warn(`Code pattern detection failed`,e)}return{patterns:n,antiPatterns:r}}function xe(e){let n=1,r=0,i=0,a=0,o=new Set,s=new Set;try{let t=M.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),c=0;N(t,{IfStatement(){n++},SwitchCase(){n++},ForStatement(){n++},WhileStatement(){n++},DoWhileStatement(){n++},ConditionalExpression(){n++},LogicalExpression(e){(e.node.operator===`&&`||e.node.operator===`||`)&&n++},CatchClause(){n++},"IfStatement|ForStatement|WhileStatement|DoWhileStatement":{enter(){c++,r+=c},exit(){c--}},BinaryExpression(e){i++,o.add(e.node.operator)},UnaryExpression(e){i++,o.add(e.node.operator)},Identifier(e){a++,s.add(e.node.name)},NumericLiteral(e){a++,s.add(String(e.node.value))},StringLiteral(e){a++,s.add(e.node.value)}})}catch(e){t.warn(`Complexity metrics calculation failed`,e)}let c=o.size,l=s.size,u=i,d=a,f=c+l,p=u+d,m=c/2*(d/(l||1)),h=m*p,g=p*Math.log2(f||1),_=e.split(`
|
|
320
|
+
`).length,v=Math.max(0,171-5.2*Math.log(g||1)-.23*n-16.2*Math.log(_));return{cyclomaticComplexity:n,cognitiveComplexity:r,maintainabilityIndex:Math.round(v),halsteadMetrics:{vocabulary:f,length:p,difficulty:Math.round(m*100)/100,effort:Math.round(h)}}}function Se(e){let n=[],r=[];try{N(e,{FunctionDeclaration(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},FunctionExpression(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},ArrowFunctionExpression(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})},ClassMethod(e){let t=L(e.node),n=R(e.node);r.push({node:e.node,hash:t,location:e.node.loc?.start.line||0,normalizedCode:n})}});for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){let i=r[e],a=r[t];if(i.hash===a.hash){n.push({location:i.location,duplicateLocation:a.location,similarity:1});continue}let o=Ce(i.normalizedCode,a.normalizedCode);o>=.85&&n.push({location:i.location,duplicateLocation:a.location,similarity:o})}}catch(e){t.debug(`Duplicate code detection failed`,e)}return n}function L(e){let t=JSON.stringify(e,(e,t)=>{if(![`loc`,`start`,`end`,`range`].includes(e)&&!(e===`comments`||e===`leadingComments`||e===`trailingComments`))return t}),n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return n.toString(36)}function R(e){let t=0,n=new Map,r=P.cloneNode(e,!0,!1);return N(P.file(P.program([r])),{Identifier(e){let r=e.node.name;[`console`,`window`,`document`,`Math`,`JSON`,`Array`,`Object`,`String`,`Number`].includes(r)||(n.has(r)||n.set(r,`VAR_${t++}`),e.node.name=n.get(r))},StringLiteral(e){e.node.value=`STRING`},NumericLiteral(e){e.node.value=0}}),JSON.stringify(r)}function Ce(e,t){let n=e.length,r=t.length;if(Math.abs(n-r)>Math.max(n,r)*.3)return 0;let i=Array.from({length:n+1},()=>Array.from({length:r+1},()=>0));for(let e=0;e<=n;e++)i[e][0]=e;for(let e=0;e<=r;e++)i[0][e]=e;for(let a=1;a<=n;a++)for(let n=1;n<=r;n++){let r=e[a-1]===t[n-1]?0:1;i[a][n]=Math.min(i[a-1][n]+1,i[a][n-1]+1,i[a-1][n-1]+r)}return 1-i[n][r]/Math.max(n,r)}async function we(e){let n={nodes:[],edges:[]},r=[],i=[],a=[],o=new Map,s=new Set(`encodeURIComponent,encodeURI,escape,decodeURIComponent,decodeURI,htmlentities,htmlspecialchars,escapeHtml,escapeHTML,he.encode,he.escape,validator.escape,validator.unescape,validator.stripLow,validator.blacklist,validator.whitelist,validator.trim,validator.isEmail,validator.isURL,validator.isInt,DOMPurify.sanitize,DOMPurify.addHook,crypto.encrypt,crypto.hash,crypto.createHash,crypto.createHmac,CryptoJS.AES.encrypt,CryptoJS.SHA256,CryptoJS.MD5,bcrypt.hash,bcrypt.compare,btoa,atob,Buffer.from,db.prepare,db.query,mysql.escape,pg.query,xss,sanitizeHtml,parseInt,parseFloat,Number,String,JSON.stringify,JSON.parse,String.prototype.replace,String.prototype.trim,Array.prototype.filter,Array.prototype.map`.split(`,`));try{let c=M.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]});N(c,{CallExpression(e){let t=e.node.callee,s=e.node.loc?.start.line||0;if(P.isMemberExpression(t)&&P.isIdentifier(t.property)){let i=t.property.name;if([`fetch`,`ajax`,`get`,`post`,`request`,`axios`].includes(i)){let t=`source-network-${s}`;r.push({type:`network`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${i}()`,type:`source`,location:{file:`current`,line:s}});let a=e.parent;P.isVariableDeclarator(a)&&P.isIdentifier(a.id)&&o.set(a.id.name,{sourceType:`network`,sourceLine:s})}else if([`querySelector`,`getElementById`,`getElementsByClassName`,`getElementsByTagName`].includes(i)){let e=`source-dom-${s}`;r.push({type:`user_input`,location:{file:`current`,line:s}}),n.nodes.push({id:e,name:`${i}()`,type:`source`,location:{file:`current`,line:s}})}}if(P.isIdentifier(t)){let r=t.name;if([`eval`,`Function`,`setTimeout`,`setInterval`].includes(r)){let t=`sink-eval-${s}`;i.push({type:`eval`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}()`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}}if(P.isMemberExpression(t)&&P.isIdentifier(t.property)){let r=t.property.name;if([`write`,`writeln`].includes(r)&&P.isIdentifier(t.object)&&t.object.name===`document`){let t=`sink-document-write-${s}`;i.push({type:`xss`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`document.${r}()`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`query`,`execute`,`exec`,`run`].includes(r)){let t=`sink-sql-${s}`;i.push({type:`sql-injection`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (SQL)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`exec`,`spawn`,`execSync`,`spawnSync`].includes(r)){let t=`sink-command-${s}`;i.push({type:`other`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (Command)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}if([`readFile`,`writeFile`,`readFileSync`,`writeFileSync`,`open`].includes(r)){let t=`sink-file-${s}`;i.push({type:`other`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:`${r}() (File)`,type:`sink`,location:{file:`current`,line:s}}),z(e.node.arguments,o,a,r,s)}}},MemberExpression(e){let t=e.node.object,i=e.node.property,a=e.node.loc?.start.line||0;if(P.isIdentifier(t)&&t.name===`location`&&P.isIdentifier(i)&&[`href`,`search`,`hash`,`pathname`].includes(i.name)){let t=`source-url-${a}`;r.push({type:`user_input`,location:{file:`current`,line:a}}),n.nodes.push({id:t,name:`location.${i.name}`,type:`source`,location:{file:`current`,line:a}});let s=e.parent;P.isVariableDeclarator(s)&&P.isIdentifier(s.id)&&o.set(s.id.name,{sourceType:`url`,sourceLine:a})}if(P.isIdentifier(t)&&t.name===`document`&&P.isIdentifier(i)&&i.name===`cookie`){let e=`source-cookie-${a}`;r.push({type:`storage`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`document.cookie`,type:`source`,location:{file:`current`,line:a}})}if(P.isIdentifier(t)&&[`localStorage`,`sessionStorage`].includes(t.name)){let e=`source-storage-${a}`;r.push({type:`storage`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`${t.name}.getItem()`,type:`source`,location:{file:`current`,line:a}})}if(P.isIdentifier(t)&&t.name===`window`&&P.isIdentifier(i)&&i.name===`name`){let e=`source-window-name-${a}`;r.push({type:`user_input`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`window.name`,type:`source`,location:{file:`current`,line:a}})}if(P.isIdentifier(t)&&t.name===`event`&&P.isIdentifier(i)&&i.name===`data`){let e=`source-postmessage-${a}`;r.push({type:`network`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`event.data (postMessage)`,type:`source`,location:{file:`current`,line:a}})}if(P.isIdentifier(t)&&t.name===`message`&&P.isIdentifier(i)&&i.name===`data`){let e=`source-websocket-${a}`;r.push({type:`network`,location:{file:`current`,line:a}}),n.nodes.push({id:e,name:`WebSocket message.data`,type:`source`,location:{file:`current`,line:a}})}},AssignmentExpression(e){let t=e.node.left,r=e.node.right,s=e.node.loc?.start.line||0;if(P.isMemberExpression(t)&&P.isIdentifier(t.property)){let e=t.property.name;if([`innerHTML`,`outerHTML`].includes(e)){let t=`sink-dom-${s}`;if(i.push({type:`xss`,location:{file:`current`,line:s}}),n.nodes.push({id:t,name:e,type:`sink`,location:{file:`current`,line:s}}),P.isIdentifier(r)&&o.has(r.name)){let e=o.get(r.name);a.push({source:{type:e.sourceType,location:{file:`current`,line:e.sourceLine}},sink:{type:`xss`,location:{file:`current`,line:s}},path:[{file:`current`,line:e.sourceLine},{file:`current`,line:s}]})}}}}}),N(c,{VariableDeclarator(e){let n=e.node.id,r=e.node.init;if(P.isIdentifier(n)&&r){if(P.isCallExpression(r)&&I(r,s)){let e=r.arguments[0];if(P.isIdentifier(e)&&o.has(e.name)){t.debug(`Taint cleaned by sanitizer: ${e.name} -> ${n.name}`);return}}if(P.isIdentifier(r)&&o.has(r.name)){let e=o.get(r.name);o.set(n.name,e)}else if(P.isBinaryExpression(r)){let e=P.isIdentifier(r.left)&&o.has(r.left.name),t=P.isIdentifier(r.right)&&o.has(r.right.name);if(e||t){let t=e?o.get(r.left.name):o.get(r.right.name);o.set(n.name,t)}}else if(P.isCallExpression(r)){let e=r.arguments[0];if(P.isIdentifier(e)&&o.has(e.name)){let t=o.get(e.name);o.set(n.name,t)}}}},AssignmentExpression(e){let t=e.node.left,n=e.node.right;if(P.isIdentifier(t)&&P.isIdentifier(n)&&o.has(n.name)){let e=o.get(n.name);o.set(t.name,e)}}})}catch(e){t.warn(`Data flow analysis failed`,e)}return{graph:n,sources:r,sinks:i,taintPaths:a}}function z(e,t,n,r,i){e.forEach(e=>{if(P.isIdentifier(e)&&t.has(e.name)){let r=t.get(e.name);n.push({source:{type:r.sourceType,location:{file:`current`,line:r.sourceLine}},sink:{type:`eval`,location:{file:`current`,line:i}},path:[{file:`current`,line:r.sourceLine},{file:`current`,line:i}]})}})}const Te=e=>typeof e==`object`&&!!e&&`traverse`in e&&typeof e.traverse==`function`;var Ee=class{constructor(e){}async understand(e){t.info(`Starting code understanding...`);let n=Date.now();try{let{code:r,context:i,focus:a=`all`}=e,o=await this.analyzeStructure(r);t.debug(`Code structure analyzed`);let s=await this.aiAnalyze(r,a);t.debug(`AI analysis completed`);let c=this.detectTechStack(r,s);t.debug(`Tech stack detected`);let l=this.extractBusinessLogic(s,i);t.debug(`Business logic extracted`);let u=await this.analyzeDataFlow(r);t.debug(`Data flow analyzed`);let d=ve(r,s);t.debug(`Security risks identified`);let{patterns:f,antiPatterns:p}=be(r);t.debug(`Detected ${f.length} patterns and ${p.length} anti-patterns`);let m=xe(r);t.debug(`Complexity metrics calculated`);let h=ye(o,d,s,m,p),g=Date.now()-n;return t.success(`Code understanding completed in ${g}ms`),{structure:o,techStack:c,businessLogic:l,dataFlow:u,securityRisks:d,qualityScore:h,codePatterns:f,antiPatterns:p,complexityMetrics:m}}catch(e){throw t.error(`Code understanding failed`,e),e}}async analyzeStructure(e){let n=[],r=[];try{N(M.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),{FunctionDeclaration:e=>{let t=e.node;n.push({name:t.id?.name||`anonymous`,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},FunctionExpression:e=>{let t=e.node,r=e.parent,i=`anonymous`;r.type===`VariableDeclarator`&&r.id.type===`Identifier`?i=r.id.name:r.type===`AssignmentExpression`&&r.left.type===`Identifier`&&(i=r.left.name),n.push({name:i,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},ArrowFunctionExpression:e=>{let t=e.node,r=e.parent,i=`arrow`;r.type===`VariableDeclarator`&&r.id.type===`Identifier`&&(i=r.id.name),n.push({name:i,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:this.calculateComplexity(e)})},ClassDeclaration(e){let t=e.node,n=[],i=[];e.traverse({ClassMethod(e){let t=e.node;n.push({name:t.key.type===`Identifier`?t.key.name:`unknown`,params:t.params.map(e=>e.type===`Identifier`?e.name:`unknown`),location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column},complexity:1})},ClassProperty(e){let t=e.node;t.key.type===`Identifier`&&i.push({name:t.key.name,type:void 0,value:void 0})}}),r.push({name:t.id?.name||`anonymous`,methods:n,properties:i,location:{file:`current`,line:t.loc?.start.line||0,column:t.loc?.start.column}})}})}catch(e){t.warn(`Failed to parse code structure`,e)}return{functions:n,classes:r,modules:this.analyzeModules(e),callGraph:this.buildCallGraph(n,e)}}async aiAnalyze(e,t){return{}}detectTechStack(e,t){let n={other:[]};if(t.techStack&&typeof t.techStack==`object`){let e=t.techStack;n.framework=e.framework,n.bundler=e.bundler,Array.isArray(e.libraries)&&(n.other=e.libraries)}e.includes(`React.`)||e.includes(`useState`)||e.includes(`useEffect`)?n.framework=`React`:e.includes(`Vue.`)||e.includes(`createApp`)?n.framework=`Vue`:e.includes(`@angular/`)&&(n.framework=`Angular`),e.includes(`__webpack_require__`)&&(n.bundler=`Webpack`);let r=[];return e.includes(`CryptoJS`)&&r.push(`CryptoJS`),e.includes(`JSEncrypt`)&&r.push(`JSEncrypt`),e.includes(`crypto-js`)&&r.push(`crypto-js`),r.length>0&&(n.cryptoLibrary=r),n}extractBusinessLogic(e,t){let n={mainFeatures:[],entities:[],rules:[],dataModel:{}};if(e.businessLogic&&typeof e.businessLogic==`object`){let t=e.businessLogic;Array.isArray(t.mainFeatures)&&(n.mainFeatures=t.mainFeatures),typeof t.dataFlow==`string`&&n.rules.push(t.dataFlow)}return t&&(n.dataModel={...n.dataModel,...t}),n}analyzeModules(e){let n=[];try{let t=M.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=[],i=[];N(t,{ImportDeclaration(e){r.push(e.node.source.value)},ExportNamedDeclaration(e){e.node.source&&i.push(e.node.source.value)},ExportDefaultDeclaration(){i.push(`default`)}}),(r.length>0||i.length>0)&&n.push({name:`current`,imports:r,exports:i})}catch(e){t.warn(`Module analysis failed`,e)}return n}buildCallGraph(e,n){let r=e.map(e=>({id:e.name,name:e.name,type:`function`})),i=[];try{let t=M.parse(n,{sourceType:`module`,plugins:[`jsx`,`typescript`]}),r=``;N(t,{FunctionDeclaration(e){r=e.node.id?.name||``},FunctionExpression(e){let t=e.parent;t.type===`VariableDeclarator`&&t.id.type===`Identifier`&&(r=t.id.name)},CallExpression(t){if(r){let n=t.node.callee,a=``;n.type===`Identifier`?a=n.name:n.type===`MemberExpression`&&n.property.type===`Identifier`&&(a=n.property.name),a&&e.some(e=>e.name===a)&&i.push({from:r,to:a})}}})}catch(e){t.warn(`Call graph construction failed`,e)}return{nodes:r,edges:i}}calculateComplexity(e){let t=1;return Te(e)&&e.traverse({IfStatement(){t++},SwitchCase(){t++},ForStatement(){t++},WhileStatement(){t++},DoWhileStatement(){t++},ConditionalExpression(){t++},LogicalExpression(e){(e.node.operator===`&&`||e.node.operator===`||`)&&t++},CatchClause(){t++}}),t}async analyzeDataFlow(e){return we(e)}};function B(e){return{os:e.os,headless:e.headless,geoip:e.geoip,humanize:e.humanize,proxy:e.proxy,block_images:e.blockImages,block_webrtc:e.blockWebrtc,block_webgl:e.blockWebgl,locale:e.locale,addons:e.addons,fonts:e.fonts,exclude_addons:e.excludeAddons,custom_fonts_only:e.customFontsOnly,screen:e.screen,window:e.window,fingerprint:e.fingerprint,webgl_config:e.webglConfig,firefox_user_prefs:e.firefoxUserPrefs,main_world_eval:e.mainWorldEval,enable_cache:e.enableCache}}var De=class e{browser=null;browserServer=null;config;isClosing=!1;launchPromise;constructor(e={}){this.config={os:e.os??`windows`,headless:e.headless??!0,geoip:e.geoip??!1,humanize:e.humanize??!1,blockImages:e.blockImages??!1,blockWebrtc:e.blockWebrtc??!1,proxy:e.proxy,blockWebgl:e.blockWebgl,locale:e.locale,addons:e.addons,fonts:e.fonts,excludeAddons:e.excludeAddons,customFontsOnly:e.customFontsOnly,screen:e.screen,window:e.window,fingerprint:e.fingerprint,webglConfig:e.webglConfig,firefoxUserPrefs:e.firefoxUserPrefs,mainWorldEval:e.mainWorldEval,enableCache:e.enableCache}}async launch(){if(this.browser?.isConnected())return this.browser;if(this.isClosing)throw Error(`Cannot launch browser while closing`);if(this.launchPromise)return this.launchPromise;this.launchPromise=this.doLaunch();try{return await this.launchPromise}finally{this.launchPromise=void 0}}async doLaunch(){this.browser&&=(t.info(`Closing existing Camoufox browser before relaunch`),await this.browser.close().catch(e=>t.warn(`Failed to close previous browser:`,e)),null),t.info(`Launching Camoufox (Firefox) [os=${this.config.os}, headless=${this.config.headless}]...`);let e;try{({Camoufox:e}=await import(`camoufox-js`))}catch(e){throw new w(`camoufox-js is not installed or its binaries are missing. Run \`pnpm run install:full\` or \`pnpm exec camoufox-js fetch\` before using the Camoufox driver. Root cause: ${e instanceof Error?e.message:String(e)}`)}this.browser=await e(B(this.config));let n=this.browser;if(typeof n.process==`function`){let e=n.process.call(this.browser);e&&typeof e.unref==`function`&&d.register(e)}if(this.isClosing)throw await this.browser.close().catch(e=>{t.warn(`Failed to close Camoufox browser launched during shutdown:`,e)}),this.browser=null,Error(`Camoufox launch aborted because close was requested`);return t.info(`Camoufox browser launched`),this.browser}async newPage(){this.browser||await this.launch();let e=await this.browser.newPage();return t.info(`New Camoufox page created`),e}async goto(e,n){let r=n??await this.newPage();return t.info(`Navigating to: ${e}`),await r.goto(e,{waitUntil:`networkidle`}),r}async close(){this.isClosing=!0;let e=this.launchPromise;if(e){e.catch(()=>void 0).finally(()=>{this.finalizeClose()});return}await this.finalizeClose()}static BROWSER_CLOSE_TIMEOUT_MS=5e3;async finalizeClose(){try{let n=this.browser;this.browser=null,n&&(await Promise.race([n.close(),new Promise((t,n)=>setTimeout(()=>n(Error(`camoufox browser.close() timed out`)),e.BROWSER_CLOSE_TIMEOUT_MS))]),t.info(`Camoufox browser closed`))}finally{this.isClosing=!1}}async launchAsServer(e,n){t.info(`Launching Camoufox server [os=${this.config.os}, port=${e??`auto`}]...`);let r;try{({launchServer:r}=await import(`camoufox-js`))}catch(e){throw new w(`camoufox-js server support is unavailable. Run \`pnpm run install:full\` or \`pnpm exec camoufox-js fetch\` before launching a Camoufox WebSocket server. Root cause: ${e instanceof Error?e.message:String(e)}`)}let i={...B(this.config),port:e,ws_path:n};this.browserServer&&=(t.info(`Closing existing Camoufox server before relaunch`),await this.browserServer.close().catch(e=>t.warn(`Failed to close previous server:`,e)),null);let a=await r(i);this.browserServer=a;let o=this.browserServer;if(typeof o.process==`function`){let e=o.process.call(this.browserServer);e&&typeof e.unref==`function`&&d.register(e)}let s=a.wsEndpoint();return t.info(`Camoufox server listening on: ${s}`),s}async connectToServer(e){t.info(`Connecting to Camoufox server: ${e}`),this.browser&&=(t.info(`Disconnecting existing browser before new connection`),await this.browser.close().catch(e=>t.warn(`Failed to close previous browser:`,e)),null);let n=(await import(`playwright-core`)).firefox;return this.browser=await n.connect(e),t.info(`Connected to Camoufox server`),this.browser}async closeBrowserServer(){this.browserServer&&(await this.browserServer.close(),this.browserServer=null,t.info(`Camoufox server closed`))}getBrowserServerEndpoint(){return this.browserServer?this.browserServer.wsEndpoint():null}getBrowser(){return this.browser}async getCDPSession(e){return t.warn(`CDP sessions on camoufox (Firefox) have limited support — consider using Chrome driver for CDP-heavy operations`),e.context().newCDPSession(e)}};function V(e){return[...new Set(e)]}const Oe=[`captcha`,`challenge`,`verify`,`verification`,`robot`,`human`,`security check`,`bot check`,`anti-bot`],ke=[`browser check`,`security challenge`,`human check`,`verification widget`,`widget challenge`],Ae=[`验证码`,`安全验证`,`人机验证`,`滑动验证`,`身份验证`,`安全检测`],je=[`captcha`,`challenge`,`verify`,`verification`,`robot-check`,`security-check`,`bot-check`],Me=[`cdn-cgi/challenge`,`challenge-platform`,`browser-check`,`security-check`,`interstitial`],Ne=[`captcha-frame`,`challenge-frame`,`widget-challenge`,`siteverify`,`sitekey`],Pe=[`slider-verify`,`drag-verify`,`slide-check`],Fe=[`Please verify`,`Verify you are human`,`Complete the security check`,`Slide to verify`,`Click to verify`,`Drag the slider`,`Prove you are human`,`I am not a robot`,`Checking your browser`,`Just a moment`,`Checking if the site connection is secure`,`This process is automatic`,`Protected by`,`Powered by`,`Are you a robot`,`Confirm you are human`,`Security verification required`],Ie=[`请完成安全验证`,`请滑动验证`,`拖动滑块`,`点击验证`,`人机验证`,`安全检测中`,`请证明您是人类`,`正在检查您的浏览器`,`请稍候`,`验证您的身份`,`请完成验证`,`滑动滑块`,`请拖动滑块完成验证`];V([...Oe,...ke,...Ae]),V([...je,...Me,...Ne,...Pe]),V([...Fe,...Ie]);const H={slider:[`.captcha-slider`,`.verify-slider`,`#captcha-slider`,`.slide-verify`,`[class*="captcha"][class*="slider"]`,`[class*="verify"][class*="slider"]`,`[id*="captcha"][id*="slider"]`,`[id*="verify"][id*="slider"]`,`[aria-label*="slider" i]`],image:[`[class*="captcha-image"]`,`[id*="captcha-image"]`,`.verify-img`,`.captcha-img`,`img[src*="captcha"]`,`img[alt*=""]`,`img[alt*="captcha"]`],widget:[`iframe[src*="captcha" i]`,`iframe[src*="challenge" i]`,`iframe[title*="captcha" i]`,`iframe[title*="verification" i]`,`[data-sitekey]`,`[class*="captcha"][class*="widget"]`,`[class*="challenge"][class*="widget"]`,`[class*="human"][class*="check"]`],browserCheck:[`#challenge-form`,`[id*="challenge-form"]`,`[class*="browser-check"]`,`[class*="security-check"]`,`[class*="challenge-page"]`,`[class*="challenge-container"]`],generic:[`[class*="captcha"]`,`[id*="captcha"]`,`[class*="verify"]`,`[id*="verify"]`,`[class*="challenge"]`,`[id*="challenge"]`,`iframe[src*="captcha"]`,`iframe[src*="verify"]`]};H.slider,H.widget,H.browserCheck;const Le=[`verification code`,`enter code`,`sms code`,`email verification`,`phone verification`,`verify your email`,`verify your phone`],Re=[`verify-email`,`verify-phone`,`email-verification`,`account-verification`,`verify-account`,`phone-verification`,`sms-verification`,`reset-password`,`forgot-password`],ze=[`Enter verification code`,`Get code`,`Send code`,`Enter the code`,`We sent a code`,`verification code sent`,`Enter your authenticator code`,`Two-factor authentication`],Be=[`短信验证`,`邮箱验证`,`输入验证码`,`手机验证`,`登录验证`,`双重验证`],Ve=[`验证邮箱`,`验证手机`,`重置密码`],He=[`输入验证码`,`获取验证码`,`发送验证码`,`已发送验证码`,`双因素认证`],Ue=[`two-factor`,`2fa`,`two-factor authentication`];V([...Le,...Be,...Ue]),V([...Re,...Ve]),V([...ze,...He]);const We=[`captcha`,`verification challenge`,`security check`,`human verification`,`slide to verify`,`drag the slider`,`select all images`,`i am not a robot`,`protected by security verification`,`checking your browser`],Ge=[`验证码`,`人机验证`,`安全验证`,`滑动验证`,`拖动滑块`,`请完成验证`,`请完成安全验证`,`请证明您是人类`,`正在检查您的浏览器`],Ke=[`verification code`,`enter verification code`,`sms code`,`email verification`,`phone verification`,`two-factor authentication`,`authenticator code`],qe=[`输入验证码`,`短信验证码`,`邮箱验证码`,`获取验证码`,`发送验证码`,`双因素认证`],U=V([...We,...Ge]),Je=V([...Ke,...qe]),Ye=[`slider`,`image`,`widget`,`browser_check`,`page_redirect`,`url_redirect`,`text_input`,`none`,`unknown`],Xe=[`regional_service`,`embedded_widget`,`edge_service`,`managed_service`,`external_review`,`unknown`],Ze={checkbox:`widget`,challenge_widget:`widget`,browsercheck:`browser_check`,"browser-check":`browser_check`,redirect:`page_redirect`},Qe={regional:`regional_service`,embedded:`embedded_widget`,widget:`embedded_widget`,edge:`edge_service`,managed:`managed_service`,"external-ai-required":`external_review`,unknown:`unknown`},$e=U,et=[`captcha`,`challenge`,`slider`,`widget`,`checkbox`,`sitekey`,`browser-check`,`security-check`];var tt=class{screenshotDir;constructor(e=`./screenshots`){this.screenshotDir=e}async saveScreenshot(e){try{await ue(this.screenshotDir,{recursive:!0});let n=`captcha-${Date.now()}.png`,r=re(this.screenshotDir,n);return await de(r,Buffer.from(e,`base64`)),t.info(`Screenshot saved: ${r}`),r}catch(e){throw t.error(`Failed to persist CAPTCHA screenshot`,e),e}}async detect(e){try{t.info(`Running rule-based captcha detection...`);let n=await this.getPageInfo(e),r=this.applyLocalGuardrails(n,this.evaluateFallbackTextAnalysis(n));return t.info(`CAPTCHA detection result: ${r.detected?`detected`:`not_detected`} (confidence: ${r.confidence}%)`),r}catch(e){return t.error(`CAPTCHA detection failed`,e),{detected:!1,type:`none`,confidence:0,reasoning:`Detection error: ${e instanceof Error?e.message:String(e)}`}}}async getPageInfo(e){return{url:e.url(),title:await e.title(),...await e.evaluate(()=>{let e=document.body.innerText.substring(0,1e3),t=document.querySelectorAll(`iframe`).length>0,n=[];for(let e of[`[class*="captcha"]`,`[id*="captcha"]`,`[class*="verify"]`,`[id*="verify"]`,`[class*="challenge"]`,`iframe[src*="captcha" i]`,`iframe[src*="challenge" i]`,`[data-sitekey]`,`[class*="browser-check"]`]){let t=document.querySelectorAll(e);t.length>0&&n.push(`${e} (${t.length})`)}return{bodyText:e,hasIframes:t,suspiciousElements:n}})}}normalizeCaptchaType(e,t){if(!t)return`none`;if(typeof e==`string`){if(Ye.includes(e))return e;let t=Ze[e.toLowerCase()];if(t)return t}return`unknown`}normalizeProviderHint(e,t){if(typeof e==`string`){if(Xe.includes(e))return e;let t=Qe[e.toLowerCase()];if(t)return t}return t?`unknown`:void 0}normalizeDetected(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return!1}normalizeConfidence(e){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(100,t)):0}applyLocalGuardrails(e,t){return t.detected||!this.hasStrongOverrideSignals(e)?t:{...this.evaluateFallbackTextAnalysis(e),reasoning:`AI reported no CAPTCHA, but local heuristics found strong CAPTCHA signals in the page context. / AI 判定为无验证码,但本地启发式在页面上下文中发现强信号。`,screenshotPath:t.screenshotPath}}hasStrongCaptchaElementSignals(e){return e.some(e=>{let t=e.toLowerCase();return et.some(e=>t.includes(e))})}hasStrongOverrideSignals(e){let t=`${e.title}\n${e.bodyText}`.toLowerCase();return this.hasStrongCaptchaElementSignals(e.suspiciousElements)?$e.some(e=>t.includes(e)):!1}evaluateFallbackTextAnalysis(e){let t=`${e.url}\n${e.title}\n${e.bodyText}`.toLowerCase(),n=this.hasStrongCaptchaElementSignals(e.suspiciousElements),r=U.some(e=>t.includes(e)),i=n&&r,a=Je.some(e=>t.includes(e));if(a&&!i)return{detected:!1,type:`none`,confidence:95,reasoning:`Fallback heuristics matched OTP or account verification text, not a CAPTCHA. / 后备启发式匹配到一次性验证码或账户校验文本,不视为 CAPTCHA。`,suggestions:[`Continue the login or verification flow normally / 继续正常登录或验证流程`]};let o=i;return{detected:o,type:o?`unknown`:`none`,confidence:o?a?55:60:90,reasoning:o?a?`Fallback heuristics found strong CAPTCHA signals despite OTP-like wording on the page. / 后备启发式发现了强 CAPTCHA 信号,优先于页面上的一次性验证码类文案。`:`Fallback heuristics matched both suspicious elements and CAPTCHA keywords. / 后备启发式匹配到可疑元素和验证码关键词。`:`Fallback heuristics did not find strong CAPTCHA signals. / 后备启发式未找到强验证码信号。`,suggestions:o?[`Switch to headed mode if needed / 如需要切换到有头模式`,`Wait for manual completion before continuing / 等待手动完成后继续`]:[`Solve the CAPTCHA manually if one is visible / 如有可见验证码请手动解决`]}}async waitForCompletion(e,n=3e5){t.info(`Waiting for CAPTCHA to be solved...`);let r=Date.now();for(;Date.now()-r<n;){let n=await this.detect(e);if(!n.detected||n.confidence<50)return t.info(`CAPTCHA is no longer detected; continuing workflow`),!0;await new Promise(e=>setTimeout(e,3e3))}return t.error(`Timed out while waiting for CAPTCHA completion`),!1}},nt=class{keywordRules=new Map;libraryRules=new Map;constantRules=new Map;patternRules=new Map;securityRules=new Map;constructor(){this.loadDefaultRules()}loadDefaultRules(){this.addKeywordRule({category:`symmetric`,keywords:[`AES`,`DES`,`3DES`,`TripleDES`,`RC4`,`RC2`,`Blowfish`,`Twofish`,`ChaCha20`,`Camellia`,`SEED`,`ARIA`,`SM4`],confidence:.6,description:`Symmetric encryption algorithms`}),this.addKeywordRule({category:`asymmetric`,keywords:[`RSA`,`ECC`,`ECDSA`,`ECDH`,`DSA`,`ElGamal`,`Ed25519`,`X25519`,`Curve25519`,`secp256k1`,`SM2`],confidence:.6,description:`Asymmetric encryption algorithms`}),this.addKeywordRule({category:`hash`,keywords:[`MD5`,`SHA1`,`SHA-1`,`SHA256`,`SHA-256`,`SHA512`,`SHA-512`,`SHA3`,`BLAKE2`,`BLAKE3`,`RIPEMD`,`Whirlpool`,`SM3`,`Keccak`],confidence:.6,description:`Hash algorithms`}),this.addKeywordRule({category:`encoding`,keywords:[`Base64`,`Base32`,`Base58`,`Hex`,`UTF8`,`UTF-8`,`Latin1`,`ASCII`],confidence:.5,description:`Encoding methods`}),this.addKeywordRule({category:`mode`,keywords:[`CBC`,`ECB`,`CTR`,`GCM`,`CFB`,`OFB`,`XTS`,`CCM`],confidence:.7,description:`Block cipher modes`}),this.addKeywordRule({category:`padding`,keywords:[`PKCS7`,`PKCS5`,`PKCS1`,`ISO10126`,`ZeroPadding`,`NoPadding`,`OAEP`,`PSS`],confidence:.7,description:`Padding schemes`}),this.addLibraryRule({name:`CryptoJS`,patterns:[`CryptoJS`,`crypto-js`],versionPattern:/CryptoJS\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`AES`,`DES`,`TripleDES`,`RC4`,`Rabbit`,`MD5`,`SHA1`,`SHA256`,`SHA512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`JSEncrypt`,patterns:[`JSEncrypt`,`jsencrypt`],versionPattern:/version:\s*['"]([^'"]+)['"]/,confidence:.9,features:[`RSA`]}),this.addLibraryRule({name:`forge`,patterns:[`forge.`,`node-forge`],versionPattern:/forge\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`RSA`,`AES`,`DES`,`3DES`,`MD5`,`SHA1`,`SHA256`,`SHA512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`sjcl`,patterns:[`sjcl.`],versionPattern:/sjcl\.version\s*=\s*['"]([^'"]+)['"]/,confidence:.9,features:[`AES`,`SHA256`,`HMAC`,`PBKDF2`,`CCM`,`GCM`]}),this.addLibraryRule({name:`Web Crypto API`,patterns:[`crypto.subtle`,`window.crypto.subtle`,`self.crypto.subtle`],confidence:.95,features:[`AES-CBC`,`AES-CTR`,`AES-GCM`,`RSA-OAEP`,`RSA-PSS`,`ECDSA`,`ECDH`,`SHA-1`,`SHA-256`,`SHA-384`,`SHA-512`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`asmCrypto`,patterns:[`asmCrypto`],confidence:.9,features:[`AES`,`RSA`,`SHA256`,`HMAC`,`PBKDF2`]}),this.addLibraryRule({name:`TweetNaCl`,patterns:[`nacl.`,`tweetnacl`],confidence:.9,features:[`Curve25519`,`Ed25519`,`Salsa20`,`Poly1305`]}),this.addLibraryRule({name:`elliptic`,patterns:[`elliptic`,`ec.keyFromPrivate`,`ec.keyFromPublic`],confidence:.9,features:[`ECDSA`,`ECDH`,`secp256k1`]}),this.addConstantRule({name:`MD5`,type:`hash`,values:[1732584193,4023233417,2562383102,271733878],confidence:.95,description:`MD5 initialization vector`}),this.addConstantRule({name:`SHA1`,type:`hash`,values:[1732584193,4023233417,2562383102,271733878,3285377520],confidence:.95,description:`SHA-1 initialization vector`}),this.addConstantRule({name:`SHA256`,type:`hash`,values:[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],confidence:.95,description:`SHA-256 initialization vector`}),this.addConstantRule({name:`AES S-box`,type:`symmetric`,values:[99,124,119,123,242,107,111,197],confidence:.9,description:`AES S-box first 8 values`}),this.addSecurityRule({name:`weak-md5`,severity:`high`,check:e=>e.algorithm===`MD5`,message:`MD5 is cryptographically broken and should not be used`,recommendation:`Use SHA-256 or SHA-3 instead`}),this.addSecurityRule({name:`weak-sha1`,severity:`high`,check:e=>e.algorithm===`SHA1`||e.algorithm===`SHA-1`,message:`SHA-1 is deprecated and vulnerable to collision attacks`,recommendation:`Use SHA-256 or SHA-3 instead`}),this.addSecurityRule({name:`weak-des`,severity:`critical`,check:e=>e.algorithm===`DES`,message:`DES has a very small key size (56 bits) and is easily broken`,recommendation:`Use AES-256 instead`}),this.addSecurityRule({name:`weak-rc4`,severity:`critical`,check:e=>e.algorithm===`RC4`,message:`RC4 has known vulnerabilities and should not be used`,recommendation:`Use AES-GCM or ChaCha20-Poly1305 instead`}),this.addSecurityRule({name:`ecb-mode`,severity:`high`,check:e=>e.mode===`ECB`,message:`ECB mode is insecure as it does not provide semantic security`,recommendation:`Use CBC, CTR, or GCM mode instead`}),this.addSecurityRule({name:`no-padding`,severity:`medium`,check:e=>e.padding===`NoPadding`&&e.mode!==`CTR`&&e.mode!==`GCM`,message:`Using no padding with non-streaming modes can be insecure`,recommendation:`Use PKCS7 padding or switch to CTR/GCM mode`}),this.addSecurityRule({name:`short-key`,severity:`high`,check:e=>!!(e.keySize&&e.keySize<128),message:`Key size is too short and vulnerable to brute force attacks`,recommendation:`Use at least 128-bit keys, preferably 256-bit`})}addKeywordRule(e){this.keywordRules.set(e.category,e)}addLibraryRule(e){this.libraryRules.set(e.name,e)}addConstantRule(e){this.constantRules.set(e.name,e)}addPatternRule(e){this.patternRules.set(e.name,e)}addSecurityRule(e){this.securityRules.set(e.name,e)}getKeywordRules(){return Array.from(this.keywordRules.values())}getLibraryRules(){return Array.from(this.libraryRules.values())}getConstantRules(){return Array.from(this.constantRules.values())}getPatternRules(){return Array.from(this.patternRules.values())}getSecurityRules(){return Array.from(this.securityRules.values())}loadFromJSON(e){try{let t=JSON.parse(e);t.keywords&&t.keywords.forEach(e=>this.addKeywordRule(e)),t.libraries&&t.libraries.forEach(e=>this.addLibraryRule(e)),t.constants&&t.constants.forEach(e=>this.addConstantRule(e))}catch(e){throw Error(`Failed to load rules from JSON: ${e}`,{cause:e})}}exportToJSON(){return JSON.stringify({keywords:this.getKeywordRules(),libraries:this.getLibraryRules(),constants:this.getConstantRules(),patterns:this.getPatternRules(),security:this.getSecurityRules()},null,2)}},rt=class{rulesManager;constructor(e,t){this.rulesManager=t||new nt}loadCustomRules(e){this.rulesManager.loadFromJSON(e)}exportRules(){return this.rulesManager.exportToJSON()}async detect(e){t.info(`Starting crypto detection...`);let n=Date.now();try{let{code:r}=e,i=[],a=[],o=[],s=this.detectByKeywords(r);i.push(...s);let c=this.detectLibraries(r);a.push(...c);let l=this.detectByAST(r);i.push(...l.algorithms),l.parameters&&this.mergeParameters(i,l.parameters);let u=this.mergeResults(i),d=this.evaluateSecurity(u,r);o.push(...d);let f=this.analyzeStrength(u,o),p=u.length>0?u.reduce((e,t)=>e+t.confidence,0)/u.length:0;return t.info(`Crypto detection completed in ${Date.now()-n}ms, found ${u.length} algorithms`),{algorithms:u,libraries:a,confidence:p,securityIssues:o,strength:f}}catch(e){throw t.error(`Crypto detection failed`,e),e}}detectByKeywords(e){let t=[];return this.rulesManager.getKeywordRules().forEach(n=>{n.keywords.forEach(r=>{let i=RegExp(`\\b${this.escapeRegex(r)}\\b`,`gi`),a=e.match(i);if(a){if(n.category===`mode`||n.category===`padding`)return;t.push({name:r,type:n.category,confidence:n.confidence,location:{file:`current`,line:this.findLineNumber(e,r)},usage:`Found ${a.length} occurrence(s) of ${r}${n.description?` (${n.description})`:``}`})}})}),t}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}detectLibraries(e){let t=[];return this.rulesManager.getLibraryRules().forEach(n=>{if(n.patterns.some(t=>e.includes(t))){let r;n.versionPattern&&(r=e.match(n.versionPattern)?.[1]),t.push({name:n.name,version:r,confidence:n.confidence})}}),t}detectByAST(e){let n=[],r=new Map;try{let t=M.parse(e,{sourceType:`module`,plugins:[`jsx`,`typescript`],errorRecovery:!0}),i=this.rulesManager.getConstantRules();N(t,{VariableDeclarator(e){let t=e.node;t.init?.type===`ArrayExpression`&&t.init.elements.length===256&&t.id.type===`Identifier`&&(t.id.name.toLowerCase().includes(`sbox`)||t.id.name.toLowerCase().includes(`box`)||t.id.name.toLowerCase().includes(`table`))&&n.push({name:`Custom Symmetric Cipher`,type:`symmetric`,confidence:.8,location:{file:`current`,line:t.loc?.start.line||0},usage:`S-box array detected (${t.id.name})`})},CallExpression(e){let t=e.node;if(P.isMemberExpression(t.callee)&&P.isIdentifier(t.callee.property)){let e=t.callee.property.name;[`modPow`,`modInverse`,`gcd`,`isProbablePrime`].includes(e)&&n.push({name:`Asymmetric Encryption`,type:`asymmetric`,confidence:.75,location:{file:`current`,line:t.loc?.start.line||0},usage:`Big number operation detected: ${e}`}),it(t,r)}},FunctionDeclaration(t){let r=t.node,i=r.id?.name.toLowerCase()||``;if(i.includes(`hash`)||i.includes(`digest`)||i.includes(`checksum`)){let t=e.substring(r.start||0,r.end||0),a=t.includes(`for`)||t.includes(`while`),o=/>>>|<<|&|\||\^/.test(t);a&&o&&n.push({name:`Custom Hash Function`,type:`hash`,confidence:.7,location:{file:`current`,line:r.loc?.start.line||0},usage:`Hash function detected: ${i}`})}},ArrayExpression(e){let t=e.node.elements;if(t.length<4)return;let r=[];t.forEach(e=>{P.isNumericLiteral(e)&&r.push(e.value)}),i.forEach(t=>{if(t.values.every((e,t)=>r[t]===e)){let r=t.type===`other`?`encoding`:t.type;n.push({name:t.name,type:r,confidence:t.confidence,location:{file:`current`,line:e.node.loc?.start.line||0},usage:`${t.name} initialization constants detected`})}})}})}catch(e){t.warn(`AST detection failed`,e)}return{algorithms:n,parameters:r}}mergeParameters(e,t){e.forEach(e=>{let n=t.get(e.name);n&&(e.parameters={...e.parameters,...n})})}evaluateSecurity(e,t){let n=[],r=this.rulesManager.getSecurityRules();return e.forEach(e=>{let t={algorithm:e.name,mode:e.parameters?.mode,padding:e.parameters?.padding,keySize:e.parameters?.keySize};r.forEach(r=>{r.check(t)&&n.push({severity:r.severity,algorithm:e.name,issue:r.message,recommendation:r.recommendation||``,location:e.location})})}),n}analyzeStrength(e,t){let n=100,r=100,i=100,a=100;t.forEach(e=>{let t={critical:40,high:25,medium:15,low:5}[e.severity];e.issue.includes(`algorithm`)||e.issue.includes(`broken`)?n-=t:e.issue.includes(`key`)?r-=t:e.issue.includes(`mode`)?i-=t:a-=t}),n=Math.max(0,n),r=Math.max(0,r),i=Math.max(0,i),a=Math.max(0,a);let o=(n+r+i+a)/4,s;return s=o>=80?`strong`:o>=60?`moderate`:o>=40?`weak`:`broken`,{overall:s,score:Math.round(o),factors:{algorithm:Math.round(n),keySize:Math.round(r),mode:Math.round(i),implementation:Math.round(a)}}}mergeResults(e){let t=new Map;return e.forEach(e=>{let n=`${e.name}-${e.type}`,r=t.get(n);(!r||e.confidence>r.confidence)&&t.set(n,e)}),Array.from(t.values()).toSorted((e,t)=>t.confidence-e.confidence)}findLineNumber(e,t){let n=e.split(`
|
|
321
|
+
`);for(let e=0;e<n.length;e++)if(n[e]?.includes(t))return e+1;return 0}};function it(e,t){if(!P.isMemberExpression(e.callee))return;let n=at(e.callee);if(n.includes(`CryptoJS`)){let r=n.match(/CryptoJS\.(AES|DES|TripleDES|RC4|Rabbit|RabbitLegacy)/);if(r){let n=r[1],i={};e.arguments.length>=3&&P.isObjectExpression(e.arguments[2])&&e.arguments[2].properties.forEach(e=>{if(P.isObjectProperty(e)&&P.isIdentifier(e.key)){let t=e.key.name;P.isIdentifier(e.value)?i[t]=e.value.name:(P.isStringLiteral(e.value)||P.isNumericLiteral(e.value))&&(i[t]=e.value.value)}}),n&&t.set(n,i)}}if(n.includes(`crypto.subtle`)&&n.match(/\.(encrypt|decrypt|sign|verify|digest|generateKey)/)&&e.arguments.length>0){let n=e.arguments[0];if(P.isObjectExpression(n)){let e={};n.properties.forEach(t=>{if(P.isObjectProperty(t)&&P.isIdentifier(t.key)){let n=t.key.name;(P.isStringLiteral(t.value)||P.isNumericLiteral(t.value))&&(e[n]=t.value.value)}});let r=e.name||`WebCrypto`;r&&t.set(r,e)}}}function at(e){let t=[],n=e=>{P.isMemberExpression(e)?(n(e.object),P.isIdentifier(e.property)&&t.push(e.property.name)):P.isIdentifier(e)&&t.push(e.name)};return n(e),t.join(`.`)}function W(e){let t=[];return(e.includes(`_0x`)||e.includes(`\\x`)||/var\s+_0x[a-f0-9]+\s*=/.test(e))&&t.push(`javascript-obfuscator`),(e.includes(`__webpack_require__`)||e.includes(`webpackJsonp`))&&t.push(`webpack`),e.length>1e3&&!e.includes(`
|
|
322
322
|
`)&&t.push(`uglify`),e.includes(`eval`)&&e.includes(`Function`)&&t.push(`vm-protection`),t.length===0&&t.push(`unknown`),t}function ot(e){let t=0;e.includes(`
|
|
323
|
-
`)&&(t+=20);let n=e.match(/\b[a-zA-Z_$][a-zA-Z0-9_$]*\b/g)||[];return n.reduce((e,t)=>e+t.length,0)/(n.length||1)>3&&(t+=30),e.replace(/\s/g,``).length/e.length<.8&&(t+=20),!e.includes(`_0x`)&&!e.includes(`\\x`)&&(t+=20),Math.min(t,100)}var st=class{resultCache=new Map;maxCacheSize=100;generateCacheKey(e){let t=JSON.stringify({code:e.code.substring(0,2e3),detectOnly:e.detectOnly,forceOutput:e.forceOutput,includeModuleCode:e.includeModuleCode,jsx:e.jsx,mangle:e.mangle,mappings:e.mappings,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,unpack:e.unpack,unminify:e.unminify});return D.createHash(`md5`).update(t).digest(`hex`)}async deobfuscate(e){let n=this.generateCacheKey(e),r=this.resultCache.get(n);if(r)return t.debug(`Advanced deobfuscation result from cache`),{...r,cached:!0};t.info(`Starting advanced webcrack deobfuscation...`);let i=W(e.code),a=[];if(e.detectOnly){let t={code:e.code,detectedTechniques:i,confidence:Math.min(.6+i.length*.05,.9),warnings:[...a,`detectOnly does not invoke a separate legacy detector anymore; techniques are inferred from the current static signature pass.`],astOptimized:!1,engine:`webcrack`,webcrackApplied:!1};return this.storeCacheEntry(n,t),{...t,cached:!1}}let o=await T(e.code,{unpack:e.unpack,unminify:e.unminify,jsx:e.jsx,mangle:e.mangle,mappings:e.mappings,includeModuleCode:e.includeModuleCode,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,forceOutput:e.forceOutput});if(!o.applied){let e=o.reason??`webcrack did not return a result`;throw t.error(`advanced webcrack deobfuscation failed: ${e}`),Error(e)}o.bundle&&i.push(`bundle-unpack`),o.optionsUsed.unminify&&i.push(`unminify`),o.optionsUsed.jsx&&i.push(`jsx-decompile`),o.optionsUsed.mangle&&i.push(`mangle`),i.push(`webcrack`);let s={code:o.code,detectedTechniques:Array.from(new Set(i)),confidence:this.calculateConfidence(o,i),warnings:a,astOptimized:!1,bundle:o.bundle,savedTo:o.savedTo,savedArtifacts:o.savedArtifacts,engine:`webcrack`,webcrackApplied:!0};return this.storeCacheEntry(n,s),{...s,cached:!1}}storeCacheEntry(e,t){if(this.resultCache.size>=this.maxCacheSize){let e=this.resultCache.keys().next().value;e&&this.resultCache.delete(e)}this.resultCache.set(e,t)}calculateConfidence(e,t){let n=.72+t.length*.03;return e.bundle&&(n+=.08),e.savedTo&&(n+=.04),Math.min(n,.99)}},ct=class{resultCache=new Map;maxCacheSize=100;constructor(e){}generateCacheKey(e){let t=JSON.stringify({code:e.code.substring(0,2e3),forceOutput:e.forceOutput,includeModuleCode:e.includeModuleCode,jsx:e.jsx,mangle:e.mangle??e.renameVariables,mappings:e.mappings,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,unpack:e.unpack,unminify:e.unminify});return D.createHash(`md5`).update(t).digest(`hex`)}async deobfuscate(e){let n=this.generateCacheKey(e),r=this.resultCache.get(n);if(r)return t.debug(`Deobfuscation result from cache`),r.cached=!0,r;t.info(`Starting webcrack deobfuscation...`);let i=Date.now(),a=this.detectObfuscationType(e.code),o=await T(e.code,{unpack:e.unpack,unminify:e.unminify,jsx:e.jsx,mangle:e.mangle??e.renameVariables,mappings:e.mappings,includeModuleCode:e.includeModuleCode,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,forceOutput:e.forceOutput});if(!o.applied){let e=o.reason??`webcrack did not return a result`;throw t.error(`webcrack deobfuscation failed: ${e}`),Error(e)}let s=this.buildAnalysis(o,a),c=[{type:`webcrack`,description:`Ran webcrack (unminify=${o.optionsUsed.unminify}, unpack=${o.optionsUsed.unpack}, jsx=${o.optionsUsed.jsx}, mangle=${o.optionsUsed.mangle})`,success:!0},...o.bundle?[{type:`webcrack-unpack`,description:`Recovered ${o.bundle.moduleCount} bundled modules`,success:!0}]:[],...o.savedTo?[{type:`webcrack-save`,description:`Saved webcrack artifacts to ${o.savedTo}`,success:!0}]:[]],l=this.calculateReadabilityScore(o.code),u=this.calculateConfidence(o,l),d=Date.now()-i;t.success(`webcrack deobfuscation completed in ${d}ms (confidence: ${(u*100).toFixed(1)}%)`);let f={code:o.code,readabilityScore:l,confidence:u,obfuscationType:a,transformations:c,analysis:s,bundle:o.bundle,savedTo:o.savedTo,savedArtifacts:o.savedArtifacts,engine:`webcrack`,webcrackApplied:!0};if(this.resultCache.size>=this.maxCacheSize){let e=this.resultCache.keys().next().value;e&&this.resultCache.delete(e)}return f.cached=!1,this.resultCache.set(n,f),f}detectObfuscationType(e){return W(e)}calculateReadabilityScore(e){return ot(e)}calculateConfidence(e,t){let n=.7;return n+=t/500,e.bundle&&(n+=.1),e.savedTo&&(n+=.05),Math.min(n,.99)}buildAnalysis(e,t){let n=[`webcrack completed deobfuscation for detected types: ${t.join(`, `)}.`];return e.bundle&&n.push(`Recovered a ${e.bundle.type} bundle with ${e.bundle.moduleCount} modules.`),e.savedTo&&n.push(`Artifacts saved to ${e.savedTo}.`),n.join(` `)}},lt=class{jsvmpDetector;constructor(){this.jsvmpDetector=new re}detect(e){let n=[],r={},i=[],a=[],o;this.detectJavaScriptObfuscator(e)&&(n.push(`javascript-obfuscator`),r[`javascript-obfuscator`]=.9,i.push(`String array with rotation`),i.push(`Control flow flattening`),a.push(`Use deobfuscate(engine="webcrack") for aggressive webcrack cleanup`)),this.detectWebpack(e)&&(n.push(`webpack`),r.webpack=.85,i.push(`__webpack_require__`),a.push(`Use deobfuscate(engine="webcrack", unpack=true) to recover modules`)),this.detectUglify(e)&&(n.push(`uglify`),r.uglify=.7,i.push(`Minified variable names`),a.push(`Use prettier or beautifier`));let s=this.detectVMProtectionDetailed(e);s&&(n.push(`vm-protection`),r[`vm-protection`]=.95,o=s,i.push(`JSVMP with ${s.instructionCount} instructions`),i.push(`Complexity: ${s.complexity}`),a.push(`Use JSVMPDeobfuscator for advanced deobfuscation`)),this.detectInvisibleUnicode(e)&&(n.push(`invisible-unicode`),r[`invisible-unicode`]=1,i.push(`Zero-width characters`),a.push(`Use AdvancedDeobfuscator.decodeInvisibleUnicode()`)),this.detectControlFlowFlattening(e)&&(n.push(`control-flow-flattening`),r[`control-flow-flattening`]=.8,i.push(`Switch-case state machine`),a.push(`Requires symbolic execution`)),this.detectStringArrayRotation(e)&&(n.push(`string-array-rotation`),r[`string-array-rotation`]=.85,i.push(`Rotated string array`),a.push(`Extract and derotate string array`)),this.detectDeadCodeInjection(e)&&(n.push(`dead-code-injection`),r[`dead-code-injection`]=.75,i.push(`Unreachable code blocks`),a.push(`Use AST-based dead code elimination`)),this.detectOpaquePredicates(e)&&(n.push(`opaque-predicates`),r[`opaque-predicates`]=.7,i.push(`Always-true/false conditions`),a.push(`Use constant folding`)),this.detectJSFuck(e)&&(n.push(`jsfuck`),r.jsfuck=1,i.push(`Only uses []()!+`),a.push(`Use jsfuck decoder`)),this.detectAAEncode(e)&&(n.push(`aaencode`),r.aaencode=1,i.push(`Japanese emoticons`),a.push(`Use aaencode decoder`)),this.detectJJEncode(e)&&(n.push(`jjencode`),r.jjencode=1,i.push(`$={___:++$`),a.push(`Use jjencode decoder`)),this.detectPacker(e)&&(n.push(`packer`),r.packer=.95,i.push(`eval(function(p,a,c,k,e,d)`),a.push(`Use unpacker tools`)),this.detectEvalObfuscation(e)&&(n.push(`eval-obfuscation`),r[`eval-obfuscation`]=.8,i.push(`Multiple eval() calls`),a.push(`Hook eval() and log arguments`)),this.detectBase64Encoding(e)&&(n.push(`base64-encoding`),r[`base64-encoding`]=.9,i.push(`atob() or Base64 strings`),a.push(`Decode Base64 strings`)),this.detectHexEncoding(e)&&(n.push(`hex-encoding`),r[`hex-encoding`]=.85,i.push(`\\x hex sequences`),a.push(`Decode hex strings`)),this.detectSelfModifying(e)&&(n.push(`self-modifying`),r[`self-modifying`]=.9,i.push(`Dynamic code generation`),a.push(`Requires runtime analysis`)),this.detectJScrambler(e)&&(n.push(`jscrambler`),r.jscrambler=.85,i.push(`Control flow flattening + Self-defending`),a.push(`Use JScrambler deobfuscator`)),this.detectURLEncode(e)&&(n.push(`urlencoded`),r.urlencoded=.95,i.push(`URL encoded strings`),a.push(`Decode URL encoding`)),n.length===0&&(n.push(`unknown`),r.unknown=.5,a.push(`Code may be clean or use custom obfuscation`));let c=this.buildClassifier(e,n,r);return t.info(`Detected obfuscation types: ${n.join(`, `)}`),{types:n,confidence:r,features:i,recommendations:a,toolRecommendations:this.buildToolRecommendations(n,e),classifier:c,vmFeatures:o}}buildClassifier(e,t,n){let r=(e,t)=>n[e]??t;return t.includes(`javascript-obfuscator`)?{name:/obfuscator\.io/i.test(e)?`obfuscator.io`:`javascript-obfuscator`,version:`unknown`,confidence:r(`javascript-obfuscator`,.9),deobfuscateStrategy:`Start with deobfuscate(engine="webcrack"), then use analysis_deflat_control_flow when dispatcher-based control flow is present.`}:t.includes(`jsfuck`)?{name:`jsfuck`,version:`unknown`,confidence:r(`jsfuck`,1),deobfuscateStrategy:`Decode the JSFuck payload first, then run deobfuscate for secondary cleanup if needed.`}:t.includes(`aaencode`)?{name:`aaencode`,version:`unknown`,confidence:r(`aaencode`,1),deobfuscateStrategy:`Decode AAEncode first, then run deobfuscate or understand_code on the decoded output.`}:t.includes(`jjencode`)?{name:`jjencode`,version:`unknown`,confidence:r(`jjencode`,1),deobfuscateStrategy:`Decode JJEncode first, then run deobfuscate or understand_code on the decoded output.`}:t.includes(`packer`)?{name:`packer`,version:`unknown`,confidence:r(`packer`,.95),deobfuscateStrategy:`Unpack the wrapper first, then run deobfuscate on the extracted inner payload.`}:t.includes(`jscrambler`)?{name:`jscrambler`,version:`unknown`,confidence:r(`jscrambler`,.85),deobfuscateStrategy:`Prioritize control-flow cleanup and runtime-assisted analysis; static deobfuscation alone is often insufficient.`}:{name:`generic`,version:`unknown`,confidence:Math.max(...t.map(e=>n[e]??0),n.unknown??.5),deobfuscateStrategy:`Use the standard webcrack-backed deobfuscation path first, then escalate to targeted transforms based on detected techniques.`}}buildToolRecommendations(e,t){let n=new Map,r=(e,t,r)=>{n.has(e)||n.set(e,{tool:e,reason:t,suggestedArgs:r})};return(e.includes(`webpack`)||e.includes(`packer`))&&r(`webcrack_unpack`,`Bundle or wrapper markers detected; unpacking modules is likely the highest-value first step.`,{code:t,unpack:!0,unminify:!0}),e.some(e=>[`javascript-obfuscator`,`string-array-rotation`,`hex-encoding`,`base64-encoding`,`urlencoded`,`unknown`].includes(e))&&r(`deobfuscate`,`Static cleanup is likely sufficient; start with the standard webcrack-backed deobfuscation path.`,{code:t,unminify:!0}),e.some(e=>[`vm-protection`,`control-flow-flattening`,`dead-code-injection`,`opaque-predicates`,`invisible-unicode`,`jscrambler`,`jsfuck`,`aaencode`,`jjencode`].includes(e))&&r(`deobfuscate`,`Complex protections detected; use the advanced webcrack-backed flow for deeper cleanup.`,{code:t,engine:`webcrack`,detectOnly:!1,unminify:!0}),(e.includes(`eval-obfuscation`)||e.includes(`self-modifying`))&&r(`ai_hook`,`Runtime-generated code is present; capture or hook execution points before static cleanup if analysis stalls.`,{action:`inject`,target:`eval`,type:`function`}),n.size===0&&r(`deobfuscate`,`No strong signature matched; start with the standard webcrack-backed path.`,{code:t}),Array.from(n.values())}detectVMProtectionDetailed(e){try{return this.jsvmpDetector.detectJSVMP(e)}catch(n){return t.warn(`VM Protection detection failed`,n),this.detectVMProtection(e)?{instructionCount:0,interpreterLocation:`Unknown`,complexity:`medium`,hasSwitch:!0,hasInstructionArray:!1,hasProgramCounter:!1}:null}}detectJavaScriptObfuscator(e){return[/_0x[a-f0-9]{4,6}/i,/var\s+_0x[a-f0-9]+\s*=\s*\[/i,/\(function\s*\(_0x[a-f0-9]+,\s*_0x[a-f0-9]+\)/i,/while\s*\(!!\[\]\)/i].filter(t=>t.test(e)).length>=2}detectWebpack(e){return e.includes(`__webpack_require__`)||e.includes(`webpackJsonp`)||/\/\*\*\*\*\*\*\/\s*\(/m.test(e)}detectUglify(e){return(e.match(/\b[a-z]\b/g)?.length||0)>50}detectVMProtection(e){return[/while\s*\(\s*true\s*\)\s*\{[\s\S]*?switch\s*\(/i,/var\s+\w+\s*=\s*\[\s*\d+(?:\s*,\s*\d+){10,}\s*\]/i,/\w+\[pc\+\+\]/i,/stack\.push|stack\.pop/i].filter(t=>t.test(e)).length>=2}detectInvisibleUnicode(e){return[``,``,``,``,``].some(t=>e.includes(t))}detectControlFlowFlattening(e){return/while\s*\(\s*!!\s*\[\s*\]\s*\)\s*\{[\s\S]*?switch\s*\(/i.test(e)}detectStringArrayRotation(e){return/var\s+\w+\s*=\s*\[.*?\];[\s\S]*?\(\s*function\s*\(\s*\w+,\s*\w+\s*\)/i.test(e)&&/\w+\s*=\s*\w+\s*\+\s*0x[0-9a-f]+/i.test(e)}detectDeadCodeInjection(e){return/if\s*\(\s*false\s*\)\s*\{/i.test(e)||/if\s*\(\s*!!\s*\[\s*\]\s*\)\s*\{/i.test(e)}detectOpaquePredicates(e){return/if\s*\(\s*\d+\s*[<>!=]+\s*\d+\s*\)/i.test(e)}detectJSFuck(e){return/^[[\]()!+\s]+$/.test(e.substring(0,1e3))}detectAAEncode(e){return/゚ω゚|゚ω゚/.test(e)}detectJJEncode(e){return/\$=\{___:\+\+\$/.test(e)}detectPacker(e){return/eval\s*\(\s*function\s*\(\s*p\s*,\s*a\s*,\s*c\s*,\s*k\s*,\s*e\s*,\s*d\s*\)/i.test(e)}detectEvalObfuscation(e){return(e.match(/\beval\s*\(/g)||[]).length>=3}detectBase64Encoding(e){return e.includes(`atob(`)||/[A-Za-z0-9+/]{50,}={0,2}/.test(e)}detectHexEncoding(e){return(e.match(/\\x[0-9a-f]{2}/gi)||[]).length>20}detectSelfModifying(e){return e.includes(`Function(`)||e.includes(`new Function`)||/eval\s*\(\s*[^)]*\+/.test(e)}detectJScrambler(e){let t=0;return(/while\s*\(\s*!!\s*\[\s*\]\s*\)/.test(e)||/while\s*\(\s*true\s*\)\s*{[\s\S]*?switch/.test(e))&&(t+=3),e.includes(`debugger`)&&e.includes(`constructor`)&&(t+=2),/function\s+\w+\s*\([^)]*\)\s*{[\s\S]*?charCodeAt[\s\S]*?fromCharCode/.test(e)&&(t+=2),(e.includes(`Function.prototype.toString`)||e.includes(`.toString.call`))&&(t+=1),t>=3}detectURLEncode(e){return(e.match(/%[0-9A-Fa-f]{2}/g)?.length||0)>10}generateReport(e){let t=`=== Obfuscation Detection Report ===
|
|
323
|
+
`)&&(t+=20);let n=e.match(/\b[a-zA-Z_$][a-zA-Z0-9_$]*\b/g)||[];return n.reduce((e,t)=>e+t.length,0)/(n.length||1)>3&&(t+=30),e.replace(/\s/g,``).length/e.length<.8&&(t+=20),!e.includes(`_0x`)&&!e.includes(`\\x`)&&(t+=20),Math.min(t,100)}var st=class{resultCache=new Map;maxCacheSize=100;generateCacheKey(e){let t=JSON.stringify({code:e.code.substring(0,2e3),detectOnly:e.detectOnly,forceOutput:e.forceOutput,includeModuleCode:e.includeModuleCode,jsx:e.jsx,mangle:e.mangle,mappings:e.mappings,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,unpack:e.unpack,unminify:e.unminify});return O.createHash(`md5`).update(t).digest(`hex`)}async deobfuscate(e){let n=this.generateCacheKey(e),r=this.resultCache.get(n);if(r)return t.debug(`Advanced deobfuscation result from cache`),{...r,cached:!0};t.info(`Starting advanced webcrack deobfuscation...`);let i=W(e.code),a=[];if(e.detectOnly){let t={code:e.code,detectedTechniques:i,confidence:Math.min(.6+i.length*.05,.9),warnings:[...a,`detectOnly does not invoke a separate legacy detector anymore; techniques are inferred from the current static signature pass.`],astOptimized:!1,engine:`webcrack`,webcrackApplied:!1};return this.storeCacheEntry(n,t),{...t,cached:!1}}let o=await E(e.code,{unpack:e.unpack,unminify:e.unminify,jsx:e.jsx,mangle:e.mangle,mappings:e.mappings,includeModuleCode:e.includeModuleCode,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,forceOutput:e.forceOutput});if(!o.applied){let e=o.reason??`webcrack did not return a result`;throw t.error(`advanced webcrack deobfuscation failed: ${e}`),Error(e)}o.bundle&&i.push(`bundle-unpack`),o.optionsUsed.unminify&&i.push(`unminify`),o.optionsUsed.jsx&&i.push(`jsx-decompile`),o.optionsUsed.mangle&&i.push(`mangle`),i.push(`webcrack`);let s={code:o.code,detectedTechniques:Array.from(new Set(i)),confidence:this.calculateConfidence(o,i),warnings:a,astOptimized:!1,bundle:o.bundle,savedTo:o.savedTo,savedArtifacts:o.savedArtifacts,engine:`webcrack`,webcrackApplied:!0};return this.storeCacheEntry(n,s),{...s,cached:!1}}storeCacheEntry(e,t){if(this.resultCache.size>=this.maxCacheSize){let e=this.resultCache.keys().next().value;e&&this.resultCache.delete(e)}this.resultCache.set(e,t)}calculateConfidence(e,t){let n=.72+t.length*.03;return e.bundle&&(n+=.08),e.savedTo&&(n+=.04),Math.min(n,.99)}},ct=class{resultCache=new Map;maxCacheSize=100;constructor(e){}generateCacheKey(e){let t=JSON.stringify({code:e.code.substring(0,2e3),forceOutput:e.forceOutput,includeModuleCode:e.includeModuleCode,jsx:e.jsx,mangle:e.mangle??e.renameVariables,mappings:e.mappings,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,unpack:e.unpack,unminify:e.unminify});return O.createHash(`md5`).update(t).digest(`hex`)}async deobfuscate(e){let n=this.generateCacheKey(e),r=this.resultCache.get(n);if(r)return t.debug(`Deobfuscation result from cache`),r.cached=!0,r;t.info(`Starting webcrack deobfuscation...`);let i=Date.now(),a=this.detectObfuscationType(e.code),o=await E(e.code,{unpack:e.unpack,unminify:e.unminify,jsx:e.jsx,mangle:e.mangle??e.renameVariables,mappings:e.mappings,includeModuleCode:e.includeModuleCode,maxBundleModules:e.maxBundleModules,outputDir:e.outputDir,forceOutput:e.forceOutput});if(!o.applied){let e=o.reason??`webcrack did not return a result`;throw t.error(`webcrack deobfuscation failed: ${e}`),Error(e)}let s=this.buildAnalysis(o,a),c=[{type:`webcrack`,description:`Ran webcrack (unminify=${o.optionsUsed.unminify}, unpack=${o.optionsUsed.unpack}, jsx=${o.optionsUsed.jsx}, mangle=${o.optionsUsed.mangle})`,success:!0},...o.bundle?[{type:`webcrack-unpack`,description:`Recovered ${o.bundle.moduleCount} bundled modules`,success:!0}]:[],...o.savedTo?[{type:`webcrack-save`,description:`Saved webcrack artifacts to ${o.savedTo}`,success:!0}]:[]],l=this.calculateReadabilityScore(o.code),u=this.calculateConfidence(o,l),d=Date.now()-i;t.success(`webcrack deobfuscation completed in ${d}ms (confidence: ${(u*100).toFixed(1)}%)`);let f={code:o.code,readabilityScore:l,confidence:u,obfuscationType:a,transformations:c,analysis:s,bundle:o.bundle,savedTo:o.savedTo,savedArtifacts:o.savedArtifacts,engine:`webcrack`,webcrackApplied:!0};if(this.resultCache.size>=this.maxCacheSize){let e=this.resultCache.keys().next().value;e&&this.resultCache.delete(e)}return f.cached=!1,this.resultCache.set(n,f),f}detectObfuscationType(e){return W(e)}calculateReadabilityScore(e){return ot(e)}calculateConfidence(e,t){let n=.7;return n+=t/500,e.bundle&&(n+=.1),e.savedTo&&(n+=.05),Math.min(n,.99)}buildAnalysis(e,t){let n=[`webcrack completed deobfuscation for detected types: ${t.join(`, `)}.`];return e.bundle&&n.push(`Recovered a ${e.bundle.type} bundle with ${e.bundle.moduleCount} modules.`),e.savedTo&&n.push(`Artifacts saved to ${e.savedTo}.`),n.join(` `)}},lt=class{jsvmpDetector;constructor(){this.jsvmpDetector=new ne}detect(e){let n=[],r={},i=[],a=[],o;this.detectJavaScriptObfuscator(e)&&(n.push(`javascript-obfuscator`),r[`javascript-obfuscator`]=.9,i.push(`String array with rotation`),i.push(`Control flow flattening`),a.push(`Use deobfuscate(engine="webcrack") for aggressive webcrack cleanup`)),this.detectWebpack(e)&&(n.push(`webpack`),r.webpack=.85,i.push(`__webpack_require__`),a.push(`Use deobfuscate(engine="webcrack", unpack=true) to recover modules`)),this.detectUglify(e)&&(n.push(`uglify`),r.uglify=.7,i.push(`Minified variable names`),a.push(`Use prettier or beautifier`));let s=this.detectVMProtectionDetailed(e);s&&(n.push(`vm-protection`),r[`vm-protection`]=.95,o=s,i.push(`JSVMP with ${s.instructionCount} instructions`),i.push(`Complexity: ${s.complexity}`),a.push(`Use JSVMPDeobfuscator for advanced deobfuscation`)),this.detectInvisibleUnicode(e)&&(n.push(`invisible-unicode`),r[`invisible-unicode`]=1,i.push(`Zero-width characters`),a.push(`Use AdvancedDeobfuscator.decodeInvisibleUnicode()`)),this.detectControlFlowFlattening(e)&&(n.push(`control-flow-flattening`),r[`control-flow-flattening`]=.8,i.push(`Switch-case state machine`),a.push(`Requires symbolic execution`)),this.detectStringArrayRotation(e)&&(n.push(`string-array-rotation`),r[`string-array-rotation`]=.85,i.push(`Rotated string array`),a.push(`Extract and derotate string array`)),this.detectDeadCodeInjection(e)&&(n.push(`dead-code-injection`),r[`dead-code-injection`]=.75,i.push(`Unreachable code blocks`),a.push(`Use AST-based dead code elimination`)),this.detectOpaquePredicates(e)&&(n.push(`opaque-predicates`),r[`opaque-predicates`]=.7,i.push(`Always-true/false conditions`),a.push(`Use constant folding`)),this.detectJSFuck(e)&&(n.push(`jsfuck`),r.jsfuck=1,i.push(`Only uses []()!+`),a.push(`Use jsfuck decoder`)),this.detectAAEncode(e)&&(n.push(`aaencode`),r.aaencode=1,i.push(`Japanese emoticons`),a.push(`Use aaencode decoder`)),this.detectJJEncode(e)&&(n.push(`jjencode`),r.jjencode=1,i.push(`$={___:++$`),a.push(`Use jjencode decoder`)),this.detectPacker(e)&&(n.push(`packer`),r.packer=.95,i.push(`eval(function(p,a,c,k,e,d)`),a.push(`Use unpacker tools`)),this.detectEvalObfuscation(e)&&(n.push(`eval-obfuscation`),r[`eval-obfuscation`]=.8,i.push(`Multiple eval() calls`),a.push(`Hook eval() and log arguments`)),this.detectBase64Encoding(e)&&(n.push(`base64-encoding`),r[`base64-encoding`]=.9,i.push(`atob() or Base64 strings`),a.push(`Decode Base64 strings`)),this.detectHexEncoding(e)&&(n.push(`hex-encoding`),r[`hex-encoding`]=.85,i.push(`\\x hex sequences`),a.push(`Decode hex strings`)),this.detectSelfModifying(e)&&(n.push(`self-modifying`),r[`self-modifying`]=.9,i.push(`Dynamic code generation`),a.push(`Requires runtime analysis`)),this.detectJScrambler(e)&&(n.push(`jscrambler`),r.jscrambler=.85,i.push(`Control flow flattening + Self-defending`),a.push(`Use JScrambler deobfuscator`)),this.detectURLEncode(e)&&(n.push(`urlencoded`),r.urlencoded=.95,i.push(`URL encoded strings`),a.push(`Decode URL encoding`)),n.length===0&&(n.push(`unknown`),r.unknown=.5,a.push(`Code may be clean or use custom obfuscation`));let c=this.buildClassifier(e,n,r);return t.info(`Detected obfuscation types: ${n.join(`, `)}`),{types:n,confidence:r,features:i,recommendations:a,toolRecommendations:this.buildToolRecommendations(n,e),classifier:c,vmFeatures:o}}buildClassifier(e,t,n){let r=(e,t)=>n[e]??t;return t.includes(`javascript-obfuscator`)?{name:/obfuscator\.io/i.test(e)?`obfuscator.io`:`javascript-obfuscator`,version:`unknown`,confidence:r(`javascript-obfuscator`,.9),deobfuscateStrategy:`Start with deobfuscate(engine="webcrack"), then use analysis_deflat_control_flow when dispatcher-based control flow is present.`}:t.includes(`jsfuck`)?{name:`jsfuck`,version:`unknown`,confidence:r(`jsfuck`,1),deobfuscateStrategy:`Decode the JSFuck payload first, then run deobfuscate for secondary cleanup if needed.`}:t.includes(`aaencode`)?{name:`aaencode`,version:`unknown`,confidence:r(`aaencode`,1),deobfuscateStrategy:`Decode AAEncode first, then run deobfuscate or understand_code on the decoded output.`}:t.includes(`jjencode`)?{name:`jjencode`,version:`unknown`,confidence:r(`jjencode`,1),deobfuscateStrategy:`Decode JJEncode first, then run deobfuscate or understand_code on the decoded output.`}:t.includes(`packer`)?{name:`packer`,version:`unknown`,confidence:r(`packer`,.95),deobfuscateStrategy:`Unpack the wrapper first, then run deobfuscate on the extracted inner payload.`}:t.includes(`jscrambler`)?{name:`jscrambler`,version:`unknown`,confidence:r(`jscrambler`,.85),deobfuscateStrategy:`Prioritize control-flow cleanup and runtime-assisted analysis; static deobfuscation alone is often insufficient.`}:{name:`generic`,version:`unknown`,confidence:Math.max(...t.map(e=>n[e]??0),n.unknown??.5),deobfuscateStrategy:`Use the standard webcrack-backed deobfuscation path first, then escalate to targeted transforms based on detected techniques.`}}buildToolRecommendations(e,t){let n=new Map,r=(e,t,r)=>{n.has(e)||n.set(e,{tool:e,reason:t,suggestedArgs:r})};return(e.includes(`webpack`)||e.includes(`packer`))&&r(`webcrack_unpack`,`Bundle or wrapper markers detected; unpacking modules is likely the highest-value first step.`,{code:t,unpack:!0,unminify:!0}),e.some(e=>[`javascript-obfuscator`,`string-array-rotation`,`hex-encoding`,`base64-encoding`,`urlencoded`,`unknown`].includes(e))&&r(`deobfuscate`,`Static cleanup is likely sufficient; start with the standard webcrack-backed deobfuscation path.`,{code:t,unminify:!0}),e.some(e=>[`vm-protection`,`control-flow-flattening`,`dead-code-injection`,`opaque-predicates`,`invisible-unicode`,`jscrambler`,`jsfuck`,`aaencode`,`jjencode`].includes(e))&&r(`deobfuscate`,`Complex protections detected; use the advanced webcrack-backed flow for deeper cleanup.`,{code:t,engine:`webcrack`,detectOnly:!1,unminify:!0}),(e.includes(`eval-obfuscation`)||e.includes(`self-modifying`))&&r(`ai_hook`,`Runtime-generated code is present; capture or hook execution points before static cleanup if analysis stalls.`,{action:`inject`,target:`eval`,type:`function`}),n.size===0&&r(`deobfuscate`,`No strong signature matched; start with the standard webcrack-backed path.`,{code:t}),Array.from(n.values())}detectVMProtectionDetailed(e){try{return this.jsvmpDetector.detectJSVMP(e)}catch(n){return t.warn(`VM Protection detection failed`,n),this.detectVMProtection(e)?{instructionCount:0,interpreterLocation:`Unknown`,complexity:`medium`,hasSwitch:!0,hasInstructionArray:!1,hasProgramCounter:!1}:null}}detectJavaScriptObfuscator(e){return[/_0x[a-f0-9]{4,6}/i,/var\s+_0x[a-f0-9]+\s*=\s*\[/i,/\(function\s*\(_0x[a-f0-9]+,\s*_0x[a-f0-9]+\)/i,/while\s*\(!!\[\]\)/i].filter(t=>t.test(e)).length>=2}detectWebpack(e){return e.includes(`__webpack_require__`)||e.includes(`webpackJsonp`)||/\/\*\*\*\*\*\*\/\s*\(/m.test(e)}detectUglify(e){return(e.match(/\b[a-z]\b/g)?.length||0)>50}detectVMProtection(e){return[/while\s*\(\s*true\s*\)\s*\{[\s\S]*?switch\s*\(/i,/var\s+\w+\s*=\s*\[\s*\d+(?:\s*,\s*\d+){10,}\s*\]/i,/\w+\[pc\+\+\]/i,/stack\.push|stack\.pop/i].filter(t=>t.test(e)).length>=2}detectInvisibleUnicode(e){return[``,``,``,``,``].some(t=>e.includes(t))}detectControlFlowFlattening(e){return/while\s*\(\s*!!\s*\[\s*\]\s*\)\s*\{[\s\S]*?switch\s*\(/i.test(e)}detectStringArrayRotation(e){return/var\s+\w+\s*=\s*\[.*?\];[\s\S]*?\(\s*function\s*\(\s*\w+,\s*\w+\s*\)/i.test(e)&&/\w+\s*=\s*\w+\s*\+\s*0x[0-9a-f]+/i.test(e)}detectDeadCodeInjection(e){return/if\s*\(\s*false\s*\)\s*\{/i.test(e)||/if\s*\(\s*!!\s*\[\s*\]\s*\)\s*\{/i.test(e)}detectOpaquePredicates(e){return/if\s*\(\s*\d+\s*[<>!=]+\s*\d+\s*\)/i.test(e)}detectJSFuck(e){return/^[[\]()!+\s]+$/.test(e.substring(0,1e3))}detectAAEncode(e){return/゚ω゚|゚ω゚/.test(e)}detectJJEncode(e){return/\$=\{___:\+\+\$/.test(e)}detectPacker(e){return/eval\s*\(\s*function\s*\(\s*p\s*,\s*a\s*,\s*c\s*,\s*k\s*,\s*e\s*,\s*d\s*\)/i.test(e)}detectEvalObfuscation(e){return(e.match(/\beval\s*\(/g)||[]).length>=3}detectBase64Encoding(e){return e.includes(`atob(`)||/[A-Za-z0-9+/]{50,}={0,2}/.test(e)}detectHexEncoding(e){return(e.match(/\\x[0-9a-f]{2}/gi)||[]).length>20}detectSelfModifying(e){return e.includes(`Function(`)||e.includes(`new Function`)||/eval\s*\(\s*[^)]*\+/.test(e)}detectJScrambler(e){let t=0;return(/while\s*\(\s*!!\s*\[\s*\]\s*\)/.test(e)||/while\s*\(\s*true\s*\)\s*{[\s\S]*?switch/.test(e))&&(t+=3),e.includes(`debugger`)&&e.includes(`constructor`)&&(t+=2),/function\s+\w+\s*\([^)]*\)\s*{[\s\S]*?charCodeAt[\s\S]*?fromCharCode/.test(e)&&(t+=2),(e.includes(`Function.prototype.toString`)||e.includes(`.toString.call`))&&(t+=1),t>=3}detectURLEncode(e){return(e.match(/%[0-9A-Fa-f]{2}/g)?.length||0)>10}generateReport(e){let t=`=== Obfuscation Detection Report ===
|
|
324
324
|
|
|
325
325
|
`;return t+=`Classifier:
|
|
326
326
|
`,t+=` - name: ${e.classifier.name}\n`,t+=` - version: ${e.classifier.version}\n`,t+=` - confidence: ${(e.classifier.confidence*100).toFixed(0)}%\n`,t+=` - strategy: ${e.classifier.deobfuscateStrategy}\n`,t+=`Detected Types (${e.types.length}):\n`,e.types.forEach(n=>{let r=e.confidence[n]||0;t+=` - ${n}: ${(r*100).toFixed(0)}% confidence\n`}),t+=`
|
|
@@ -329,5 +329,5 @@ Features:
|
|
|
329
329
|
Recommendations:
|
|
330
330
|
`,e.recommendations.forEach(e=>{t+=` - ${e}\n`}),e.toolRecommendations.length>0&&(t+=`
|
|
331
331
|
Suggested Tools:
|
|
332
|
-
`,e.toolRecommendations.forEach(e=>{t+=` - ${e.tool}: ${e.reason}\n`,e.suggestedArgs&&(t+=` args: ${JSON.stringify(e.suggestedArgs)}\n`)})),t}},ut=class{runtimeInspector;watches=new Map;watchCounter=0;constructor(e){this.runtimeInspector=e}addWatch(e,n){let r=`watch_${++this.watchCounter}`;return this.watches.set(r,{id:r,expression:e,name:n||e,enabled:!0,lastValue:void 0,lastError:null,valueHistory:[],createdAt:Date.now()}),t.info(`Watch expression added: ${r}`,{expression:e,name:n}),r}removeWatch(e){let n=this.watches.delete(e);return n&&t.info(`Watch expression removed: ${e}`),n}setWatchEnabled(e,n){let r=this.watches.get(e);return r?(r.enabled=n,t.info(`Watch expression ${n?`enabled`:`disabled`}: ${e}`),!0):!1}getAllWatches(){return Array.from(this.watches.values())}getWatch(e){return this.watches.get(e)}async evaluateAll(e,t=a){let n=[];for(let r of this.watches.values())if(r.enabled)try{let i=await Promise.race([this.runtimeInspector.evaluate(r.expression,e),new Promise((e,n)=>setTimeout(()=>n(Error(`Evaluation timeout after ${t}ms`)),t))]),a=!this.deepEqual(i,r.lastValue);a&&(r.valueHistory.push({value:i,timestamp:Date.now()}),r.valueHistory.length>100&&r.valueHistory.shift()),r.lastValue=i,r.lastError=null,n.push({watchId:r.id,name:r.name,expression:r.expression,value:i,error:null,valueChanged:a,timestamp:Date.now()})}catch(e){r.lastError=e,n.push({watchId:r.id,name:r.name,expression:r.expression,value:null,error:e,valueChanged:!1,timestamp:Date.now()})}return n}clearAll(){this.watches.clear(),t.info(`All watch expressions cleared`)}getValueHistory(e){let t=this.watches.get(e);return t?t.valueHistory:null}deepEqual(e,t){if(e===t)return!0;if(e==null||t==null||!this.isRecord(e)||!this.isRecord(t))return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!this.deepEqual(e[r],t[r]))return!1;return!0}isRecord(e){return typeof e==`object`&&!!e}exportWatches(){return Array.from(this.watches.values()).map(e=>({expression:e.expression,name:e.name,enabled:e.enabled}))}importWatches(e){for(let t of e){let e=this.addWatch(t.expression,t.name);t.enabled===!1&&this.setWatchEnabled(e,!1)}t.info(`Imported ${e.length} watch expressions`)}},dt=class{cdpSession;xhrBreakpoints=new Map;breakpointCounter=0;constructor(e){this.cdpSession=e,t.info(`XHRBreakpointManager initialized with shared CDP session`)}async setXHRBreakpoint(e){try{await this.cdpSession.send(`DOMDebugger.setXHRBreakpoint`,{url:e});let n=`xhr_${++this.breakpointCounter}`;return this.xhrBreakpoints.set(n,{id:n,urlPattern:e,enabled:!0,hitCount:0,createdAt:Date.now()}),t.info(`XHR breakpoint set: ${e}`,{breakpointId:n}),n}catch(e){throw t.error(`Failed to set XHR breakpoint:`,e),e}}async removeXHRBreakpoint(e){let n=this.xhrBreakpoints.get(e);if(!n)return!1;try{return await this.cdpSession.send(`DOMDebugger.removeXHRBreakpoint`,{url:n.urlPattern}),this.xhrBreakpoints.delete(e),t.info(`XHR breakpoint removed: ${e}`),!0}catch(e){throw t.error(`Failed to remove XHR breakpoint:`,e),e}}getAllXHRBreakpoints(){return Array.from(this.xhrBreakpoints.values())}getXHRBreakpoint(e){return this.xhrBreakpoints.get(e)}async clearAllXHRBreakpoints(){let e=Array.from(this.xhrBreakpoints.values());for(let n of e)try{await this.cdpSession.send(`DOMDebugger.removeXHRBreakpoint`,{url:n.urlPattern})}catch(e){t.warn(`Failed to remove XHR breakpoint ${n.id}:`,e)}this.xhrBreakpoints.clear(),t.info(`All XHR breakpoints cleared`)}async close(){try{await this.clearAllXHRBreakpoints(),t.info(`XHRBreakpointManager closed`)}catch(e){throw t.error(`Failed to close XHRBreakpointManager:`,e),e}}},ft=class e{cdpSession;eventBreakpoints=new Map;breakpointCounter=0;static MOUSE_EVENTS=[`click`,`dblclick`,`mousedown`,`mouseup`,`mousemove`,`mouseenter`,`mouseleave`];static KEYBOARD_EVENTS=[`keydown`,`keyup`,`keypress`];static TIMER_EVENTS=[`setTimeout`,`setInterval`,`requestAnimationFrame`];static WEBSOCKET_EVENTS=[`message`,`open`,`close`,`error`];constructor(e){this.cdpSession=e,t.info(`EventBreakpointManager initialized with shared CDP session`)}async setEventListenerBreakpoint(e,n){try{await this.cdpSession.send(`DOMDebugger.setEventListenerBreakpoint`,{eventName:e,targetName:n});let r=`event_${++this.breakpointCounter}`;return this.eventBreakpoints.set(r,{id:r,eventName:e,targetName:n,enabled:!0,hitCount:0,createdAt:Date.now()}),t.info(`Event listener breakpoint set: ${e}`,{breakpointId:r,targetName:n}),r}catch(e){throw t.error(`Failed to set event listener breakpoint:`,e),e}}async removeEventListenerBreakpoint(e){let n=this.eventBreakpoints.get(e);if(!n)return!1;try{return await this.cdpSession.send(`DOMDebugger.removeEventListenerBreakpoint`,{eventName:n.eventName,targetName:n.targetName}),this.eventBreakpoints.delete(e),t.info(`Event listener breakpoint removed: ${e}`),!0}catch(e){throw t.error(`Failed to remove event listener breakpoint:`,e),e}}async setMouseEventBreakpoints(){let n=[];for(let t of e.MOUSE_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} mouse event breakpoints`),n}async setKeyboardEventBreakpoints(){let n=[];for(let t of e.KEYBOARD_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} keyboard event breakpoints`),n}async setTimerEventBreakpoints(){let n=[];for(let t of e.TIMER_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} timer event breakpoints`),n}async setWebSocketEventBreakpoints(){let n=[];for(let t of e.WEBSOCKET_EVENTS){let e=await this.setEventListenerBreakpoint(t,`WebSocket`);n.push(e)}return t.info(`Set ${n.length} WebSocket event breakpoints`),n}getAllEventBreakpoints(){return Array.from(this.eventBreakpoints.values())}getEventBreakpoint(e){return this.eventBreakpoints.get(e)}async clearAllEventBreakpoints(){let e=Array.from(this.eventBreakpoints.values());for(let n of e)try{await this.cdpSession.send(`DOMDebugger.removeEventListenerBreakpoint`,{eventName:n.eventName,targetName:n.targetName})}catch(e){t.warn(`Failed to remove event breakpoint ${n.id}:`,e)}this.eventBreakpoints.clear(),t.info(`All event breakpoints cleared`)}async close(){try{await this.clearAllEventBreakpoints(),t.info(`EventBreakpointManager closed`)}catch(e){throw t.error(`Failed to close EventBreakpointManager:`,e),e}}},pt=class e{cdpSession;blackboxedPatterns=new Set;static COMMON_LIBRARY_PATTERNS=[`*jquery*.js`,`*react*.js`,`*react-dom*.js`,`*vue*.js`,`*angular*.js`,`*lodash*.js`,`*underscore*.js`,`*moment*.js`,`*axios*.js`,`*node_modules/*`,`*webpack*`,`*bundle*.js`,`*vendor*.js`];constructor(e){this.cdpSession=e,t.info(`BlackboxManager initialized with shared CDP session`)}normalizePattern(e){let t=String(e||``).trim();if(!t)throw Error(`Pattern cannot be empty`);if(t.includes(`*`)||t.includes(`?`))return t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`);try{return new RegExp(t),t}catch{return t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}}async blackboxByPattern(e){let n=this.normalizePattern(e);this.blackboxedPatterns.add(n);try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Blackboxed pattern: ${e} -> ${n}`)}catch(e){throw t.error(`Failed to set blackbox pattern:`,e),this.blackboxedPatterns.delete(n),e}}async unblackboxByPattern(e){let n=this.normalizePattern(e);if(!this.blackboxedPatterns.delete(n))return!1;try{return await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Unblackboxed pattern: ${e} -> ${n}`),!0}catch(e){throw t.error(`Failed to remove blackbox pattern:`,e),this.blackboxedPatterns.add(n),e}}async blackboxCommonLibraries(){for(let t of e.COMMON_LIBRARY_PATTERNS)this.blackboxedPatterns.add(this.normalizePattern(t));try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Blackboxed ${e.COMMON_LIBRARY_PATTERNS.length} common library patterns`)}catch(e){throw t.error(`Failed to blackbox common libraries:`,e),e}}getAllBlackboxedPatterns(){return Array.from(this.blackboxedPatterns)}async clearAllBlackboxedPatterns(){this.blackboxedPatterns.clear();try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:[]}),t.info(`All blackbox patterns cleared`)}catch(e){throw t.error(`Failed to clear blackbox patterns:`,e),e}}async close(){try{await this.clearAllBlackboxedPatterns(),t.info(`BlackboxManager closed`)}catch(e){throw t.error(`Failed to close BlackboxManager:`,e),e}}},mt=class{debuggerManager;SESSION_IMPORT_BATCH_SIZE=8;SESSION_FILE_READ_BATCH_SIZE=8;constructor(e){this.debuggerManager=e}async processInBatches(e,t,n){for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t);await Promise.all(i.map(e=>n(e)))}}async readSessionFile(e){return A.readFile(e,`utf-8`)}async validateFilePath(e){let t=E.resolve(e),n=await A.realpath(process.cwd()),r=await A.realpath(pe.tmpdir()),i=E.dirname(t),a;try{a=await A.realpath(i)}catch{a=i}let o=E.join(a,E.basename(t)),s=o===n||o.startsWith(n+E.sep),c=o===r||o.startsWith(r+E.sep);if(!s&&!c)throw Error(`filePath must be within the current working directory or system temp dir.`);return o}exportSession(e){let n={version:`1.0`,timestamp:Date.now(),breakpoints:Array.from(this.debuggerManager.getBreakpoints().values()).map(e=>({location:{scriptId:e.location.scriptId,url:e.location.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber},condition:e.condition,enabled:e.enabled})),pauseOnExceptions:this.debuggerManager.getPauseOnExceptionsState(),metadata:e||{}};return t.info(`Session exported`,{breakpointCount:n.breakpoints.length,pauseOnExceptions:n.pauseOnExceptions}),n}async saveSession(e,n){let r=this.exportSession(n);if(e){e=await this.validateFilePath(e);let t=E.dirname(e);await A.mkdir(t,{recursive:!0})}else{let t=v();await A.mkdir(t,{recursive:!0}),e=E.join(t,`session-${Date.now()}.json`)}return await A.writeFile(e,JSON.stringify(r,null,2),`utf-8`),t.info(`Session saved to ${e}`,{breakpointCount:r.breakpoints.length}),e}async loadSessionFromFile(e){let n=await this.validateFilePath(e),r=await this.readSessionFile(n),i=JSON.parse(r);await this.importSession(i),t.info(`Session loaded from ${n}`,{breakpointCount:i.breakpoints.length})}async importSession(e){if(!this.debuggerManager.isEnabled())throw Error(`Debugger must be enabled before importing session. Call init() or enable() first.`);let n=typeof e==`string`?JSON.parse(e):e;n.version!==`1.0`&&t.warn(`Session version mismatch: ${n.version} (expected 1.0)`),t.info(`Importing session...`,{breakpointCount:n.breakpoints.length,pauseOnExceptions:n.pauseOnExceptions,timestamp:new Date(n.timestamp).toISOString()}),await this.debuggerManager.clearAllBreakpoints();let r=0,i=0;await this.processInBatches(n.breakpoints,this.SESSION_IMPORT_BATCH_SIZE,async e=>{try{e.location.url?(await this.debuggerManager.setBreakpointByUrl({url:e.location.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber,condition:e.condition}),r++):e.location.scriptId?(await this.debuggerManager.setBreakpoint({scriptId:e.location.scriptId,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber,condition:e.condition}),r++):(t.warn(`Breakpoint has neither url nor scriptId, skipping`,e),i++)}catch(n){t.error(`Failed to restore breakpoint:`,n,e),i++}}),n.pauseOnExceptions&&await this.debuggerManager.setPauseOnExceptions(n.pauseOnExceptions),t.info(`Session imported`,{totalBreakpoints:n.breakpoints.length,successCount:r,failCount:i,pauseOnExceptions:n.pauseOnExceptions})}async listSavedSessions(){let e=v();try{await A.access(e)}catch{return[]}let n=await A.readdir(e),r=[],i=n.filter(e=>e.endsWith(`.json`));return await this.processInBatches(i,this.SESSION_FILE_READ_BATCH_SIZE,async n=>{let i=E.join(e,n);try{let e=await this.readSessionFile(i),t=JSON.parse(e);r.push({path:i,timestamp:t.timestamp,metadata:t.metadata})}catch(e){t.warn(`Failed to read session file ${n}:`,e)}}),r.sort((e,t)=>t.timestamp-e.timestamp),r}};function G(e){return e}async function ht(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)try{await r.ensureSession()}catch(e){throw t.warn(`Debugger auto-reconnect failed: ${e instanceof Error?e.message:String(e)}`),new b(`Debugger is not enabled and auto-reconnect failed. Call init() or enable() first.`)}if(!n.url)throw Error(`url parameter is required`);if(n.lineNumber<0)throw Error(`lineNumber must be a non-negative number`);if(n.columnNumber!==void 0&&n.columnNumber<0)throw Error(`columnNumber must be a non-negative number`);try{let e=await r.cdpSession.send(`Debugger.setBreakpointByUrl`,{url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,condition:n.condition}),i={breakpointId:e.breakpointId,location:{url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition,enabled:!0,hitCount:0,createdAt:Date.now()};return r.breakpoints.set(e.breakpointId,i),t.info(`Breakpoint set: ${n.url}:${n.lineNumber}`,{breakpointId:e.breakpointId,condition:n.condition}),i}catch(e){throw t.error(`Failed to set breakpoint:`,e),e}}async function gt(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)try{await r.ensureSession()}catch(e){throw t.warn(`Debugger auto-reconnect failed: ${e instanceof Error?e.message:String(e)}`),new b(`Debugger is not enabled and auto-reconnect failed. Call init() or enable() first.`)}if(!n.scriptId)throw Error(`scriptId parameter is required`);if(n.lineNumber<0)throw Error(`lineNumber must be a non-negative number`);if(n.columnNumber!==void 0&&n.columnNumber<0)throw Error(`columnNumber must be a non-negative number`);try{let e=await r.cdpSession.send(`Debugger.setBreakpoint`,{location:{scriptId:n.scriptId,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition}),i={breakpointId:e.breakpointId,location:{scriptId:n.scriptId,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition,enabled:!0,hitCount:0,createdAt:Date.now()};return r.breakpoints.set(e.breakpointId,i),t.info(`Breakpoint set: scriptId=${n.scriptId}:${n.lineNumber}`,{breakpointId:e.breakpointId}),i}catch(e){throw t.error(`Failed to set breakpoint:`,e),e}}async function _t(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger is not enabled. Call init() or enable() first.`);if(!n)throw Error(`breakpointId parameter is required`);if(!r.breakpoints.has(n))throw Error(`Breakpoint not found: ${n}. Use listBreakpoints() to see active breakpoints.`);try{await r.cdpSession.send(`Debugger.removeBreakpoint`,{breakpointId:n}),r.breakpoints.delete(n),t.info(`Breakpoint removed: ${n}`)}catch(e){throw t.error(`Failed to remove breakpoint ${n}:`,e),e}}function vt(e){let t=G(e);return Array.from(t.breakpoints.values())}function yt(e,t){return G(e).breakpoints.get(t)}async function bt(e){let n=G(e),r=Array.from(n.breakpoints.keys());for(let e of r)await n.removeBreakpoint(e);t.info(`Cleared ${r.length} breakpoints`)}function K(e){return e}async function xt(e,n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger not enabled`);try{await r.cdpSession.send(`Debugger.setPauseOnExceptions`,{state:n}),r.pauseOnExceptionsState=n,t.info(`Pause on exceptions set to: ${n}`)}catch(e){throw t.error(`Failed to set pause on exceptions:`,e),e}}function St(e){return K(e).pauseOnExceptionsState}async function Ct(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.pause`),t.info(`Execution paused`)}catch(e){throw t.error(`Failed to pause execution:`,e),e}}async function wt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.resume`),t.info(`Execution resumed`)}catch(e){let n=e instanceof Error?e.message:String(e);if(n.includes(`not paused`)||n.includes(`cannot be resumed`)||n.includes(`while paused`)){t.warn(`Debugger resume skipped: not currently paused`);return}throw t.error(`Failed to resume execution:`,e),e}}async function Tt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepInto`),t.info(`Step into`)}catch(e){throw t.error(`Failed to step into:`,e),e}}async function Et(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepOver`),t.info(`Step over`)}catch(e){throw t.error(`Failed to step over:`,e),e}}async function Dt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new b(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepOut`),t.info(`Step out`)}catch(e){throw t.error(`Failed to step out:`,e),e}}function Ot(e){return K(e).pausedState}function kt(e){return K(e).pausedState!==null}async function At(e,t=n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger is not enabled. Call init() or enable() first.`);return r.pausedState?r.pausedState:new Promise((e,n)=>{let i=setTimeout(()=>{let t=r.pausedResolvers.indexOf(e);t>-1&&r.pausedResolvers.splice(t,1),n(Error(`Timeout waiting for paused event`))},t);r.pausedResolvers.push(t=>{clearTimeout(i),e(t)})})}async function jt(e,n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger not enabled`);if(!r.pausedState)throw new b(`Not in paused state`);try{let e=await r.cdpSession.send(`Debugger.evaluateOnCallFrame`,{callFrameId:n.callFrameId,expression:n.expression,returnByValue:n.returnByValue!==!1});return t.info(`Evaluated on call frame: ${n.expression}`,{result:e.result.value}),e.result}catch(e){throw t.error(`Failed to evaluate on call frame:`,e),e}}function q(e){return e}function J(e){return e instanceof Error?e.message:String(e)}async function Mt(e,n={}){let r=q(e);if(!r.enabled||!r.cdpSession)throw new b(`Debugger not enabled. Call init() or enable() first.`);if(!r.pausedState)throw new b(`Not in paused state. Use pause() or set a breakpoint first.`);let{callFrameId:i,includeObjectProperties:a=!1,maxDepth:o=1,skipErrors:s=!0}=n;try{let e=i?r.pausedState.callFrames.find(e=>e.callFrameId===i):r.pausedState.callFrames[0];if(!e)throw Error(`Call frame not found: ${i||`top frame`}`);let n=[],c=[],l=0;for(let i of e.scopeChain)try{if(i.object.objectId){let e=await r.cdpSession.send(`Runtime.getProperties`,{objectId:i.object.objectId,ownProperties:!0});for(let s of e.result){if(s.name===`__proto__`)continue;let e={name:s.name,value:s.value?.value,type:s.value?.type||`unknown`,scope:i.type,writable:s.writable,configurable:s.configurable,enumerable:s.enumerable,objectId:s.value?.objectId};if(n.push(e),a&&s.value?.objectId&&o>0)try{let e=await Y(r,s.value.objectId,o-1);for(let t of e)n.push({...t,name:`${s.name}.${t.name}`,scope:i.type})}catch(e){t.debug(`Failed to get nested properties for ${s.name}:`,e)}}l++}}catch(e){let n=J(e);if(t.warn(`Failed to get properties for scope ${i.type}:`,n),c.push({scope:i.type,error:n}),!s)throw e}let u={success:!0,variables:n,callFrameId:e.callFrameId,callFrameInfo:{functionName:e.functionName||`(anonymous)`,location:`${e.url}:${e.location.lineNumber}:${e.location.columnNumber}`},totalScopes:e.scopeChain.length,successfulScopes:l};return c.length>0&&(u.errors=c),t.info(`Got ${n.length} variables from ${l}/${e.scopeChain.length} scopes`,{callFrameId:e.callFrameId,functionName:e.functionName,errors:c.length}),u}catch(e){throw t.error(`Failed to get scope variables:`,e),e}}async function Nt(e,t){let n=q(e);if(!n.enabled||!n.cdpSession)throw Error(`Debugger not enabled`);if(!t||typeof t!=`string`)throw Error(`objectId parameter is required`);try{let e=await n.cdpSession.send(`Runtime.getProperties`,{objectId:t,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),r=[];for(let t of e.result)t.value&&r.push({name:t.name,value:t.value.value??t.value.description,type:t.value.type||`unknown`,objectId:t.value.objectId,className:t.value.className,description:t.value.description});return r}catch(e){let t=J(e);throw t.includes(`Could not find object with given id`)||t.includes(`Invalid remote object id`)?Error(`Object handle is expired or invalid. Pause execution again and reacquire objectId from get_scope_variables_enhanced.`,{cause:e}):e}}async function Y(e,n,r){let i=q(e);if(r<=0||!i.cdpSession)return[];try{let e=await i.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0}),t=[];for(let n of e.result)n.name!==`__proto__`&&t.push({name:n.name,value:n.value?.value,type:n.value?.type||`unknown`,scope:`local`,objectId:n.value?.objectId});return t}catch(e){return t.debug(`Failed to get object properties for ${n}:`,e),[]}}function X(e){return e}function Pt(e,n){let r=X(e);r.breakpointHitCallbacks.add(n),t.info(`Breakpoint hit callback registered`,{totalCallbacks:r.breakpointHitCallbacks.size})}function Ft(e,n){let r=X(e);r.breakpointHitCallbacks.delete(n),t.info(`Breakpoint hit callback removed`,{totalCallbacks:r.breakpointHitCallbacks.size})}function It(e){X(e).breakpointHitCallbacks.clear(),t.info(`All breakpoint hit callbacks cleared`)}function Lt(e){return X(e).breakpointHitCallbacks.size}async function Rt(e,n){let r=X(e);if(r.pausedState={callFrames:n.callFrames,reason:n.reason,data:n.data,hitBreakpoints:n.hitBreakpoints,timestamp:Date.now()},n.hitBreakpoints)for(let e of n.hitBreakpoints){let t=r.breakpoints.get(e);t&&t.hitCount++}if(t.info(`Execution paused`,{reason:n.reason,location:n.callFrames[0]?.location,hitBreakpoints:n.hitBreakpoints}),n.hitBreakpoints&&n.hitBreakpoints.length>0&&r.breakpointHitCallbacks.size>0){let e=n.hitBreakpoints[0],i=n.callFrames[0],a;try{a=(await r.getScopeVariables({skipErrors:!0})).variables}catch(e){t.debug(`Failed to auto-fetch variables for breakpoint hit callback:`,e)}let o={breakpointId:e,breakpointInfo:r.breakpoints.get(e),location:{scriptId:i.location.scriptId,lineNumber:i.location.lineNumber,columnNumber:i.location.columnNumber,url:i.url},callFrames:n.callFrames,timestamp:Date.now(),variables:a,reason:n.reason};for(let e of r.breakpointHitCallbacks)try{await Promise.resolve(e(o))}catch(e){t.error(`Breakpoint hit callback error:`,e)}}for(let e of r.pausedResolvers)e(r.pausedState);r.pausedResolvers=[]}function zt(e){let n=X(e);n.pausedState=null,t.info(`Execution resumed`)}function Bt(e,n){X(e).breakpoints.get(n.breakpointId)&&t.info(`Breakpoint resolved`,{breakpointId:n.breakpointId,location:n.location})}var Vt=class{collector;cdpSession=null;enabled=!1;initPromise;breakpoints=new Map;pausedState=null;pausedResolvers=[];breakpointHitCallbacks=new Set;pauseOnExceptionsState=`none`;watchManager=null;xhrManager=null;eventManager=null;blackboxManager=null;advancedFeatureSession=null;pausedListener=null;resumedListener=null;breakpointResolvedListener=null;sessionManager;constructor(e){this.collector=e,this.sessionManager=new mt(this),this.touchInternalStateForTypeCheck()}touchInternalStateForTypeCheck(){this.pausedState,this.pausedResolvers,this.breakpointHitCallbacks,this.pauseOnExceptionsState}getBreakpoints(){return this.breakpoints}getCDPSession(){if(!this.cdpSession||!this.enabled)throw Error(`Debugger not enabled. Call init() or enable() first to get CDP session.`);return this.cdpSession}getWatchManager(){if(!this.watchManager)throw Error(`WatchExpressionManager not initialized. Call initAdvancedFeatures() first.`);return this.watchManager}getXHRManager(){if(!this.xhrManager)throw Error(`XHRBreakpointManager not initialized. Call initAdvancedFeatures() first.`);return this.xhrManager}getEventManager(){if(!this.eventManager)throw Error(`EventBreakpointManager not initialized. Call initAdvancedFeatures() first.`);return this.eventManager}getBlackboxManager(){if(!this.blackboxManager)throw Error(`BlackboxManager not initialized. Call initAdvancedFeatures() first.`);return this.blackboxManager}async init(){if(!this.enabled){if(this.initPromise)return this.initPromise;this.initPromise=this.doInit();try{return await this.initPromise}finally{this.initPromise=void 0}}}async doInit(){try{let e=await this.collector.getActivePage();this.cdpSession=await e.createCDPSession(),this.cdpSession.on(`disconnected`,()=>{t.warn(`CDP session disconnected, marking as disabled`),this.enabled=!1,this.cdpSession=null,this.advancedFeatureSession=null,this.xhrManager=null,this.eventManager=null,this.blackboxManager=null}),await this.cdpSession.send(`Debugger.enable`),this.enabled=!0,this.pausedListener=e=>this.handlePaused(e),this.resumedListener=()=>this.handleResumed(),this.breakpointResolvedListener=e=>this.handleBreakpointResolved(e),this.cdpSession.on(`Debugger.paused`,this.pausedListener),this.cdpSession.on(`Debugger.resumed`,this.resumedListener),this.cdpSession.on(`Debugger.breakpointResolved`,this.breakpointResolvedListener),t.info(`Debugger enabled successfully`)}catch(e){throw t.error(`Failed to enable debugger:`,e),e}}async ensureSession(){if(!this.enabled||!this.cdpSession){t.info(`CDP session not active, reinitializing...`),await this.init();return}try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{t.warn(`Debugger CDP session unresponsive (zombie), reinitializing...`),this.enabled=!1,this.cdpSession=null,this.advancedFeatureSession=null,this.xhrManager=null,this.eventManager=null,this.blackboxManager=null,this.watchManager=null,await this.init()}}isSessionConnected(){return this.enabled&&this.cdpSession!==null}async enable(){return this.init()}async initAdvancedFeatures(e){if(!this.enabled||!this.cdpSession)throw Error(`Debugger must be enabled before initializing advanced features. Call init() first.`);try{e&&(this.watchManager=new ut(e),t.info(`WatchExpressionManager initialized`)),this.xhrManager=new dt(this.cdpSession),t.info(`XHRBreakpointManager initialized`),this.eventManager=new ft(this.cdpSession),t.info(`EventBreakpointManager initialized`),this.blackboxManager=new pt(this.cdpSession),t.info(`BlackboxManager initialized`),this.advancedFeatureSession=this.cdpSession,t.info(`All advanced debugging features initialized`)}catch(e){throw t.error(`Failed to initialize advanced features:`,e),e}}async ensureAdvancedFeatures(){if(await this.ensureSession(),!this.cdpSession)throw Error(`CDP session unavailable after reconnect.`);(this.advancedFeatureSession!==this.cdpSession||!this.xhrManager||!this.eventManager||!this.blackboxManager)&&await this.initAdvancedFeatures()}async disable(){if(!this.enabled||!this.cdpSession){t.warn(`Debugger not enabled`);return}try{this.xhrManager&&=(await this.xhrManager.close(),null),this.eventManager&&=(await this.eventManager.close(),null),this.blackboxManager&&=(await this.blackboxManager.close(),null),this.watchManager&&=(this.watchManager.clearAll(),null),this.pausedListener&&=(this.cdpSession.off(`Debugger.paused`,this.pausedListener),null),this.resumedListener&&=(this.cdpSession.off(`Debugger.resumed`,this.resumedListener),null),this.breakpointResolvedListener&&=(this.cdpSession.off(`Debugger.breakpointResolved`,this.breakpointResolvedListener),null),await this.cdpSession.send(`Debugger.disable`)}catch(e){t.error(`Failed to disable debugger:`,e)}finally{if(this.initPromise=void 0,this.enabled=!1,this.breakpoints.clear(),this.pausedState=null,this.pausedResolvers=[],this.advancedFeatureSession=null,this.cdpSession){try{await this.cdpSession.detach()}catch(e){t.warn(`Failed to detach CDP session:`,e)}this.cdpSession=null}t.info(`Debugger disabled and cleaned up`)}}isEnabled(){return this.enabled}async setBreakpointByUrl(e){return ht(this,e)}async setBreakpoint(e){return gt(this,e)}async removeBreakpoint(e){return _t(this,e)}listBreakpoints(){return vt(this)}getBreakpoint(e){return yt(this,e)}async clearAllBreakpoints(){return bt(this)}async setPauseOnExceptions(e){return xt(this,e)}getPauseOnExceptionsState(){return St(this)}async pause(){return Ct(this)}async resume(){return wt(this)}async stepInto(){return Tt(this)}async stepOver(){return Et(this)}async stepOut(){return Dt(this)}getPausedState(){return Ot(this)}isPaused(){return kt(this)}async waitForPaused(e=n){return At(this,e)}async evaluateOnCallFrame(e){return jt(this,e)}async getScopeVariables(e={}){return Mt(this,e)}async getObjectPropertiesById(e){return Nt(this,e)}async getObjectProperties(e,t){return Y(this,e,t)}onBreakpointHit(e){Pt(this,e)}offBreakpointHit(e){Ft(this,e)}clearBreakpointHitCallbacks(){It(this)}getBreakpointHitCallbackCount(){return Lt(this)}async handlePaused(e){return Rt(this,this.normalizePausedEventParams(e))}handleResumed(){zt(this)}handleBreakpointResolved(e){Bt(this,this.normalizeBreakpointResolvedParams(e))}exportSession(e){return this.sessionManager.exportSession(e)}async saveSession(e,t){return this.sessionManager.saveSession(e,t)}async loadSessionFromFile(e){return this.sessionManager.loadSessionFromFile(e)}async importSession(e){return this.sessionManager.importSession(e)}async listSavedSessions(){return this.sessionManager.listSavedSessions()}async close(){this.initPromise=void 0,this.enabled&&await this.disable(),this.cdpSession&&=(await this.cdpSession.detach(),null),t.info(`Debugger manager closed`)}normalizePausedEventParams(e){let t=this.asRecord(e);return{callFrames:(Array.isArray(t.callFrames)?t.callFrames:[]).map(e=>this.normalizeCallFrame(e)),reason:typeof t.reason==`string`?t.reason:`unknown`,data:t.data,hitBreakpoints:Array.isArray(t.hitBreakpoints)?t.hitBreakpoints.filter(e=>typeof e==`string`):void 0}}normalizeBreakpointResolvedParams(e){let t=this.asRecord(e);return{breakpointId:typeof t.breakpointId==`string`?t.breakpointId:``,location:t.location}}normalizeCallFrame(e){let t=this.asRecord(e),n=this.asRecord(t.location),r=Array.isArray(t.scopeChain)?t.scopeChain:[];return{callFrameId:typeof t.callFrameId==`string`?t.callFrameId:``,functionName:typeof t.functionName==`string`?t.functionName:``,location:{scriptId:typeof n.scriptId==`string`?n.scriptId:``,lineNumber:typeof n.lineNumber==`number`?n.lineNumber:0,columnNumber:typeof n.columnNumber==`number`?n.columnNumber:0},url:typeof t.url==`string`?t.url:``,scopeChain:r.map(e=>this.normalizeScope(e)),this:t.this}}normalizeScope(e){let t=this.asRecord(e),n=this.asRecord(t.object),r=this.normalizeScriptLocation(t.startLocation),i=this.normalizeScriptLocation(t.endLocation);return{type:this.normalizeScopeType(t.type),object:{type:typeof n.type==`string`?n.type:`object`,objectId:typeof n.objectId==`string`?n.objectId:void 0,className:typeof n.className==`string`?n.className:void 0,description:typeof n.description==`string`?n.description:void 0},name:typeof t.name==`string`?t.name:void 0,startLocation:r,endLocation:i}}normalizeScriptLocation(e){let t=this.asRecord(e);if(Object.keys(t).length!==0)return{scriptId:typeof t.scriptId==`string`?t.scriptId:``,lineNumber:typeof t.lineNumber==`number`?t.lineNumber:0,columnNumber:typeof t.columnNumber==`number`?t.columnNumber:0}}normalizeScopeType(e){return e===`global`||e===`local`||e===`with`||e===`closure`||e===`catch`||e===`block`||e===`script`||e===`eval`||e===`module`?e:`local`}asRecord(e){return typeof e==`object`&&e?e:{}}},Ht=class{collector;debuggerManager;cdpSession=null;enabled=!1;initPromise;constructor(e,t){this.collector=e,this.debuggerManager=t}async init(){if(!this.enabled){if(this.initPromise)return this.initPromise;this.initPromise=this.doInit();try{return await this.initPromise}finally{this.initPromise=void 0}}}async doInit(){try{let e=await this.collector.getActivePage();this.cdpSession=await e.createCDPSession(),await this.cdpSession.send(`Runtime.enable`),this.enabled=!0,t.info(`Runtime inspector enabled`)}catch(e){throw t.error(`Failed to enable runtime inspector:`,e),e}}async enable(){return this.init()}async enableAsyncStackTraces(e=32){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector not enabled. Call init() or enable() first.`);try{await this.cdpSession.send(`Debugger.setAsyncCallStackDepth`,{maxDepth:e}),t.info(`Async stack traces enabled with max depth: ${e}`)}catch(e){throw t.error(`Failed to enable async stack traces:`,e),e}}async disableAsyncStackTraces(){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector not enabled`);try{await this.cdpSession.send(`Debugger.setAsyncCallStackDepth`,{maxDepth:0}),t.info(`Async stack traces disabled`)}catch(e){throw t.error(`Failed to disable async stack traces:`,e),e}}async disable(){if(!(!this.enabled||!this.cdpSession))try{await this.cdpSession.send(`Runtime.disable`),this.enabled=!1,await this.cdpSession.detach(),this.cdpSession=null,t.info(`Runtime inspector disabled and cleaned up`)}catch(e){throw t.error(`Failed to disable runtime inspector:`,e),e}finally{this.initPromise=void 0}}async getCallStack(){let e=this.debuggerManager.getPausedState();if(!e)return t.warn(`Not in paused state, cannot get call stack`),null;try{let n={callFrames:e.callFrames.map(e=>({callFrameId:e.callFrameId,functionName:e.functionName||`(anonymous)`,location:{scriptId:e.location.scriptId,url:e.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber},scopeChain:e.scopeChain.map(e=>({type:e.type,name:e.name}))})),reason:e.reason,timestamp:e.timestamp};return t.info(`Call stack retrieved`,{frameCount:n.callFrames.length,topFrame:n.callFrames[0]?.functionName}),n}catch(e){throw t.error(`Failed to get call stack:`,e),e}}async getScopeVariables(e){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e)throw Error(`callFrameId parameter is required`);let n=this.debuggerManager.getPausedState();if(!n)throw new b(`Not in paused state. Debugger must be paused to get scope variables.`);let r=n.callFrames.find(t=>t.callFrameId===e);if(!r)throw Error(`Call frame not found: ${e}. Use getCallStack() to see available frames.`);try{let n=[];for(let e of r.scopeChain){if(!e.object.objectId)continue;let t=await this.getObjectProperties(e.object.objectId);n.push({scopeType:e.type,scopeName:e.name,variables:t})}return t.info(`Scope variables retrieved for call frame ${e}`,{scopeCount:n.length}),n}catch(e){throw t.error(`Failed to get scope variables:`,e),e}}async getCurrentScopeVariables(){let e=this.debuggerManager.getPausedState();if(!e||e.callFrames.length===0)throw new b(`Not in paused state or no call frames`);let t=e.callFrames[0];if(!t)throw new b(`No top frame available`);return await this.getScopeVariables(t.callFrameId)}async getObjectProperties(e){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e)throw Error(`objectId parameter is required`);try{let n=await this.cdpSession.send(`Runtime.getProperties`,{objectId:e,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),r=[];for(let e of n.result)e.value&&r.push({name:e.name,value:this.formatValue(e.value),type:e.value.type||`unknown`,objectId:e.value.objectId,className:e.value.className,description:e.value.description});return t.info(`Object properties retrieved: ${e}`,{propertyCount:r.length}),r}catch(e){throw t.error(`Failed to get object properties:`,e),e}}async evaluate(e,n){if(!e||e.trim()===``)throw Error(`expression parameter is required and cannot be empty`);let r=this.debuggerManager.getPausedState();if(!r)throw new b(`Not in paused state. Use evaluateGlobal() for global context evaluation.`);let i=n||r.callFrames[0]?.callFrameId;if(!i)throw new b(`No call frame available for evaluation`);try{let n=await this.debuggerManager.evaluateOnCallFrame({callFrameId:i,expression:e,returnByValue:!0});return t.info(`Expression evaluated: ${e}`,{result:n.value}),this.formatValue(n)}catch(e){throw t.error(`Failed to evaluate expression:`,e),e}}async evaluateGlobal(e){if(!this.enabled||!this.cdpSession)throw new b(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e||e.trim()===``)throw Error(`expression parameter is required and cannot be empty`);try{let n=await this.cdpSession.send(`Runtime.evaluate`,{expression:e,returnByValue:!0});return t.info(`Global expression evaluated: ${e}`,{result:n.result.value}),this.formatValue(n.result)}catch(e){throw t.error(`Failed to evaluate global expression:`,e),e}}formatValue(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.type!==`undefined`)return t.type===`object`&&t.subtype===`null`?null:t.value===void 0?t.description?t.description:`[${t.type||`unknown`}]`:t.value}async close(){this.initPromise=void 0,this.enabled&&await this.disable(),this.cdpSession&&=(await this.cdpSession.detach(),null),t.info(`Runtime inspector closed`)}};const Z=i,Ut=o,Wt=r;function Gt(){return[process.env.TEMP,process.env.TMP,ae(),`/tmp`,`/var/tmp`].filter(e=>!!e)}var Kt=class{registry;constructor(e){this.registry=e}async probeAll(e=!1){return this.registry.probeAll(e)}async run(e){return x(()=>this.runInternal(e))}async runInternal(e){let n=this.registry.getSpec(e.tool),r=this.registry.getCachedProbe(e.tool);if(r&&!r.available)return{ok:!1,exitCode:null,signal:null,stdout:``,stderr:`Tool '${e.tool}' (${n.command}) is not available: ${r.reason}`,durationMs:0,truncated:!1};let i=this.validateCwd(e.cwd),a=[...n.defaultArgs||[],...e.args],o={PATH:process.env.PATH||``};if(process.platform===`win32`){let e=process.env.SYSTEMROOT||process.env.SystemRoot||process.env.WINDIR;e&&(o.SYSTEMROOT=e),process.env.TEMP&&(o.TEMP=process.env.TEMP),process.env.TMP&&(o.TMP=process.env.TMP)}if(n.envAllowlist)for(let e of n.envAllowlist)process.env[e]&&(o[e]=process.env[e]);let l=e.timeoutMs??Z,u=e.maxStdoutBytes??Ut,d=e.maxStderrBytes??Wt,f=e.outputLabel?.trim()||`output`;t.debug(`[ExternalToolRunner] Running: ${n.command} ${a.join(` `)}`);let p=Date.now();return new Promise(r=>{let m=ue(n.command,a,{cwd:i,env:o,shell:!1,windowsHide:!0,stdio:[`pipe`,`pipe`,`pipe`]});c.register(m);let h=[],g=[],_=0,v=0,y=!1,b=!1,x=!1,S=setTimeout(()=>{x||(m.kill(`SIGTERM`),setTimeout(()=>{x||(m.kill(`SIGKILL`),C(null,`SIGKILL`))},s),e.onProgress?.({phase:`timeout`,ts:Date.now()}))},l),C=async(i,a)=>{if(x)return;x=!0,clearTimeout(S);let o=h.length===1?h[0].toString(`utf-8`):h.length>1?Buffer.concat(h).toString(`utf-8`):``,s=g.length===1?g[0].toString(`utf-8`):g.length>1?Buffer.concat(g).toString(`utf-8`):``;h=[],g=[];let c=Date.now()-p,l={ok:i===0,exitCode:i,signal:a,stdout:o,stderr:s,durationMs:c,truncated:y||b};if(l.ok){let t=await this.collectSuccessDiagnostics(e,{stdout:o,stderr:s,outputLabel:f});t.length>0&&(l.ok=!1,l.diagnostics=t,l.diagnosticCode=t.some(e=>e.includes(`0 bytes`))?`EMPTY_OUTPUT_ARTIFACT`:`EMPTY_OUTPUT`,l.stderr=[s.trim(),...t].filter(Boolean).join(`
|
|
333
|
-
`))}l.ok?t.debug(`[ExternalToolRunner] ${n.command} completed in ${c}ms`):t.warn(`[ExternalToolRunner] ${n.command} failed (exit=${i}, signal=${a}) in ${c}ms`),r(l)};e.stdin&&m.stdin.write(e.stdin),m.stdin.end(),m.stdout.on(`data`,t=>{if(_<u){let e=u-_,n=t.length<=e?t:t.subarray(0,e);h.push(n),_+=n.length,_>=u&&(y=!0)}e.onProgress?.({phase:`stdout`,bytesRead:_,ts:Date.now()})}),m.stderr.on(`data`,t=>{if(v<d){let e=d-v,n=t.length<=e?t:t.subarray(0,e);g.push(n),v+=n.length,v>=d&&(b=!0)}e.onProgress?.({phase:`stderr`,bytesRead:v,ts:Date.now()})}),m.on(`close`,(e,t)=>{C(e,t)}),m.on(`error`,e=>{let t=Buffer.from(`\nSpawn error: ${e.message}`,`utf-8`);g.push(t),v+=t.length,C(1,null)}),e.onProgress?.({phase:`spawn`,ts:Date.now()})})}validateCwd(e){if(!e)return _();let n=O(e),r=_(),i=se(r,n);if(i&&!i.startsWith(`..`)&&!oe(i))return n;let a=Gt();for(let e of a){let t=O(e);if(n===t||n.startsWith(t+ce))return n}return t.warn(`[ExternalToolRunner] CWD '${e}' outside allowed boundaries, using project root`),r}async collectSuccessDiagnostics(e,t){let n=[];if(Array.isArray(e.expectedOutputPaths)&&e.expectedOutputPaths.length>0){let r=[],i=[];for(let t of e.expectedOutputPaths)try{let n=await le(t);if(n.isDirectory()){e.allowDirectoryOutputs||i.push(t);continue}n.size<=0&&r.push(t)}catch{i.push(t)}i.length>0&&n.push(`Expected ${t.outputLabel} artifact was not created: ${i.join(`, `)}`),r.length>0&&n.push(`Expected ${t.outputLabel} artifact is 0 bytes: ${r.join(`, `)}`)}if(e.requireNonEmptyOutput){let r=t.stdout.trim().length>0,i=t.stderr.trim().length>0,a=!n.some(e=>e.includes(`not created`)||e.includes(`0 bytes`));!r&&!i&&(!e.expectedOutputPaths||!a)&&n.push(`Process exited successfully but produced no stdout, stderr, or usable ${t.outputLabel}.`)}return n}};function qt(e,t,n,r,i,a=!1){switch(t){case`function`:return p(e,n,r,i,a);case`xhr`:return he(n,r,i,a);case`fetch`:return ge(n,r,i,a);case`websocket`:return _e(n,r,i,a);case`localstorage`:return f(n,r,i,a);case`cookie`:return g(n,r,i,a);case`eval`:return l(n,r,i,a);case`object-method`:return u(e,n,r,i,a);default:throw Error(`Unsupported hook type: ${t}`)}}var Jt=class{hooks=new Map;hookScripts=new Map;hookMetadata=new Map;hookConditions=new Map;MAX_HOOK_RECORDS=1e3;MAX_TOTAL_RECORDS=1e4;MAX_HOOKS=200;async createHook(e){if(this.hookScripts.size>=this.MAX_HOOKS){let e=null,n=1/0;for(let[t,r]of this.hookMetadata)r.createdAt<n&&(n=r.createdAt,e=t);e&&(t.warn(`Hook limit (${this.MAX_HOOKS}) reached, evicting oldest: ${e}`),this.deleteHook(e))}t.info(`Creating hook for ${e.target} (type: ${e.type})...`);try{let{target:n,type:r,action:i=`log`,condition:a,performance:o=!1}=e,s=qt(n,r,i,e.customCode,a,o),c=`${n}-${r}-${Date.now()}`;return this.hookScripts.set(c,s),a&&this.hookConditions.set(c,a),this.hookMetadata.set(c,{id:c,enabled:!0,createdAt:Date.now(),callCount:0,totalExecutionTime:0}),t.success(`Hook created: ${c}`),{hookId:c,script:s,instructions:m(r)}}catch(e){throw t.error(`Failed to create hook`,e),e}}recordHookEvent(e,n){let r={hookId:e,timestamp:Date.now(),context:n},i=this.hooks.get(e)||[];i.push(r),this.hooks.set(e,i),t.debug(`Hook event recorded: ${e}`)}getHookRecords(e){return this.hooks.get(e)||[]}clearHookRecords(e){e?(this.hooks.delete(e),t.info(`Cleared records for hook: ${e}`)):(this.hooks.clear(),t.info(`Cleared all hook records`))}enableHook(e){let n=this.hookMetadata.get(e);n?(n.enabled=!0,t.info(`Hook enabled: ${e}`)):t.warn(`Hook not found: ${e}`)}disableHook(e){let n=this.hookMetadata.get(e);n?(n.enabled=!1,t.info(`Hook disabled: ${e}`)):t.warn(`Hook not found: ${e}`)}getHookMetadata(e){return this.hookMetadata.get(e)}getAllHookMetadata(){return Array.from(this.hookMetadata.values())}exportHookData(e){if(e){let t=this.hookMetadata.get(e),n=this.hooks.get(e)||[],r=this.hookScripts.get(e)||``;return{metadata:t?[t]:[],records:{[e]:n},scripts:{[e]:r}}}let t=Array.from(this.hookMetadata.values()),n={},r={};return this.hooks.forEach((e,t)=>{n[t]=e}),this.hookScripts.forEach((e,t)=>{r[t]=e}),{metadata:t,records:n,scripts:r}}getHookStats(e){let t=this.hookMetadata.get(e);return t?{callCount:t.callCount,avgExecutionTime:t.callCount>0?t.totalExecutionTime/t.callCount:0,totalExecutionTime:t.totalExecutionTime,enabled:t.enabled}:null}deleteHook(e){this.hookScripts.delete(e),this.hookMetadata.delete(e),this.hookConditions.delete(e),this.hooks.delete(e),t.info(`Hook deleted: ${e}`)}getAllHooks(){return Array.from(this.hookScripts.keys())}recordHookCall(e,n){this.hooks.has(e)||this.hooks.set(e,[]);let r=this.hooks.get(e);r.length>=this.MAX_HOOK_RECORDS&&(r.shift(),t.debug(`Hook ${e} reached max records, removed oldest`)),r.push(n),Array.from(this.hooks.values()).reduce((e,t)=>e+t.length,0)>this.MAX_TOTAL_RECORDS&&this.cleanupOldestRecords();let i=this.hookMetadata.get(e);i&&(i.callCount++,i.lastCalled=Date.now())}cleanupOldestRecords(){let e=null,n=1/0;for(let[t,r]of this.hooks.entries())if(r.length>0){let i=r[0];i&&i.timestamp<n&&(n=i.timestamp,e=t)}if(e){let n=this.hooks.get(e),r=Math.floor(n.length/2);n.splice(0,r),t.warn(`Cleaned up ${r} old records from ${e} (total records exceeded limit)`)}}getHookRecordsStats(){let e=0,t=null,n=null,r={};for(let[i,a]of this.hooks.entries())if(r[i]=a.length,e+=a.length,a.length>0){let e=a[0],r=a[a.length-1];if(e){let n=e.timestamp;(t===null||n<t)&&(t=n)}if(r){let e=r.timestamp;(n===null||e>n)&&(n=e)}}return{totalHooks:this.hooks.size,totalRecords:e,recordsByHook:r,oldestRecord:t,newestRecord:n}}async createBatchHooks(e){t.info(`Creating ${e.length} hooks...`);let n=[];for(let{target:r,type:i,action:a=`log`}of e)try{let e=await this.createHook({target:r,type:i,action:a});n.push(e)}catch(e){t.error(`Failed to create hook for ${r}:`,e)}return t.success(`Created ${n.length}/${e.length} hooks`),n}generateAntiDebugBypass(){return d()}generateHookTemplate(e,t){return h(e,t)}generateHookChain(e){return P(e)}};function Q(e){return typeof e==`object`&&!!e}function Yt(e){return Q(e)&&typeof e.chunk==`string`}function Xt(e){if(!Q(e))return!1;let{callFrame:t,selfSize:n,children:r}=e;return!(t!==void 0&&(!Q(t)||t.functionName!==void 0&&typeof t.functionName!=`string`||t.url!==void 0&&typeof t.url!=`string`)||n!==void 0&&typeof n!=`number`||r!==void 0&&!Array.isArray(r))}function Zt(e){return Q(e)&&Q(e.profile)&&Xt(e.profile.head)}async function $(){await me()}function Qt(e){let t=/"ph"\s*:/g,n=0;for(;t.exec(e)!==null;)n++;return n}function $t(e,t,n){if(n<=0||e.length===n&&t.selfSize<=e[e.length-1].selfSize)return;let r=e.findIndex(e=>t.selfSize>e.selfSize);r===-1&&(r=e.length),e.splice(r,0,t),e.length>n&&(e.length=n)}function en(e,t){let n=[e],r=[],i=0;for(;n.length>0;){let e=n.pop();if(e&&(e.callFrame&&(i++,$t(r,{functionName:e.callFrame.functionName||`(anonymous)`,url:e.callFrame.url||``,selfSize:e.selfSize||0},t)),Array.isArray(e.children)))for(let t=e.children.length-1;t>=0;t--){let r=e.children[t];r&&n.push(r)}}return{sampleCount:i,topAllocations:r}}async function tn(e){await Promise.race([e.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_unreachable`)),500))])}var nn=class{collector;cdpSession=null;coverageEnabled=!1;profilerEnabled=!1;tracingEnabled=!1;heapSamplingEnabled=!1;coveragePage=null;tracingPage=null;constructor(e){this.collector=e}async ensureCDPSession(){if(!this.cdpSession){let e=await this.collector.getActivePage();return this.cdpSession=await Promise.race([e.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),this.cdpSession}try{return await tn(this.cdpSession),this.cdpSession}catch(e){if((e instanceof Error?e.message:String(e))!==`cdp_unreachable`)throw e;t.warn(`PerformanceMonitor CDP session unresponsive, recreating...`);try{await this.cdpSession.detach()}catch{}this.cdpSession=null;let n=await this.collector.getActivePage();return this.cdpSession=await Promise.race([n.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),this.cdpSession}}async getPerformanceMetrics(){let e=await w(await this.collector.getActivePage(),()=>{let e={},t=performance.getEntriesByType(`navigation`)[0];t&&(e.domContentLoaded=t.domContentLoadedEventEnd-t.fetchStart,e.loadComplete=t.loadEventEnd-t.fetchStart,e.ttfb=t.responseStart-t.requestStart);let n=performance.getEntriesByType(`paint`).find(e=>e.name===`first-contentful-paint`);n&&(e.fcp=n.startTime);let r=performance.getEntriesByType(`largest-contentful-paint`).at(-1);r&&(e.lcp=r.renderTime||r.loadTime);let i=0,a=performance.getEntriesByType(`layout-shift`);for(let e of a)e.hadRecentInput||(i+=e.value??0);e.cls=i;let o=performance;if(o.memory){let t=o.memory;e.jsHeapSizeLimit=t.jsHeapSizeLimit,e.totalJSHeapSize=t.totalJSHeapSize,e.usedJSHeapSize=t.usedJSHeapSize}return e});return t.info(`Performance metrics collected`,{fcp:e.fcp,lcp:e.lcp,cls:e.cls}),e}async getPerformanceTimeline(){let e=await w(await this.collector.getActivePage(),()=>performance.getEntries().map(e=>({name:e.name,entryType:e.entryType,startTime:e.startTime,duration:e.duration})));return t.info(`Performance timeline collected: ${e.length} entries`),e}async startCoverage(e){let n=await this.collector.getActivePage();await Promise.all([ne(n,{resetOnNavigation:e?.resetOnNavigation,reportAnonymousScripts:e?.reportAnonymousScripts}),te(n,{resetOnNavigation:e?.resetOnNavigation})]),this.coverageEnabled=!0,this.coveragePage=n,t.info(`Code coverage collection started`)}async stopCoverage(){if(!this.coverageEnabled)throw new b(`Coverage not enabled. Call startCoverage() first.`);let e=this.coveragePage??await this.collector.getActivePage(),[n,r]=await Promise.all([C(e),ee(e)]),i=n,a=r;this.coverageEnabled=!1,this.coveragePage=null;let o=[...i,...a].map(e=>{let t=e.text.length,n=e.ranges.reduce((e,t)=>e+(t.end-t.start),0);return{url:e.url,text:e.text,ranges:e.ranges.map(e=>({start:e.start,end:e.end,count:1})),totalBytes:t,usedBytes:n,coveragePercentage:t>0?n/t*100:0}});return t.success(`Code coverage collected: ${o.length} scripts`,{totalScripts:o.length,avgCoverage:o.reduce((e,t)=>e+t.coveragePercentage,0)/o.length}),o}async startCPUProfiling(){let e=await this.ensureCDPSession();await e.send(`Profiler.enable`),await e.send(`Profiler.start`),this.profilerEnabled=!0,t.info(`CPU profiling started`)}async stopCPUProfiling(){if(!this.profilerEnabled)throw new b(`CPU profiling not enabled. Call startCPUProfiling() first.`);let e=await this.ensureCDPSession(),{profile:n}=await e.send(`Profiler.stop`);return await e.send(`Profiler.disable`),this.profilerEnabled=!1,t.success(`CPU profiling stopped`,{nodes:n.nodes.length,samples:n.samples?.length||0}),n}async takeHeapSnapshot(){let e=await this.ensureCDPSession();await e.send(`HeapProfiler.enable`);let n=0,r=e=>{Yt(e)&&(n+=e.chunk.length)};e.on(`HeapProfiler.addHeapSnapshotChunk`,r);try{await e.send(`HeapProfiler.takeHeapSnapshot`,{reportProgress:!1,treatGlobalObjectsAsRoots:!0})}finally{e.off(`HeapProfiler.addHeapSnapshotChunk`,r),await e.send(`HeapProfiler.disable`).catch(()=>{})}return t.success(`Heap snapshot taken`,{size:n}),n}async startTracing(e){return S(async()=>{if(this.tracingEnabled)throw Error(`Tracing already in progress. Call stopTracing() first.`);let n=await this.collector.getActivePage(),r=e?.categories??[`-*`,`devtools.timeline`,`v8.execute`,`disabled-by-default-devtools.timeline`,`disabled-by-default-devtools.timeline.frame`,`toplevel`,`blink.console`,`blink.user_timing`,`latencyInfo`,...e?.screenshots?[`disabled-by-default-devtools.screenshot`]:[]];await n.tracing.start({categories:r,screenshots:e?.screenshots}),this.tracingEnabled=!0,this.tracingPage=n,t.info(`Performance tracing started`,{categories:r.length})})}async stopTracing(e){return S(async()=>{if(!this.tracingEnabled)throw new b(`Tracing not in progress. Call startTracing() first.`);let n=await(this.tracingPage??await this.collector.getActivePage()).tracing.stop(),r=n?Buffer.from(n).toString(`utf-8`):``;this.tracingEnabled=!1,this.tracingPage=null;let i=Qt(r),a;if(e?.artifactPath)await k(e.artifactPath,r,`utf-8`),a=e.artifactPath;else{let{absolutePath:e,displayPath:t}=await y({category:`traces`,toolName:`performance-trace`,ext:`json`});await k(e,r,`utf-8`),a=t}return t.success(`Performance trace saved`,{eventCount:i,sizeBytes:r.length,path:a}),{artifactPath:a,eventCount:i,sizeBytes:r.length}})}async startHeapSampling(e){return S(async()=>{if(this.heapSamplingEnabled)throw Error(`Heap sampling already in progress. Call stopHeapSampling() first.`);let n=await this.ensureCDPSession();await n.send(`HeapProfiler.enable`),await n.send(`HeapProfiler.startSampling`,{samplingInterval:e?.samplingInterval??32768}),this.heapSamplingEnabled=!0,t.info(`Heap sampling profiler started`)})}async stopHeapSampling(e){return S(async()=>{if(!this.heapSamplingEnabled)throw new b(`Heap sampling not in progress. Call startHeapSampling() first.`);let n=await this.ensureCDPSession(),r=await n.send(`HeapProfiler.stopSampling`);if(!Zt(r))throw Error(`Unexpected HeapProfiler.stopSampling payload shape`);let{profile:i}=r;await n.send(`HeapProfiler.disable`),this.heapSamplingEnabled=!1;let a=e?.topN??20;await $();let{sampleCount:o,topAllocations:s}=en(i.head,a);await $();let c=JSON.stringify(i),l;if(e?.artifactPath)await k(e.artifactPath,c,`utf-8`),l=e.artifactPath;else{let{absolutePath:e,displayPath:t}=await y({category:`profiles`,toolName:`heap-sampling`,ext:`json`});await k(e,c,`utf-8`),l=t}return t.success(`Heap sampling profile saved`,{sampleCount:o,path:l}),{artifactPath:l,sampleCount:o,topAllocations:s}})}async close(){this.cdpSession&&=(this.coverageEnabled&&await this.stopCoverage().catch(()=>{}),this.profilerEnabled&&await this.stopCPUProfiling().catch(()=>{}),this.tracingEnabled&&await this.stopTracing().catch(()=>{}),this.heapSamplingEnabled&&await this.stopHeapSampling().catch(()=>{}),await this.cdpSession.detach(),null),t.info(`PerformanceMonitor closed`)}},rn=class e{constructor(){}static injectedPages=new WeakSet;static async injectAll(e){if(this.injectedPages.has(e)){t.info(`Stealth scripts already injected on this page, skipping`);return}t.info(`Injecting modern stealth scripts...`),await Promise.all([this.hideWebDriver(e),this.mockChrome(e),this.mockPlugins(e),this.fixPermissions(e),this.mockCanvas(e),this.mockWebGL(e),this.fixLanguages(e),this.mockBattery(e),this.fixMediaDevices(e),this.mockNotifications(e)]),await this.injectTimingDefense(e),this.injectedPages.add(e),t.info(` `)}static async injectTimingDefense(e){await e.evaluateOnNewDocument(()=>{let e=performance.now.bind(performance),t=Date.now,n=0;performance.now=function(){let t=window;return typeof t.__cdpTimingOffset==`number`&&(n=t.__cdpTimingOffset),e()-n},Date.now=function(){let e=window;return typeof e.__cdpTimingOffset==`number`&&(n=e.__cdpTimingOffset),t.call(Date)-Math.floor(n)};let r=Date,i=function(...e){return e.length===0?new r(r.now()):new r(...e)};i.now=r.now,i.parse=r.parse.bind(r),i.UTC=r.UTC.bind(r),Object.defineProperty(i,`prototype`,{value:r.prototype}),globalThis.Date=i})}static async hideWebDriver(e){await e.evaluateOnNewDocument(()=>{let e=Object.getPrototypeOf(navigator);delete e.webdriver,Object.defineProperty(navigator,`webdriver`,{get:()=>void 0,configurable:!0});let t=Object.getOwnPropertyNames;if(Object.getOwnPropertyNames=function(e){return t(e).filter(e=>e!==`webdriver`)},typeof document<`u`){let e=document;for(let t of Object.keys(e))(t.startsWith(`cdc_`)||t.startsWith(`$cdc_`))&&delete e[t]}})}static async mockChrome(e){await e.evaluateOnNewDocument(()=>{let e=window;e.chrome={runtime:{connect:()=>{},sendMessage:()=>{},onMessage:{addListener:()=>{},removeListener:()=>{}}},loadTimes:function(){return{commitLoadTime:Date.now()/1e3,connectionInfo:`http/1.1`,finishDocumentLoadTime:Date.now()/1e3,finishLoadTime:Date.now()/1e3,firstPaintAfterLoadTime:0,firstPaintTime:Date.now()/1e3,navigationType:`Other`,npnNegotiatedProtocol:`unknown`,requestTime:0,startLoadTime:Date.now()/1e3,wasAlternateProtocolAvailable:!1,wasFetchedViaSpdy:!1,wasNpnNegotiated:!1}},csi:function(){return{onloadT:Date.now(),pageT:Date.now(),startE:Date.now(),tran:15}},app:{isInstalled:!1,InstallState:{DISABLED:`disabled`,INSTALLED:`installed`,NOT_INSTALLED:`not_installed`},RunningState:{CANNOT_RUN:`cannot_run`,READY_TO_RUN:`ready_to_run`,RUNNING:`running`}}}})}static async mockPlugins(e){await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,`plugins`,{configurable:!0,get:()=>[{0:{type:`application/pdf`,suffixes:`pdf`,description:`Portable Document Format`},description:`Portable Document Format`,filename:`internal-pdf-viewer`,length:1,name:`Chrome PDF Plugin`},{0:{type:`application/x-google-chrome-pdf`,suffixes:`pdf`,description:``},description:``,filename:`internal-pdf-viewer`,length:1,name:`Chrome PDF Viewer`},{0:{type:`application/x-nacl`,suffixes:``,description:`Native Client Executable`},1:{type:`application/x-pnacl`,suffixes:``,description:`Portable Native Client Executable`},description:``,filename:`internal-nacl-plugin`,length:2,name:`Native Client`}]})})}static async fixPermissions(e){await e.evaluateOnNewDocument(()=>{let e=window.navigator.permissions.query.bind(window.navigator.permissions),t=Notification;window.navigator.permissions.query=n=>n.name===`notifications`?Promise.resolve({state:t.permission}):e(n)})}static async mockCanvas(e){await e.evaluateOnNewDocument(()=>{let e=HTMLCanvasElement.prototype.toDataURL,t=CanvasRenderingContext2D.prototype.getImageData;HTMLCanvasElement.prototype.toDataURL=function(...t){let n=this.getContext(`2d`);if(n){let e=n.getImageData(0,0,this.width,this.height),t=e.data;if(t)for(let e=0;e<t.length;e+=4)t[e]=t[e]^1,t[e+1]=t[e+1]^1,t[e+2]=t[e+2]^1;n.putImageData(e,0,0)}return e.apply(this,t)},CanvasRenderingContext2D.prototype.getImageData=function(...e){let n=t.apply(this,e),r=n.data;if(r)for(let e=0;e<r.length;e+=4)r[e]=r[e]^1,r[e+1]=r[e+1]^1,r[e+2]=r[e+2]^1;return n}})}static async mockWebGL(e){await e.evaluateOnNewDocument(()=>{let e=WebGLRenderingContext.prototype.getParameter;WebGLRenderingContext.prototype.getParameter=function(t){return t===37445?`Intel Inc.`:t===37446?`Intel Iris OpenGL Engine`:e.apply(this,[t])}})}static async fixLanguages(e){await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,`language`,{configurable:!0,get:()=>`en-US`}),Object.defineProperty(navigator,`languages`,{configurable:!0,get:()=>[`en-US`,`en`]})})}static async mockBattery(e){await e.evaluateOnNewDocument(()=>{let e=navigator;if(typeof e.getBattery==`function`){let t=e.getBattery;e.getBattery=function(){return t.call(navigator).then(e=>(Object.defineProperty(e,`charging`,{configurable:!0,get:()=>!0}),Object.defineProperty(e,`chargingTime`,{configurable:!0,get:()=>0}),Object.defineProperty(e,`dischargingTime`,{configurable:!0,get:()=>1/0}),Object.defineProperty(e,`level`,{configurable:!0,get:()=>1}),e))}}})}static async fixMediaDevices(e){await e.evaluateOnNewDocument(()=>{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){let e=navigator.mediaDevices.enumerateDevices;navigator.mediaDevices.enumerateDevices=function(){return e.call(navigator.mediaDevices).then(e=>e.length===0?[{deviceId:`default`,kind:`audioinput`,label:`Default - Microphone`,groupId:`default`,toJSON:()=>({})},{deviceId:`default`,kind:`videoinput`,label:`Default - Camera`,groupId:`default`,toJSON:()=>({})}]:e)}}})}static async mockNotifications(e){await e.evaluateOnNewDocument(()=>{`Notification`in window&&Object.defineProperty(Notification,`permission`,{configurable:!0,get:()=>`default`})})}static async setRealisticUserAgent(e,t=`windows`){let n={windows:`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`,mac:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`,linux:`Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`},r={windows:`Win32`,mac:`MacIntel`,linux:`Linux x86_64`},i={windows:16,mac:12,linux:8};await e.setUserAgent(n[t]);let a=i[t];await e.evaluateOnNewDocument((e,t)=>{Object.defineProperty(navigator,`platform`,{configurable:!0,get:()=>e}),Object.defineProperty(navigator,`vendor`,{configurable:!0,get:()=>`Google Inc.`}),Object.defineProperty(navigator,`hardwareConcurrency`,{configurable:!0,get:()=>t}),Object.defineProperty(navigator,`deviceMemory`,{configurable:!0,get:()=>8})},r[t],a)}static getRecommendedLaunchArgs(){return[`--no-sandbox`,`--disable-setuid-sandbox`,`--disable-blink-features=AutomationControlled`,`--disable-dev-shm-usage`,`--disable-accelerated-2d-canvas`,`--no-first-run`,`--no-zygote`,`--disable-gpu`,`--disable-web-security`,`--disable-features=IsolateOrigins,site-per-process`,`--window-size=1920,1080`,`--disable-infobars`,`--disable-extensions`,`--disable-default-apps`,`--disable-sync`,`--metrics-recording-only`,`--mute-audio`,`--no-default-browser-check`,`--disable-background-timer-throttling`,`--disable-backgrounding-occluded-windows`,`--disable-renderer-backgrounding`,...e.getPatchrightLaunchArgs()]}static getPatchrightLaunchArgs(){return[`--disable-component-update`,`--disable-features=OptimizationGuideModelDownloading,OptimizationHintsFetching,OptimizationHints`,`--disable-hang-monitor`,`--disable-domain-reliability`,`--disable-client-side-phishing-detection`,`--disable-popup-blocking`]}},an=e({AdvancedDeobfuscator:()=>st,CodeAnalyzer:()=>Ee,CryptoDetector:()=>rt,DebuggerManager:()=>Vt,Deobfuscator:()=>ct,HookManager:()=>Jt,ObfuscationDetector:()=>lt,RuntimeInspector:()=>Ht});export{tt as a,Kt as i,rn as n,De as o,nn as r,an as t};
|
|
332
|
+
`,e.toolRecommendations.forEach(e=>{t+=` - ${e.tool}: ${e.reason}\n`,e.suggestedArgs&&(t+=` args: ${JSON.stringify(e.suggestedArgs)}\n`)})),t}},ut=class{runtimeInspector;watches=new Map;watchCounter=0;constructor(e){this.runtimeInspector=e}addWatch(e,n){let r=`watch_${++this.watchCounter}`;return this.watches.set(r,{id:r,expression:e,name:n||e,enabled:!0,lastValue:void 0,lastError:null,valueHistory:[],createdAt:Date.now()}),t.info(`Watch expression added: ${r}`,{expression:e,name:n}),r}removeWatch(e){let n=this.watches.delete(e);return n&&t.info(`Watch expression removed: ${e}`),n}setWatchEnabled(e,n){let r=this.watches.get(e);return r?(r.enabled=n,t.info(`Watch expression ${n?`enabled`:`disabled`}: ${e}`),!0):!1}getAllWatches(){return Array.from(this.watches.values())}getWatch(e){return this.watches.get(e)}async evaluateAll(e,t=s){let n=[];for(let r of this.watches.values())if(r.enabled)try{let i=await Promise.race([this.runtimeInspector.evaluate(r.expression,e),new Promise((e,n)=>setTimeout(()=>n(Error(`Evaluation timeout after ${t}ms`)),t))]),a=!this.deepEqual(i,r.lastValue);a&&(r.valueHistory.push({value:i,timestamp:Date.now()}),r.valueHistory.length>100&&r.valueHistory.shift()),r.lastValue=i,r.lastError=null,n.push({watchId:r.id,name:r.name,expression:r.expression,value:i,error:null,valueChanged:a,timestamp:Date.now()})}catch(e){r.lastError=e,n.push({watchId:r.id,name:r.name,expression:r.expression,value:null,error:e,valueChanged:!1,timestamp:Date.now()})}return n}clearAll(){this.watches.clear(),t.info(`All watch expressions cleared`)}getValueHistory(e){let t=this.watches.get(e);return t?t.valueHistory:null}deepEqual(e,t){if(e===t)return!0;if(e==null||t==null||!this.isRecord(e)||!this.isRecord(t))return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!this.deepEqual(e[r],t[r]))return!1;return!0}isRecord(e){return typeof e==`object`&&!!e}exportWatches(){return Array.from(this.watches.values()).map(e=>({expression:e.expression,name:e.name,enabled:e.enabled}))}importWatches(e){for(let t of e){let e=this.addWatch(t.expression,t.name);t.enabled===!1&&this.setWatchEnabled(e,!1)}t.info(`Imported ${e.length} watch expressions`)}},dt=class{cdpSession;xhrBreakpoints=new Map;breakpointCounter=0;constructor(e){this.cdpSession=e,t.info(`XHRBreakpointManager initialized with shared CDP session`)}async setXHRBreakpoint(e){try{await this.cdpSession.send(`DOMDebugger.setXHRBreakpoint`,{url:e});let n=`xhr_${++this.breakpointCounter}`;return this.xhrBreakpoints.set(n,{id:n,urlPattern:e,enabled:!0,hitCount:0,createdAt:Date.now()}),t.info(`XHR breakpoint set: ${e}`,{breakpointId:n}),n}catch(e){throw t.error(`Failed to set XHR breakpoint:`,e),e}}async removeXHRBreakpoint(e){let n=this.xhrBreakpoints.get(e);if(!n)return!1;try{return await this.cdpSession.send(`DOMDebugger.removeXHRBreakpoint`,{url:n.urlPattern}),this.xhrBreakpoints.delete(e),t.info(`XHR breakpoint removed: ${e}`),!0}catch(e){throw t.error(`Failed to remove XHR breakpoint:`,e),e}}getAllXHRBreakpoints(){return Array.from(this.xhrBreakpoints.values())}getXHRBreakpoint(e){return this.xhrBreakpoints.get(e)}async clearAllXHRBreakpoints(){let e=Array.from(this.xhrBreakpoints.values());for(let n of e)try{await this.cdpSession.send(`DOMDebugger.removeXHRBreakpoint`,{url:n.urlPattern})}catch(e){t.warn(`Failed to remove XHR breakpoint ${n.id}:`,e)}this.xhrBreakpoints.clear(),t.info(`All XHR breakpoints cleared`)}async close(){try{await this.clearAllXHRBreakpoints(),t.info(`XHRBreakpointManager closed`)}catch(e){throw t.error(`Failed to close XHRBreakpointManager:`,e),e}}},ft=class e{cdpSession;eventBreakpoints=new Map;breakpointCounter=0;static MOUSE_EVENTS=[`click`,`dblclick`,`mousedown`,`mouseup`,`mousemove`,`mouseenter`,`mouseleave`];static KEYBOARD_EVENTS=[`keydown`,`keyup`,`keypress`];static TIMER_EVENTS=[`setTimeout`,`setInterval`,`requestAnimationFrame`];static WEBSOCKET_EVENTS=[`message`,`open`,`close`,`error`];constructor(e){this.cdpSession=e,t.info(`EventBreakpointManager initialized with shared CDP session`)}async setEventListenerBreakpoint(e,n){try{await this.cdpSession.send(`DOMDebugger.setEventListenerBreakpoint`,{eventName:e,targetName:n});let r=`event_${++this.breakpointCounter}`;return this.eventBreakpoints.set(r,{id:r,eventName:e,targetName:n,enabled:!0,hitCount:0,createdAt:Date.now()}),t.info(`Event listener breakpoint set: ${e}`,{breakpointId:r,targetName:n}),r}catch(e){throw t.error(`Failed to set event listener breakpoint:`,e),e}}async removeEventListenerBreakpoint(e){let n=this.eventBreakpoints.get(e);if(!n)return!1;try{return await this.cdpSession.send(`DOMDebugger.removeEventListenerBreakpoint`,{eventName:n.eventName,targetName:n.targetName}),this.eventBreakpoints.delete(e),t.info(`Event listener breakpoint removed: ${e}`),!0}catch(e){throw t.error(`Failed to remove event listener breakpoint:`,e),e}}async setMouseEventBreakpoints(){let n=[];for(let t of e.MOUSE_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} mouse event breakpoints`),n}async setKeyboardEventBreakpoints(){let n=[];for(let t of e.KEYBOARD_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} keyboard event breakpoints`),n}async setTimerEventBreakpoints(){let n=[];for(let t of e.TIMER_EVENTS){let e=await this.setEventListenerBreakpoint(t);n.push(e)}return t.info(`Set ${n.length} timer event breakpoints`),n}async setWebSocketEventBreakpoints(){let n=[];for(let t of e.WEBSOCKET_EVENTS){let e=await this.setEventListenerBreakpoint(t,`WebSocket`);n.push(e)}return t.info(`Set ${n.length} WebSocket event breakpoints`),n}getAllEventBreakpoints(){return Array.from(this.eventBreakpoints.values())}getEventBreakpoint(e){return this.eventBreakpoints.get(e)}async clearAllEventBreakpoints(){let e=Array.from(this.eventBreakpoints.values());for(let n of e)try{await this.cdpSession.send(`DOMDebugger.removeEventListenerBreakpoint`,{eventName:n.eventName,targetName:n.targetName})}catch(e){t.warn(`Failed to remove event breakpoint ${n.id}:`,e)}this.eventBreakpoints.clear(),t.info(`All event breakpoints cleared`)}async close(){try{await this.clearAllEventBreakpoints(),t.info(`EventBreakpointManager closed`)}catch(e){throw t.error(`Failed to close EventBreakpointManager:`,e),e}}},pt=class e{cdpSession;blackboxedPatterns=new Set;static COMMON_LIBRARY_PATTERNS=[`*jquery*.js`,`*react*.js`,`*react-dom*.js`,`*vue*.js`,`*angular*.js`,`*lodash*.js`,`*underscore*.js`,`*moment*.js`,`*axios*.js`,`*node_modules/*`,`*webpack*`,`*bundle*.js`,`*vendor*.js`];constructor(e){this.cdpSession=e,t.info(`BlackboxManager initialized with shared CDP session`)}normalizePattern(e){let t=String(e||``).trim();if(!t)throw Error(`Pattern cannot be empty`);if(t.includes(`*`)||t.includes(`?`))return t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`);try{return new RegExp(t),t}catch{return t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}}async blackboxByPattern(e){let n=this.normalizePattern(e);this.blackboxedPatterns.add(n);try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Blackboxed pattern: ${e} -> ${n}`)}catch(e){throw t.error(`Failed to set blackbox pattern:`,e),this.blackboxedPatterns.delete(n),e}}async unblackboxByPattern(e){let n=this.normalizePattern(e);if(!this.blackboxedPatterns.delete(n))return!1;try{return await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Unblackboxed pattern: ${e} -> ${n}`),!0}catch(e){throw t.error(`Failed to remove blackbox pattern:`,e),this.blackboxedPatterns.add(n),e}}async blackboxCommonLibraries(){for(let t of e.COMMON_LIBRARY_PATTERNS)this.blackboxedPatterns.add(this.normalizePattern(t));try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:Array.from(this.blackboxedPatterns)}),t.info(`Blackboxed ${e.COMMON_LIBRARY_PATTERNS.length} common library patterns`)}catch(e){throw t.error(`Failed to blackbox common libraries:`,e),e}}getAllBlackboxedPatterns(){return Array.from(this.blackboxedPatterns)}async clearAllBlackboxedPatterns(){this.blackboxedPatterns.clear();try{await this.cdpSession.send(`Debugger.setBlackboxPatterns`,{patterns:[]}),t.info(`All blackbox patterns cleared`)}catch(e){throw t.error(`Failed to clear blackbox patterns:`,e),e}}async close(){try{await this.clearAllBlackboxedPatterns(),t.info(`BlackboxManager closed`)}catch(e){throw t.error(`Failed to close BlackboxManager:`,e),e}}},mt=class{debuggerManager;SESSION_IMPORT_BATCH_SIZE=8;SESSION_FILE_READ_BATCH_SIZE=8;constructor(e){this.debuggerManager=e}async processInBatches(e,t,n){for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t);await Promise.all(i.map(e=>n(e)))}}async readSessionFile(e){return j.readFile(e,`utf-8`)}async validateFilePath(e){let t=D.resolve(e),n=await j.realpath(process.cwd()),r=await j.realpath(fe.tmpdir()),i=D.dirname(t),a;try{a=await j.realpath(i)}catch{a=i}let o=D.join(a,D.basename(t)),s=o===n||o.startsWith(n+D.sep),c=o===r||o.startsWith(r+D.sep);if(!s&&!c)throw Error(`filePath must be within the current working directory or system temp dir.`);return o}exportSession(e){let n={version:`1.0`,timestamp:Date.now(),breakpoints:Array.from(this.debuggerManager.getBreakpoints().values()).map(e=>({location:{scriptId:e.location.scriptId,url:e.location.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber},condition:e.condition,enabled:e.enabled})),pauseOnExceptions:this.debuggerManager.getPauseOnExceptionsState(),metadata:e||{}};return t.info(`Session exported`,{breakpointCount:n.breakpoints.length,pauseOnExceptions:n.pauseOnExceptions}),n}async saveSession(e,n){let r=this.exportSession(n);if(e){e=await this.validateFilePath(e);let t=D.dirname(e);await j.mkdir(t,{recursive:!0})}else{let t=l();await j.mkdir(t,{recursive:!0}),e=D.join(t,`session-${Date.now()}.json`)}return await j.writeFile(e,JSON.stringify(r,null,2),`utf-8`),t.info(`Session saved to ${e}`,{breakpointCount:r.breakpoints.length}),e}async loadSessionFromFile(e){let n=await this.validateFilePath(e),r=await this.readSessionFile(n),i=JSON.parse(r);await this.importSession(i),t.info(`Session loaded from ${n}`,{breakpointCount:i.breakpoints.length})}async importSession(e){if(!this.debuggerManager.isEnabled())throw Error(`Debugger must be enabled before importing session. Call init() or enable() first.`);let n=typeof e==`string`?JSON.parse(e):e;n.version!==`1.0`&&t.warn(`Session version mismatch: ${n.version} (expected 1.0)`),t.info(`Importing session...`,{breakpointCount:n.breakpoints.length,pauseOnExceptions:n.pauseOnExceptions,timestamp:new Date(n.timestamp).toISOString()}),await this.debuggerManager.clearAllBreakpoints();let r=0,i=0;await this.processInBatches(n.breakpoints,this.SESSION_IMPORT_BATCH_SIZE,async e=>{try{e.location.url?(await this.debuggerManager.setBreakpointByUrl({url:e.location.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber,condition:e.condition}),r++):e.location.scriptId?(await this.debuggerManager.setBreakpoint({scriptId:e.location.scriptId,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber,condition:e.condition}),r++):(t.warn(`Breakpoint has neither url nor scriptId, skipping`,e),i++)}catch(n){t.error(`Failed to restore breakpoint:`,n,e),i++}}),n.pauseOnExceptions&&await this.debuggerManager.setPauseOnExceptions(n.pauseOnExceptions),t.info(`Session imported`,{totalBreakpoints:n.breakpoints.length,successCount:r,failCount:i,pauseOnExceptions:n.pauseOnExceptions})}async listSavedSessions(){let e=l();try{await j.access(e)}catch{return[]}let n=await j.readdir(e),r=[],i=n.filter(e=>e.endsWith(`.json`));return await this.processInBatches(i,this.SESSION_FILE_READ_BATCH_SIZE,async n=>{let i=D.join(e,n);try{let e=await this.readSessionFile(i),t=JSON.parse(e);r.push({path:i,timestamp:t.timestamp,metadata:t.metadata})}catch(e){t.warn(`Failed to read session file ${n}:`,e)}}),r.sort((e,t)=>t.timestamp-e.timestamp),r}};function G(e){return e}async function ht(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)try{await r.ensureSession()}catch(e){throw t.warn(`Debugger auto-reconnect failed: ${e instanceof Error?e.message:String(e)}`),new w(`Debugger is not enabled and auto-reconnect failed. Call init() or enable() first.`)}if(!n.url)throw Error(`url parameter is required`);if(n.lineNumber<0)throw Error(`lineNumber must be a non-negative number`);if(n.columnNumber!==void 0&&n.columnNumber<0)throw Error(`columnNumber must be a non-negative number`);try{let e=await r.cdpSession.send(`Debugger.setBreakpointByUrl`,{url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber,condition:n.condition}),i={breakpointId:e.breakpointId,location:{url:n.url,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition,enabled:!0,hitCount:0,createdAt:Date.now()};return r.breakpoints.set(e.breakpointId,i),t.info(`Breakpoint set: ${n.url}:${n.lineNumber}`,{breakpointId:e.breakpointId,condition:n.condition}),i}catch(e){throw t.error(`Failed to set breakpoint:`,e),e}}async function gt(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)try{await r.ensureSession()}catch(e){throw t.warn(`Debugger auto-reconnect failed: ${e instanceof Error?e.message:String(e)}`),new w(`Debugger is not enabled and auto-reconnect failed. Call init() or enable() first.`)}if(!n.scriptId)throw Error(`scriptId parameter is required`);if(n.lineNumber<0)throw Error(`lineNumber must be a non-negative number`);if(n.columnNumber!==void 0&&n.columnNumber<0)throw Error(`columnNumber must be a non-negative number`);try{let e=await r.cdpSession.send(`Debugger.setBreakpoint`,{location:{scriptId:n.scriptId,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition}),i={breakpointId:e.breakpointId,location:{scriptId:n.scriptId,lineNumber:n.lineNumber,columnNumber:n.columnNumber},condition:n.condition,enabled:!0,hitCount:0,createdAt:Date.now()};return r.breakpoints.set(e.breakpointId,i),t.info(`Breakpoint set: scriptId=${n.scriptId}:${n.lineNumber}`,{breakpointId:e.breakpointId}),i}catch(e){throw t.error(`Failed to set breakpoint:`,e),e}}async function _t(e,n){let r=G(e);if(!r.enabled||!r.cdpSession)throw new w(`Debugger is not enabled. Call init() or enable() first.`);if(!n)throw Error(`breakpointId parameter is required`);if(!r.breakpoints.has(n))throw Error(`Breakpoint not found: ${n}. Use listBreakpoints() to see active breakpoints.`);try{await r.cdpSession.send(`Debugger.removeBreakpoint`,{breakpointId:n}),r.breakpoints.delete(n),t.info(`Breakpoint removed: ${n}`)}catch(e){throw t.error(`Failed to remove breakpoint ${n}:`,e),e}}function vt(e){let t=G(e);return Array.from(t.breakpoints.values())}function yt(e,t){return G(e).breakpoints.get(t)}async function bt(e){let n=G(e),r=Array.from(n.breakpoints.keys());for(let e of r)await n.removeBreakpoint(e);t.info(`Cleared ${r.length} breakpoints`)}function K(e){return e}async function xt(e,n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new w(`Debugger not enabled`);try{await r.cdpSession.send(`Debugger.setPauseOnExceptions`,{state:n}),r.pauseOnExceptionsState=n,t.info(`Pause on exceptions set to: ${n}`)}catch(e){throw t.error(`Failed to set pause on exceptions:`,e),e}}function St(e){return K(e).pauseOnExceptionsState}async function Ct(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new w(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.pause`),t.info(`Execution paused`)}catch(e){throw t.error(`Failed to pause execution:`,e),e}}async function wt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new w(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.resume`),t.info(`Execution resumed`)}catch(e){let n=e instanceof Error?e.message:String(e);if(n.includes(`not paused`)||n.includes(`cannot be resumed`)||n.includes(`while paused`)){t.warn(`Debugger resume skipped: not currently paused`);return}throw t.error(`Failed to resume execution:`,e),e}}async function Tt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new w(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepInto`),t.info(`Step into`)}catch(e){throw t.error(`Failed to step into:`,e),e}}async function Et(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new w(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepOver`),t.info(`Step over`)}catch(e){throw t.error(`Failed to step over:`,e),e}}async function Dt(e){let n=K(e);if(!n.enabled||!n.cdpSession)throw new w(`Debugger not enabled`);try{await n.cdpSession.send(`Debugger.stepOut`),t.info(`Step out`)}catch(e){throw t.error(`Failed to step out:`,e),e}}function Ot(e){return K(e).pausedState}function kt(e){return K(e).pausedState!==null}async function At(e,t=n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new w(`Debugger is not enabled. Call init() or enable() first.`);return r.pausedState?r.pausedState:new Promise((e,n)=>{let i=setTimeout(()=>{let t=r.pausedResolvers.indexOf(e);t>-1&&r.pausedResolvers.splice(t,1),n(Error(`Timeout waiting for paused event`))},t);r.pausedResolvers.push(t=>{clearTimeout(i),e(t)})})}async function jt(e,n){let r=K(e);if(!r.enabled||!r.cdpSession)throw new w(`Debugger not enabled`);if(!r.pausedState)throw new w(`Not in paused state`);try{let e=await r.cdpSession.send(`Debugger.evaluateOnCallFrame`,{callFrameId:n.callFrameId,expression:n.expression,returnByValue:n.returnByValue!==!1});return t.info(`Evaluated on call frame: ${n.expression}`,{result:e.result.value}),e.result}catch(e){throw t.error(`Failed to evaluate on call frame:`,e),e}}function q(e){return e}function J(e){return e instanceof Error?e.message:String(e)}async function Mt(e,n={}){let r=q(e);if(!r.enabled||!r.cdpSession)throw new w(`Debugger not enabled. Call init() or enable() first.`);if(!r.pausedState)throw new w(`Not in paused state. Use pause() or set a breakpoint first.`);let{callFrameId:i,includeObjectProperties:a=!1,maxDepth:o=1,skipErrors:s=!0}=n;try{let e=i?r.pausedState.callFrames.find(e=>e.callFrameId===i):r.pausedState.callFrames[0];if(!e)throw Error(`Call frame not found: ${i||`top frame`}`);let n=[],c=[],l=0;for(let i of e.scopeChain)try{if(i.object.objectId){let e=await r.cdpSession.send(`Runtime.getProperties`,{objectId:i.object.objectId,ownProperties:!0});for(let s of e.result){if(s.name===`__proto__`)continue;let e={name:s.name,value:s.value?.value,type:s.value?.type||`unknown`,scope:i.type,writable:s.writable,configurable:s.configurable,enumerable:s.enumerable,objectId:s.value?.objectId};if(n.push(e),a&&s.value?.objectId&&o>0)try{let e=await Y(r,s.value.objectId,o-1);for(let t of e)n.push({...t,name:`${s.name}.${t.name}`,scope:i.type})}catch(e){t.debug(`Failed to get nested properties for ${s.name}:`,e)}}l++}}catch(e){let n=J(e);if(t.warn(`Failed to get properties for scope ${i.type}:`,n),c.push({scope:i.type,error:n}),!s)throw e}let u={success:!0,variables:n,callFrameId:e.callFrameId,callFrameInfo:{functionName:e.functionName||`(anonymous)`,location:`${e.url}:${e.location.lineNumber}:${e.location.columnNumber}`},totalScopes:e.scopeChain.length,successfulScopes:l};return c.length>0&&(u.errors=c),t.info(`Got ${n.length} variables from ${l}/${e.scopeChain.length} scopes`,{callFrameId:e.callFrameId,functionName:e.functionName,errors:c.length}),u}catch(e){throw t.error(`Failed to get scope variables:`,e),e}}async function Nt(e,t){let n=q(e);if(!n.enabled||!n.cdpSession)throw Error(`Debugger not enabled`);if(!t||typeof t!=`string`)throw Error(`objectId parameter is required`);try{let e=await n.cdpSession.send(`Runtime.getProperties`,{objectId:t,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),r=[];for(let t of e.result)t.value&&r.push({name:t.name,value:t.value.value??t.value.description,type:t.value.type||`unknown`,objectId:t.value.objectId,className:t.value.className,description:t.value.description});return r}catch(e){let t=J(e);throw t.includes(`Could not find object with given id`)||t.includes(`Invalid remote object id`)?Error(`Object handle is expired or invalid. Pause execution again and reacquire objectId from get_scope_variables_enhanced.`,{cause:e}):e}}async function Y(e,n,r){let i=q(e);if(r<=0||!i.cdpSession)return[];try{let e=await i.cdpSession.send(`Runtime.getProperties`,{objectId:n,ownProperties:!0}),t=[];for(let n of e.result)n.name!==`__proto__`&&t.push({name:n.name,value:n.value?.value,type:n.value?.type||`unknown`,scope:`local`,objectId:n.value?.objectId});return t}catch(e){return t.debug(`Failed to get object properties for ${n}:`,e),[]}}function X(e){return e}function Pt(e,n){let r=X(e);r.breakpointHitCallbacks.add(n),t.info(`Breakpoint hit callback registered`,{totalCallbacks:r.breakpointHitCallbacks.size})}function Ft(e,n){let r=X(e);r.breakpointHitCallbacks.delete(n),t.info(`Breakpoint hit callback removed`,{totalCallbacks:r.breakpointHitCallbacks.size})}function It(e){X(e).breakpointHitCallbacks.clear(),t.info(`All breakpoint hit callbacks cleared`)}function Lt(e){return X(e).breakpointHitCallbacks.size}async function Rt(e,n){let r=X(e);if(r.pausedState={callFrames:n.callFrames,reason:n.reason,data:n.data,hitBreakpoints:n.hitBreakpoints,timestamp:Date.now()},n.hitBreakpoints)for(let e of n.hitBreakpoints){let t=r.breakpoints.get(e);t&&t.hitCount++}if(t.info(`Execution paused`,{reason:n.reason,location:n.callFrames[0]?.location,hitBreakpoints:n.hitBreakpoints}),n.hitBreakpoints&&n.hitBreakpoints.length>0&&r.breakpointHitCallbacks.size>0){let e=n.hitBreakpoints[0],i=n.callFrames[0],a;try{a=(await r.getScopeVariables({skipErrors:!0})).variables}catch(e){t.debug(`Failed to auto-fetch variables for breakpoint hit callback:`,e)}let o={breakpointId:e,breakpointInfo:r.breakpoints.get(e),location:{scriptId:i.location.scriptId,lineNumber:i.location.lineNumber,columnNumber:i.location.columnNumber,url:i.url},callFrames:n.callFrames,timestamp:Date.now(),variables:a,reason:n.reason};for(let e of r.breakpointHitCallbacks)try{await Promise.resolve(e(o))}catch(e){t.error(`Breakpoint hit callback error:`,e)}}for(let e of r.pausedResolvers)e(r.pausedState);r.pausedResolvers=[]}function zt(e){let n=X(e);n.pausedState=null,t.info(`Execution resumed`)}function Bt(e,n){X(e).breakpoints.get(n.breakpointId)&&t.info(`Breakpoint resolved`,{breakpointId:n.breakpointId,location:n.location})}var Vt=class{collector;cdpSession=null;enabled=!1;initPromise;breakpoints=new Map;pausedState=null;pausedResolvers=[];breakpointHitCallbacks=new Set;pauseOnExceptionsState=`none`;watchManager=null;xhrManager=null;eventManager=null;blackboxManager=null;advancedFeatureSession=null;pausedListener=null;resumedListener=null;breakpointResolvedListener=null;sessionManager;constructor(e){this.collector=e,this.sessionManager=new mt(this),this.touchInternalStateForTypeCheck()}touchInternalStateForTypeCheck(){this.pausedState,this.pausedResolvers,this.breakpointHitCallbacks,this.pauseOnExceptionsState}getBreakpoints(){return this.breakpoints}getCDPSession(){if(!this.cdpSession||!this.enabled)throw Error(`Debugger not enabled. Call init() or enable() first to get CDP session.`);return this.cdpSession}getWatchManager(){if(!this.watchManager)throw Error(`WatchExpressionManager not initialized. Call initAdvancedFeatures() first.`);return this.watchManager}getXHRManager(){if(!this.xhrManager)throw Error(`XHRBreakpointManager not initialized. Call initAdvancedFeatures() first.`);return this.xhrManager}getEventManager(){if(!this.eventManager)throw Error(`EventBreakpointManager not initialized. Call initAdvancedFeatures() first.`);return this.eventManager}getBlackboxManager(){if(!this.blackboxManager)throw Error(`BlackboxManager not initialized. Call initAdvancedFeatures() first.`);return this.blackboxManager}async init(){if(!this.enabled){if(this.initPromise)return this.initPromise;this.initPromise=this.doInit();try{return await this.initPromise}finally{this.initPromise=void 0}}}async doInit(){try{let e=await this.collector.getActivePage();this.cdpSession=await e.createCDPSession(),this.cdpSession.on(`disconnected`,()=>{t.warn(`CDP session disconnected, marking as disabled`),this.enabled=!1,this.cdpSession=null,this.advancedFeatureSession=null,this.xhrManager=null,this.eventManager=null,this.blackboxManager=null}),await this.cdpSession.send(`Debugger.enable`),this.enabled=!0,this.pausedListener=e=>this.handlePaused(e),this.resumedListener=()=>this.handleResumed(),this.breakpointResolvedListener=e=>this.handleBreakpointResolved(e),this.cdpSession.on(`Debugger.paused`,this.pausedListener),this.cdpSession.on(`Debugger.resumed`,this.resumedListener),this.cdpSession.on(`Debugger.breakpointResolved`,this.breakpointResolvedListener),t.info(`Debugger enabled successfully`)}catch(e){throw t.error(`Failed to enable debugger:`,e),e}}async ensureSession(){if(!this.enabled||!this.cdpSession){t.info(`CDP session not active, reinitializing...`),await this.init();return}try{await Promise.race([this.cdpSession.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`session_unreachable`)),3e3))]);return}catch{t.warn(`Debugger CDP session unresponsive (zombie), reinitializing...`),this.enabled=!1,this.cdpSession=null,this.advancedFeatureSession=null,this.xhrManager=null,this.eventManager=null,this.blackboxManager=null,this.watchManager=null,await this.init()}}isSessionConnected(){return this.enabled&&this.cdpSession!==null}async enable(){return this.init()}async initAdvancedFeatures(e){if(!this.enabled||!this.cdpSession)throw Error(`Debugger must be enabled before initializing advanced features. Call init() first.`);try{e&&(this.watchManager=new ut(e),t.info(`WatchExpressionManager initialized`)),this.xhrManager=new dt(this.cdpSession),t.info(`XHRBreakpointManager initialized`),this.eventManager=new ft(this.cdpSession),t.info(`EventBreakpointManager initialized`),this.blackboxManager=new pt(this.cdpSession),t.info(`BlackboxManager initialized`),this.advancedFeatureSession=this.cdpSession,t.info(`All advanced debugging features initialized`)}catch(e){throw t.error(`Failed to initialize advanced features:`,e),e}}async ensureAdvancedFeatures(){if(await this.ensureSession(),!this.cdpSession)throw Error(`CDP session unavailable after reconnect.`);(this.advancedFeatureSession!==this.cdpSession||!this.xhrManager||!this.eventManager||!this.blackboxManager)&&await this.initAdvancedFeatures()}async disable(){if(!this.enabled||!this.cdpSession){t.warn(`Debugger not enabled`);return}try{this.xhrManager&&=(await this.xhrManager.close(),null),this.eventManager&&=(await this.eventManager.close(),null),this.blackboxManager&&=(await this.blackboxManager.close(),null),this.watchManager&&=(this.watchManager.clearAll(),null),this.pausedListener&&=(this.cdpSession.off(`Debugger.paused`,this.pausedListener),null),this.resumedListener&&=(this.cdpSession.off(`Debugger.resumed`,this.resumedListener),null),this.breakpointResolvedListener&&=(this.cdpSession.off(`Debugger.breakpointResolved`,this.breakpointResolvedListener),null),await this.cdpSession.send(`Debugger.disable`)}catch(e){t.error(`Failed to disable debugger:`,e)}finally{if(this.initPromise=void 0,this.enabled=!1,this.breakpoints.clear(),this.pausedState=null,this.pausedResolvers=[],this.advancedFeatureSession=null,this.cdpSession){try{await this.cdpSession.detach()}catch(e){t.warn(`Failed to detach CDP session:`,e)}this.cdpSession=null}t.info(`Debugger disabled and cleaned up`)}}isEnabled(){return this.enabled}async setBreakpointByUrl(e){return ht(this,e)}async setBreakpoint(e){return gt(this,e)}async removeBreakpoint(e){return _t(this,e)}listBreakpoints(){return vt(this)}getBreakpoint(e){return yt(this,e)}async clearAllBreakpoints(){return bt(this)}async setPauseOnExceptions(e){return xt(this,e)}getPauseOnExceptionsState(){return St(this)}async pause(){return Ct(this)}async resume(){return wt(this)}async stepInto(){return Tt(this)}async stepOver(){return Et(this)}async stepOut(){return Dt(this)}getPausedState(){return Ot(this)}isPaused(){return kt(this)}async waitForPaused(e=n){return At(this,e)}async evaluateOnCallFrame(e){return jt(this,e)}async getScopeVariables(e={}){return Mt(this,e)}async getObjectPropertiesById(e){return Nt(this,e)}async getObjectProperties(e,t){return Y(this,e,t)}onBreakpointHit(e){Pt(this,e)}offBreakpointHit(e){Ft(this,e)}clearBreakpointHitCallbacks(){It(this)}getBreakpointHitCallbackCount(){return Lt(this)}async handlePaused(e){return Rt(this,this.normalizePausedEventParams(e))}handleResumed(){zt(this)}handleBreakpointResolved(e){Bt(this,this.normalizeBreakpointResolvedParams(e))}exportSession(e){return this.sessionManager.exportSession(e)}async saveSession(e,t){return this.sessionManager.saveSession(e,t)}async loadSessionFromFile(e){return this.sessionManager.loadSessionFromFile(e)}async importSession(e){return this.sessionManager.importSession(e)}async listSavedSessions(){return this.sessionManager.listSavedSessions()}async close(){this.initPromise=void 0,this.enabled&&await this.disable(),this.cdpSession&&=(await this.cdpSession.detach(),null),t.info(`Debugger manager closed`)}normalizePausedEventParams(e){let t=this.asRecord(e);return{callFrames:(Array.isArray(t.callFrames)?t.callFrames:[]).map(e=>this.normalizeCallFrame(e)),reason:typeof t.reason==`string`?t.reason:`unknown`,data:t.data,hitBreakpoints:Array.isArray(t.hitBreakpoints)?t.hitBreakpoints.filter(e=>typeof e==`string`):void 0}}normalizeBreakpointResolvedParams(e){let t=this.asRecord(e);return{breakpointId:typeof t.breakpointId==`string`?t.breakpointId:``,location:t.location}}normalizeCallFrame(e){let t=this.asRecord(e),n=this.asRecord(t.location),r=Array.isArray(t.scopeChain)?t.scopeChain:[];return{callFrameId:typeof t.callFrameId==`string`?t.callFrameId:``,functionName:typeof t.functionName==`string`?t.functionName:``,location:{scriptId:typeof n.scriptId==`string`?n.scriptId:``,lineNumber:typeof n.lineNumber==`number`?n.lineNumber:0,columnNumber:typeof n.columnNumber==`number`?n.columnNumber:0},url:typeof t.url==`string`?t.url:``,scopeChain:r.map(e=>this.normalizeScope(e)),this:t.this}}normalizeScope(e){let t=this.asRecord(e),n=this.asRecord(t.object),r=this.normalizeScriptLocation(t.startLocation),i=this.normalizeScriptLocation(t.endLocation);return{type:this.normalizeScopeType(t.type),object:{type:typeof n.type==`string`?n.type:`object`,objectId:typeof n.objectId==`string`?n.objectId:void 0,className:typeof n.className==`string`?n.className:void 0,description:typeof n.description==`string`?n.description:void 0},name:typeof t.name==`string`?t.name:void 0,startLocation:r,endLocation:i}}normalizeScriptLocation(e){let t=this.asRecord(e);if(Object.keys(t).length!==0)return{scriptId:typeof t.scriptId==`string`?t.scriptId:``,lineNumber:typeof t.lineNumber==`number`?t.lineNumber:0,columnNumber:typeof t.columnNumber==`number`?t.columnNumber:0}}normalizeScopeType(e){return e===`global`||e===`local`||e===`with`||e===`closure`||e===`catch`||e===`block`||e===`script`||e===`eval`||e===`module`?e:`local`}asRecord(e){return typeof e==`object`&&e?e:{}}},Ht=class{collector;debuggerManager;cdpSession=null;enabled=!1;initPromise;constructor(e,t){this.collector=e,this.debuggerManager=t}async init(){if(!this.enabled){if(this.initPromise)return this.initPromise;this.initPromise=this.doInit();try{return await this.initPromise}finally{this.initPromise=void 0}}}async doInit(){try{let e=await this.collector.getActivePage();this.cdpSession=await e.createCDPSession(),await this.cdpSession.send(`Runtime.enable`),this.enabled=!0,t.info(`Runtime inspector enabled`)}catch(e){throw t.error(`Failed to enable runtime inspector:`,e),e}}async enable(){return this.init()}async enableAsyncStackTraces(e=32){if(!this.enabled||!this.cdpSession)throw new w(`Runtime inspector not enabled. Call init() or enable() first.`);try{await this.cdpSession.send(`Debugger.setAsyncCallStackDepth`,{maxDepth:e}),t.info(`Async stack traces enabled with max depth: ${e}`)}catch(e){throw t.error(`Failed to enable async stack traces:`,e),e}}async disableAsyncStackTraces(){if(!this.enabled||!this.cdpSession)throw new w(`Runtime inspector not enabled`);try{await this.cdpSession.send(`Debugger.setAsyncCallStackDepth`,{maxDepth:0}),t.info(`Async stack traces disabled`)}catch(e){throw t.error(`Failed to disable async stack traces:`,e),e}}async disable(){if(!(!this.enabled||!this.cdpSession))try{await this.cdpSession.send(`Runtime.disable`),this.enabled=!1,await this.cdpSession.detach(),this.cdpSession=null,t.info(`Runtime inspector disabled and cleaned up`)}catch(e){throw t.error(`Failed to disable runtime inspector:`,e),e}finally{this.initPromise=void 0}}async getCallStack(){let e=this.debuggerManager.getPausedState();if(!e)return t.warn(`Not in paused state, cannot get call stack`),null;try{let n={callFrames:e.callFrames.map(e=>({callFrameId:e.callFrameId,functionName:e.functionName||`(anonymous)`,location:{scriptId:e.location.scriptId,url:e.url,lineNumber:e.location.lineNumber,columnNumber:e.location.columnNumber},scopeChain:e.scopeChain.map(e=>({type:e.type,name:e.name}))})),reason:e.reason,timestamp:e.timestamp};return t.info(`Call stack retrieved`,{frameCount:n.callFrames.length,topFrame:n.callFrames[0]?.functionName}),n}catch(e){throw t.error(`Failed to get call stack:`,e),e}}async getScopeVariables(e){if(!this.enabled||!this.cdpSession)throw new w(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e)throw Error(`callFrameId parameter is required`);let n=this.debuggerManager.getPausedState();if(!n)throw new w(`Not in paused state. Debugger must be paused to get scope variables.`);let r=n.callFrames.find(t=>t.callFrameId===e);if(!r)throw Error(`Call frame not found: ${e}. Use getCallStack() to see available frames.`);try{let n=[];for(let e of r.scopeChain){if(!e.object.objectId)continue;let t=await this.getObjectProperties(e.object.objectId);n.push({scopeType:e.type,scopeName:e.name,variables:t})}return t.info(`Scope variables retrieved for call frame ${e}`,{scopeCount:n.length}),n}catch(e){throw t.error(`Failed to get scope variables:`,e),e}}async getCurrentScopeVariables(){let e=this.debuggerManager.getPausedState();if(!e||e.callFrames.length===0)throw new w(`Not in paused state or no call frames`);let t=e.callFrames[0];if(!t)throw new w(`No top frame available`);return await this.getScopeVariables(t.callFrameId)}async getObjectProperties(e){if(!this.enabled||!this.cdpSession)throw new w(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e)throw Error(`objectId parameter is required`);try{let n=await this.cdpSession.send(`Runtime.getProperties`,{objectId:e,ownProperties:!0,accessorPropertiesOnly:!1,generatePreview:!0}),r=[];for(let e of n.result)e.value&&r.push({name:e.name,value:this.formatValue(e.value),type:e.value.type||`unknown`,objectId:e.value.objectId,className:e.value.className,description:e.value.description});return t.info(`Object properties retrieved: ${e}`,{propertyCount:r.length}),r}catch(e){throw t.error(`Failed to get object properties:`,e),e}}async evaluate(e,n){if(!e||e.trim()===``)throw Error(`expression parameter is required and cannot be empty`);let r=this.debuggerManager.getPausedState();if(!r)throw new w(`Not in paused state. Use evaluateGlobal() for global context evaluation.`);let i=n||r.callFrames[0]?.callFrameId;if(!i)throw new w(`No call frame available for evaluation`);try{let n=await this.debuggerManager.evaluateOnCallFrame({callFrameId:i,expression:e,returnByValue:!0});return t.info(`Expression evaluated: ${e}`,{result:n.value}),this.formatValue(n)}catch(e){throw t.error(`Failed to evaluate expression:`,e),e}}async evaluateGlobal(e){if(!this.enabled||!this.cdpSession)throw new w(`Runtime inspector is not enabled. Call init() or enable() first.`);if(!e||e.trim()===``)throw Error(`expression parameter is required and cannot be empty`);try{let n=await this.cdpSession.send(`Runtime.evaluate`,{expression:e,returnByValue:!0});return t.info(`Global expression evaluated: ${e}`,{result:n.result.value}),this.formatValue(n.result)}catch(e){throw t.error(`Failed to evaluate global expression:`,e),e}}formatValue(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.type!==`undefined`)return t.type===`object`&&t.subtype===`null`?null:t.value===void 0?t.description?t.description:`[${t.type||`unknown`}]`:t.value}async close(){this.initPromise=void 0,this.enabled&&await this.disable(),this.cdpSession&&=(await this.cdpSession.detach(),null),t.info(`Runtime inspector closed`)}};const Z=o,Ut=a,Wt=i;function Gt(){return[process.env.TEMP,process.env.TMP,ie(),`/tmp`,`/var/tmp`].filter(e=>!!e)}var Kt=class{registry;constructor(e){this.registry=e}async probeAll(e=!1){return this.registry.probeAll(e)}async run(e){return te(()=>this.runInternal(e))}async runInternal(e){let n=this.registry.getSpec(e.tool),i=this.registry.getCachedProbe(e.tool);if(i&&!i.available)return{ok:!1,exitCode:null,signal:null,stdout:``,stderr:`Tool '${e.tool}' (${n.command}) is not available: ${i.reason}`,durationMs:0,truncated:!1};let a=this.validateCwd(e.cwd),o=[...n.defaultArgs||[],...e.args],s={PATH:process.env.PATH||``};if(process.platform===`win32`){let e=process.env.SYSTEMROOT||process.env.SystemRoot||process.env.WINDIR;e&&(s.SYSTEMROOT=e),process.env.TEMP&&(s.TEMP=process.env.TEMP),process.env.TMP&&(s.TMP=process.env.TMP)}if(n.envAllowlist)for(let e of n.envAllowlist)process.env[e]&&(s[e]=process.env[e]);let c=e.timeoutMs??Z,l=e.maxStdoutBytes??Ut,u=e.maxStderrBytes??Wt,f=e.outputLabel?.trim()||`output`;t.debug(`[ExternalToolRunner] Running: ${n.command} ${o.join(` `)}`);let p=Date.now();return new Promise(i=>{let m=le(n.command,o,{cwd:a,env:s,shell:!1,windowsHide:!0,stdio:[`pipe`,`pipe`,`pipe`]});d.register(m);let h=[],g=[],_=0,v=0,y=!1,b=!1,x=!1,S=setTimeout(()=>{x||(m.kill(`SIGTERM`),setTimeout(()=>{x||(m.kill(`SIGKILL`),C(null,`SIGKILL`))},r),e.onProgress?.({phase:`timeout`,ts:Date.now()}))},c),C=async(r,a)=>{if(x)return;x=!0,clearTimeout(S);let o=h.length===1?h[0].toString(`utf-8`):h.length>1?Buffer.concat(h).toString(`utf-8`):``,s=g.length===1?g[0].toString(`utf-8`):g.length>1?Buffer.concat(g).toString(`utf-8`):``;h=[],g=[];let c=Date.now()-p,l={ok:r===0,exitCode:r,signal:a,stdout:o,stderr:s,durationMs:c,truncated:y||b};if(l.ok){let t=await this.collectSuccessDiagnostics(e,{stdout:o,stderr:s,outputLabel:f});t.length>0&&(l.ok=!1,l.diagnostics=t,l.diagnosticCode=t.some(e=>e.includes(`0 bytes`))?`EMPTY_OUTPUT_ARTIFACT`:`EMPTY_OUTPUT`,l.stderr=[s.trim(),...t].filter(Boolean).join(`
|
|
333
|
+
`))}l.ok?t.debug(`[ExternalToolRunner] ${n.command} completed in ${c}ms`):t.warn(`[ExternalToolRunner] ${n.command} failed (exit=${r}, signal=${a}) in ${c}ms`),i(l)};e.stdin&&m.stdin.write(e.stdin),m.stdin.end(),m.stdout.on(`data`,t=>{if(_<l){let e=l-_,n=t.length<=e?t:t.subarray(0,e);h.push(n),_+=n.length,_>=l&&(y=!0)}e.onProgress?.({phase:`stdout`,bytesRead:_,ts:Date.now()})}),m.stderr.on(`data`,t=>{if(v<u){let e=u-v,n=t.length<=e?t:t.subarray(0,e);g.push(n),v+=n.length,v>=u&&(b=!0)}e.onProgress?.({phase:`stderr`,bytesRead:v,ts:Date.now()})}),m.on(`close`,(e,t)=>{C(e,t)}),m.on(`error`,e=>{let t=Buffer.from(`\nSpawn error: ${e.message}`,`utf-8`);g.push(t),v+=t.length,C(1,null)}),e.onProgress?.({phase:`spawn`,ts:Date.now()})})}validateCwd(e){if(!e)return c();let n=k(e),r=c(),i=oe(r,n);if(i&&!i.startsWith(`..`)&&!ae(i))return n;let a=Gt();for(let e of a){let t=k(e);if(n===t||n.startsWith(t+se))return n}return t.warn(`[ExternalToolRunner] CWD '${e}' outside allowed boundaries, using project root`),r}async collectSuccessDiagnostics(e,t){let n=[];if(Array.isArray(e.expectedOutputPaths)&&e.expectedOutputPaths.length>0){let r=[],i=[];for(let t of e.expectedOutputPaths)try{let n=await ce(t);if(n.isDirectory()){e.allowDirectoryOutputs||i.push(t);continue}n.size<=0&&r.push(t)}catch{i.push(t)}i.length>0&&n.push(`Expected ${t.outputLabel} artifact was not created: ${i.join(`, `)}`),r.length>0&&n.push(`Expected ${t.outputLabel} artifact is 0 bytes: ${r.join(`, `)}`)}if(e.requireNonEmptyOutput){let r=t.stdout.trim().length>0,i=t.stderr.trim().length>0,a=!n.some(e=>e.includes(`not created`)||e.includes(`0 bytes`));!r&&!i&&(!e.expectedOutputPaths||!a)&&n.push(`Process exited successfully but produced no stdout, stderr, or usable ${t.outputLabel}.`)}return n}};function qt(e,t,n,r,i,a=!1){switch(t){case`function`:return g(e,n,r,i,a);case`xhr`:return me(n,r,i,a);case`fetch`:return he(n,r,i,a);case`websocket`:return ge(n,r,i,a);case`localstorage`:return h(n,r,i,a);case`cookie`:return y(n,r,i,a);case`eval`:return f(n,r,i,a);case`object-method`:return p(e,n,r,i,a);default:throw Error(`Unsupported hook type: ${t}`)}}var Jt=class{hooks=new Map;hookScripts=new Map;hookMetadata=new Map;hookConditions=new Map;MAX_HOOK_RECORDS=1e3;MAX_TOTAL_RECORDS=1e4;MAX_HOOKS=200;async createHook(e){if(this.hookScripts.size>=this.MAX_HOOKS){let e=null,n=1/0;for(let[t,r]of this.hookMetadata)r.createdAt<n&&(n=r.createdAt,e=t);e&&(t.warn(`Hook limit (${this.MAX_HOOKS}) reached, evicting oldest: ${e}`),this.deleteHook(e))}t.info(`Creating hook for ${e.target} (type: ${e.type})...`);try{let{target:n,type:r,action:i=`log`,condition:a,performance:o=!1}=e,s=qt(n,r,i,e.customCode,a,o),c=`${n}-${r}-${Date.now()}`;return this.hookScripts.set(c,s),a&&this.hookConditions.set(c,a),this.hookMetadata.set(c,{id:c,enabled:!0,createdAt:Date.now(),callCount:0,totalExecutionTime:0}),t.success(`Hook created: ${c}`),{hookId:c,script:s,instructions:_(r)}}catch(e){throw t.error(`Failed to create hook`,e),e}}recordHookEvent(e,n){let r={hookId:e,timestamp:Date.now(),context:n},i=this.hooks.get(e)||[];i.push(r),this.hooks.set(e,i),t.debug(`Hook event recorded: ${e}`)}getHookRecords(e){return this.hooks.get(e)||[]}clearHookRecords(e){e?(this.hooks.delete(e),t.info(`Cleared records for hook: ${e}`)):(this.hooks.clear(),t.info(`Cleared all hook records`))}enableHook(e){let n=this.hookMetadata.get(e);n?(n.enabled=!0,t.info(`Hook enabled: ${e}`)):t.warn(`Hook not found: ${e}`)}disableHook(e){let n=this.hookMetadata.get(e);n?(n.enabled=!1,t.info(`Hook disabled: ${e}`)):t.warn(`Hook not found: ${e}`)}getHookMetadata(e){return this.hookMetadata.get(e)}getAllHookMetadata(){return Array.from(this.hookMetadata.values())}exportHookData(e){if(e){let t=this.hookMetadata.get(e),n=this.hooks.get(e)||[],r=this.hookScripts.get(e)||``;return{metadata:t?[t]:[],records:{[e]:n},scripts:{[e]:r}}}let t=Array.from(this.hookMetadata.values()),n={},r={};return this.hooks.forEach((e,t)=>{n[t]=e}),this.hookScripts.forEach((e,t)=>{r[t]=e}),{metadata:t,records:n,scripts:r}}getHookStats(e){let t=this.hookMetadata.get(e);return t?{callCount:t.callCount,avgExecutionTime:t.callCount>0?t.totalExecutionTime/t.callCount:0,totalExecutionTime:t.totalExecutionTime,enabled:t.enabled}:null}deleteHook(e){this.hookScripts.delete(e),this.hookMetadata.delete(e),this.hookConditions.delete(e),this.hooks.delete(e),t.info(`Hook deleted: ${e}`)}getAllHooks(){return Array.from(this.hookScripts.keys())}recordHookCall(e,n){this.hooks.has(e)||this.hooks.set(e,[]);let r=this.hooks.get(e);r.length>=this.MAX_HOOK_RECORDS&&(r.shift(),t.debug(`Hook ${e} reached max records, removed oldest`)),r.push(n),Array.from(this.hooks.values()).reduce((e,t)=>e+t.length,0)>this.MAX_TOTAL_RECORDS&&this.cleanupOldestRecords();let i=this.hookMetadata.get(e);i&&(i.callCount++,i.lastCalled=Date.now())}cleanupOldestRecords(){let e=null,n=1/0;for(let[t,r]of this.hooks.entries())if(r.length>0){let i=r[0];i&&i.timestamp<n&&(n=i.timestamp,e=t)}if(e){let n=this.hooks.get(e),r=Math.floor(n.length/2);n.splice(0,r),t.warn(`Cleaned up ${r} old records from ${e} (total records exceeded limit)`)}}getHookRecordsStats(){let e=0,t=null,n=null,r={};for(let[i,a]of this.hooks.entries())if(r[i]=a.length,e+=a.length,a.length>0){let e=a[0],r=a[a.length-1];if(e){let n=e.timestamp;(t===null||n<t)&&(t=n)}if(r){let e=r.timestamp;(n===null||e>n)&&(n=e)}}return{totalHooks:this.hooks.size,totalRecords:e,recordsByHook:r,oldestRecord:t,newestRecord:n}}async createBatchHooks(e){t.info(`Creating ${e.length} hooks...`);let n=[];for(let{target:r,type:i,action:a=`log`}of e)try{let e=await this.createHook({target:r,type:i,action:a});n.push(e)}catch(e){t.error(`Failed to create hook for ${r}:`,e)}return t.success(`Created ${n.length}/${e.length} hooks`),n}generateAntiDebugBypass(){return m()}generateHookTemplate(e,t){return v(e,t)}generateHookChain(e){return _e(e)}};function Q(e){return typeof e==`object`&&!!e}function Yt(e){return Q(e)&&typeof e.chunk==`string`}function Xt(e){if(!Q(e))return!1;let{callFrame:t,selfSize:n,children:r}=e;return!(t!==void 0&&(!Q(t)||t.functionName!==void 0&&typeof t.functionName!=`string`||t.url!==void 0&&typeof t.url!=`string`)||n!==void 0&&typeof n!=`number`||r!==void 0&&!Array.isArray(r))}function Zt(e){return Q(e)&&Q(e.profile)&&Xt(e.profile.head)}async function $(){await pe()}function Qt(e){let t=/"ph"\s*:/g,n=0;for(;t.exec(e)!==null;)n++;return n}function $t(e,t,n){if(n<=0||e.length===n&&t.selfSize<=e[e.length-1].selfSize)return;let r=e.findIndex(e=>t.selfSize>e.selfSize);r===-1&&(r=e.length),e.splice(r,0,t),e.length>n&&(e.length=n)}function en(e,t){let n=[e],r=[],i=0;for(;n.length>0;){let e=n.pop();if(e&&(e.callFrame&&(i++,$t(r,{functionName:e.callFrame.functionName||`(anonymous)`,url:e.callFrame.url||``,selfSize:e.selfSize||0},t)),Array.isArray(e.children)))for(let t=e.children.length-1;t>=0;t--){let r=e.children[t];r&&n.push(r)}}return{sampleCount:i,topAllocations:r}}async function tn(e){await Promise.race([e.send(`Runtime.evaluate`,{expression:`1`,returnByValue:!0}),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_unreachable`)),500))])}var nn=class{collector;cdpSession=null;coverageEnabled=!1;profilerEnabled=!1;tracingEnabled=!1;heapSamplingEnabled=!1;coveragePage=null;tracingPage=null;constructor(e){this.collector=e}async ensureCDPSession(){if(!this.cdpSession){let e=await this.collector.getActivePage();return this.cdpSession=await Promise.race([e.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),this.cdpSession}try{return await tn(this.cdpSession),this.cdpSession}catch(e){if((e instanceof Error?e.message:String(e))!==`cdp_unreachable`)throw e;t.warn(`PerformanceMonitor CDP session unresponsive, recreating...`);try{await this.cdpSession.detach()}catch{}this.cdpSession=null;let n=await this.collector.getActivePage();return this.cdpSession=await Promise.race([n.createCDPSession(),new Promise((e,t)=>setTimeout(()=>t(Error(`cdp_session_timeout`)),500))]),this.cdpSession}}async getPerformanceMetrics(){let e=await x(await this.collector.getActivePage(),()=>{let e={},t=performance.getEntriesByType(`navigation`)[0];t&&(e.domContentLoaded=t.domContentLoadedEventEnd-t.fetchStart,e.loadComplete=t.loadEventEnd-t.fetchStart,e.ttfb=t.responseStart-t.requestStart);let n=performance.getEntriesByType(`paint`).find(e=>e.name===`first-contentful-paint`);n&&(e.fcp=n.startTime);let r=performance.getEntriesByType(`largest-contentful-paint`).at(-1);r&&(e.lcp=r.renderTime||r.loadTime);let i=0,a=performance.getEntriesByType(`layout-shift`);for(let e of a)e.hadRecentInput||(i+=e.value??0);e.cls=i;let o=performance;if(o.memory){let t=o.memory;e.jsHeapSizeLimit=t.jsHeapSizeLimit,e.totalJSHeapSize=t.totalJSHeapSize,e.usedJSHeapSize=t.usedJSHeapSize}return e});return t.info(`Performance metrics collected`,{fcp:e.fcp,lcp:e.lcp,cls:e.cls}),e}async getPerformanceTimeline(){let e=await x(await this.collector.getActivePage(),()=>performance.getEntries().map(e=>({name:e.name,entryType:e.entryType,startTime:e.startTime,duration:e.duration})));return t.info(`Performance timeline collected: ${e.length} entries`),e}async startCoverage(e){let n=await this.collector.getActivePage();await Promise.all([ee(n,{resetOnNavigation:e?.resetOnNavigation,reportAnonymousScripts:e?.reportAnonymousScripts}),C(n,{resetOnNavigation:e?.resetOnNavigation})]),this.coverageEnabled=!0,this.coveragePage=n,t.info(`Code coverage collection started`)}async stopCoverage(){if(!this.coverageEnabled)throw new w(`Coverage not enabled. Call startCoverage() first.`);let e=this.coveragePage??await this.collector.getActivePage(),[n,r]=await Promise.all([S(e),b(e)]),i=n,a=r;this.coverageEnabled=!1,this.coveragePage=null;let o=[...i,...a].map(e=>{let t=e.text.length,n=e.ranges.reduce((e,t)=>e+(t.end-t.start),0);return{url:e.url,text:e.text,ranges:e.ranges.map(e=>({start:e.start,end:e.end,count:1})),totalBytes:t,usedBytes:n,coveragePercentage:t>0?n/t*100:0}});return t.success(`Code coverage collected: ${o.length} scripts`,{totalScripts:o.length,avgCoverage:o.reduce((e,t)=>e+t.coveragePercentage,0)/o.length}),o}async startCPUProfiling(){let e=await this.ensureCDPSession();await e.send(`Profiler.enable`),await e.send(`Profiler.start`),this.profilerEnabled=!0,t.info(`CPU profiling started`)}async stopCPUProfiling(){if(!this.profilerEnabled)throw new w(`CPU profiling not enabled. Call startCPUProfiling() first.`);let e=await this.ensureCDPSession(),{profile:n}=await e.send(`Profiler.stop`);return await e.send(`Profiler.disable`),this.profilerEnabled=!1,t.success(`CPU profiling stopped`,{nodes:n.nodes.length,samples:n.samples?.length||0}),n}async takeHeapSnapshot(){let e=await this.ensureCDPSession();await e.send(`HeapProfiler.enable`);let n=0,r=e=>{Yt(e)&&(n+=e.chunk.length)};e.on(`HeapProfiler.addHeapSnapshotChunk`,r);try{await e.send(`HeapProfiler.takeHeapSnapshot`,{reportProgress:!1,treatGlobalObjectsAsRoots:!0})}finally{e.off(`HeapProfiler.addHeapSnapshotChunk`,r),await e.send(`HeapProfiler.disable`).catch(()=>{})}return t.success(`Heap snapshot taken`,{size:n}),n}async startTracing(e){return T(async()=>{if(this.tracingEnabled)throw Error(`Tracing already in progress. Call stopTracing() first.`);let n=await this.collector.getActivePage(),r=e?.categories??[`-*`,`devtools.timeline`,`v8.execute`,`disabled-by-default-devtools.timeline`,`disabled-by-default-devtools.timeline.frame`,`toplevel`,`blink.console`,`blink.user_timing`,`latencyInfo`,...e?.screenshots?[`disabled-by-default-devtools.screenshot`]:[]];await n.tracing.start({categories:r,screenshots:e?.screenshots}),this.tracingEnabled=!0,this.tracingPage=n,t.info(`Performance tracing started`,{categories:r.length})})}async stopTracing(e){return T(async()=>{if(!this.tracingEnabled)throw new w(`Tracing not in progress. Call startTracing() first.`);let n=await(this.tracingPage??await this.collector.getActivePage()).tracing.stop(),r=n?Buffer.from(n).toString(`utf-8`):``;this.tracingEnabled=!1,this.tracingPage=null;let i=Qt(r),a;if(e?.artifactPath)await A(e.artifactPath,r,`utf-8`),a=e.artifactPath;else{let{absolutePath:e,displayPath:t}=await u({category:`traces`,toolName:`performance-trace`,ext:`json`});await A(e,r,`utf-8`),a=t}return t.success(`Performance trace saved`,{eventCount:i,sizeBytes:r.length,path:a}),{artifactPath:a,eventCount:i,sizeBytes:r.length}})}async startHeapSampling(e){return T(async()=>{if(this.heapSamplingEnabled)throw Error(`Heap sampling already in progress. Call stopHeapSampling() first.`);let n=await this.ensureCDPSession();await n.send(`HeapProfiler.enable`),await n.send(`HeapProfiler.startSampling`,{samplingInterval:e?.samplingInterval??32768}),this.heapSamplingEnabled=!0,t.info(`Heap sampling profiler started`)})}async stopHeapSampling(e){return T(async()=>{if(!this.heapSamplingEnabled)throw new w(`Heap sampling not in progress. Call startHeapSampling() first.`);let n=await this.ensureCDPSession(),r=await n.send(`HeapProfiler.stopSampling`);if(!Zt(r))throw Error(`Unexpected HeapProfiler.stopSampling payload shape`);let{profile:i}=r;await n.send(`HeapProfiler.disable`),this.heapSamplingEnabled=!1;let a=e?.topN??20;await $();let{sampleCount:o,topAllocations:s}=en(i.head,a);await $();let c=JSON.stringify(i),l;if(e?.artifactPath)await A(e.artifactPath,c,`utf-8`),l=e.artifactPath;else{let{absolutePath:e,displayPath:t}=await u({category:`profiles`,toolName:`heap-sampling`,ext:`json`});await A(e,c,`utf-8`),l=t}return t.success(`Heap sampling profile saved`,{sampleCount:o,path:l}),{artifactPath:l,sampleCount:o,topAllocations:s}})}async close(){this.cdpSession&&=(this.coverageEnabled&&await this.stopCoverage().catch(()=>{}),this.profilerEnabled&&await this.stopCPUProfiling().catch(()=>{}),this.tracingEnabled&&await this.stopTracing().catch(()=>{}),this.heapSamplingEnabled&&await this.stopHeapSampling().catch(()=>{}),await this.cdpSession.detach(),null),t.info(`PerformanceMonitor closed`)}},rn=class e{constructor(){}static injectedPages=new WeakSet;static async injectAll(e){if(this.injectedPages.has(e)){t.info(`Stealth scripts already injected on this page, skipping`);return}t.info(`Injecting modern stealth scripts...`),await Promise.all([this.hideWebDriver(e),this.mockChrome(e),this.mockPlugins(e),this.fixPermissions(e),this.mockCanvas(e),this.mockWebGL(e),this.fixLanguages(e),this.mockBattery(e),this.fixMediaDevices(e),this.mockNotifications(e)]),await this.injectTimingDefense(e),this.injectedPages.add(e),t.info(` `)}static async injectTimingDefense(e){await e.evaluateOnNewDocument(()=>{let e=performance.now.bind(performance),t=Date.now,n=0;performance.now=function(){let t=window;return typeof t.__cdpTimingOffset==`number`&&(n=t.__cdpTimingOffset),e()-n},Date.now=function(){let e=window;return typeof e.__cdpTimingOffset==`number`&&(n=e.__cdpTimingOffset),t.call(Date)-Math.floor(n)};let r=Date,i=function(...e){return e.length===0?new r(r.now()):new r(...e)};i.now=r.now,i.parse=r.parse.bind(r),i.UTC=r.UTC.bind(r),Object.defineProperty(i,"prototype",{value:r.prototype}),globalThis.Date=i})}static async hideWebDriver(e){await e.evaluateOnNewDocument(()=>{let e=Object.getPrototypeOf(navigator);delete e.webdriver,Object.defineProperty(navigator,"webdriver",{get:()=>void 0,configurable:!0});let t=Object.getOwnPropertyNames;if(Object.getOwnPropertyNames=function(e){return t(e).filter(e=>e!==`webdriver`)},typeof document<`u`){let e=document;for(let t of Object.keys(e))(t.startsWith(`cdc_`)||t.startsWith(`$cdc_`))&&delete e[t]}})}static async mockChrome(e){await e.evaluateOnNewDocument(()=>{let e=window;e.chrome={runtime:{connect:()=>{},sendMessage:()=>{},onMessage:{addListener:()=>{},removeListener:()=>{}}},loadTimes:function(){return{commitLoadTime:Date.now()/1e3,connectionInfo:`http/1.1`,finishDocumentLoadTime:Date.now()/1e3,finishLoadTime:Date.now()/1e3,firstPaintAfterLoadTime:0,firstPaintTime:Date.now()/1e3,navigationType:`Other`,npnNegotiatedProtocol:`unknown`,requestTime:0,startLoadTime:Date.now()/1e3,wasAlternateProtocolAvailable:!1,wasFetchedViaSpdy:!1,wasNpnNegotiated:!1}},csi:function(){return{onloadT:Date.now(),pageT:Date.now(),startE:Date.now(),tran:15}},app:{isInstalled:!1,InstallState:{DISABLED:`disabled`,INSTALLED:`installed`,NOT_INSTALLED:`not_installed`},RunningState:{CANNOT_RUN:`cannot_run`,READY_TO_RUN:`ready_to_run`,RUNNING:`running`}}}})}static async mockPlugins(e){await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"plugins",{configurable:!0,get:()=>[{0:{type:`application/pdf`,suffixes:`pdf`,description:`Portable Document Format`},description:`Portable Document Format`,filename:`internal-pdf-viewer`,length:1,name:`Chrome PDF Plugin`},{0:{type:`application/x-google-chrome-pdf`,suffixes:`pdf`,description:``},description:``,filename:`internal-pdf-viewer`,length:1,name:`Chrome PDF Viewer`},{0:{type:`application/x-nacl`,suffixes:``,description:`Native Client Executable`},1:{type:`application/x-pnacl`,suffixes:``,description:`Portable Native Client Executable`},description:``,filename:`internal-nacl-plugin`,length:2,name:`Native Client`}]})})}static async fixPermissions(e){await e.evaluateOnNewDocument(()=>{let e=window.navigator.permissions.query.bind(window.navigator.permissions),t=Notification;window.navigator.permissions.query=n=>n.name===`notifications`?Promise.resolve({state:t.permission}):e(n)})}static async mockCanvas(e){await e.evaluateOnNewDocument(()=>{let e=HTMLCanvasElement.prototype.toDataURL,t=CanvasRenderingContext2D.prototype.getImageData;HTMLCanvasElement.prototype.toDataURL=function(...t){let n=this.getContext(`2d`);if(n){let e=n.getImageData(0,0,this.width,this.height),t=e.data;if(t)for(let e=0;e<t.length;e+=4)t[e]=t[e]^1,t[e+1]=t[e+1]^1,t[e+2]=t[e+2]^1;n.putImageData(e,0,0)}return e.apply(this,t)},CanvasRenderingContext2D.prototype.getImageData=function(...e){let n=t.apply(this,e),r=n.data;if(r)for(let e=0;e<r.length;e+=4)r[e]=r[e]^1,r[e+1]=r[e+1]^1,r[e+2]=r[e+2]^1;return n}})}static async mockWebGL(e){await e.evaluateOnNewDocument(()=>{let e=WebGLRenderingContext.prototype.getParameter;WebGLRenderingContext.prototype.getParameter=function(t){return t===37445?`Intel Inc.`:t===37446?`Intel Iris OpenGL Engine`:e.apply(this,[t])}})}static async fixLanguages(e){await e.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"language",{configurable:!0,get:()=>`en-US`}),Object.defineProperty(navigator,"languages",{configurable:!0,get:()=>[`en-US`,`en`]})})}static async mockBattery(e){await e.evaluateOnNewDocument(()=>{let e=navigator;if(typeof e.getBattery==`function`){let t=e.getBattery;e.getBattery=function(){return t.call(navigator).then(e=>(Object.defineProperty(e,"charging",{configurable:!0,get:()=>!0}),Object.defineProperty(e,"chargingTime",{configurable:!0,get:()=>0}),Object.defineProperty(e,"dischargingTime",{configurable:!0,get:()=>1/0}),Object.defineProperty(e,"level",{configurable:!0,get:()=>1}),e))}}})}static async fixMediaDevices(e){await e.evaluateOnNewDocument(()=>{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){let e=navigator.mediaDevices.enumerateDevices;navigator.mediaDevices.enumerateDevices=function(){return e.call(navigator.mediaDevices).then(e=>e.length===0?[{deviceId:`default`,kind:`audioinput`,label:`Default - Microphone`,groupId:`default`,toJSON:()=>({})},{deviceId:`default`,kind:`videoinput`,label:`Default - Camera`,groupId:`default`,toJSON:()=>({})}]:e)}}})}static async mockNotifications(e){await e.evaluateOnNewDocument(()=>{`Notification`in window&&Object.defineProperty(Notification,"permission",{configurable:!0,get:()=>`default`})})}static async setRealisticUserAgent(e,t=`windows`){let n={windows:`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`,mac:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`,linux:`Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`},r={windows:`Win32`,mac:`MacIntel`,linux:`Linux x86_64`},i={windows:16,mac:12,linux:8};await e.setUserAgent(n[t]);let a=i[t];await e.evaluateOnNewDocument((e,t)=>{Object.defineProperty(navigator,"platform",{configurable:!0,get:()=>e}),Object.defineProperty(navigator,"vendor",{configurable:!0,get:()=>`Google Inc.`}),Object.defineProperty(navigator,"hardwareConcurrency",{configurable:!0,get:()=>t}),Object.defineProperty(navigator,"deviceMemory",{configurable:!0,get:()=>8})},r[t],a)}static getRecommendedLaunchArgs(){return[`--no-sandbox`,`--disable-setuid-sandbox`,`--disable-blink-features=AutomationControlled`,`--disable-dev-shm-usage`,`--disable-accelerated-2d-canvas`,`--no-first-run`,`--no-zygote`,`--disable-gpu`,`--disable-web-security`,`--disable-features=IsolateOrigins,site-per-process`,`--window-size=1920,1080`,`--disable-infobars`,`--disable-extensions`,`--disable-default-apps`,`--disable-sync`,`--metrics-recording-only`,`--mute-audio`,`--no-default-browser-check`,`--disable-background-timer-throttling`,`--disable-backgrounding-occluded-windows`,`--disable-renderer-backgrounding`,...e.getPatchrightLaunchArgs()]}static getPatchrightLaunchArgs(){return[`--disable-component-update`,`--disable-features=OptimizationGuideModelDownloading,OptimizationHintsFetching,OptimizationHints`,`--disable-hang-monitor`,`--disable-domain-reliability`,`--disable-client-side-phishing-detection`,`--disable-popup-blocking`]}},an=e({AdvancedDeobfuscator:()=>st,CodeAnalyzer:()=>Ee,CryptoDetector:()=>rt,DebuggerManager:()=>Vt,Deobfuscator:()=>ct,HookManager:()=>Jt,ObfuscationDetector:()=>lt,RuntimeInspector:()=>Ht});export{tt as a,Kt as i,rn as n,De as o,nn as r,an as t};
|