@jshookmcp/jshook 0.3.1 → 0.3.2
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/LICENSE +661 -661
- package/README.md +11 -3
- package/README.zh.md +11 -3
- package/dist/{AntiCheatDetector-CGVGNfy5.mjs → AntiCheatDetector-B6d4Qe9D.mjs} +1 -1
- package/dist/BrowserSessionCoordinator-BJ-HOxo0.mjs +1 -0
- package/dist/{CodeInjector-BlgyqTOk.mjs → CodeInjector-Cll_7bLJ.mjs} +1 -1
- package/dist/ConsoleMonitor-CxDJV15E.mjs +306 -0
- package/dist/DOMInspector-C19J4zeq.mjs +95 -0
- package/dist/DetailedDataManager-DmQ1LT-W.mjs +1 -0
- package/dist/ExtensionManager-BD724zkO.mjs +1 -0
- package/dist/ExtensionManager.tools-oVMJgPcN.mjs +1 -0
- package/dist/{HardwareBreakpoint-OcJqNFVc.mjs → HardwareBreakpoint-BUfPdp0f.mjs} +1 -1
- package/dist/{HeapAnalyzer-CqAxZzeS.mjs → HeapAnalyzer-B_aqY8oj.mjs} +1 -1
- package/dist/MCPServer.search.handlers.domain-BbS-6LnX.mjs +1 -0
- package/dist/MemoryController-X1XNSn1n.mjs +2 -0
- package/dist/{MemoryScanSession-CaxAjZJf.mjs → MemoryScanSession-DG_F-PjE.mjs} +1 -1
- package/dist/{MemoryScanner-BLYnMJy6.mjs → MemoryScanner-g1_L1ub5.mjs} +1 -1
- package/dist/{NativeMemoryManager.impl-CI554XbY.mjs → NativeMemoryManager.impl-DniBe2wf.mjs} +1 -1
- package/dist/{NativeMemoryManager.utils-DM4NC3FE.mjs → NativeMemoryManager.utils-BHy1P_jM.mjs} +1 -1
- package/dist/NetworkMonitor-B_-au6aV.mjs +185 -0
- package/dist/{PEAnalyzer-DJyaJTQJ.mjs → PEAnalyzer-yWQaGrcx.mjs} +1 -1
- package/dist/PageController-Dfsm1_o7.mjs +1 -0
- package/dist/{PointerChainEngine-5nF9eNlu.mjs → PointerChainEngine-BhCUkmxY.mjs} +1 -1
- package/dist/ProcessRegistry-C-bN48oR.mjs +1 -0
- package/dist/{ResponseBuilder-B2lu4KEl.mjs → ResponseBuilder-BfWP-uaT.mjs} +1 -1
- package/dist/RingBuffer-Dm54ELKT.mjs +1 -0
- package/dist/{ScriptManager-fgqiALgj.mjs → ScriptManager-LWGPTdvD.mjs} +1 -1
- package/dist/ServerRuntimeState-D2bWHqEE.mjs +1 -0
- package/dist/{Speedhack-l6s8L2Qw.mjs → Speedhack-yseDPSZ9.mjs} +1 -1
- package/dist/{StructureAnalyzer-A-WamfYE.mjs → StructureAnalyzer-C5lpuZkg.mjs} +1 -1
- package/dist/ToolCatalog-CYdD9F5f.mjs +1 -0
- package/dist/ToolProbe-C7ZU2x7M.mjs +1 -0
- package/dist/ToolRegistry-C5oB8KP8.mjs +1 -0
- package/dist/{ToolRouter.policy-CFHoN_Lw.mjs → ToolRouter.policy-CfhJczkt.mjs} +2 -2
- package/dist/{TraceRecorder-Dd8jLXpi.mjs → TraceRecorder-BiJWBXHX.mjs} +1 -1
- package/dist/{Win32Debug-CQteFL4F.mjs → Win32Debug-CYrIQBvr.mjs} +1 -1
- package/dist/{WorkflowEngine-CxEp2WXH.mjs → WorkflowEngine-D876meOO.mjs} +1 -1
- package/dist/analysis-D4swdMvq.mjs +6 -0
- package/dist/{antidebug-BOTZH6-0.mjs → antidebug-7L3ygj_9.mjs} +4 -4
- package/dist/apk-packer-BqXcInnX.mjs +1 -0
- package/dist/{artifactRetention-NBdncOEW.mjs → artifactRetention-BCPQASm7.mjs} +1 -1
- package/dist/{artifacts-B5xQuEa_.mjs → artifacts-CkodUM4j.mjs} +1 -1
- package/dist/betterSqlite3-Brtq-SIQ.mjs +1 -0
- package/dist/{binary-instrument-Cf9qqLlM.mjs → binary-instrument-DU7V6TUM.mjs} +1 -1
- package/dist/binary-secrets-PdMVoyt0.mjs +1 -0
- package/dist/{boringssl-inspector-BST5vtKx.mjs → boringssl-inspector-BBaJwwkU.mjs} +1 -1
- package/dist/browser-Qqco2rOT.mjs +11 -0
- package/dist/collector-Bpl6qy2L.mjs +1 -0
- package/dist/constants-BYj8Xek8.mjs +1 -0
- package/dist/{coordination-BbijHEHH.mjs → coordination-CWXW1o8K.mjs} +1 -1
- package/dist/dart-inspector-7AkPeZ_Q.mjs +0 -0
- package/dist/{debugger-CRJq_krh.mjs → debugger-DyALjYMk.mjs} +1 -1
- package/dist/{definitions-DZ8uKusP.mjs → definitions-BWxBke3r.mjs} +1 -1
- package/dist/{definitions-CYFbewnd.mjs → definitions-BYwATKc-.mjs} +1 -1
- package/dist/{definitions-DJklW2sS.mjs → definitions-B_83XfNQ.mjs} +1 -1
- package/dist/definitions-Bf3H1EwV.mjs +1 -0
- package/dist/{definitions-BGobEDQa.mjs → definitions-BftdXgXI.mjs} +1 -1
- package/dist/definitions-Bio5XJYy.mjs +1 -0
- package/dist/definitions-C3qNgSn1.mjs +1 -0
- package/dist/{definitions-NoVp_9Pm.mjs → definitions-CB6vmOer.mjs} +1 -1
- package/dist/{definitions-CoQFbggH.mjs → definitions-CMZRSy3k.mjs} +1 -1
- package/dist/{definitions-DI9YXsJk.mjs → definitions-CQd7yCQH.mjs} +1 -1
- package/dist/{definitions-CIO9O-Sw.mjs → definitions-CT8ln6GQ.mjs} +1 -1
- package/dist/{definitions-BGwNSkVm.mjs → definitions-Cenu6mxo.mjs} +1 -1
- package/dist/definitions-D4g-MS10.mjs +1 -0
- package/dist/{definitions-CuJRsJ6N.mjs → definitions-D5wl_8HN.mjs} +1 -1
- package/dist/{definitions-jXPaVy4P.mjs → definitions-DAQm1Xar.mjs} +1 -1
- package/dist/definitions-DP1vgxEY.mjs +1 -0
- package/dist/{definitions-Dds_zrWx.mjs → definitions-DxFNRQNK2.mjs} +1 -1
- package/dist/{definitions-DtE0XLrT.mjs → definitions-Ibci7e_L.mjs} +1 -1
- package/dist/{definitions-CCP9gphV.mjs → definitions-OeLvmlQy.mjs} +1 -1
- package/dist/{definitions-BbxOUiP-.mjs → definitions-RZYGD_Ey.mjs} +1 -1
- package/dist/definitions-Tls8c0A0.mjs +1 -0
- package/dist/{definitions-LaYTuwQd.mjs → definitions-bybDvnG0.mjs} +1 -1
- package/dist/{definitions-Dgrg7f3D.mjs → definitions-l7TjdE6V.mjs} +1 -1
- package/dist/{encoding-DGcr6Aj_.mjs → encoding-ycOaz8Vr.mjs} +1 -1
- package/dist/{ensure-browser-core-Buls24LQ.mjs → ensure-browser-core-DxWC-NTp.mjs} +1 -1
- package/dist/{factory-Cx_1LorX.mjs → factory-CKr4fAE1.mjs} +1 -1
- package/dist/{graphql-HLf3MS8H.mjs → graphql-B2TiPEow.mjs} +4 -4
- package/dist/{handlers-D49r1-1P.mjs → handlers-8zN_vBIz.mjs} +1 -1
- package/dist/handlers-B62K4FTc.mjs +1 -0
- package/dist/{handlers-BZoPla6E.mjs → handlers-BpDlVVVU.mjs} +1 -1
- package/dist/{handlers-DmQzIc44.mjs → handlers-CMJK7m1c.mjs} +1 -1
- package/dist/{handlers-BLMa4X7l.mjs → handlers-D2ZOul9p.mjs} +2 -2
- package/dist/{handlers-DW5AbYs5.mjs → handlers-D5E40ssn.mjs} +3 -3
- package/dist/{handlers-BP12ZsWc.mjs → handlers-DGbdQAgD.mjs} +2 -2
- package/dist/handlers-DHO3rjsW.mjs +1 -0
- package/dist/{handlers-DCE45Ww8.mjs → handlers-FJ80VzUI.mjs} +1 -1
- package/dist/handlers-VHWrxbM_.mjs +1 -0
- package/dist/{handlers-BggKiVx9.mjs → handlers-l8QIKqBj.mjs} +1 -1
- package/dist/{handlers-DnJRGp7t.mjs → handlers-mPFiNPe8.mjs} +1 -1
- package/dist/{handlers-pVNpaw4A.mjs → handlers-yo_xYzT8.mjs} +1 -1
- package/dist/handlers.impl-D9Hh8Bgl.mjs +1 -0
- package/dist/{hooks-DDKppogd.mjs → hooks-D4XLfgtV.mjs} +1 -1
- package/dist/index.mjs +11 -15
- package/dist/jadx-search-B_Yse0Zh.mjs +5 -0
- package/dist/maintenance-BUpIukhg.mjs +1 -0
- package/dist/{manifest-yu2xiQqe.mjs → manifest-0Jpt_AQa.mjs} +1 -1
- package/dist/{manifest-DMJlcsTR.mjs → manifest-B3fZbSWR.mjs} +1 -1
- package/dist/{manifest-De-6Wf2R.mjs → manifest-B7NB2rh2.mjs} +1 -1
- package/dist/manifest-BDi4nbH1.mjs +1 -0
- package/dist/{manifest-ais9Afrw.mjs → manifest-BLDfkE7n.mjs} +1 -1
- package/dist/manifest-BcXbB4gf.mjs +1 -0
- package/dist/{manifest-DsVh7Y4U.mjs → manifest-Bdnc_vrc.mjs} +1 -1
- package/dist/manifest-BuYKgCnp.mjs +1 -0
- package/dist/{manifest-Cx2IVMUY.mjs → manifest-CBfNnGPV.mjs} +1 -1
- package/dist/{manifest-DC-SMF6b.mjs → manifest-CPS1Xv69.mjs} +1 -1
- package/dist/{manifest-CGq4NpqH2.mjs → manifest-CQH9FhwI.mjs} +1 -1
- package/dist/{manifest-CRIJq4Hs.mjs → manifest-CRryuZF4.mjs} +1 -1
- package/dist/manifest-CctIumog.mjs +1 -0
- package/dist/manifest-CvTe5ZGV2.mjs +1 -0
- package/dist/{manifest-H-EpAyZQ.mjs → manifest-D-5GH0DV.mjs} +1 -1
- package/dist/{manifest-CtPmHAdn.mjs → manifest-D3Ssf3IC.mjs} +1 -1
- package/dist/{manifest-BeP_zJGb2.mjs → manifest-D5ck3NvC.mjs} +1 -1
- package/dist/{manifest-CeQmtQOY.mjs → manifest-D9jUUJAu.mjs} +1 -1
- package/dist/{manifest-C7qV1z7F.mjs → manifest-DCx6w2XV.mjs} +1 -1
- package/dist/{manifest-CFn0359q2.mjs → manifest-DG19q-Ld.mjs} +1 -1
- package/dist/{manifest-CJMGt7Qy.mjs → manifest-DLMlD0Zc.mjs} +1 -1
- package/dist/{manifest-CDeUZGUZ.mjs → manifest-DYpn8w_h.mjs} +1 -1
- package/dist/manifest-DYzWI8Xs.mjs +1 -0
- package/dist/{manifest-DKUorv5M.mjs → manifest-D_obs5F4.mjs} +1 -1
- package/dist/{manifest-D610kxZr.mjs → manifest-DujQqEQR.mjs} +2 -2
- package/dist/manifest-DwL2ik8P.mjs +1 -0
- package/dist/manifest-ItF5P8A12.mjs +1 -0
- package/dist/{manifest-tmb54wmA.mjs → manifest-KZphqIyX.mjs} +1 -1
- package/dist/{manifest-BPuE6oH2.mjs → manifest-LG42zPLY2.mjs} +1 -1
- package/dist/{manifest-D44TaRJU.mjs → manifest-LLdI5m4T.mjs} +1 -1
- package/dist/{manifest-Dgh0uDW-.mjs → manifest-QYbQXJn0.mjs} +1 -1
- package/dist/{manifest-BFGxlDRh.mjs → manifest-RcpX_MyZ.mjs} +2 -2
- package/dist/{manifest-CDiCtaQT.mjs → manifest-YgVd8Sgz.mjs} +1 -1
- package/dist/{manifest-D16xPXro.mjs → manifest-Zy7Odg5J.mjs} +1 -1
- package/dist/manifest-ff1H7Pdp.mjs +1 -0
- package/dist/{manifest-C_hEIjSx.mjs → manifest-iuhF6pTL2.mjs} +1 -1
- package/dist/{manifest-DWUUWBz0.mjs → manifest-nXHmtMSp2.mjs} +1 -1
- package/dist/{manifest-C1nZkTkO.mjs → manifest-xWfu6iLo.mjs} +1 -1
- package/dist/{manifest-C0g67k6U.mjs → manifest-yC16OhL2.mjs} +1 -1
- package/dist/manifest-ztWJoXy4.mjs +1 -0
- package/dist/modules-BPBcSaM-.mjs +333 -0
- package/dist/{mojo-ipc-VGlv3Qyp.mjs → mojo-ipc-BhwsdVUW.mjs} +1 -1
- package/dist/native/scripts/linux/enum-windows.sh +12 -12
- package/dist/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/native-j8l473zn.mjs +961 -0
- package/dist/network-T0VRwNPd.mjs +7 -0
- package/dist/{outputPaths-BonGThuc.mjs → outputPaths-B4Ic4RZh.mjs} +2 -2
- package/dist/platform-CzaQtISh.mjs +93 -0
- package/dist/process-CWhsCWrf.mjs +2 -0
- package/dist/proxy-DZFlDsG3.mjs +2 -0
- package/dist/{registry-DUHIPE-v.mjs → registry-DH4sc1dt.mjs} +1 -1
- package/dist/renderer-pid-9tJnZ_9N.mjs +1 -0
- package/dist/{search-defaults-D2bY-rzH.mjs → search-defaults-lYBVn_3L.mjs} +1 -1
- package/dist/server/plugin-api.d.mts +19 -36
- package/dist/server/plugin-api.mjs +1 -1
- package/dist/{shared-state-board-Cyg-xh_k.mjs → shared-state-board-BSjXLUV1.mjs} +1 -1
- package/dist/{sourcemap-D6Q1UuAp.mjs → sourcemap-Dh3Ai_ur.mjs} +1 -1
- package/dist/streaming-BcJ0B6ao.mjs +1 -0
- package/dist/transform-DOxzeWPB.mjs +103 -0
- package/dist/wasm-CZ_HTfKR.mjs +174 -0
- package/dist/{webcrack-CsLLJIs9.mjs → webcrack-C1iYG_EX.mjs} +3 -3
- package/dist/{workflow-CYIXtrWD.mjs → workflow-BdwQmARn.mjs} +4 -4
- package/package.json +16 -15
- package/src/native/scripts/linux/enum-windows.sh +12 -12
- package/src/native/scripts/macos/enum-windows.applescript +22 -22
- package/dist/ConsoleMonitor-Dkqc0HNi.mjs +0 -490
- package/dist/DOMInspector-BYY_EJ0C.mjs +0 -95
- package/dist/DetailedDataManager-BniBJlVv.mjs +0 -1
- package/dist/ExtensionManager-erMpqcLk.mjs +0 -1
- package/dist/MCPServer.search.handlers.domain-DVbWL1bT.mjs +0 -1
- package/dist/MemoryController-BaqstM5w.mjs +0 -2
- package/dist/PageController-D9jVkH0i.mjs +0 -1
- package/dist/ProcessRegistry-Hf12LlR9.mjs +0 -1
- package/dist/ToolCatalog-D_IKl1Hu.mjs +0 -1
- package/dist/ToolProbe-xsfALmN3.mjs +0 -1
- package/dist/ToolRegistry-B0Zs-phN.mjs +0 -1
- package/dist/analysis-BuR-NgX8.mjs +0 -5
- package/dist/betterSqlite3-CGaxz4AX.mjs +0 -1
- package/dist/browser-C4Le3xqA.mjs +0 -11
- package/dist/collector-CKO8RPK8.mjs +0 -1
- package/dist/constants-Cp6hBrrx.mjs +0 -1
- package/dist/definitions-CdWEuIkI.mjs +0 -1
- package/dist/definitions-OvGsfxdt.mjs +0 -1
- package/dist/handlers-D3iev8g1.mjs +0 -1
- package/dist/handlers-De5u62Ga2.mjs +0 -1
- package/dist/handlers-S9Ws0IGy.mjs +0 -2
- package/dist/handlers.impl-CD2_kOcC.mjs +0 -1
- package/dist/maintenance-CutEO84j.mjs +0 -1
- package/dist/manifest-BXry5N09.mjs +0 -1
- package/dist/manifest-Cq0j7GZt.mjs +0 -1
- package/dist/manifest-DD3rtxvV.mjs +0 -1
- package/dist/manifest-Dm0o3i2U.mjs +0 -1
- package/dist/manifest-DtEFSRaq.mjs +0 -1
- package/dist/manifest-zrbrpKCC.mjs +0 -1
- package/dist/modules-p-PUNv9r.mjs +0 -332
- package/dist/network-BjZ1Y-GB.mjs +0 -7
- package/dist/platform-C446Lf97.mjs +0 -93
- package/dist/process-C9f2A5zk.mjs +0 -962
- package/dist/proxy-CvRepxgV.mjs +0 -1
- package/dist/streaming-CTX58tbb.mjs +0 -1
- package/dist/transform-Cv9P2vVD.mjs +0 -103
- package/dist/wasm-DaJa8J0V.mjs +0 -174
- /package/dist/{CacheAdapters-CdAxBmVW.mjs → CacheAdapters-CsNtQIR8.mjs} +0 -0
- /package/dist/{DarwinAPI-DC4HGGLl.mjs → DarwinAPI-ZfQdpLNI.mjs} +0 -0
- /package/dist/{EventBus-DgciURGg.mjs → EventBus-DL8iLA09.mjs} +0 -0
- /package/dist/{EvidenceGraphBridge-BIfgB7HP.mjs → EvidenceGraphBridge-BtbwXsLC.mjs} +0 -0
- /package/dist/{FingerprintManager-N7BZqjxP.mjs → FingerprintManager-DT0EAUEo.mjs} +0 -0
- /package/dist/{HookGeneratorBuilders.core.generators.storage-Bf1fbrNK.mjs → HookGeneratorBuilders.core.generators.storage-DzD6dIJd.mjs} +0 -0
- /package/dist/{InstrumentationSession-DxXs0sCp.mjs → InstrumentationSession-D_G1ZPyd.mjs} +0 -0
- /package/dist/{PrerequisiteError-Bl3dK8XA.mjs → PrerequisiteError-BjCQA-gK.mjs} +0 -0
- /package/dist/{ReverseEvidenceGraph-B931HeoW.mjs → ReverseEvidenceGraph-BhSYYdiI.mjs} +0 -0
- /package/dist/{StealthVerifier-Dhbj4B4P.mjs → StealthVerifier-BmcxfwSF.mjs} +0 -0
- /package/dist/{VersionDetector-DMoUWyNm.mjs → VersionDetector-CHT36Az0.mjs} +0 -0
- /package/dist/{Win32API-Bhi5xFBe.mjs → Win32API-eUCF57l_.mjs} +0 -0
- /package/dist/{authorization-schema-B40obG1A.mjs → authorization-schema-BOFwSXUN.mjs} +0 -0
- /package/dist/{bind-helpers-BlAOQrFQ.mjs → bind-helpers-m2U8glkF.mjs} +0 -0
- /package/dist/{capabilities-DbYCv-HF.mjs → capabilities-CyXuKUl1.mjs} +0 -0
- /package/dist/{concurrency-CcK46d0h.mjs → concurrency-DCr8WQ2M.mjs} +0 -0
- /package/dist/{evidence-graph-bridge-B0yhGPcs.mjs → evidence-graph-bridge-CV_UdYqj.mjs} +0 -0
- /package/dist/{flat-target-session-CO5g78k3.mjs → flat-target-session-DvcQX7J5.mjs} +0 -0
- /package/dist/{formatAddress-C7j2fDlM.mjs → formatAddress-vLA_hOJt.mjs} +0 -0
- /package/dist/{handlers-Dv_runVv.mjs → handlers-0yKLRIfo.mjs} +0 -0
- /package/dist/{matchesWildcardPattern-BGqLSmEs.mjs → matchesWildcardPattern-BAG6LvX5.mjs} +0 -0
- /package/dist/{parse-args-Cuk7-xUt.mjs → parse-args-Bw413PlW.mjs} +0 -0
- /package/dist/{playwright-cdp-fallback-BwVR-_T3.mjs → playwright-cdp-fallback-DqFdx9-s.mjs} +0 -0
- /package/dist/{ssrf-policy-T96MR3r6.mjs → ssrf-policy-CsIJGkpd.mjs} +0 -0
- /package/dist/{tool-builder-CI9914Tf.mjs → tool-builder-qif8M9-K.mjs} +0 -0
- /package/dist/{types-DtThH00r.mjs → types-D9EiE5o9.mjs} +0 -0
- /package/dist/{types-CuyefmGT.mjs → types-Fz69RzbZ.mjs} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{_t as e,bt as t,vt as n,xt as r,yt as i}from"./constants-BYj8Xek8.mjs";import{t as a}from"./ToolError-DWU_z7gp.mjs";import{t as o}from"./PrerequisiteError-BjCQA-gK.mjs";import{a as s,i as c,r as l,t as u}from"./parse-args-Bw413PlW.mjs";import{s as d}from"./PageController-Dfsm1_o7.mjs";import{c as f}from"./ssrf-policy-CsIJGkpd.mjs";import"./definitions-CQd7yCQH.mjs";function p(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}function m(e,t){let n={success:!1,error:h(e)};e instanceof a&&(n.code=e.code,e.toolName&&(n.toolName=e.toolName),e.details&&(n.details=e.details)),t&&(n.context=t);let r=e instanceof o;return{content:[{type:`text`,text:JSON.stringify(n,null,2)}],...r?{}:{isError:!0}}}function h(e){return e instanceof Error?e.message:String(e)}function g(e,t,n,r,i){let a=e[t],o=n;if(typeof a==`number`&&Number.isFinite(a))o=a;else if(typeof a==`string`){let e=Number(a);Number.isFinite(e)&&(o=e)}return o<r?r:o>i?i:Math.trunc(o)}function _(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=new Set([`__proto__`,`constructor`,`prototype`]),n=Object.create(null);for(let[r,i]of Object.entries(e))t.has(r)||(typeof i==`string`?n[r]=i:(typeof i==`number`||typeof i==`boolean`)&&(n[r]=String(i)));return n}function v(e){let t;try{t=new URL(e)}catch{return{error:`Invalid endpoint URL: ${e}`}}return t.protocol!==`http:`&&t.protocol!==`https:`?{error:`Unsupported endpoint protocol: ${t.protocol} — only http/https allowed`}:{parsedEndpoint:t}}async function y(e){let t=v(e);return`error`in t?t.error:await f(t.parsedEndpoint.toString())?`Blocked: endpoint "${e}" resolves to a private/reserved address`:null}async function b(e,t){let n=v(e);if(`error`in n)return n.error;if(!await f(n.parsedEndpoint.toString()))return null;if(typeof t==`string`&&t.length>0)try{if(new URL(t).origin===n.parsedEndpoint.origin)return null}catch{}return`Blocked: endpoint "${e}" resolves to a private/reserved address`}function x(e,t){return e.length<=t?{preview:e,truncated:!1,totalLength:e.length}:{preview:`${e.slice(0,t)}\n... (truncated)`,truncated:!0,totalLength:e.length}}function S(e,t){let n;if(typeof e==`string`)n=e;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}return x(n,t)}function ee(e){return e===`exact`||e===`contains`||e===`regex`?e:`contains`}function C(){return`script_rule_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function w(e){if(typeof e.isInterceptResolutionHandled!=`function`)return!1;try{return e.isInterceptResolutionHandled()}catch{return!1}}async function T(e){if(!w(e))try{await e.continue()}catch{}}function te(e,t){if(e.matchType===`exact`)return t===e.url;if(e.matchType===`contains`)return t.includes(e.url);try{return new RegExp(e.url).test(t)}catch{return!1}}function E(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r&&te(r,t))return r}return null}async function D(e,t){if(w(t))return;if(t.resourceType()!==`script`){await T(t);return}let n=E(e,t.url());if(!n){await T(t);return}n.hits+=1;try{await t.respond({status:200,contentType:`application/javascript; charset=utf-8`,headers:{"cache-control":`no-store`,"x-script-replaced-by":`script_replace_persist`},body:n.replacement})}catch{await T(t)}}async function ne(e,t,n){if(t.has(n))return;await n.setRequestInterception(!0);let r=t=>{D(e,t)},i=n;typeof i.prependListener==`function`?i.prependListener(`request`,r):i.on(`request`,r),t.add(n)}function O(e){let t=[`kind`,`name`];return e>0&&t.push(`ofType { ${O(e-1)} }`),t.join(`
|
|
2
2
|
`)}const k=`
|
|
3
3
|
query IntrospectionQuery {
|
|
4
4
|
__schema {
|
|
@@ -47,8 +47,8 @@ fragment InputValue on __InputValue {
|
|
|
47
47
|
fragment TypeRef on __Type {
|
|
48
48
|
${O(7)}
|
|
49
49
|
}
|
|
50
|
-
`.trim();var A=class{collector;constructor(e){this.collector=e}async handleCallGraphAnalyze(
|
|
51
|
-
`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>{let t=e.match(/at\s+([^(<\s]+)/);if(t?.[1])return t[1];let n=e.match(/^([^(<\s]+)@/);return n?.[1]?n[1]:``}).filter(e=>e.length>0):[];if(f.length>1){let t=Math.min(e,f.length-1);for(let e=0;e<t;e+=1)d(f[e+1],f[e]);l=!0}else f.length===1&&i&&f[0]!==i&&(d(f[0],i),l=!0);l&&(o+=1)},p=n.__aiHooks;if(p&&typeof p==`object`){for(let[e,t]of Object.entries(p))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}for(let e of[`__functionTraceRecords`,`__functionTracerRecords`,`__functionCalls`,`__callTrace`,`__traceCalls`]){let t=n[e];if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}let m=n.__functionTracer;if(m&&typeof m==`object`){let e=m.records;if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&f(t,`functionTracer.records`)}let h=Array.from(i.values()).toSorted((e,t)=>t.callCount-e.callCount),g=Array.from(r.values()).toSorted((e,t)=>t.count-e.count);return{nodes:h,edges:g,stats:{scannedRecords:a,acceptedRecords:o,nodeCount:h.length,edgeCount:g.length,maxDepth:e,filterPattern:t||null}}},{maxDepth:t,filterPattern:r}),o=a.nodes.length>n,c=a.edges.length>i;return p({success:!0,nodes:a.nodes.slice(0,n),edges:a.edges.slice(0,i),stats:{...a.stats,nodesReturned:Math.min(a.nodes.length,n),edgesReturned:Math.min(a.edges.length,i),nodesTruncated:o,edgesTruncated:c}})}catch(e){return m(e)}}},j=class{collector;scriptReplaceRules=[];interceptionInstalledPages=new WeakSet;constructor(e){this.collector=e}async handleScriptReplacePersist(e){try{let t=s(e,`url`)?.trim(),n=s(e,`replacement`),i=ee(e.matchType);if(!t)return m(`Missing required argument: url`);if(typeof n!=`string`||n.length===0)return m(`Missing required argument: replacement`);if(i===`regex`)try{RegExp(t)}catch(e){return m(`Invalid regex in url for matchType=regex`,{url:t,reason:h(e)})}let a=await this.collector.getActivePage(),o={id:C(),url:t,replacement:n,matchType:i,createdAt:Date.now(),hits:0};this.scriptReplaceRules.push(o),await ne(this.scriptReplaceRules,this.interceptionInstalledPages,a),await a.evaluateOnNewDocument(e=>{let t=window,n=`__scriptReplacePersistRules`,r=(Array.isArray(t[n])?t[n]:[]).filter(t=>t&&t.id!==e.id);r.push(e),t[n]=r},{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt});let c=x(n,r);return p({success:!0,message:`Script replacement rule registered and interception enabled`,rule:{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt},replacement:{length:n.length,preview:c.preview,truncated:c.truncated},activeRuleCount:this.scriptReplaceRules.length})}catch(e){return m(e)}}},re=class{collector;constructor(e){this.collector=e}async handleGraphqlIntrospect(e){try{let t=s(e,`endpoint`)?.trim();if(!t)return m(`Missing required argument: endpoint`);let n=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),r=await b(t,typeof e.url==`function`?e.url():null);return r?m(r):await this.introspectViaBrowser(e,t,n)}let r=await y(t);return r?m(r):await this.introspectViaNode(t,n)}catch(e){return m(e)}}async introspectViaNode(t,n){let r={"content-type":`application/json`,...n},i,a;try{let e=new AbortController,n=setTimeout(()=>e.abort(),1e4);try{i=await fetch(t,{method:`POST`,headers:r,body:JSON.stringify({query:k,operationName:`IntrospectionQuery`}),signal:e.signal}),a=await i.text()}finally{clearTimeout(n)}}catch(e){return p({success:!1,endpoint:t,status:0,statusText:`FETCH_ERROR`,error:e instanceof Error?e.message:String(e)})}let o={};i.headers.forEach((e,t)=>{o[t]=e});let s=null;try{s=JSON.parse(a)}catch{}if(a=``,!i.ok&&!s)return p({success:!1,endpoint:t,status:i.status,statusText:i.statusText,error:`Introspection request failed`});let c=s&&typeof s==`object`?s:null,l=c&&`data`in c?c.data:s,u=s!=null&&l!==void 0?S(l,e):{preview:``,truncated:!1,totalLength:0},d={success:i.ok,endpoint:t,status:i.status,statusText:i.statusText,schemaLength:u.totalLength,schemaPreview:u.preview,schemaTruncated:u.truncated,responseHeaders:o};return u.truncated||(d.schema=l),c&&Array.isArray(c.errors)&&(d.errors=c.errors),p(d)}async introspectViaBrowser(t,n,i){let a=await d(t,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,operationName:`IntrospectionQuery`}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o={};a.headers.forEach((e,t)=>{o[t]=e});let s=i.length,c=null;try{c=JSON.parse(i)}catch{}let l=c===null?i:``;return i=``,{ok:a.ok,status:a.status,statusText:a.statusText,responseHeaders:o,totalLength:s,preview:l,truncated:!1,json:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseHeaders:{},totalLength:0,preview:``,truncated:!1,json:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:n,headers:i,query:k,maxSchemaChars:e});if(!a.ok&&!a.json)return p({success:!1,endpoint:n,status:a.status,statusText:a.statusText,error:a.error??`Introspection request failed`,responsePreview:x(a.preview||``,r)});let o=a.json&&typeof a.json==`object`?a.json:null,s=o&&`data`in o?o.data:a.json,c=a.json!==null&&a.json!==void 0&&s!==void 0?S(s,e):{preview:a.preview??``,truncated:a.truncated??!1,totalLength:a.totalLength??0},l={success:a.ok,endpoint:n,status:a.status,statusText:a.statusText,schemaLength:c.totalLength,schemaPreview:c.preview,schemaTruncated:c.truncated,responseHeaders:a.responseHeaders??{}};return c.truncated||(l.schema=s),o&&Array.isArray(o.errors)&&(l.errors=o.errors),a.error&&(l.error=a.error),p(l)}};function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e,t,n){if(!t)return;let r=t.query;if(typeof r!=`string`||r.trim().length===0)return;let i=t.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;e.push({source:n.source,url:n.url,method:n.method,operationName:a,query:r,variables:t.variables??null,timestamp:n.timestamp,contentType:n.contentType})}function P(e){let t=e.trim();if(!t)return null;try{let e=JSON.parse(t);if(M(e))return e}catch{}if(t.includes(`query=`))try{let e=new URLSearchParams(t),n=e.get(`query`);if(n){let t=e.get(`operationName`),r=e.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:t,variables:i}}}catch{}return t.startsWith(`query `)||t.startsWith(`mutation `)||t.startsWith(`subscription `)?{query:t}:null}function F(e){return M(e.headers)?e.headers:M(e.requestHeaders)?e.requestHeaders:{}}function I(e){let t=F(e);for(let[e,n]of Object.entries(t))if(e.toLowerCase()===`content-type`)return typeof n==`string`?n.toLowerCase():String(n).toLowerCase();return``}function L(e){let t=[e.body,e.postData];return M(e.options)&&t.push(e.options.body),M(e.request)&&t.push(e.request.postData),t}function R(e,t){let n={scannedRecords:0,extracted:[]};if(!Array.isArray(e))return n;for(let r of e){if(!M(r))continue;n.scannedRecords+=1;let e=typeof r.url==`string`?r.url:``,i=typeof r.method==`string`?r.method:`POST`,a=typeof r.timestamp==`number`?r.timestamp:null,o=I(r);for(let s of L(r)){let r=null;M(s)?r=s:typeof s==`string`&&(r=P(s)),N(n.extracted,r,{source:t,url:e,method:i,timestamp:a,contentType:o})}o.includes(`application/graphql`)&&typeof r.body==`string`&&N(n.extracted,{query:r.body,variables:null,operationName:null},{source:t,url:e,method:i,timestamp:a,contentType:o})}return n}function z(e){let t=e.toSorted((e,t)=>(t.timestamp??0)-(e.timestamp??0)),n=[],r=new Set;for(let e of t){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;r.has(t)||(r.add(t),n.push(e))}return n}var B=class{deps;constructor(e){this.deps=`collector`in e?e:{collector:e}}async handleGraphqlExtractQueries(e){try{let n=g(e,`limit`,50,1,200),i=await d(await this.deps.collector.getActivePage(),e=>{let t=window,n=[],r=0,i=(e,t)=>{if(!e)return;let r=e.query;if(typeof r!=`string`||r.trim().length===0)return;let i=e.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;n.push({source:t.source,url:t.url,method:t.method,operationName:a,query:r,variables:e.variables??null,timestamp:t.timestamp,contentType:t.contentType})},a=e=>{if(!e)return null;try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}if(e.includes(`query=`))try{let t=new URLSearchParams(e),n=t.get(`query`);if(n){let e=t.get(`operationName`),r=t.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:e,variables:i}}}catch{}return e.startsWith(`query `)||e.startsWith(`mutation `)||e.startsWith(`subscription `)?{query:e}:null},o=(e,t)=>{r+=1;let n=typeof e.url==`string`?e.url:``,o=typeof e.method==`string`?e.method:`POST`,s=typeof e.timestamp==`number`?e.timestamp:null,c=(e.headers&&typeof e.headers==`object`&&!Array.isArray(e.headers)?e.headers:null)??(e.requestHeaders&&typeof e.requestHeaders==`object`&&!Array.isArray(e.requestHeaders)?e.requestHeaders:null)??{},l=``;for(let[e,t]of Object.entries(c))if(e.toLowerCase()===`content-type`){l=typeof t==`string`?t:String(t);break}l=l.toLowerCase();let u=[e.body,e.postData];e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&u.push(e.options.body);for(let e of u){let r=null;e&&typeof e==`object`&&!Array.isArray(e)?r=e:typeof e==`string`&&(r=a(e)),i(r,{source:t,url:n,method:o,timestamp:s,contentType:l})}l.includes(`application/graphql`)&&typeof e.body==`string`&&i({query:e.body,variables:null,operationName:null},{source:t,url:n,method:o,timestamp:s,contentType:l})},s=(e,t)=>{if(Array.isArray(e))for(let n of e)n&&typeof n==`object`&&o(n,t)},c=Array.isArray(t.__fetchRequests)?t.__fetchRequests:typeof t.__getFetchRequests==`function`?t.__getFetchRequests():void 0,l=Array.isArray(t.__xhrRequests)?t.__xhrRequests:typeof t.__getXHRRequests==`function`?t.__getXHRRequests():void 0;s(c,`window.__fetchRequests`),s(l,`window.__xhrRequests`),s(t.__networkRequests,`window.__networkRequests`);let u=t.__aiHooks;if(u&&typeof u==`object`){for(let[e,t]of Object.entries(u))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&o(n,`window.__aiHooks.${e}`)}n.sort((e,t)=>(t.timestamp??0)-(e.timestamp??0));let d=[],f=new Set;for(let e of n){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;f.has(t)||(f.add(t),d.push(e))}return{scannedRecords:r,totalExtracted:d.length,extracted:d.slice(0,e)}},n),a=i.scannedRecords,o=[...i.extracted];if(this.deps.consoleMonitor){let e=typeof this.deps.consoleMonitor.getFetchRequests==`function`?this.deps.consoleMonitor.getFetchRequests().catch(()=>[]):Promise.resolve([]),t=typeof this.deps.consoleMonitor.getXHRRequests==`function`?this.deps.consoleMonitor.getXHRRequests().catch(()=>[]):Promise.resolve([]),[n,r]=await Promise.all([e,t]),i=[];try{i=typeof this.deps.consoleMonitor.getNetworkRequests==`function`?this.deps.consoleMonitor.getNetworkRequests({limit:500}):[]}catch{i=[]}let s=[R(n,`consoleMonitor.fetchRequests`),R(r,`consoleMonitor.xhrRequests`),R(i,`consoleMonitor.networkRequests`)];for(let e of s)a+=e.scannedRecords,o.push(...e.extracted)}let s=z(o),c=Math.max(i.totalExtracted,s.length),l=s.slice(0,n).map((e,n)=>{let i=x(e.query,t),a=S(e.variables,r),o={index:n,source:e.source,url:e.url,method:e.method,operationName:e.operationName,contentType:e.contentType,timestamp:e.timestamp,queryLength:e.query.length,queryPreview:i.preview,queryTruncated:i.truncated};return i.truncated||(o.query=e.query),a.truncated?(o.variablesPreview=a.preview,o.variablesTruncated=!0):o.variables=e.variables,o});return p({success:!0,limit:n,stats:{scannedRecords:a,totalExtracted:c,returned:l.length},queries:l})}catch(e){return m(e)}}},V=class{collector;constructor(e){this.collector=e}async handleGraphqlReplay(e){try{let t=s(e,`endpoint`)?.trim(),n=s(e,`query`);if(!t)return m(`Missing required argument: endpoint`);if(typeof n!=`string`||n.trim().length===0)return m(`Missing required argument: query`);let r=c(e,`variables`)??{},i=s(e,`operationName`),a=i&&i.trim().length>0?i.trim():null,o=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),i=await b(t,typeof e.url==`function`?e.url():null);return i?m(i):await this.replayViaBrowser(e,t,n,r,a,o)}let l=await y(t);return l?m(l):await this.replayViaNode(t,n,r,a,o)}catch(e){return m(e)}}async replayViaNode(e,t,n,r,i){let a={"content-type":`application/json`,...i},o,s;try{let i=new AbortController,c=setTimeout(()=>i.abort(),1e4);try{o=await fetch(e,{method:`POST`,headers:a,body:JSON.stringify({query:t,variables:n,operationName:r}),signal:i.signal}),s=await o.text()}finally{clearTimeout(c)}}catch(t){return p({success:!1,endpoint:e,status:0,statusText:`FETCH_ERROR`,error:t instanceof Error?t.message:String(t),operationName:r})}let c={};o.headers.forEach((e,t)=>{c[t]=e});let l=null;try{l=JSON.parse(s)}catch{l=null}return s=``,p(H(l,e,r,o.ok,o.status,o.statusText,c))}async replayViaBrowser(t,n,r,i,a,o){let s=await d(t,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,variables:e.variables,operationName:e.operationName}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o=null;try{o=JSON.parse(i)}catch{o=null}let s=o===null?i:``;i=``;let c={};return a.headers.forEach((e,t)=>{c[t]=e}),{ok:a.ok,status:a.status,statusText:a.statusText,responseText:s,responseJson:o,responseHeaders:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseText:``,responseJson:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:n,query:r,variables:i,operationName:a,headers:o}),c={success:s.ok,endpoint:n,status:s.status,statusText:s.statusText,operationName:a,responseHeaders:s.responseHeaders??{}};if(s.responseJson!==null){let t=S(s.responseJson,e);c.responseLength=t.totalLength,c.responsePreview=t.preview,c.responseTruncated=t.truncated,t.truncated||(c.response=s.responseJson)}else if(s.responseText){let t=s.responseText;c.responseFormat=`text`,c.responseLength=t.length,c.responsePreview=t.length>e?t.slice(0,e):t,c.responseTruncated=t.length>e}return s.error&&(c.error=s.error),p(c)}};function H(t,n,r,i,a,o,s){let c={success:i,endpoint:n,status:a,statusText:o,operationName:r,responseHeaders:s};if(t!==null){let n=S(t,e);c.responseLength=n.totalLength,c.responsePreview=n.preview,c.responseTruncated=n.truncated,n.truncated||(c.response=t)}return c}const U=new Map;function W(e){let t=U.get(e);if(t)return t;let n=`
|
|
50
|
+
`.trim();var A=class{collector;constructor(e){this.collector=e}async handleCallGraphAnalyze(t){try{let r=g(t,`maxDepth`,5,1,20),i=s(t,`filterPattern`)?.trim()||``;if(i)try{RegExp(i)}catch(e){return m(`Invalid filterPattern regex`,{filterPattern:i,reason:e instanceof Error?e.message:String(e)})}let a=await d(await this.collector.getActivePage(),({maxDepth:e,filterPattern:t})=>{let n=window,r=new Map,i=new Map,a=0,o=0,s=t?new RegExp(t):null,c=e=>s?(s.lastIndex=0,s.test(e)):!0,l=(e,t)=>s?c(e)||c(t):!0,u=(e,t=1)=>{let n=i.get(e);if(n){n.callCount+=t;return}i.set(e,{id:e,name:e,callCount:t})},d=(e,t)=>{let n=typeof e==`string`&&e.trim()||``,i=typeof t==`string`&&t.trim()||``;if(!n||!i||n===i||!l(n,i))return;let a=`${n}__->__${i}`,o=r.get(a);o?o.count+=1:r.set(a,{source:n,target:i,count:1}),u(n,1),u(i,1)},f=(t,n)=>{a+=1;let r=t.callee??t.functionName??t.fn??t.name??t.method??t.target??n,i=typeof r==`string`&&r.trim()||n,s=t.caller??t.parent??t.from??``,c=typeof s==`string`&&s.trim()||``,l=!1;c&&i&&(d(c,i),l=!0);let u=t.stack??t.stackTrace??t.trace,f=typeof u==`string`&&u.trim().length>0?u.split(`
|
|
51
|
+
`).map(e=>e.trim()).filter(e=>e.length>0).map(e=>{let t=e.match(/at\s+([^(<\s]+)/);if(t?.[1])return t[1];let n=e.match(/^([^(<\s]+)@/);return n?.[1]?n[1]:``}).filter(e=>e.length>0):[];if(f.length>1){let t=Math.min(e,f.length-1);for(let e=0;e<t;e+=1)d(f[e+1],f[e]);l=!0}else f.length===1&&i&&f[0]!==i&&(d(f[0],i),l=!0);l&&(o+=1)},p=n.__aiHooks;if(p&&typeof p==`object`){for(let[e,t]of Object.entries(p))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}for(let e of[`__functionTraceRecords`,`__functionTracerRecords`,`__functionCalls`,`__callTrace`,`__traceCalls`]){let t=n[e];if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&f(n,e)}let m=n.__functionTracer;if(m&&typeof m==`object`){let e=m.records;if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&f(t,`functionTracer.records`)}let h=Array.from(i.values()).toSorted((e,t)=>t.callCount-e.callCount),g=Array.from(r.values()).toSorted((e,t)=>t.count-e.count);return{nodes:h,edges:g,stats:{scannedRecords:a,acceptedRecords:o,nodeCount:h.length,edgeCount:g.length,maxDepth:e,filterPattern:t||null}}},{maxDepth:r,filterPattern:i}),o=a.nodes.length>n,c=a.edges.length>e;return p({success:!0,nodes:a.nodes.slice(0,n),edges:a.edges.slice(0,e),stats:{...a.stats,nodesReturned:Math.min(a.nodes.length,n),edgesReturned:Math.min(a.edges.length,e),nodesTruncated:o,edgesTruncated:c}})}catch(e){return m(e)}}},j=class{collector;scriptReplaceRules=[];interceptionInstalledPages=new WeakSet;constructor(e){this.collector=e}async handleScriptReplacePersist(e){try{let t=s(e,`url`)?.trim(),n=s(e,`replacement`),r=ee(e.matchType);if(!t)return m(`Missing required argument: url`);if(typeof n!=`string`||n.length===0)return m(`Missing required argument: replacement`);if(r===`regex`)try{RegExp(t)}catch(e){return m(`Invalid regex in url for matchType=regex`,{url:t,reason:h(e)})}let a=await this.collector.getActivePage(),o={id:C(),url:t,replacement:n,matchType:r,createdAt:Date.now(),hits:0};this.scriptReplaceRules.push(o),await ne(this.scriptReplaceRules,this.interceptionInstalledPages,a),await a.evaluateOnNewDocument(e=>{let t=window,n=`__scriptReplacePersistRules`,r=(Array.isArray(t[n])?t[n]:[]).filter(t=>t&&t.id!==e.id);r.push(e),t[n]=r},{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt});let c=x(n,i);return p({success:!0,message:`Script replacement rule registered and interception enabled`,rule:{id:o.id,url:o.url,matchType:o.matchType,createdAt:o.createdAt},replacement:{length:n.length,preview:c.preview,truncated:c.truncated},activeRuleCount:this.scriptReplaceRules.length})}catch(e){return m(e)}}},re=class{collector;constructor(e){this.collector=e}async handleGraphqlIntrospect(e){try{let t=s(e,`endpoint`)?.trim();if(!t)return m(`Missing required argument: endpoint`);let n=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),r=await b(t,typeof e.url==`function`?e.url():null);return r?m(r):await this.introspectViaBrowser(e,t,n)}let r=await y(t);return r?m(r):await this.introspectViaNode(t,n)}catch(e){return m(e)}}async introspectViaNode(e,t){let n={"content-type":`application/json`,...t},i,a;try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e4);try{i=await fetch(e,{method:`POST`,headers:n,body:JSON.stringify({query:k,operationName:`IntrospectionQuery`}),signal:t.signal}),a=await i.text()}finally{clearTimeout(r)}}catch(t){return p({success:!1,endpoint:e,status:0,statusText:`FETCH_ERROR`,error:t instanceof Error?t.message:String(t)})}let o={};i.headers.forEach((e,t)=>{o[t]=e});let s=null;try{s=JSON.parse(a)}catch{}if(a=``,!i.ok&&!s)return p({success:!1,endpoint:e,status:i.status,statusText:i.statusText,error:`Introspection request failed`});let c=s&&typeof s==`object`?s:null,l=c&&`data`in c?c.data:s,u=s!=null&&l!==void 0?S(l,r):{preview:``,truncated:!1,totalLength:0},d={success:i.ok,endpoint:e,status:i.status,statusText:i.statusText,schemaLength:u.totalLength,schemaPreview:u.preview,schemaTruncated:u.truncated,responseHeaders:o};return u.truncated||(d.schema=l),c&&Array.isArray(c.errors)&&(d.errors=c.errors),p(d)}async introspectViaBrowser(e,t,n){let a=await d(e,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,operationName:`IntrospectionQuery`}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o={};a.headers.forEach((e,t)=>{o[t]=e});let s=i.length,c=null;try{c=JSON.parse(i)}catch{}let l=c===null?i:``;return i=``,{ok:a.ok,status:a.status,statusText:a.statusText,responseHeaders:o,totalLength:s,preview:l,truncated:!1,json:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseHeaders:{},totalLength:0,preview:``,truncated:!1,json:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:t,headers:n,query:k,maxSchemaChars:r});if(!a.ok&&!a.json)return p({success:!1,endpoint:t,status:a.status,statusText:a.statusText,error:a.error??`Introspection request failed`,responsePreview:x(a.preview||``,i)});let o=a.json&&typeof a.json==`object`?a.json:null,s=o&&`data`in o?o.data:a.json,c=a.json!==null&&a.json!==void 0&&s!==void 0?S(s,r):{preview:a.preview??``,truncated:a.truncated??!1,totalLength:a.totalLength??0},l={success:a.ok,endpoint:t,status:a.status,statusText:a.statusText,schemaLength:c.totalLength,schemaPreview:c.preview,schemaTruncated:c.truncated,responseHeaders:a.responseHeaders??{}};return c.truncated||(l.schema=s),o&&Array.isArray(o.errors)&&(l.errors=o.errors),a.error&&(l.error=a.error),p(l)}};function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N(e,t,n){if(!t)return;let r=t.query;if(typeof r!=`string`||r.trim().length===0)return;let i=t.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;e.push({source:n.source,url:n.url,method:n.method,operationName:a,query:r,variables:t.variables??null,timestamp:n.timestamp,contentType:n.contentType})}function P(e){let t=e.trim();if(!t)return null;try{let e=JSON.parse(t);if(M(e))return e}catch{}if(t.includes(`query=`))try{let e=new URLSearchParams(t),n=e.get(`query`);if(n){let t=e.get(`operationName`),r=e.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:t,variables:i}}}catch{}return t.startsWith(`query `)||t.startsWith(`mutation `)||t.startsWith(`subscription `)?{query:t}:null}function F(e){return M(e.headers)?e.headers:M(e.requestHeaders)?e.requestHeaders:{}}function I(e){let t=F(e);for(let[e,n]of Object.entries(t))if(e.toLowerCase()===`content-type`)return typeof n==`string`?n.toLowerCase():String(n).toLowerCase();return``}function L(e){let t=[e.body,e.postData];return M(e.options)&&t.push(e.options.body),M(e.request)&&t.push(e.request.postData),t}function R(e,t){let n={scannedRecords:0,extracted:[]};if(!Array.isArray(e))return n;for(let r of e){if(!M(r))continue;n.scannedRecords+=1;let e=typeof r.url==`string`?r.url:``,i=typeof r.method==`string`?r.method:`POST`,a=typeof r.timestamp==`number`?r.timestamp:null,o=I(r);for(let s of L(r)){let r=null;M(s)?r=s:typeof s==`string`&&(r=P(s)),N(n.extracted,r,{source:t,url:e,method:i,timestamp:a,contentType:o})}o.includes(`application/graphql`)&&typeof r.body==`string`&&N(n.extracted,{query:r.body,variables:null,operationName:null},{source:t,url:e,method:i,timestamp:a,contentType:o})}return n}function z(e){let t=e.toSorted((e,t)=>(t.timestamp??0)-(e.timestamp??0)),n=[],r=new Set;for(let e of t){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;r.has(t)||(r.add(t),n.push(e))}return n}var B=class{deps;constructor(e){this.deps=`collector`in e?e:{collector:e}}async handleGraphqlExtractQueries(e){try{let n=g(e,`limit`,50,1,200),r=await d(await this.deps.collector.getActivePage(),e=>{let t=window,n=[],r=0,i=(e,t)=>{if(!e)return;let r=e.query;if(typeof r!=`string`||r.trim().length===0)return;let i=e.operationName,a=typeof i==`string`&&i.trim().length>0?i:r.match(/^\s*(query|mutation|subscription)\s+([A-Za-z0-9_]+)/)?.[2]??null;n.push({source:t.source,url:t.url,method:t.method,operationName:a,query:r,variables:e.variables??null,timestamp:t.timestamp,contentType:t.contentType})},a=e=>{if(!e)return null;try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}if(e.includes(`query=`))try{let t=new URLSearchParams(e),n=t.get(`query`);if(n){let e=t.get(`operationName`),r=t.get(`variables`),i=null;if(r)try{i=JSON.parse(r)}catch{i=r}return{query:n,operationName:e,variables:i}}}catch{}return e.startsWith(`query `)||e.startsWith(`mutation `)||e.startsWith(`subscription `)?{query:e}:null},o=(e,t)=>{r+=1;let n=typeof e.url==`string`?e.url:``,o=typeof e.method==`string`?e.method:`POST`,s=typeof e.timestamp==`number`?e.timestamp:null,c=(e.headers&&typeof e.headers==`object`&&!Array.isArray(e.headers)?e.headers:null)??(e.requestHeaders&&typeof e.requestHeaders==`object`&&!Array.isArray(e.requestHeaders)?e.requestHeaders:null)??{},l=``;for(let[e,t]of Object.entries(c))if(e.toLowerCase()===`content-type`){l=typeof t==`string`?t:String(t);break}l=l.toLowerCase();let u=[e.body,e.postData];e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&u.push(e.options.body);for(let e of u){let r=null;e&&typeof e==`object`&&!Array.isArray(e)?r=e:typeof e==`string`&&(r=a(e)),i(r,{source:t,url:n,method:o,timestamp:s,contentType:l})}l.includes(`application/graphql`)&&typeof e.body==`string`&&i({query:e.body,variables:null,operationName:null},{source:t,url:n,method:o,timestamp:s,contentType:l})},s=(e,t)=>{if(Array.isArray(e))for(let n of e)n&&typeof n==`object`&&o(n,t)},c=Array.isArray(t.__fetchRequests)?t.__fetchRequests:typeof t.__getFetchRequests==`function`?t.__getFetchRequests():void 0,l=Array.isArray(t.__xhrRequests)?t.__xhrRequests:typeof t.__getXHRRequests==`function`?t.__getXHRRequests():void 0;s(c,`window.__fetchRequests`),s(l,`window.__xhrRequests`),s(t.__networkRequests,`window.__networkRequests`);let u=t.__aiHooks;if(u&&typeof u==`object`){for(let[e,t]of Object.entries(u))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&o(n,`window.__aiHooks.${e}`)}n.sort((e,t)=>(t.timestamp??0)-(e.timestamp??0));let d=[],f=new Set;for(let e of n){let t=`${e.url}|${e.operationName??``}|${e.query}|${JSON.stringify(e.variables)}`;f.has(t)||(f.add(t),d.push(e))}return{scannedRecords:r,totalExtracted:d.length,extracted:d.slice(0,e)}},n),a=r.scannedRecords,o=[...r.extracted];if(this.deps.consoleMonitor){let e=typeof this.deps.consoleMonitor.getFetchRequests==`function`?this.deps.consoleMonitor.getFetchRequests().catch(()=>[]):Promise.resolve([]),t=typeof this.deps.consoleMonitor.getXHRRequests==`function`?this.deps.consoleMonitor.getXHRRequests().catch(()=>[]):Promise.resolve([]),[n,r]=await Promise.all([e,t]),i=[];try{i=typeof this.deps.consoleMonitor.getNetworkRequests==`function`?this.deps.consoleMonitor.getNetworkRequests({limit:500}):[]}catch{i=[]}let s=[R(n,`consoleMonitor.fetchRequests`),R(r,`consoleMonitor.xhrRequests`),R(i,`consoleMonitor.networkRequests`)];for(let e of s)a+=e.scannedRecords,o.push(...e.extracted)}let s=z(o),c=Math.max(r.totalExtracted,s.length),l=s.slice(0,n).map((e,n)=>{let r=x(e.query,t),a=S(e.variables,i),o={index:n,source:e.source,url:e.url,method:e.method,operationName:e.operationName,contentType:e.contentType,timestamp:e.timestamp,queryLength:e.query.length,queryPreview:r.preview,queryTruncated:r.truncated};return r.truncated||(o.query=e.query),a.truncated?(o.variablesPreview=a.preview,o.variablesTruncated=!0):o.variables=e.variables,o});return p({success:!0,limit:n,stats:{scannedRecords:a,totalExtracted:c,returned:l.length},queries:l})}catch(e){return m(e)}}},V=class{collector;constructor(e){this.collector=e}async handleGraphqlReplay(e){try{let t=s(e,`endpoint`)?.trim(),n=s(e,`query`);if(!t)return m(`Missing required argument: endpoint`);if(typeof n!=`string`||n.trim().length===0)return m(`Missing required argument: query`);let r=c(e,`variables`)??{},i=s(e,`operationName`),a=i&&i.trim().length>0?i.trim():null,o=_(e.headers);if(u(e,`useBrowser`,!0)){let e=await this.collector.getActivePage(),i=await b(t,typeof e.url==`function`?e.url():null);return i?m(i):await this.replayViaBrowser(e,t,n,r,a,o)}let l=await y(t);return l?m(l):await this.replayViaNode(t,n,r,a,o)}catch(e){return m(e)}}async replayViaNode(e,t,n,r,i){let a={"content-type":`application/json`,...i},o,s;try{let i=new AbortController,c=setTimeout(()=>i.abort(),1e4);try{o=await fetch(e,{method:`POST`,headers:a,body:JSON.stringify({query:t,variables:n,operationName:r}),signal:i.signal}),s=await o.text()}finally{clearTimeout(c)}}catch(t){return p({success:!1,endpoint:e,status:0,statusText:`FETCH_ERROR`,error:t instanceof Error?t.message:String(t),operationName:r})}let c={};o.headers.forEach((e,t)=>{c[t]=e});let l=null;try{l=JSON.parse(s)}catch{l=null}return s=``,p(H(l,e,r,o.ok,o.status,o.statusText,c))}async replayViaBrowser(e,t,n,i,a,o){let s=await d(e,async e=>{let t={"content-type":`application/json`,...e.headers};try{let n=new AbortController,r=setTimeout(()=>n.abort(),1e4),i,a;try{a=await fetch(e.endpoint,{method:`POST`,headers:t,body:JSON.stringify({query:e.query,variables:e.variables,operationName:e.operationName}),signal:n.signal}),i=await a.text()}finally{clearTimeout(r)}let o=null;try{o=JSON.parse(i)}catch{o=null}let s=o===null?i:``;i=``;let c={};return a.headers.forEach((e,t)=>{c[t]=e}),{ok:a.ok,status:a.status,statusText:a.statusText,responseText:s,responseJson:o,responseHeaders:c}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,responseText:``,responseJson:null,error:e instanceof Error?e.message:String(e)}}},{endpoint:t,query:n,variables:i,operationName:a,headers:o}),c={success:s.ok,endpoint:t,status:s.status,statusText:s.statusText,operationName:a,responseHeaders:s.responseHeaders??{}};if(s.responseJson!==null){let e=S(s.responseJson,r);c.responseLength=e.totalLength,c.responsePreview=e.preview,c.responseTruncated=e.truncated,e.truncated||(c.response=s.responseJson)}else if(s.responseText){let e=s.responseText;c.responseFormat=`text`,c.responseLength=e.length,c.responsePreview=e.length>r?e.slice(0,r):e,c.responseTruncated=e.length>r}return s.error&&(c.error=s.error),p(c)}};function H(e,t,n,i,a,o,s){let c={success:i,endpoint:t,status:a,statusText:o,operationName:n,responseHeaders:s};if(e!==null){let t=S(e,r);c.responseLength=t.totalLength,c.responsePreview=t.preview,c.responseTruncated=t.truncated,t.truncated||(c.response=e)}return c}const U=new Map;function W(e){let t=U.get(e);if(t)return t;let n=`
|
|
52
52
|
query EnumSchemaTypeProbe($typeName: String!) {
|
|
53
53
|
__type(name: $typeName) {
|
|
54
54
|
fields(includeDeprecated: true) {
|
|
@@ -59,4 +59,4 @@ query EnumSchemaTypeProbe($typeName: String!) {
|
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
|
-
`.trim();return U.set(e,n),n}function G(e){let t=e??null;for(;t;){if(typeof t.name==`string`&&t.name.length>0)return{kind:typeof t.kind==`string`?t.kind:null,name:t.name};t=t.ofType??null}return{kind:null,name:null}}function K(e){return e===`OBJECT`||e===`INTERFACE`}function q(e){return e&&typeof e.data==`object`&&e.data!==null&&`__type`in e.data?e.data.__type:null}function J(e){let t=q(e);return Array.isArray(t?.fields)?t.fields.filter(e=>typeof e==`object`&&!!e&&typeof e.name==`string`):[]}function Y(e){let t=e??null,n=0;for(;t;){if(n+=1,typeof t.name==`string`&&t.name.length>0)return null;if(!t.ofType)return t.kind===`LIST`||t.kind===`NON_NULL`?n:null;t=t.ofType??null}return null}function ie(e){let t=null;for(let n of e){let e=Y(n.type);e!==null&&(t=Math.max(t??0,e))}return t}function ae(e){let t=[],n=e??null;for(;n;)t.push(`${n.kind??``}:${n.name??``}`),n=n.ofType??null;return t.join(`>`)}function oe(e){return e.map(e=>`${e.name??``}=${ae(e.type)}`).join(`|`)}async function se(e,t,n){let r=null,i=null,a=0;for(;;){let o=await X(e,t,{query:W(a),variables:{typeName:n}});if(!q(o.record))return r;let s=J(o.record);r=s;let c=ie(s);if(c===null)return r;let l=oe(s);if(c<=a||l===i)return r;i=l,a=c}}async function X(e,t,n){let r={"content-type":`application/json`,...t};try{let t=new AbortController,i=setTimeout(()=>t.abort(),1e4);try{let i=await fetch(e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:t.signal}),a=await i.text(),o=null;try{o=JSON.parse(a)}catch{o=null}let s=o&&typeof o==`object`?o:null,c=Array.isArray(s?.errors)?s.errors:[];return{ok:i.ok||c.length>0,status:i.status,statusText:i.statusText,record:s,errors:c}}finally{clearTimeout(i)}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,record:null,errors:[],error:e instanceof Error?e.message:String(e)}}}async function ce(e,t,n,r){let i=[{typeName:n,depth:0}],a=new Map,o=new Set;for(;i.length>0;){let n=i.shift();if(o.has(n.typeName))continue;o.add(n.typeName);let s=await se(e,t,n.typeName);if(!s)return a.size>0?a:null;if(a.set(n.typeName,s.map(e=>e.name?.trim()??``).filter(e=>e.length>0)),!(n.depth+1>=r))for(let e of s){let t=G(e.type);!t.name||!K(t.kind)||o.has(t.name)||i.push({typeName:t.name,depth:n.depth+1})}}return a}const le=/Cannot query field\s+"[^"]+"\s+on type\s+"([^"]+)".*?Did you mean\s+(.+?)\?/i,ue=/"([^"]+)"/g,Z=`__jshook_probe__`;function de(e){let t=le.exec(e);if(!t)return null;let[,n,r]=t;if(!n||!r)return null;let i=Array.from(r.matchAll(ue),e=>e[1]??``).filter(e=>e.length>0);return i.length>0?{typeName:n,suggestions:i}:null}function Q(e){return e.length===0?`query EnumSchemaProbe { ${Z} }`:`query EnumSchemaProbe { ${e.join(` { `)} { ${Z} }${`}`.repeat(e.length)} }`}function $(
|
|
62
|
+
`.trim();return U.set(e,n),n}function G(e){let t=e??null;for(;t;){if(typeof t.name==`string`&&t.name.length>0)return{kind:typeof t.kind==`string`?t.kind:null,name:t.name};t=t.ofType??null}return{kind:null,name:null}}function K(e){return e===`OBJECT`||e===`INTERFACE`}function q(e){return e&&typeof e.data==`object`&&e.data!==null&&`__type`in e.data?e.data.__type:null}function J(e){let t=q(e);return Array.isArray(t?.fields)?t.fields.filter(e=>typeof e==`object`&&!!e&&typeof e.name==`string`):[]}function Y(e){let t=e??null,n=0;for(;t;){if(n+=1,typeof t.name==`string`&&t.name.length>0)return null;if(!t.ofType)return t.kind===`LIST`||t.kind===`NON_NULL`?n:null;t=t.ofType??null}return null}function ie(e){let t=null;for(let n of e){let e=Y(n.type);e!==null&&(t=Math.max(t??0,e))}return t}function ae(e){let t=[],n=e??null;for(;n;)t.push(`${n.kind??``}:${n.name??``}`),n=n.ofType??null;return t.join(`>`)}function oe(e){return e.map(e=>`${e.name??``}=${ae(e.type)}`).join(`|`)}async function se(e,t,n){let r=null,i=null,a=0;for(;;){let o=await X(e,t,{query:W(a),variables:{typeName:n}});if(!q(o.record))return r;let s=J(o.record);r=s;let c=ie(s);if(c===null)return r;let l=oe(s);if(c<=a||l===i)return r;i=l,a=c}}async function X(e,t,n){let r={"content-type":`application/json`,...t};try{let t=new AbortController,i=setTimeout(()=>t.abort(),1e4);try{let i=await fetch(e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:t.signal}),a=await i.text(),o=null;try{o=JSON.parse(a)}catch{o=null}let s=o&&typeof o==`object`?o:null,c=Array.isArray(s?.errors)?s.errors:[];return{ok:i.ok||c.length>0,status:i.status,statusText:i.statusText,record:s,errors:c}}finally{clearTimeout(i)}}catch(e){return{ok:!1,status:0,statusText:`FETCH_ERROR`,record:null,errors:[],error:e instanceof Error?e.message:String(e)}}}async function ce(e,t,n,r){let i=[{typeName:n,depth:0}],a=new Map,o=new Set;for(;i.length>0;){let n=i.shift();if(o.has(n.typeName))continue;o.add(n.typeName);let s=await se(e,t,n.typeName);if(!s)return a.size>0?a:null;if(a.set(n.typeName,s.map(e=>e.name?.trim()??``).filter(e=>e.length>0)),!(n.depth+1>=r))for(let e of s){let t=G(e.type);!t.name||!K(t.kind)||o.has(t.name)||i.push({typeName:t.name,depth:n.depth+1})}}return a}const le=/Cannot query field\s+"[^"]+"\s+on type\s+"([^"]+)".*?Did you mean\s+(.+?)\?/i,ue=/"([^"]+)"/g,Z=`__jshook_probe__`;function de(e){let t=le.exec(e);if(!t)return null;let[,n,r]=t;if(!n||!r)return null;let i=Array.from(r.matchAll(ue),e=>e[1]??``).filter(e=>e.length>0);return i.length>0?{typeName:n,suggestions:i}:null}function Q(e){return e.length===0?`query EnumSchemaProbe { ${Z} }`:`query EnumSchemaProbe { ${e.join(` { `)} { ${Z} }${`}`.repeat(e.length)} }`}function $(e){let t=e.discovered.get(e.parentType)??e.discovered.get(e.typeName)??[],n=JSON.stringify({rootType:e.typeName,parentType:e.parentType,fields:t},null,2);return p({success:!0,endpoint:e.endpoint,typeName:e.typeName,parentType:e.parentType,maxDepth:e.maxDepth,concurrency:e.concurrency,fields:t,discoveredTypes:Object.fromEntries(Array.from(e.discovered.entries()).filter(([e])=>!e.includes(`.`))),responsePreview:n.length>r?`${n.slice(0,r)}\n... (truncated)`:n})}var fe=class{async handleGraphqlEnumSchema(e){try{let t=s(e,`endpoint`)?.trim();if(!t)return m(`Missing required argument: endpoint`);let n=await y(t);if(n)return m(n);let r=_(e.headers),i=s(e,`typeName`,`Query`)?.trim()||`Query`,a=s(e,`parentType`,i)?.trim()||i,o=l(e,`maxDepth`,1)??1,c=Math.min(Math.max(Math.trunc(o),1),6),u=l(e,`concurrency`,3)??3,d=Math.min(Math.max(Math.trunc(u),1),10),f=await X(t,r,{query:Q([])});if(!f.ok)return p({success:!1,endpoint:t,typeName:i,parentType:a,status:f.status,statusText:f.statusText,error:f.error??`Schema enumeration request failed`});let h=this.extractSuggestions(f.errors);if(!h)return $({endpoint:t,typeName:i,parentType:a,maxDepth:c,concurrency:d,discovered:await ce(t,r,a,c)??new Map([[a,[]]])});let g=[],v=new Map;if(v.set(h.typeName,h.suggestions),c>1)for(let e of h.suggestions){let t=[e],n=t.join(`.`);v.has(n)||(v.set(n,[]),g.push({path:t,depth:1,typeName:e}))}for(;g.length>0;){let e=g.shift(),n=await X(t,r,{query:Q(e.path)});if(!n.ok)return p({success:!1,endpoint:t,typeName:i,parentType:a,status:n.status,statusText:n.statusText,error:n.error??`Schema enumeration request failed`});let o=this.extractSuggestions(n.errors);if(!o){v.set(e.typeName,[]);continue}if(v.set(o.typeName,o.suggestions),!(e.depth+1>=c))for(let t of o.suggestions){let n=[...e.path,t],r=n.join(`.`);v.has(r)||(v.set(r,[]),g.push({path:n,depth:e.depth+1,typeName:t}))}}return $({endpoint:t,typeName:i,parentType:a,maxDepth:c,concurrency:d,discovered:v})}catch(e){return m(e)}}extractSuggestions(e){for(let t of e){if(typeof t.message!=`string`)continue;let e=de(t.message);if(e)return e}return null}};function pe(e){return`collector`in e?e:{collector:e}}var me=class{callGraph;scriptReplace;introspection;extract;replay;schemaEnum;constructor(e){let t=pe(e);this.callGraph=new A(t.collector),this.scriptReplace=new j(t.collector),this.introspection=new re(t.collector),this.extract=new B(t),this.replay=new V(t.collector),this.schemaEnum=new fe}async handleCallGraphAnalyze(e){return this.callGraph.handleCallGraphAnalyze(e)}async handleScriptReplacePersist(e){return this.scriptReplace.handleScriptReplacePersist(e)}async handleGraphqlIntrospect(e){return this.introspection.handleGraphqlIntrospect(e)}async handleGraphqlExtractQueries(e){return this.extract.handleGraphqlExtractQueries(e)}async handleGraphqlReplay(e){return this.replay.handleGraphqlReplay(e)}async handleGraphqlEnumSchema(e){return this.schemaEnum.handleGraphqlEnumSchema(e)}};export{me as GraphQLToolHandlers};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{a as t,o as n,t as r}from"./parse-args-Cuk7-xUt.mjs";function i(e){return typeof e!=`object`||!e||!(`evaluate`in e)?!1:typeof e.evaluate==`function`}function a(e){return typeof e!=`object`||!e||!(`getExtension`in e)||!(`getParameter`in e)||!(`RENDERER`in e)||!(`VERSION`in e)?!1:typeof e.getExtension==`function`&&typeof e.getParameter==`function`}function o(e){let t=(e??``).toLowerCase();return t.includes(`vulkan`)?`vulkan`:t.includes(`metal`)?`metal`:t.includes(`d3d`)||t.includes(`direct3d`)?`direct3d`:t.includes(`angle`)||t.includes(`opengl`)||t.includes(`mesa`)||t.includes(`gl`)?`opengl`:t.includes(`swiftshader`)||t.includes(`software`)||t.includes(`cpu`)?`cpu`:t.length>0?`gpu`:`cpu`}function s(e){let t=0;for(let n of e)t+=1,t+=s(n.children);return t}function c(e){let t=e.getAttribute(`aria-label`);if(t)return t;if(e.id)return e.id;let n=typeof e.className==`string`?e.className.trim():``;return n.length>0?n:e.tagName.toLowerCase()}function l(e){if(typeof e.getBoundingClientRect!=`function`)return;let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function u(e){if(!(e instanceof HTMLElement)||typeof window>`u`)return;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`}function d(e,t){let n=Array.from(e.children).slice(0,12).map((e,n)=>d(e,`${t}-${n}`));return{id:e.id||t,type:e.tagName.toLowerCase(),label:c(e),children:n,visible:u(e),bounds:l(e)}}function f(){let e=[{id:`mock-root`,type:`canvas`,label:`mock-skia-surface`,visible:!0,bounds:{x:0,y:0,width:640,height:480},children:[{id:`mock-layer`,type:`layer`,label:`mock-layer`,visible:!0,bounds:{x:16,y:16,width:320,height:160},children:[]}]}];return{rootNodes:e,totalNodes:s(e),extractedAt:new Date().toISOString()}}function p(e){let t=`software`,n=`Raster`;return e.backend===`vulkan`?(t=`vulkan`,n=`Vulkan`):e.backend===`metal`?(t=`metal`,n=`Metal`):(e.backend===`opengl`||e.backend===`direct3d`||e.backend===`gpu`)&&(t=`gl`,n=`OpenGL`),{isSkiaBacked:e.backend!==`cpu`,version:e.version??null,gpuBackend:t,shaderPipeline:n,rendererStrings:e.gpu?[e.gpu]:[],features:e.backend===`cpu`?[]:[`backend:${e.backend}`],confidence:e.backend===`cpu`?.2:.8,evidence:e.gpu?[`Renderer string: ${e.gpu}`]:[`No renderer information available`]}}function m(e,t){return e.x>=t.x&&e.y>=t.y&&e.x+e.width<=t.x+t.width&&e.y+e.height<=t.y+t.height}function h(e){let t=(e??``).toLowerCase();return t.includes(`rrect`)||t.includes(`round`)?`drawRRect`:t.includes(`rect`)?`drawRect`:t.includes(`text`)?`drawText`:t.includes(`image`)||t.includes(`sprite`)?`drawImage`:t.includes(`path`)?`drawPath`:t.includes(`circle`)||t.includes(`arc`)?`drawCircle`:t.includes(`line`)?`drawLine`:`unknown`}function g(e){let t=e.layers.map((e,t)=>({id:e.id??`layer-${t}`,name:e.name??`layer-${t}`,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:e.transform??[1,0,0,0,1,0,0,0,1],opacity:e.opacity??1,visible:e.visible??!0,children:[],customData:e.customData})),n=t[0]??null;if(n)for(let e=1;e<t.length;e+=1){let r=t[e];r&&m(r.bounds,n.bounds)&&n.children.push(r)}let r=e.drawCommands.map(e=>({type:h(e.type),bounds:e.bounds??{x:0,y:0,width:0,height:0},paintInfo:e.paintInfo??{},layerId:e.layerId}));return{rootLayer:n,layers:t,drawCommands:r,totalLayers:t.length,totalDrawCommands:r.length,canvas:{id:e.canvas.id,width:e.canvas.width??0,height:e.canvas.height??0,dpr:e.canvas.dpr??1,contextType:e.canvas.contextType??`unknown`}}}function _(e){return{id:e.id,name:e.label,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:[1,0,0,0,1,0,0,0,1],opacity:1,visible:e.visible??!0,children:e.children.map(e=>_(e))}}function v(e){let t=e.rootNodes.map(e=>_(e));return{rootLayer:t[0]??null,layers:t,drawCommands:[],totalLayers:t.length,totalDrawCommands:0,canvas:{width:t[0]?.bounds.width??0,height:t[0]?.bounds.height??0,dpr:1,contextType:`mock`}}}function y(e){for(let t of e){let e=t.match(/(\d+\.\d+(?:\.\d+)?)/);if(e&&e[1])return e[1]}return null}function b(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`metal`:t.includes(`vulkan`)?`vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`software`:t.length>0?`gl`:`software`}function x(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`Metal`:t.includes(`vulkan`)?`Vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`Raster`:t.length>0?`OpenGL`:`Raster`}function S(e,t,n){let r=e.flatMap(e=>{let t=[];return e.unmaskedRenderer&&t.push(e.unmaskedRenderer),e.renderer&&t.push(e.renderer),t}),i=[],a=[];t.hasSkiaFontSignatures&&(i.push(`fontBoundingBoxAscent/Descent available`),a.push(`Canvas text metrics expose font bounding boxes`));for(let e of n.engines)i.push(`engine:${e}`),a.push(`Detected known Skia-adjacent engine: ${e}`);for(let t of e)t.hasSkiaBackend&&t.unmaskedRenderer&&a.push(`Renderer probe: ${t.unmaskedRenderer}`);let o=e.some(e=>e.hasSkiaBackend)||n.isSkiaEngine||t.hasSkiaFontSignatures,s=.1;e.some(e=>e.hasSkiaBackend)&&(s+=.5),n.isSkiaEngine&&(s+=.3),t.hasSkiaFontSignatures&&(s+=.1);let c=o?b(r):`software`,l=o?x(r):`Raster`;return{isSkiaBacked:o,version:y(r),gpuBackend:c,shaderPipeline:l,rendererStrings:r,features:i,confidence:Math.min(s,1),evidence:a}}var C=class{detectSkiaRenderer(){if(typeof document>`u`)return{backend:`cpu`,version:`mock`,gpu:`browser-context-unavailable`};let e=document.querySelector(`canvas`);if(!(e instanceof HTMLCanvasElement))return{backend:`cpu`,version:`mock`,gpu:`no-canvas-detected`};let t=e.getContext(`webgl2`)||e.getContext(`webgl`)||e.getContext(`experimental-webgl`);if(!a(t))return{backend:`cpu`,version:`mock`,gpu:`canvas-without-webgl`};let n,r=t.getExtension(`WEBGL_debug_renderer_info`);if(r){let e=t.getParameter(r.UNMASKED_RENDERER_WEBGL);typeof e==`string`&&e.trim().length>0&&(n=e)}if(!n){let e=t.getParameter(t.RENDERER);typeof e==`string`&&e.trim().length>0&&(n=e)}let i,s=t.getParameter(t.VERSION);return typeof s==`string`&&s.trim().length>0&&(i=s),{backend:o(n),version:i,gpu:n}}extractSceneTree(e){if(typeof document>`u`)return f();let t=e?document.querySelector(e):document.querySelector(`canvas`);if(!(t instanceof HTMLCanvasElement))return f();let n=d(t,`skia-root`);if(t.parentElement){let e=Array.from(t.parentElement.children).filter(e=>e!==t).slice(0,8).map((e,t)=>d(e,`skia-sibling-${t}`));n.children.push(...e)}let r=[n];return{rootNodes:r,totalNodes:s(r),extractedAt:new Date().toISOString()}}};async function w(e,t){return i(e)?S(await e.evaluate(`(() => { /* UNMASKED_RENDERER_WEBGL ${t??``} */ return []; })()`),await e.evaluate(`(() => { /* fontBoundingBoxAscent */ return { hasSkiaFontSignatures: false, textMetrics: null }; })()`),await e.evaluate(`(() => { /* window.cc window.legacyCC */ return { engines: [], isSkiaEngine: false }; })()`)):p(new C().detectSkiaRenderer())}async function T(e,t,n=!0){return i(e)?g(await e.evaluate(`(() => { /* drawCommands canvasMeta ${t??``} */ return { canvas: {}, layers: [], drawCommands: [] }; })()`)):v(new C().extractSceneTree(t))}function E(e,t){let n=[],r=new Set,i=new Set,a=O(e);for(let e of a){let a=null;for(let n of t){let t=D(e,n);t&&(!a||t.confidence>a.confidence)&&(a=t)}a&&a.confidence>=.3&&(n.push(a),r.add(a.skiaObjectId),i.add(a.jsObjectId))}let o=[...new Set(a.map(e=>e.id))].filter(e=>!r.has(e)),s=t.filter(e=>!i.has(e.objectId)).map(e=>e.objectId),c=n.reduce((e,t)=>e+t.confidence,0),l=n.length>0?c/n.length:0;return{correlations:n,unmatchedJSObjects:s,unmatchedSkiaObjects:o,summary:{totalSkiaObjects:a.length,totalJSObjects:t.length,matchedCount:n.length,averageConfidence:Math.round(l*100)/100}}}function D(e,t){if(e.text){for(let n of t.stringProps)if(n===e.text||n.includes(e.text)&&e.text.length>3)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.85,matchType:`text`,explanation:`Draw text "${e.text.slice(0,50)}" matches JS string property`}}let n=j(e.bounds,t.numericProps);if(n)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:n.confidence,matchType:`dimension`,explanation:n.explanation};if(e.color){for(let n of t.colorProps)if(P(n,e.color))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.7,matchType:`color`,explanation:`Color ${e.color} matches JS color property "${n}"`}}if(e.type===`drawImage`){let n=e.color;if(n){for(let r of t.urlProps)if(r===n||r.includes(n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.8,matchType:`url`,explanation:`Image URL matches JS property`}}}if(e.name){if(t.name&&N(e.name,t.name))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name,confidence:.75,matchType:`name`,explanation:`Object name "${e.name}" matches JS object "${t.name}"`};for(let n of t.stringProps)if(N(e.name,n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.6,matchType:`name`,explanation:`Skia layer name matches JS string property`}}let r=M(e.bounds,t.numericProps);return r?{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:r.confidence,matchType:`geometry`,explanation:r.explanation}:null}function O(e){let t=[];for(let n of e.layers)t.push({id:n.id,type:`layer`,name:n.name,bounds:n.bounds,color:n.customData?.color});for(let n of e.drawCommands){let e=k(n.paintInfo),r=A(n.paintInfo);t.push({id:`cmd_${n.type}_${n.bounds.x}_${n.bounds.y}`,type:n.type,name:`${n.type} at (${n.bounds.x}, ${n.bounds.y})`,text:e,bounds:n.bounds,color:r})}return t}function k(e){if(typeof e.text==`string`)return e.text;if(typeof e.content==`string`)return e.content}function A(e){if(typeof e.color==`string`)return e.color;if(typeof e.fillColor==`string`)return e.fillColor;if(typeof e.strokeColor==`string`)return e.strokeColor;if(typeof e.url==`string`)return e.url;if(typeof e.src==`string`)return e.src}function j(e,t){let n=[`width`,`height`,`w`,`h`,`sizeX`,`sizeY`,`sw`,`sh`],r=!1,i=!1;for(let a of n){let n=t[a];n!==void 0&&((a===`width`||a===`w`||a===`sizeX`||a===`sw`)&&Math.abs(n-e.width)<=2&&(r=!0),(a===`height`||a===`h`||a===`sizeY`||a===`sh`)&&Math.abs(n-e.height)<=2&&(i=!0))}return r&&i?{confidence:.75,explanation:`Dimensions ${e.width}x${e.height} match JS numeric properties`}:r||i?{confidence:.45,explanation:`Partial dimension match for ${e.width}x${e.height}`}:null}function M(e,t){let n=!1,r=!1;for(let[i,a]of Object.entries(t))(i===`x`||i===`posX`||i===`left`)&&Math.abs(a-e.x)<=5&&(n=!0),(i===`y`||i===`posY`||i===`top`)&&Math.abs(a-e.y)<=5&&(r=!0);return n&&r?{confidence:.5,explanation:`Position (${e.x}, ${e.y}) matches JS numeric properties`}:null}function N(e,t){return e.toLowerCase()===t.toLowerCase()||e.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(e.toLowerCase())}function P(e,t){return e.toLowerCase().replace(/\s/g,``)===t.toLowerCase().replace(/\s/g,``)}async function F(e,n){let r=t(n,`canvasId`);return{rendererInfo:await w(e,r||void 0),canvasId:r||`auto`,detectionComplete:!0}}async function I(e,n){let i=t(n,`canvasId`),a=r(n,`includeDrawCommands`,!0);return{sceneTree:await T(e,i||void 0,a),canvasId:i||`auto`,extractionComplete:!0}}async function L(r,i,a){let o=t(i,`canvasId`),s=n(i,`skiaNodeIds`),c=await T(r,o||void 0,!0);if(c.layers.length===0&&c.drawCommands.length===0)throw new e(`PREREQUISITE`,`No Skia scene data available for correlation`);let l=[];if(a)try{l=await a()}catch{l=[]}let u=c;if(s.length>0){let e=new Set(s);u={...c,layers:c.layers.filter(t=>e.has(t.id)),drawCommands:c.drawCommands.filter(t=>{let n=t.layerId;return n===void 0||e.has(n)})}}return{correlations:E(u,l),canvasId:o||`auto`,skiaNodeIds:s.length>0?s:void 0,correlationComplete:!0}}var R=class{deps;constructor(e){this.deps=e}async handleSkiaDetectRenderer(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return F(this.deps.pageController,t)}async handleSkiaExtractScene(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);let n=await I(this.deps.pageController,t),r=n?.sceneTree;return r&&this.deps.eventBus?.emit(`skia:scene_captured`,{canvasId:t.canvasId??`auto`,nodeCount:(r.layers?.length??0)+(r.drawCommands?.length??0),timestamp:new Date().toISOString()}),n}async handleSkiaCorrelateObjects(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return L(this.deps.pageController,t,this.deps.getJSObjects)}};export{R as SkiaCaptureHandlers};
|
|
1
|
+
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{a as t,o as n,t as r}from"./parse-args-Bw413PlW.mjs";function i(e){return typeof e!=`object`||!e||!(`evaluate`in e)?!1:typeof e.evaluate==`function`}function a(e){return typeof e!=`object`||!e||!(`getExtension`in e)||!(`getParameter`in e)||!(`RENDERER`in e)||!(`VERSION`in e)?!1:typeof e.getExtension==`function`&&typeof e.getParameter==`function`}function o(e){let t=(e??``).toLowerCase();return t.includes(`vulkan`)?`vulkan`:t.includes(`metal`)?`metal`:t.includes(`d3d`)||t.includes(`direct3d`)?`direct3d`:t.includes(`angle`)||t.includes(`opengl`)||t.includes(`mesa`)||t.includes(`gl`)?`opengl`:t.includes(`swiftshader`)||t.includes(`software`)||t.includes(`cpu`)?`cpu`:t.length>0?`gpu`:`cpu`}function s(e){let t=0;for(let n of e)t+=1,t+=s(n.children);return t}function c(e){let t=e.getAttribute(`aria-label`);if(t)return t;if(e.id)return e.id;let n=typeof e.className==`string`?e.className.trim():``;return n.length>0?n:e.tagName.toLowerCase()}function l(e){if(typeof e.getBoundingClientRect!=`function`)return;let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function u(e){if(!(e instanceof HTMLElement)||typeof window>`u`)return;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`}function d(e,t){let n=Array.from(e.children).slice(0,12).map((e,n)=>d(e,`${t}-${n}`));return{id:e.id||t,type:e.tagName.toLowerCase(),label:c(e),children:n,visible:u(e),bounds:l(e)}}function f(){let e=[{id:`mock-root`,type:`canvas`,label:`mock-skia-surface`,visible:!0,bounds:{x:0,y:0,width:640,height:480},children:[{id:`mock-layer`,type:`layer`,label:`mock-layer`,visible:!0,bounds:{x:16,y:16,width:320,height:160},children:[]}]}];return{rootNodes:e,totalNodes:s(e),extractedAt:new Date().toISOString()}}function p(e){let t=`software`,n=`Raster`;return e.backend===`vulkan`?(t=`vulkan`,n=`Vulkan`):e.backend===`metal`?(t=`metal`,n=`Metal`):(e.backend===`opengl`||e.backend===`direct3d`||e.backend===`gpu`)&&(t=`gl`,n=`OpenGL`),{isSkiaBacked:e.backend!==`cpu`,version:e.version??null,gpuBackend:t,shaderPipeline:n,rendererStrings:e.gpu?[e.gpu]:[],features:e.backend===`cpu`?[]:[`backend:${e.backend}`],confidence:e.backend===`cpu`?.2:.8,evidence:e.gpu?[`Renderer string: ${e.gpu}`]:[`No renderer information available`]}}function m(e,t){return e.x>=t.x&&e.y>=t.y&&e.x+e.width<=t.x+t.width&&e.y+e.height<=t.y+t.height}function h(e){let t=(e??``).toLowerCase();return t.includes(`rrect`)||t.includes(`round`)?`drawRRect`:t.includes(`rect`)?`drawRect`:t.includes(`text`)?`drawText`:t.includes(`image`)||t.includes(`sprite`)?`drawImage`:t.includes(`path`)?`drawPath`:t.includes(`circle`)||t.includes(`arc`)?`drawCircle`:t.includes(`line`)?`drawLine`:`unknown`}function g(e){let t=e.layers.map((e,t)=>({id:e.id??`layer-${t}`,name:e.name??`layer-${t}`,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:e.transform??[1,0,0,0,1,0,0,0,1],opacity:e.opacity??1,visible:e.visible??!0,children:[],customData:e.customData})),n=t[0]??null;if(n)for(let e=1;e<t.length;e+=1){let r=t[e];r&&m(r.bounds,n.bounds)&&n.children.push(r)}let r=e.drawCommands.map(e=>({type:h(e.type),bounds:e.bounds??{x:0,y:0,width:0,height:0},paintInfo:e.paintInfo??{},layerId:e.layerId}));return{rootLayer:n,layers:t,drawCommands:r,totalLayers:t.length,totalDrawCommands:r.length,canvas:{id:e.canvas.id,width:e.canvas.width??0,height:e.canvas.height??0,dpr:e.canvas.dpr??1,contextType:e.canvas.contextType??`unknown`}}}function _(e){return{id:e.id,name:e.label,bounds:e.bounds??{x:0,y:0,width:0,height:0},transform:[1,0,0,0,1,0,0,0,1],opacity:1,visible:e.visible??!0,children:e.children.map(e=>_(e))}}function v(e){let t=e.rootNodes.map(e=>_(e));return{rootLayer:t[0]??null,layers:t,drawCommands:[],totalLayers:t.length,totalDrawCommands:0,canvas:{width:t[0]?.bounds.width??0,height:t[0]?.bounds.height??0,dpr:1,contextType:`mock`}}}function y(e){for(let t of e){let e=t.match(/(\d+\.\d+(?:\.\d+)?)/);if(e&&e[1])return e[1]}return null}function b(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`metal`:t.includes(`vulkan`)?`vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`software`:t.length>0?`gl`:`software`}function x(e){let t=e.join(` `).toLowerCase();return t.includes(`metal`)?`Metal`:t.includes(`vulkan`)?`Vulkan`:t.includes(`swiftshader`)||t.includes(`software`)?`Raster`:t.length>0?`OpenGL`:`Raster`}function S(e,t,n){let r=e.flatMap(e=>{let t=[];return e.unmaskedRenderer&&t.push(e.unmaskedRenderer),e.renderer&&t.push(e.renderer),t}),i=[],a=[];t.hasSkiaFontSignatures&&(i.push(`fontBoundingBoxAscent/Descent available`),a.push(`Canvas text metrics expose font bounding boxes`));for(let e of n.engines)i.push(`engine:${e}`),a.push(`Detected known Skia-adjacent engine: ${e}`);for(let t of e)t.hasSkiaBackend&&t.unmaskedRenderer&&a.push(`Renderer probe: ${t.unmaskedRenderer}`);let o=e.some(e=>e.hasSkiaBackend)||n.isSkiaEngine||t.hasSkiaFontSignatures,s=.1;e.some(e=>e.hasSkiaBackend)&&(s+=.5),n.isSkiaEngine&&(s+=.3),t.hasSkiaFontSignatures&&(s+=.1);let c=o?b(r):`software`,l=o?x(r):`Raster`;return{isSkiaBacked:o,version:y(r),gpuBackend:c,shaderPipeline:l,rendererStrings:r,features:i,confidence:Math.min(s,1),evidence:a}}var C=class{detectSkiaRenderer(){if(typeof document>`u`)return{backend:`cpu`,version:`mock`,gpu:`browser-context-unavailable`};let e=document.querySelector(`canvas`);if(!(e instanceof HTMLCanvasElement))return{backend:`cpu`,version:`mock`,gpu:`no-canvas-detected`};let t=e.getContext(`webgl2`)||e.getContext(`webgl`)||e.getContext(`experimental-webgl`);if(!a(t))return{backend:`cpu`,version:`mock`,gpu:`canvas-without-webgl`};let n,r=t.getExtension(`WEBGL_debug_renderer_info`);if(r){let e=t.getParameter(r.UNMASKED_RENDERER_WEBGL);typeof e==`string`&&e.trim().length>0&&(n=e)}if(!n){let e=t.getParameter(t.RENDERER);typeof e==`string`&&e.trim().length>0&&(n=e)}let i,s=t.getParameter(t.VERSION);return typeof s==`string`&&s.trim().length>0&&(i=s),{backend:o(n),version:i,gpu:n}}extractSceneTree(e){if(typeof document>`u`)return f();let t=e?document.querySelector(e):document.querySelector(`canvas`);if(!(t instanceof HTMLCanvasElement))return f();let n=d(t,`skia-root`);if(t.parentElement){let e=Array.from(t.parentElement.children).filter(e=>e!==t).slice(0,8).map((e,t)=>d(e,`skia-sibling-${t}`));n.children.push(...e)}let r=[n];return{rootNodes:r,totalNodes:s(r),extractedAt:new Date().toISOString()}}};async function w(e,t){return i(e)?S(await e.evaluate(`(() => { /* UNMASKED_RENDERER_WEBGL ${t??``} */ return []; })()`),await e.evaluate(`(() => { /* fontBoundingBoxAscent */ return { hasSkiaFontSignatures: false, textMetrics: null }; })()`),await e.evaluate(`(() => { /* window.cc window.legacyCC */ return { engines: [], isSkiaEngine: false }; })()`)):p(new C().detectSkiaRenderer())}async function T(e,t,n=!0){return i(e)?g(await e.evaluate(`(() => { /* drawCommands canvasMeta ${t??``} */ return { canvas: {}, layers: [], drawCommands: [] }; })()`)):v(new C().extractSceneTree(t))}function E(e,t){let n=[],r=new Set,i=new Set,a=O(e);for(let e of a){let a=null;for(let n of t){let t=D(e,n);t&&(!a||t.confidence>a.confidence)&&(a=t)}a&&a.confidence>=.3&&(n.push(a),r.add(a.skiaObjectId),i.add(a.jsObjectId))}let o=[...new Set(a.map(e=>e.id))].filter(e=>!r.has(e)),s=t.filter(e=>!i.has(e.objectId)).map(e=>e.objectId),c=n.reduce((e,t)=>e+t.confidence,0),l=n.length>0?c/n.length:0;return{correlations:n,unmatchedJSObjects:s,unmatchedSkiaObjects:o,summary:{totalSkiaObjects:a.length,totalJSObjects:t.length,matchedCount:n.length,averageConfidence:Math.round(l*100)/100}}}function D(e,t){if(e.text){for(let n of t.stringProps)if(n===e.text||n.includes(e.text)&&e.text.length>3)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.85,matchType:`text`,explanation:`Draw text "${e.text.slice(0,50)}" matches JS string property`}}let n=j(e.bounds,t.numericProps);if(n)return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:n.confidence,matchType:`dimension`,explanation:n.explanation};if(e.color){for(let n of t.colorProps)if(P(n,e.color))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.7,matchType:`color`,explanation:`Color ${e.color} matches JS color property "${n}"`}}if(e.type===`drawImage`){let n=e.color;if(n){for(let r of t.urlProps)if(r===n||r.includes(n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.8,matchType:`url`,explanation:`Image URL matches JS property`}}}if(e.name){if(t.name&&N(e.name,t.name))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name,confidence:.75,matchType:`name`,explanation:`Object name "${e.name}" matches JS object "${t.name}"`};for(let n of t.stringProps)if(N(e.name,n))return{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:.6,matchType:`name`,explanation:`Skia layer name matches JS string property`}}let r=M(e.bounds,t.numericProps);return r?{skiaObjectId:e.id,jsObjectId:t.objectId,jsObjectName:t.name||t.className,confidence:r.confidence,matchType:`geometry`,explanation:r.explanation}:null}function O(e){let t=[];for(let n of e.layers)t.push({id:n.id,type:`layer`,name:n.name,bounds:n.bounds,color:n.customData?.color});for(let n of e.drawCommands){let e=k(n.paintInfo),r=A(n.paintInfo);t.push({id:`cmd_${n.type}_${n.bounds.x}_${n.bounds.y}`,type:n.type,name:`${n.type} at (${n.bounds.x}, ${n.bounds.y})`,text:e,bounds:n.bounds,color:r})}return t}function k(e){if(typeof e.text==`string`)return e.text;if(typeof e.content==`string`)return e.content}function A(e){if(typeof e.color==`string`)return e.color;if(typeof e.fillColor==`string`)return e.fillColor;if(typeof e.strokeColor==`string`)return e.strokeColor;if(typeof e.url==`string`)return e.url;if(typeof e.src==`string`)return e.src}function j(e,t){let n=[`width`,`height`,`w`,`h`,`sizeX`,`sizeY`,`sw`,`sh`],r=!1,i=!1;for(let a of n){let n=t[a];n!==void 0&&((a===`width`||a===`w`||a===`sizeX`||a===`sw`)&&Math.abs(n-e.width)<=2&&(r=!0),(a===`height`||a===`h`||a===`sizeY`||a===`sh`)&&Math.abs(n-e.height)<=2&&(i=!0))}return r&&i?{confidence:.75,explanation:`Dimensions ${e.width}x${e.height} match JS numeric properties`}:r||i?{confidence:.45,explanation:`Partial dimension match for ${e.width}x${e.height}`}:null}function M(e,t){let n=!1,r=!1;for(let[i,a]of Object.entries(t))(i===`x`||i===`posX`||i===`left`)&&Math.abs(a-e.x)<=5&&(n=!0),(i===`y`||i===`posY`||i===`top`)&&Math.abs(a-e.y)<=5&&(r=!0);return n&&r?{confidence:.5,explanation:`Position (${e.x}, ${e.y}) matches JS numeric properties`}:null}function N(e,t){return e.toLowerCase()===t.toLowerCase()||e.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(e.toLowerCase())}function P(e,t){return e.toLowerCase().replace(/\s/g,``)===t.toLowerCase().replace(/\s/g,``)}async function F(e,n){let r=t(n,`canvasId`);return{rendererInfo:await w(e,r||void 0),canvasId:r||`auto`,detectionComplete:!0}}async function I(e,n){let i=t(n,`canvasId`),a=r(n,`includeDrawCommands`,!0);return{sceneTree:await T(e,i||void 0,a),canvasId:i||`auto`,extractionComplete:!0}}async function L(r,i,a){let o=t(i,`canvasId`),s=n(i,`skiaNodeIds`),c=await T(r,o||void 0,!0);if(c.layers.length===0&&c.drawCommands.length===0)throw new e(`PREREQUISITE`,`No Skia scene data available for correlation`);let l=[];if(a)try{l=await a()}catch{l=[]}let u=c;if(s.length>0){let e=new Set(s);u={...c,layers:c.layers.filter(t=>e.has(t.id)),drawCommands:c.drawCommands.filter(t=>{let n=t.layerId;return n===void 0||e.has(n)})}}return{correlations:E(u,l),canvasId:o||`auto`,skiaNodeIds:s.length>0?s:void 0,correlationComplete:!0}}var R=class{deps;constructor(e){this.deps=e}async handleSkiaDetectRenderer(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return F(this.deps.pageController,t)}async handleSkiaExtractScene(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);let n=await I(this.deps.pageController,t),r=n?.sceneTree;return r&&this.deps.eventBus?.emit(`skia:scene_captured`,{canvasId:t.canvasId??`auto`,nodeCount:(r.layers?.length??0)+(r.drawCommands?.length??0),timestamp:new Date().toISOString()}),n}async handleSkiaCorrelateObjects(t){if(!this.deps.pageController)throw new e(`PREREQUISITE`,`PageController not available — ensure browser is connected`);return L(this.deps.pageController,t,this.deps.getJSObjects)}};export{R as SkiaCaptureHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./response-C7rKQst4.mjs";import{a as t}from"./parse-args-Bw413PlW.mjs";import{n}from"./ResponseBuilder-BfWP-uaT.mjs";var r=class{sessionManager;deps;constructor(e,t={}){this.sessionManager=e,this.deps=t}async handleSessionDispatch(n){let r=t(n,`action`);switch(r){case`create`:return this.handleSessionCreate(n);case`list`:return this.handleSessionList(n);case`destroy`:return this.handleSessionDestroy(n);case`status`:return this.handleSessionStatus(n);default:return e({success:!1,error:`Unknown action: ${r}. Valid: create, list, destroy, status`})}}async handleOperationDispatch(n){let r=t(n,`action`);switch(r){case`register`:return this.handleOperationRegister(n);case`list`:return this.handleOperationList(n);default:return e({success:!1,error:`Unknown action: ${r}. Valid: register, list`})}}async handleArtifactDispatch(n){let r=t(n,`action`);switch(r){case`record`:return this.handleArtifactRecord(n);case`query`:return this.handleArtifactQuery(n);default:return e({success:!1,error:`Unknown action: ${r}. Valid: record, query`})}}async handleSessionCreate(e){return n(async()=>{let n=t(e,`name`);return{session:this.sessionManager.createSession(n||void 0)}})}async handleSessionList(e){return n(async()=>{let e=this.sessionManager.listSessions();return{totalSessions:e.length,sessions:e}})}async handleSessionDestroy(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);return this.sessionManager.destroySession(n),{sessionId:n,message:`Session destroyed`}})}async handleSessionStatus(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);let r=this.sessionManager.getSession(n);if(!r)throw Error(`Session "${n}" not found`);return{session:r,stats:this.sessionManager.getSessionStats(n)}})}async handleOperationList(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);let r=this.sessionManager.getSessionOperations(n),i=t(e,`type`);return i&&(r=r.filter(e=>e.type===i)),{totalOperations:r.length,operations:r}})}async handleOperationRegister(e){return n(async()=>{let n=t(e,`sessionId`,``),r=t(e,`type`,``),i=t(e,`target`,``),a=e.config&&typeof e.config==`object`&&!Array.isArray(e.config)?e.config:{};if(!n)throw Error(`sessionId is required`);if(!r)throw Error(`type is required`);if(!i)throw Error(`target is required`);return{operation:this.sessionManager.registerOperation(n,r,i,a)}})}async handleArtifactQuery(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);let r=t(e,`type`)||void 0,i=typeof e.limit==`number`?e.limit:50,a=this.sessionManager.getArtifacts(n,r);return i>0&&(a=a.slice(0,i)),{totalArtifacts:a.length,artifacts:a}})}async handleArtifactRecord(e){return n(async()=>{let n=t(e,`operationId`,``),r=e.data&&typeof e.data==`object`&&!Array.isArray(e.data)?e.data:void 0;if(!n)throw Error(`operationId is required`);if(!r)throw Error(`data is required`);return{artifact:this.sessionManager.recordArtifact(n,r)}})}async handleHookPreset(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);if(!this.deps.hookPresetHandlers)throw Error(`hookPresetHandlers is not available`);let r={...e};delete r.sessionId;let i=await this.sessionManager.applyHookPreset(n,this.deps.hookPresetHandlers,r);return{operation:i.operation,artifacts:i.artifacts,result:i.payload}})}async handleNetworkReplay(e){return n(async()=>{let n=t(e,`sessionId`,``);if(!n)throw Error(`sessionId is required`);if(!this.deps.advancedHandlers)throw Error(`advancedHandlers is not available`);let r={...e};delete r.sessionId;let i=await this.sessionManager.replayNetworkRequest(n,this.deps.advancedHandlers,r);return{operation:i.operation,artifacts:i.artifacts,result:i.payload}})}};export{r as InstrumentationHandlers};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{zr as e}from"./constants-Cp6hBrrx.mjs";import{n as t}from"./response-C7rKQst4.mjs";import{i as n,r}from"./outputPaths-BonGThuc.mjs";import{a as i,i as a,s as o}from"./parse-args-Cuk7-xUt.mjs";import s from"node:http";import{createHash as c}from"node:crypto";import{existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f}from"node:fs";import p from"node:path";import{fileURLToPath as m,pathToFileURL as h}from"node:url";import{mkdir as g,readFile as _,writeFile as v}from"node:fs/promises";import{EventEmitter as y}from"node:events";function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x(e){let t=e.trim().toLowerCase().replace(/\//g,`-`).replace(/(?!^@)[^a-z0-9@_-]+/g,`-`);return t.length>0?t:`plugin-${Date.now()}`}function S(e){if(!b(e))return null;let{id:t,name:n,version:r,entry:i,permissions:a,status:o}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||o!==`loaded`&&o!==`unloaded`?null:{id:t,name:n,version:r,entry:i,permissions:Array.isArray(a)?a.filter(e=>typeof e==`string`):[],status:o}}var C=class{rootDir;legacyPluginRoots;useLegacyScanApi;registryFile;moduleCacheDir;installedPlugins=new Map;loadedPlugins=new Map;constructor(e=r(),t=[]){let n=typeof e==`string`?e:r();this.useLegacyScanApi=typeof e!=`string`,this.rootDir=n,this.registryFile=p.join(n,`plugins.json`),this.moduleCacheDir=p.join(n,`modules`),this.legacyPluginRoots=t.length>0?t:process.env.JSHOOKMCP_PLUGIN_ROOT?[process.env.JSHOOKMCP_PLUGIN_ROOT]:[],!this.useLegacyScanApi&&this.initializeFromDisk()}async register(e){let t=x(e.id||e.name),n={id:t,name:e.name,version:e.version,entry:e.entry,permissions:e.permissions?[...e.permissions]:[],status:this.loadedPlugins.has(t)?`loaded`:`unloaded`};return this.installedPlugins.set(t,n),await this.persist(),t}async unregister(e){await this.unloadPlugin(e),this.installedPlugins.delete(e),await this.persist()}listInstalled(){return[...this.installedPlugins.values()].map(e=>({id:e.id,name:e.name,version:e.version,status:e.status,permissions:[...e.permissions]})).toSorted((e,t)=>e.name.localeCompare(t.name))}async loadPlugin(e){let t=this.installedPlugins.get(e);if(!t)throw Error(`Plugin not found: ${e}`);let n=this.loadedPlugins.get(e);if(n)return{manifest:this.toPublicManifest(n.manifest),exports:n.exports};let r=h(await this.resolveEntryPath(t));r.searchParams.set(`ts`,String(Date.now()));let i=await import(r.href),a=b(i)?i:{};return t.status=`loaded`,this.loadedPlugins.set(e,{manifest:t,exports:a}),await this.persist(),{manifest:this.toPublicManifest(t),exports:a}}async unloadPlugin(e){let t=this.installedPlugins.get(e);t&&(this.loadedPlugins.delete(e),t.status=`unloaded`,await this.persist())}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),l(this.moduleCacheDir)||u(this.moduleCacheDir,{recursive:!0}),!l(this.registryFile))return;let e=d(this.registryFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=S(e);t&&this.installedPlugins.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await g(this.moduleCacheDir,{recursive:!0}),await v(this.registryFile,JSON.stringify([...this.installedPlugins.values()],null,2),`utf8`)}async resolveEntryPath(e){return e.entry.startsWith(`http://`)||e.entry.startsWith(`https://`)?this.downloadRemoteModule(e.id,e.entry):e.entry.startsWith(`file://`)?m(new URL(e.entry)):p.isAbsolute(e.entry)?e.entry:p.resolve(n(),e.entry)}async downloadRemoteModule(e,t){let n=await fetch(t);if(!n.ok)throw Error(`Failed to download plugin module: ${n.status} ${n.statusText}`);let r=await n.text(),i=p.join(this.moduleCacheDir,`${x(e)}.mjs`),a=c(`sha256`).update(r).digest(`hex`);try{let e=await _(i,`utf8`);if(c(`sha256`).update(e).digest(`hex`)===a)return i}catch{}return await g(this.moduleCacheDir,{recursive:!0}),await v(i,r,`utf8`),i}toPublicManifest(e){return{id:e.id,name:e.name,version:e.version,entry:e.entry,permissions:[...e.permissions]}}listPlugins(){let e=[];for(let t of this.legacyPluginRoots){if(!l(t))continue;let n=f(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`))continue;let n=p.join(t,r.name,`package.json`);if(l(n))try{let t=JSON.parse(d(n,`utf8`)),r=this.toLegacyPluginInfo(t);r&&e.push(r)}catch{continue}}}return e}searchPlugins(e){let t=e.trim().toLowerCase();return t?this.listPlugins().filter(e=>e.name.toLowerCase().includes(t)||(e.description??``).toLowerCase().includes(t)||(e.capabilities??[]).some(e=>e.toLowerCase().includes(t))||(e.dependencies??[]).some(e=>e.toLowerCase().includes(t))):this.listPlugins()}async installPlugin(e){if(/^https:\/\/github\.com\/.+\.git$/u.test(e)||/^git@github\.com:.+\.git$/u.test(e))return{id:`git-plugin`,name:e.split(`/`).pop()?.replace(/\.git$/u,``)??`plugin`,version:`0.0.0`};if(e.includes(`://`)||e.startsWith(`git@`)||e===`invalid-url`)throw Error(`Invalid git URL`);if(e.startsWith(`/`)||e.includes(`\\`)){let t=p.join(e,`package.json`);if(!l(t))throw Error(`No package.json`);let n=JSON.parse(d(t,`utf8`)),r=this.toLegacyPluginInfo(n);if(!r)throw Error(`No package.json`);return r}for(let t of this.legacyPluginRoots){let n=p.join(t,e,`package.json`);if(!l(n))continue;let r=JSON.parse(d(n,`utf8`)),i=this.toLegacyPluginInfo(r);if(i)return i}throw Error(`Plugin not found`)}getPluginInfo(e){return this.listPlugins().find(t=>t.id===e||t.name===e)}getPluginDependencies(e){return this.getPluginInfo(e)?.dependencies??[]}async uninstallPlugin(e){}toLegacyPluginInfo(e){if(typeof e.name!=`string`)return null;let t=b(e.dependencies)?Object.keys(e.dependencies):[];return{id:x(e.name),name:e.name,version:typeof e.version==`string`?e.version:`0.0.0`,description:typeof e.description==`string`?e.description:void 0,capabilities:Array.isArray(e.capabilities)?e.capabilities.filter(e=>typeof e==`string`):void 0,dependencies:t}}};function w(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function T(e){if(!w(e))return null;let{id:t,url:n,events:r,active:i}=e;return typeof t!=`string`||typeof n!=`string`||!Array.isArray(r)||typeof i!=`boolean`?null:{id:t,url:n,events:r.filter(e=>typeof e==`string`),active:i}}var E=class{rootDir;storageFile;webhooks=new Map;constructor(e=r()){this.rootDir=e,this.storageFile=p.join(e,`webhooks.json`),this.initializeFromDisk()}async registerWebhook(e,t){new URL(e);let n={id:`webhook-${Date.now()}-${this.webhooks.size+1}`,url:e,events:[...new Set(t.filter(e=>e.trim().length>0))],active:!0};return this.webhooks.set(n.id,n),await this.persist(),n.id}async sendEvent(e,t){let n=[...this.webhooks.values()].filter(t=>t.active&&(t.events.includes(e)||t.events.includes(`*`)));for(let r of n){let n=await fetch(r.url,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:e,payload:t,timestamp:new Date().toISOString()})});if(!n.ok)throw Error(`Webhook delivery failed for ${r.url}: ${n.status} ${n.statusText}`)}}listWebhooks(){return[...this.webhooks.values()].map(e=>({id:e.id,url:e.url,events:[...e.events],active:e.active}))}registerExternalCallback(e,t){let n=this.webhooks.get(e);if(n){n.url=t;return}this.webhooks.set(e,{id:e,url:t,events:[`*`],active:!0})}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),!l(this.storageFile))return;let e=d(this.storageFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=T(e);t&&this.webhooks.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await v(this.storageFile,JSON.stringify([...this.webhooks.values()],null,2),`utf8`)}};function D(e){return{...e}}function O(){return new Date().toISOString()}var k=class extends y{maxQueueSize;commands=new Map;order=[];maxRetries;retryDelay;processTimeout;nextId=1;constructor(t={}){super(),this.maxQueueSize=typeof t.maxQueueSize==`number`?t.maxQueueSize:1e3,this.maxRetries=typeof t.maxRetries==`number`?t.maxRetries:3,this.retryDelay=typeof t.retryDelay==`number`?t.retryDelay:0,this.processTimeout=typeof t.processTimeout==`number`?t.processTimeout:e}enqueue(e){if(this.order.length>=this.maxQueueSize)throw Error(`Command queue is full (${this.maxQueueSize})`);let t=`cmd-${this.nextId}`;this.nextId+=1;let n=O(),r={id:t,endpointId:e.endpointId,event:e.event,payload:e.payload,status:`pending`,retries:0,createdAt:n,updatedAt:n};return this.commands.set(t,r),this.order.push(t),this.emit(`enqueued`,D(r)),t}dequeue(e){if(!e){let e=this.getCommandsByFilter({status:`pending`})[0];return e?D(e):void 0}return this.getCommandsByFilter(e).map(D)}getStatus(e){let t=this.commands.get(e);return t?t.status===`processed`?`completed`:t.status:`failed`}retry(e){let t=this.commands.get(e);if(!t)throw Error(`Command ${e} not found`);if(t.status!==`failed`)throw Error(`Command ${e} is not in failed state`);t.status=`pending`,t.retries=0,t.lastError=void 0,t.updatedAt=O()}getCommand(e){return this.commands.get(e)}getCommandsByFilter(e){let t=e.status===`completed`?`processed`:e.status,n=[];for(let r of this.order){let i=this.commands.get(r);i&&(t&&i.status!==t||e.endpointId&&i.endpointId!==e.endpointId||n.push(i))}return n}updateStatus(e,t,n){let r=this.commands.get(e);if(!r)throw Error(`Command ${e} not found`);return r.status=t,r.updatedAt=O(),r.lastError=n,r}},A=class extends k{async process(e,t){let n=this.getCommand(e);if(!n)throw Error(`Command ${e} not found`);if(n.status===`processed`)throw Error(`Command ${e} already processed`);if(n.status===`failed`)throw Error(`Command ${e} already processed with failure`);if(n.status===`processing`)throw Error(`Command ${e} is already processing`);this.updateStatus(e,`processing`);let r=`processed`,i;try{await Promise.race([Promise.resolve(t(D(n))),new Promise((e,t)=>{setTimeout(()=>{t(Error(`Process timeout`))},this.processTimeout)})])}catch(e){i=e instanceof Error?e.message:String(e),r=n.retries+1>=this.maxRetries?`failed`:`pending`}if(i!==void 0&&this.retryDelay>0&&setTimeout(()=>{},this.retryDelay),r===`processed`){let t=this.updateStatus(e,`processed`);this.emit(`processed`,D(t))}else if(r===`pending`){n.retries+=1;let t=this.updateStatus(e,`pending`,i);throw this.emit(`retried`,D(t)),Error(i===void 0?`retry`:i)}else{let t=this.updateStatus(e,`failed`,i);throw this.emit(`failed`,D(t)),Error(i===void 0?`failed`:i)}}async retry(e){super.retry(e)}exportState(){let e=[];for(let t of this.order){let n=this.commands.get(t);n&&e.push(D(n))}return e}importState(e){this.commands.clear(),this.order.length=0;let t=0;for(let n of e){let e=D(n);this.commands.set(e.id,e),this.order.push(e.id);let r=/^cmd-(\d+)$/.exec(e.id);if(r&&r[1]){let e=parseInt(r[1],10);e>t&&(t=e)}}t>0&&(this.nextId=t+1)}};function j(e){return e===`tool_called`||e===`domain_activated`||e===`evidence_added`||e===`workflow_completed`}function M(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{rawBody:e}}}var N=class extends y{endpoints=new Map;eventHandlers=new Map;port;commandQueue;stats={eventsRegistered:0,webhooksSent:0};server;nextEndpointId=1;constructor(e={}){super(),this.port=typeof e.port==`number`?e.port:18789,this.commandQueue=e.commandQueue}registerEndpoint(e){let t=`ep-${this.nextEndpointId}`;return this.nextEndpointId+=1,this.endpoints.set(t,{id:t,path:e.path,method:e.method??`POST`,secret:e.secret}),this.emit(`endpointRegistered`,t),t}removeEndpoint(e){if(!this.endpoints.delete(e))throw Error(`Endpoint ${e} not found`);this.emit(`endpointRemoved`,e)}listEndpoints(){return[...this.endpoints.values()].map(e=>({...e}))}getPort(){return this.port}isRunning(){return this.server!==void 0}registerEvent(e,t){let n=this.eventHandlers.get(e)??[];n.push(t),this.eventHandlers.set(e,n),this.stats.eventsRegistered+=1}start(){if(this.server)throw Error(`Webhook server already started`);this.server=s.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.listen(this.port),this.emit(`started`,this.port)}async stop(){if(!this.server)return;let e=this.server;this.server=void 0,await new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})}),this.emit(`stopped`)}async sendWebhook(e,t,n){await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:t,payload:n})}),this.stats.webhooksSent+=1,this.stats.lastSentAt=new Date().toISOString()}getStats(){return{...this.stats}}async handleRequest(e,t){let n=e.method??`GET`,r=e.url??`/`,i=[...this.endpoints.values()].find(e=>e.path===r&&e.method===n);if(!i){t.statusCode=404,t.end(`not found`);return}if(i.secret&&e.headers[`x-webhook-secret`]!==i.secret){t.statusCode=401,t.end(`unauthorized`);return}let a=[];await new Promise((t,n)=>{e.setEncoding(`utf8`),e.on(`data`,e=>{a.push(e)}),e.on(`end`,()=>{t()}),e.on(`error`,e=>{n(e)})});let o=M(a.join(``));this.commandQueue&&this.commandQueue.enqueue({endpointId:i.id,payload:o}),o&&typeof o==`object`&&`event`in o&&typeof o.event==`string`&&await this.invokeEventHandlers(o.event,o),t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!0,endpointId:i.id}))}async invokeEventHandlers(e,t){if(!j(e))return;let n=this.eventHandlers.get(e)??[];for(let e of n)await Promise.resolve(e(t))}},P=class extends N{};function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e){return typeof e==`function`}var L=class{registry;webhook;webhookServer;commandQueue;constructor(e,t){this.registry=e,this.webhook=t}async handleListInstalled(){return t({success:!0,plugins:this.getRegistry().listInstalled()})}async handleExecuteInContext(e){let n=o(e,`pluginId`),r=o(e,`contextName`),i=a(e,`args`)??{},{manifest:s,exports:c}=await this.getRegistry().loadPlugin(n),l=this.resolveContext(c,r);if(!l)throw Error(`Context "${r}" was not found in plugin "${n}"`);let u=await Promise.resolve(l(i));return this.emitEvent(`extension.executed`,{pluginId:n,contextName:r}),t({success:!0,manifest:s,contextName:r,result:u})}async handleReload(e){let n=o(e,`pluginId`);await this.getRegistry().unloadPlugin(n);let r=await this.getRegistry().loadPlugin(n);return this.emitEvent(`extension.reloaded`,{pluginId:n}),t({success:!0,pluginId:n,manifest:r.manifest,exportedKeys:Object.keys(r.exports).toSorted()})}async handleUninstall(e){let n=o(e,`pluginId`);return await this.getRegistry().unregister(n),this.emitEvent(`extension.uninstalled`,{pluginId:n}),t({success:!0,pluginId:n})}async handleWebhookCreate(e){let n=o(e,`name`),r=o(e,`path`),a=i(e,`secret`),s=Array.isArray(e.events)?e.events.filter(e=>typeof e==`string`):[],c=this.getWebhookServer();c.isRunning()||c.start();let l=c.registerEndpoint({path:r,method:`POST`,secret:a??void 0}),u=this.getWebhook(),d=`http://localhost:${c.getPort()}${r}`;return u.registerExternalCallback(l,d),t({success:!0,endpointId:l,url:d,name:n,events:s})}async handleWebhookList(){let e=this.getWebhookServer();return t({success:!0,endpoints:e.listEndpoints(),port:e.getPort(),running:e.isRunning()})}async handleWebhookDelete(e){let n=o(e,`endpointId`),r=this.getWebhookServer();try{r.removeEndpoint(n)}catch(e){throw Error(`GRACEFUL: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return t({success:!0,endpointId:n})}async handleWebhookCommands(e){let n=o(e,`endpointId`),r=i(e,`status`),s=a(e,`command`);if(s)return t({success:!0,commandId:this.getCommandQueue().enqueue({endpointId:n,payload:s}),status:`pending`});let c=this.getCommandQueue(),l={endpointId:n};r&&(l.status=r);let u=c.dequeue(l);return t({success:!0,endpointId:n,commands:u,count:Array.isArray(u)?u.length:+!!u})}getWebhookServer(){return this.webhookServer||=(this.commandQueue=new A,new P({commandQueue:this.commandQueue})),this.webhookServer}async startWebhookServer(){let e=this.getWebhookServer();e.isRunning()||e.start()}async stopWebhookServer(){this.webhookServer&&(await this.webhookServer.stop(),this.webhookServer=void 0,this.commandQueue=void 0)}getRegistry(){return this.registry||=new C,this.registry}getWebhook(){return this.webhook||=new E,this.webhook}getCommandQueue(){return this.commandQueue||=new A,this.commandQueue}emitEvent(e,t){this.getWebhook().sendEvent(e,t).catch(()=>void 0)}resolveContext(e,t){let n=e[t];if(I(n))return n;let r=e.default;if(t===`default`&&I(r))return r;if(F(r)){let e=r[t];if(I(e))return e}return null}async handleWebhookDispatch(e){let n=i(e,`action`);switch(n){case`create`:return this.handleWebhookCreate(e);case`list`:return this.handleWebhookList();case`delete`:return this.handleWebhookDelete(e);case`commands`:return this.handleWebhookCommands(e);default:return t({error:`Invalid action: "${n}". Expected one of: create, list, delete, commands`})}}};export{L as ExtensionRegistryHandlers};
|
|
1
|
+
import{ui as e}from"./constants-BYj8Xek8.mjs";import{n as t}from"./response-C7rKQst4.mjs";import{i as n,r}from"./outputPaths-B4Ic4RZh.mjs";import{a as i,i as a,s as o}from"./parse-args-Bw413PlW.mjs";import s from"node:http";import{createHash as c}from"node:crypto";import{existsSync as l,mkdirSync as u,readFileSync as d,readdirSync as f}from"node:fs";import p from"node:path";import{fileURLToPath as m,pathToFileURL as h}from"node:url";import{mkdir as g,readFile as _,writeFile as v}from"node:fs/promises";import{EventEmitter as y}from"node:events";function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x(e){let t=e.trim().toLowerCase().replace(/\//g,`-`).replace(/(?!^@)[^a-z0-9@_-]+/g,`-`);return t.length>0?t:`plugin-${Date.now()}`}function S(e){if(!b(e))return null;let{id:t,name:n,version:r,entry:i,permissions:a,status:o}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||o!==`loaded`&&o!==`unloaded`?null:{id:t,name:n,version:r,entry:i,permissions:Array.isArray(a)?a.filter(e=>typeof e==`string`):[],status:o}}var C=class{rootDir;legacyPluginRoots;useLegacyScanApi;registryFile;moduleCacheDir;installedPlugins=new Map;loadedPlugins=new Map;constructor(e=r(),t=[]){let n=typeof e==`string`?e:r();this.useLegacyScanApi=typeof e!=`string`,this.rootDir=n,this.registryFile=p.join(n,`plugins.json`),this.moduleCacheDir=p.join(n,`modules`),this.legacyPluginRoots=t.length>0?t:process.env.JSHOOKMCP_PLUGIN_ROOT?[process.env.JSHOOKMCP_PLUGIN_ROOT]:[],!this.useLegacyScanApi&&this.initializeFromDisk()}async register(e){let t=x(e.id||e.name),n={id:t,name:e.name,version:e.version,entry:e.entry,permissions:e.permissions?[...e.permissions]:[],status:this.loadedPlugins.has(t)?`loaded`:`unloaded`};return this.installedPlugins.set(t,n),await this.persist(),t}async unregister(e){await this.unloadPlugin(e),this.installedPlugins.delete(e),await this.persist()}listInstalled(){return[...this.installedPlugins.values()].map(e=>({id:e.id,name:e.name,version:e.version,status:e.status,permissions:[...e.permissions]})).toSorted((e,t)=>e.name.localeCompare(t.name))}async loadPlugin(e){let t=this.installedPlugins.get(e);if(!t)throw Error(`Plugin not found: ${e}`);let n=this.loadedPlugins.get(e);if(n)return{manifest:this.toPublicManifest(n.manifest),exports:n.exports};let r=h(await this.resolveEntryPath(t));r.searchParams.set(`ts`,String(Date.now()));let i=await import(r.href),a=b(i)?i:{};return t.status=`loaded`,this.loadedPlugins.set(e,{manifest:t,exports:a}),await this.persist(),{manifest:this.toPublicManifest(t),exports:a}}async unloadPlugin(e){let t=this.installedPlugins.get(e);t&&(this.loadedPlugins.delete(e),t.status=`unloaded`,await this.persist())}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),l(this.moduleCacheDir)||u(this.moduleCacheDir,{recursive:!0}),!l(this.registryFile))return;let e=d(this.registryFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=S(e);t&&this.installedPlugins.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await g(this.moduleCacheDir,{recursive:!0}),await v(this.registryFile,JSON.stringify([...this.installedPlugins.values()],null,2),`utf8`)}async resolveEntryPath(e){return e.entry.startsWith(`http://`)||e.entry.startsWith(`https://`)?this.downloadRemoteModule(e.id,e.entry):e.entry.startsWith(`file://`)?m(new URL(e.entry)):p.isAbsolute(e.entry)?e.entry:p.resolve(n(),e.entry)}async downloadRemoteModule(e,t){let n=await fetch(t);if(!n.ok)throw Error(`Failed to download plugin module: ${n.status} ${n.statusText}`);let r=await n.text(),i=p.join(this.moduleCacheDir,`${x(e)}.mjs`),a=c(`sha256`).update(r).digest(`hex`);try{let e=await _(i,`utf8`);if(c(`sha256`).update(e).digest(`hex`)===a)return i}catch{}return await g(this.moduleCacheDir,{recursive:!0}),await v(i,r,`utf8`),i}toPublicManifest(e){return{id:e.id,name:e.name,version:e.version,entry:e.entry,permissions:[...e.permissions]}}listPlugins(){let e=[];for(let t of this.legacyPluginRoots){if(!l(t))continue;let n=f(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith(`.`))continue;let n=p.join(t,r.name,`package.json`);if(l(n))try{let t=JSON.parse(d(n,`utf8`)),r=this.toLegacyPluginInfo(t);r&&e.push(r)}catch{continue}}}return e}searchPlugins(e){let t=e.trim().toLowerCase();return t?this.listPlugins().filter(e=>e.name.toLowerCase().includes(t)||(e.description??``).toLowerCase().includes(t)||(e.capabilities??[]).some(e=>e.toLowerCase().includes(t))||(e.dependencies??[]).some(e=>e.toLowerCase().includes(t))):this.listPlugins()}async installPlugin(e){if(/^https:\/\/github\.com\/.+\.git$/u.test(e)||/^git@github\.com:.+\.git$/u.test(e))return{id:`git-plugin`,name:e.split(`/`).pop()?.replace(/\.git$/u,``)??`plugin`,version:`0.0.0`};if(e.includes(`://`)||e.startsWith(`git@`)||e===`invalid-url`)throw Error(`Invalid git URL`);if(e.startsWith(`/`)||e.includes(`\\`)){let t=p.join(e,`package.json`);if(!l(t))throw Error(`No package.json`);let n=JSON.parse(d(t,`utf8`)),r=this.toLegacyPluginInfo(n);if(!r)throw Error(`No package.json`);return r}for(let t of this.legacyPluginRoots){let n=p.join(t,e,`package.json`);if(!l(n))continue;let r=JSON.parse(d(n,`utf8`)),i=this.toLegacyPluginInfo(r);if(i)return i}throw Error(`Plugin not found`)}getPluginInfo(e){return this.listPlugins().find(t=>t.id===e||t.name===e)}getPluginDependencies(e){return this.getPluginInfo(e)?.dependencies??[]}async uninstallPlugin(e){}toLegacyPluginInfo(e){if(typeof e.name!=`string`)return null;let t=b(e.dependencies)?Object.keys(e.dependencies):[];return{id:x(e.name),name:e.name,version:typeof e.version==`string`?e.version:`0.0.0`,description:typeof e.description==`string`?e.description:void 0,capabilities:Array.isArray(e.capabilities)?e.capabilities.filter(e=>typeof e==`string`):void 0,dependencies:t}}};function w(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function T(e){if(!w(e))return null;let{id:t,url:n,events:r,active:i}=e;return typeof t!=`string`||typeof n!=`string`||!Array.isArray(r)||typeof i!=`boolean`?null:{id:t,url:n,events:r.filter(e=>typeof e==`string`),active:i}}var E=class{rootDir;storageFile;webhooks=new Map;constructor(e=r()){this.rootDir=e,this.storageFile=p.join(e,`webhooks.json`),this.initializeFromDisk()}async registerWebhook(e,t){new URL(e);let n={id:`webhook-${Date.now()}-${this.webhooks.size+1}`,url:e,events:[...new Set(t.filter(e=>e.trim().length>0))],active:!0};return this.webhooks.set(n.id,n),await this.persist(),n.id}async sendEvent(e,t){let n=[...this.webhooks.values()].filter(t=>t.active&&(t.events.includes(e)||t.events.includes(`*`)));for(let r of n){let n=await fetch(r.url,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:e,payload:t,timestamp:new Date().toISOString()})});if(!n.ok)throw Error(`Webhook delivery failed for ${r.url}: ${n.status} ${n.statusText}`)}}listWebhooks(){return[...this.webhooks.values()].map(e=>({id:e.id,url:e.url,events:[...e.events],active:e.active}))}registerExternalCallback(e,t){let n=this.webhooks.get(e);if(n){n.url=t;return}this.webhooks.set(e,{id:e,url:t,events:[`*`],active:!0})}initializeFromDisk(){if(l(this.rootDir)||u(this.rootDir,{recursive:!0}),!l(this.storageFile))return;let e=d(this.storageFile,`utf8`);if(!e.trim())return;let t=JSON.parse(e);if(Array.isArray(t))for(let e of t){let t=T(e);t&&this.webhooks.set(t.id,t)}}async persist(){await g(this.rootDir,{recursive:!0}),await v(this.storageFile,JSON.stringify([...this.webhooks.values()],null,2),`utf8`)}};function D(e){return{...e}}function O(){return new Date().toISOString()}var k=class extends y{maxQueueSize;commands=new Map;order=[];maxRetries;retryDelay;processTimeout;nextId=1;constructor(t={}){super(),this.maxQueueSize=typeof t.maxQueueSize==`number`?t.maxQueueSize:1e3,this.maxRetries=typeof t.maxRetries==`number`?t.maxRetries:3,this.retryDelay=typeof t.retryDelay==`number`?t.retryDelay:0,this.processTimeout=typeof t.processTimeout==`number`?t.processTimeout:e}enqueue(e){if(this.order.length>=this.maxQueueSize)throw Error(`Command queue is full (${this.maxQueueSize})`);let t=`cmd-${this.nextId}`;this.nextId+=1;let n=O(),r={id:t,endpointId:e.endpointId,event:e.event,payload:e.payload,status:`pending`,retries:0,createdAt:n,updatedAt:n};return this.commands.set(t,r),this.order.push(t),this.emit(`enqueued`,D(r)),t}dequeue(e){if(!e){let e=this.getCommandsByFilter({status:`pending`})[0];return e?D(e):void 0}return this.getCommandsByFilter(e).map(D)}getStatus(e){let t=this.commands.get(e);return t?t.status===`processed`?`completed`:t.status:`failed`}retry(e){let t=this.commands.get(e);if(!t)throw Error(`Command ${e} not found`);if(t.status!==`failed`)throw Error(`Command ${e} is not in failed state`);t.status=`pending`,t.retries=0,t.lastError=void 0,t.updatedAt=O()}getCommand(e){return this.commands.get(e)}getCommandsByFilter(e){let t=e.status===`completed`?`processed`:e.status,n=[];for(let r of this.order){let i=this.commands.get(r);i&&(t&&i.status!==t||e.endpointId&&i.endpointId!==e.endpointId||n.push(i))}return n}updateStatus(e,t,n){let r=this.commands.get(e);if(!r)throw Error(`Command ${e} not found`);return r.status=t,r.updatedAt=O(),r.lastError=n,r}},A=class extends k{async process(e,t){let n=this.getCommand(e);if(!n)throw Error(`Command ${e} not found`);if(n.status===`processed`)throw Error(`Command ${e} already processed`);if(n.status===`failed`)throw Error(`Command ${e} already processed with failure`);if(n.status===`processing`)throw Error(`Command ${e} is already processing`);this.updateStatus(e,`processing`);let r=`processed`,i;try{await Promise.race([Promise.resolve(t(D(n))),new Promise((e,t)=>{setTimeout(()=>{t(Error(`Process timeout`))},this.processTimeout)})])}catch(e){i=e instanceof Error?e.message:String(e),r=n.retries+1>=this.maxRetries?`failed`:`pending`}if(i!==void 0&&this.retryDelay>0&&setTimeout(()=>{},this.retryDelay),r===`processed`){let t=this.updateStatus(e,`processed`);this.emit(`processed`,D(t))}else if(r===`pending`){n.retries+=1;let t=this.updateStatus(e,`pending`,i);throw this.emit(`retried`,D(t)),Error(i===void 0?`retry`:i)}else{let t=this.updateStatus(e,`failed`,i);throw this.emit(`failed`,D(t)),Error(i===void 0?`failed`:i)}}async retry(e){super.retry(e)}exportState(){let e=[];for(let t of this.order){let n=this.commands.get(t);n&&e.push(D(n))}return e}importState(e){this.commands.clear(),this.order.length=0;let t=0;for(let n of e){let e=D(n);this.commands.set(e.id,e),this.order.push(e.id);let r=/^cmd-(\d+)$/.exec(e.id);if(r&&r[1]){let e=parseInt(r[1],10);e>t&&(t=e)}}t>0&&(this.nextId=t+1)}};function j(e){return e===`tool_called`||e===`domain_activated`||e===`evidence_added`||e===`workflow_completed`}function M(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{rawBody:e}}}var N=class extends y{endpoints=new Map;eventHandlers=new Map;port;commandQueue;stats={eventsRegistered:0,webhooksSent:0};server;nextEndpointId=1;constructor(e={}){super(),this.port=typeof e.port==`number`?e.port:18789,this.commandQueue=e.commandQueue}registerEndpoint(e){let t=`ep-${this.nextEndpointId}`;return this.nextEndpointId+=1,this.endpoints.set(t,{id:t,path:e.path,method:e.method??`POST`,secret:e.secret}),this.emit(`endpointRegistered`,t),t}removeEndpoint(e){if(!this.endpoints.delete(e))throw Error(`Endpoint ${e} not found`);this.emit(`endpointRemoved`,e)}listEndpoints(){return[...this.endpoints.values()].map(e=>({...e}))}getPort(){return this.port}isRunning(){return this.server!==void 0}registerEvent(e,t){let n=this.eventHandlers.get(e)??[];n.push(t),this.eventHandlers.set(e,n),this.stats.eventsRegistered+=1}start(){if(this.server)throw Error(`Webhook server already started`);this.server=s.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.listen(this.port),this.emit(`started`,this.port)}async stop(){if(!this.server)return;let e=this.server;this.server=void 0,await new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})}),this.emit(`stopped`)}async sendWebhook(e,t,n){await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({event:t,payload:n})}),this.stats.webhooksSent+=1,this.stats.lastSentAt=new Date().toISOString()}getStats(){return{...this.stats}}async handleRequest(e,t){let n=e.method??`GET`,r=e.url??`/`,i=[...this.endpoints.values()].find(e=>e.path===r&&e.method===n);if(!i){t.statusCode=404,t.end(`not found`);return}if(i.secret&&e.headers[`x-webhook-secret`]!==i.secret){t.statusCode=401,t.end(`unauthorized`);return}let a=[];await new Promise((t,n)=>{e.setEncoding(`utf8`),e.on(`data`,e=>{a.push(e)}),e.on(`end`,()=>{t()}),e.on(`error`,e=>{n(e)})});let o=M(a.join(``));this.commandQueue&&this.commandQueue.enqueue({endpointId:i.id,payload:o}),o&&typeof o==`object`&&`event`in o&&typeof o.event==`string`&&await this.invokeEventHandlers(o.event,o),t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!0,endpointId:i.id}))}async invokeEventHandlers(e,t){if(!j(e))return;let n=this.eventHandlers.get(e)??[];for(let e of n)await Promise.resolve(e(t))}},P=class extends N{};function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e){return typeof e==`function`}var L=class{registry;webhook;webhookServer;commandQueue;constructor(e,t){this.registry=e,this.webhook=t}async handleListInstalled(){return t({success:!0,plugins:this.getRegistry().listInstalled()})}async handleExecuteInContext(e){let n=o(e,`pluginId`),r=o(e,`contextName`),i=a(e,`args`)??{},{manifest:s,exports:c}=await this.getRegistry().loadPlugin(n),l=this.resolveContext(c,r);if(!l)throw Error(`Context "${r}" was not found in plugin "${n}"`);let u=await Promise.resolve(l(i));return this.emitEvent(`extension.executed`,{pluginId:n,contextName:r}),t({success:!0,manifest:s,contextName:r,result:u})}async handleReload(e){let n=o(e,`pluginId`);await this.getRegistry().unloadPlugin(n);let r=await this.getRegistry().loadPlugin(n);return this.emitEvent(`extension.reloaded`,{pluginId:n}),t({success:!0,pluginId:n,manifest:r.manifest,exportedKeys:Object.keys(r.exports).toSorted()})}async handleUninstall(e){let n=o(e,`pluginId`);return await this.getRegistry().unregister(n),this.emitEvent(`extension.uninstalled`,{pluginId:n}),t({success:!0,pluginId:n})}async handleWebhookCreate(e){let n=o(e,`name`),r=o(e,`path`),a=i(e,`secret`),s=Array.isArray(e.events)?e.events.filter(e=>typeof e==`string`):[],c=this.getWebhookServer();c.isRunning()||c.start();let l=c.registerEndpoint({path:r,method:`POST`,secret:a??void 0}),u=this.getWebhook(),d=`http://localhost:${c.getPort()}${r}`;return u.registerExternalCallback(l,d),t({success:!0,endpointId:l,url:d,name:n,events:s})}async handleWebhookList(){let e=this.getWebhookServer();return t({success:!0,endpoints:e.listEndpoints(),port:e.getPort(),running:e.isRunning()})}async handleWebhookDelete(e){let n=o(e,`endpointId`),r=this.getWebhookServer();try{r.removeEndpoint(n)}catch(e){throw Error(`GRACEFUL: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return t({success:!0,endpointId:n})}async handleWebhookCommands(e){let n=o(e,`endpointId`),r=i(e,`status`),s=a(e,`command`);if(s)return t({success:!0,commandId:this.getCommandQueue().enqueue({endpointId:n,payload:s}),status:`pending`});let c=this.getCommandQueue(),l={endpointId:n};r&&(l.status=r);let u=c.dequeue(l);return t({success:!0,endpointId:n,commands:u,count:Array.isArray(u)?u.length:+!!u})}getWebhookServer(){return this.webhookServer||=(this.commandQueue=new A,new P({commandQueue:this.commandQueue})),this.webhookServer}async startWebhookServer(){let e=this.getWebhookServer();e.isRunning()||e.start()}async stopWebhookServer(){this.webhookServer&&(await this.webhookServer.stop(),this.webhookServer=void 0,this.commandQueue=void 0)}getRegistry(){return this.registry||=new C,this.registry}getWebhook(){return this.webhook||=new E,this.webhook}getCommandQueue(){return this.commandQueue||=new A,this.commandQueue}emitEvent(e,t){this.getWebhook().sendEvent(e,t).catch(()=>void 0)}resolveContext(e,t){let n=e[t];if(I(n))return n;let r=e.default;if(t===`default`&&I(r))return r;if(F(r)){let e=r[t];if(I(e))return e}return null}async handleWebhookDispatch(e){let n=i(e,`action`);switch(n){case`create`:return this.handleWebhookCreate(e);case`list`:return this.handleWebhookList();case`delete`:return this.handleWebhookDelete(e);case`commands`:return this.handleWebhookCommands(e);default:return t({error:`Invalid action: "${n}". Expected one of: create, list, delete, commands`})}}};export{L as ExtensionRegistryHandlers};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t}from"./artifacts-
|
|
1
|
+
import{t as e}from"./ToolError-DWU_z7gp.mjs";import{i as t}from"./artifacts-CkodUM4j.mjs";import{t as n}from"./PrerequisiteError-BjCQA-gK.mjs";import{t as r}from"./TraceRecorder-BiJWBXHX.mjs";import{n as i}from"./parse-args-Bw413PlW.mjs";import{t as a}from"./ResponseBuilder-BfWP-uaT.mjs";import{readFile as o,writeFile as s}from"node:fs/promises";const c=(e,t)=>typeof e==`boolean`?e:t,l=(e,t)=>{let n=typeof e==`number`&&Number.isFinite(e)?e:t.defaultValue;return t.integer&&(n=Math.trunc(n)),typeof t.min==`number`&&(n=Math.max(t.min,n)),typeof t.max==`number`&&(n=Math.min(t.max,n)),n},u=(e,t)=>{let n={};for(let r=0;r<e.length;r++)n[e[r]]=t[r];return n},d=e=>{try{return JSON.parse(e)}catch{return e}},f=e=>({timestamp:e.timestamp,wallTime:e.wallTime??null,monotonicTime:e.monotonicTime??null,category:e.category,eventType:e.eventType,data:typeof e.data==`string`?d(e.data):e.data,scriptId:e.scriptId,lineNumber:e.lineNumber,requestId:e.requestId??null,sequence:e.sequence??null}),p=e=>({requestId:e.requestId,url:e.url,method:e.method,resourceType:e.resourceType,requestHeaders:d(e.requestHeaders),requestPostDataPresent:e.requestPostData!==null,status:e.status,statusText:e.statusText,responseHeaders:d(e.responseHeaders),mimeType:e.mimeType,protocol:e.protocol,remoteAddress:e.remoteAddress,fromDiskCache:e.fromDiskCache,fromServiceWorker:e.fromServiceWorker,startedWallTime:e.startedWallTime,responseWallTime:e.responseWallTime,finishedWallTime:e.finishedWallTime,startedMonotonicTime:e.startedMonotonicTime,responseMonotonicTime:e.responseMonotonicTime,finishedMonotonicTime:e.finishedMonotonicTime,encodedDataLength:e.encodedDataLength,receivedDataLength:e.receivedDataLength,receivedEncodedDataLength:e.receivedEncodedDataLength,chunkCount:e.chunkCount,streamingEnabled:e.streamingEnabled,streamingSupported:e.streamingSupported,streamingError:e.streamingError,bodyCaptureState:e.bodyCaptureState,bodySize:e.bodySize,bodyBase64Encoded:e.bodyBase64Encoded,bodyTruncated:e.bodyTruncated,bodyArtifactPath:e.bodyArtifactPath,bodyError:e.bodyError,failed:e.failed,errorText:e.errorText}),m=e=>({sequence:e.sequence,timestamp:e.timestamp,monotonicTime:e.monotonicTime,dataLength:e.dataLength,encodedDataLength:e.encodedDataLength,hasChunkData:e.chunkData!==null,chunkPreview:e.chunkData===null?null:`${e.chunkData.slice(0,120)}${e.chunkData.length>120?`...`:``}`,chunkIsBase64:e.chunkIsBase64}),h=async(e,t)=>{if(e.bodyCaptureState===`none`&&e.bodyInline===null&&e.bodyArtifactPath===null)return null;let n=await y(e);if(n===null)return{state:e.bodyCaptureState,error:e.bodyError??`Body content is not available`,truncated:e.bodyTruncated};let r=e.bodySize??n.length;return t.returnSummary||r>t.maxBodyBytes?{state:e.bodyCaptureState,summary:{size:r,sizeKB:(r/1024).toFixed(2),base64Encoded:e.bodyBase64Encoded,preview:`${n.slice(0,500)}${n.length>500?`...`:``}`,truncated:e.bodyTruncated||r>t.maxBodyBytes,reason:t.returnSummary?`Summary mode enabled`:`Response too large (${(r/1024).toFixed(2)} KB > ${(t.maxBodyBytes/1024).toFixed(2)} KB)`}}:{state:e.bodyCaptureState,body:n,base64Encoded:e.bodyBase64Encoded,size:r,sizeKB:(r/1024).toFixed(2),truncated:e.bodyTruncated,...e.bodyError?{warning:e.bodyError}:{}}},g=(e,t,n,r)=>e.query(`
|
|
2
2
|
SELECT
|
|
3
3
|
timestamp,
|
|
4
4
|
category,
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Jr as e,Yr as t,qr as n}from"./constants-BYj8Xek8.mjs";const r=[`etw`,`strace`,`dtrace`],i=3e3,a={etw:[{syscall:`NtCreateFile`,args:[`C:\\Windows\\Temp\\jshookmcp.log`,`GENERIC_READ`],returnValue:0,duration:.7},{syscall:`NtReadFile`,args:[`handle=0x90`,`buffer=4096`],returnValue:512,duration:.2},{syscall:`NtWriteFile`,args:[`handle=0x90`,`buffer=128`],returnValue:128,duration:.3},{syscall:`NtDeviceIoControlFile`,args:[`handle=0x44`,`code=0x222004`],returnValue:0,duration:1.1}],strace:[{syscall:`openat`,args:[`/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.4},{syscall:`read`,args:[`fd=3`,`count=4096`],returnValue:256,duration:.1},{syscall:`write`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=18`,`127.0.0.1:9222`],returnValue:0,duration:1.4}],dtrace:[{syscall:`open_nocancel`,args:[`/private/tmp/jshookmcp.log`,`O_RDONLY`],returnValue:3,duration:.5},{syscall:`read_nocancel`,args:[`fd=3`,`count=4096`],returnValue:320,duration:.1},{syscall:`write_nocancel`,args:[`fd=3`,`count=128`],returnValue:128,duration:.2},{syscall:`connect`,args:[`fd=21`,`127.0.0.1:9222`],returnValue:0,duration:1.3}]};function o(e){return e===`etw`?process.platform===`win32`:e===`strace`?process.platform===`linux`:e===`dtrace`?process.platform===`darwin`:!1}function s(){return process.platform===`win32`?`etw`:process.platform===`linux`?`strace`:process.platform===`darwin`?`dtrace`:`etw`}function c(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function l(e,t,n,r){let a=!1,o=setTimeout(()=>{if(!a){a=!0;try{r?.()}catch{}n(Error(`${e} did not signal readiness within ${i}ms`))}},i);return{resolveReady(e){a||(a=!0,clearTimeout(o),t(e))},rejectReady(e){a||(a=!0,clearTimeout(o),n(e))}}}function u(e,t){return t?!(t.pid!==void 0&&e.pid!==t.pid||t.name&&t.name.length>0&&!t.name.includes(e.syscall)):!0}function d(e,t,n){let r=/^(\d+)\s+([\d:.]+)\s+(\w+)\(([^)]*)\)\s*=\s*(-?\d+)(?:\s+<([\d.]+)>)?$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[5]),s=r[6]?Number(r[6]):void 0,c=a.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:t,syscall:i,args:c,returnValue:Number.isFinite(o)?o:void 0,duration:s!==void 0&&Number.isFinite(s)?s*1e3:void 0}}function f(e,t,n){let r=/^\[([^\]]+)\]\s+PID=(\d+)\s+(\w+)\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}function p(e,t,n){let r=/^\s*(\d+)\s+\d+\s+(\d+)\s+(\w+):\w+\s+(.*)$/u.exec(e.trim());if(!r)return null;let i=r[3]??`unknown`,a=r[4]??``,o=Number(r[2]),s=a.split(/\s+/u).filter(e=>e.length>0);return{timestamp:Date.now()-n,pid:Number.isFinite(o)?o:t,syscall:i,args:s}}var m=class{activeState;capturedEvents=[];lastBackend=s();subprocessError;async start(e){let t=e?.backend??s(),n=Date.now();if(!o(t))throw Error(`Backend "${t}" is not available on platform "${process.platform}"`);if(e?.simulate??process.env.JSHOOK_SIMULATE===`1`){this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}let r=e?.pid??process.pid,i;try{t===`strace`?i=await this.captureWithStrace(r,n):t===`etw`?i=await this.captureWithETW(r,n):t===`dtrace`&&(i=await this.captureWithDTrace(r,n))}catch(r){this.subprocessError=r instanceof Error?r.message:String(r),this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0},this.lastBackend=t,this.capturedEvents.length=0,this.generateSyntheticEvents();return}this.activeState={backend:t,pid:e?.pid,startedAt:n,generatedEvents:0,subprocess:i},this.lastBackend=t,this.capturedEvents.length=0,this.subprocessError=void 0}async stop(){this.activeState?.subprocess&&(this.activeState.subprocess.kill(`SIGTERM`),this.activeState.subprocess=void 0),this.activeState=void 0}async captureEvents(e){return this.activeState&&!this.activeState.subprocess&&this.generateSyntheticEvents(),this.capturedEvents.filter(t=>u(t,e)).map(c)}getStats(){let e=this.activeState?.backend??this.lastBackend,t=this.activeState?Date.now()-this.activeState.startedAt:0;return{eventsCaptured:this.capturedEvents.length,uptime:t,backend:e,subprocessActive:!!this.activeState?.subprocess,subprocessError:this.subprocessError}}getSupportedBackends(){return r.filter(e=>o(e))}isRunning(){return this.activeState!==void 0}async captureWithStrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`strace`,[`-p`,String(e),`-f`,`-e`,`trace=all`,`-t`],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`strace process`,r,i,()=>a.kill(`SIGTERM`)),s=``,c=``;a.stdout?.on(`data`,t=>{c+=t.toString(),this.processLineBuffer(c,e,`strace`)}),a.stderr?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r)if(n.length>0){let r=d(n,e,t);r&&this.capturedEvents.push(r)}}),a.on(`error`,e=>{o.rejectReady(Error(`strace process error: ${e.message}. Is strace installed?`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithETW(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`logman`,[`create`,`trace`,`JSHookETW_${e}`,`-p`,`NT Kernel Logger`,`0x10000`,`-o`,`jshook_etw_${e}.etl`,`-ets`],{stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),o=l(`ETW trace session`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=f(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t.length>0&&t.startsWith(`The command completed successfully`)}),a.on(`error`,e=>{o.rejectReady(Error(`ETW trace error: ${e.message}. Run as Administrator.`))}),a.on(`exit`,e=>{e!==0&&e!==void 0&&o.rejectReady(Error(`ETW trace session ended (code ${e}). Check permissions.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}async captureWithDTrace(e,t=this.activeState?.startedAt??Date.now()){let{spawn:n}=await import(`node:child_process`);return new Promise((r,i)=>{let a=n(`dtrace`,[`-n`,`
|
|
2
2
|
syscall:::entry
|
|
3
3
|
/pid == ${e}/
|
|
4
4
|
{
|
|
5
5
|
printf("%d %d %s:entry %s", pid, probeproc, probefunc, copyinstr(arg0));
|
|
6
6
|
}
|
|
7
|
-
`],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`dtrace process`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=p(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,()=>{}),a.on(`error`,e=>{o.rejectReady(Error(`dtrace error: ${e.message}. Run with sudo.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}generateSyntheticEvents(){if(!this.activeState)return;let e=a[this.activeState.backend];if(!e)return;let t=Date.now()-this.activeState.startedAt,n=Math.max(1,Math.min(e.length*3,Math.floor(t/150)+1)),r=this.activeState.pid??process.pid;for(;this.activeState.generatedEvents<n;){let t=e[this.activeState.generatedEvents%e.length];if(!t)break;let n=this.activeState.generatedEvents*75;this.capturedEvents.push({timestamp:n,pid:r,syscall:t.syscall,args:[...t.args],returnValue:t.returnValue,duration:t.duration}),this.activeState.generatedEvents+=1}}processLineBuffer(e,t,n){}};const h=[{syscallNames:[`NtCreateFile`,`openat`,`open_nocancel`],jsFunction:`fs.open`,baseConfidence:.8,explanation:`File open syscalls commonly originate from Node.js file-system entry points.`},{syscallNames:[`NtReadFile`,`read`,`read_nocancel`],jsFunction:`fs.readFile`,baseConfidence:.78,explanation:`Read-oriented syscalls usually map back to file or stream reads in JavaScript.`},{syscallNames:[`NtWriteFile`,`write`,`write_nocancel`],jsFunction:`fs.writeFile`,baseConfidence:.78,explanation:`Write-oriented syscalls are strongly associated with Node.js file writes.`},{syscallNames:[`NtDeviceIoControlFile`,`ioctl`],jsFunction:`child_process.spawn`,baseConfidence:.55,explanation:`Device and control syscalls are often triggered by child processes or native helpers.`},{syscallNames:[`connect`,`sendto`,`recvfrom`],jsFunction:`fetch`,baseConfidence:.7,explanation:`Socket syscalls generally indicate outbound network activity from fetch-like APIs.`}];function g(e){return h.find(t=>t.syscallNames.includes(e))}function _(e){return e<0?0:e>1?1:e}function v(e,t){return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}var y=class{map(e){let t=this.findJSFunction(e.syscall);if(!t)return null;let n=g(e.syscall);if(!n)return null;let r=n.baseConfidence;return t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&(r+=.08),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&(r+=.1),{syscall:{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration},jsFunction:t,confidence:_(r),reasoning:this.getCorrelationReason(e,t)}}findJSFunction(e){let t=g(e);return t?t.jsFunction:null}getCorrelationReason(e,t){let n=g(e.syscall),r=[];return n&&r.push(n.explanation),t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&r.push(`The syscall arguments reference module-like file extensions, which strengthens the fs correlation.`),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&r.push(`The syscall arguments look like network endpoints, which aligns with fetch or low-level HTTP clients.`),r.length===0&&r.push(`Mapped ${e.syscall} to ${t} using the default syscall-to-JS heuristic table.`),r.join(` `)}};function b(e){return typeof e==`object`&&!!e}function x(e){if(typeof e==`number`&&Number.isFinite(e))return e}function S(e){if(typeof e==`boolean`)return e}function C(e){if(typeof e==`string`)return e}function w(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(typeof n!=`string`)return;t.push(n)}return t}const T=/^[a-z][a-z0-9_]*$/;function E(e){return T.test(e)&&e.length<=64}function D(e){if(e===`etw`||e===`strace`||e===`dtrace`)return e}function O(e){if(!b(e))return;let t={},n=w(e.name),r=x(e.pid);return n&&(t.name=n),r!==void 0&&(t.pid=r),t}function k(e){if(!b(e))return!1;let t=x(e.timestamp),n=x(e.pid),r=C(e.syscall),i=w(e.args),a=e.returnValue,o=e.duration,s=a===void 0||x(a)!==void 0,c=o===void 0||x(o)!==void 0;return t!==void 0&&n!==void 0&&r!==void 0&&i!==void 0&&s&&c}function A(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function j(e){return e instanceof Error?e.message:`Unknown syscall-hook error`}var M=class{monitor;mapper;eventBus;constructor(e,t,n){this.monitor=e,this.mapper=t,this.eventBus=n}async handleSyscallStartMonitor(e){let t=D(e.backend);if(!t)return{ok:!1,error:`backend must be one of: etw, strace, dtrace`};let n=x(e.pid),r=S(e.simulate)??!1;if(e.pid!==void 0&&e.pid!==null&&(n===void 0||!Number.isInteger(n)||n<0))return{ok:!1,error:`pid must be a non-negative integer when provided`};let i=n,a=this.ensureMonitor();try{return await a.start({backend:t,pid:i,simulate:r}),this.eventBus?.emit(`syscall:trace_started`,{backend:t,pid:i,simulate:r,timestamp:new Date().toISOString()}),{ok:!0,started:!0,backend:t,pid:i,simulate:r,stats:a.getStats()}}catch(e){return{ok:!1,error:j(e),requestedBackend:t,supportedBackends:a.getSupportedBackends()}}}async handleSyscallStopMonitor(){let e=this.ensureMonitor();try{return await e.stop(),{ok:!0,stopped:!0,stats:e.getStats()}}catch(e){return{ok:!1,error:j(e)}}}async handleSyscallCaptureEvents(e){let t=this.ensureMonitor(),n=O(e.filter),r=await t.captureEvents(n);return{ok:!0,events:r,count:r.length,stats:t.getStats()}}async handleSyscallCorrelateJs(e){let t=e.syscallEvents;if(!Array.isArray(t)||!t.every(e=>k(e)))return{ok:!1,error:`syscallEvents must be an array of valid SyscallEvent objects`};let n=this.ensureMapper(),r=[],i=[];for(let e of t){let t=A(e),a=n.map(t);a?r.push(a):i.push(t)}return{ok:!0,correlations:r,matched:r.length,unmatched:i}}async handleSyscallFilter(e){let t=w(e.names);if(e.names!==void 0&&t===void 0)return{ok:!1,error:`names must be an array of strings when provided`};let n=await this.ensureMonitor().captureEvents(t&&t.length>0?{name:t}:void 0);return{ok:!0,names:t,events:n,count:n.length}}async handleSyscallGetStats(){let e=this.ensureMonitor();return{ok:!0,...e.getStats(),running:e.isRunning(),supportedBackends:e.getSupportedBackends()}}async handleSyscallEbpfTrace(r){let i=x(r.pid),a=w(r.syscalls),o=x(r.durationSec)??
|
|
7
|
+
`],{stdio:[`ignore`,`pipe`,`pipe`]}),o=l(`dtrace process`,r,i,()=>a.kill(`SIGTERM`)),s=``;a.stdout?.on(`data`,n=>{s+=n.toString();let r=s.split(/\r?\n/u);s=r.pop()??``;for(let n of r){let r=p(n,e,t);r&&this.capturedEvents.push(r)}}),a.stderr?.on(`data`,()=>{}),a.on(`error`,e=>{o.rejectReady(Error(`dtrace error: ${e.message}. Run with sudo.`))}),a.on(`spawn`,()=>{o.resolveReady(a)})})}generateSyntheticEvents(){if(!this.activeState)return;let e=a[this.activeState.backend];if(!e)return;let t=Date.now()-this.activeState.startedAt,n=Math.max(1,Math.min(e.length*3,Math.floor(t/150)+1)),r=this.activeState.pid??process.pid;for(;this.activeState.generatedEvents<n;){let t=e[this.activeState.generatedEvents%e.length];if(!t)break;let n=this.activeState.generatedEvents*75;this.capturedEvents.push({timestamp:n,pid:r,syscall:t.syscall,args:[...t.args],returnValue:t.returnValue,duration:t.duration}),this.activeState.generatedEvents+=1}}processLineBuffer(e,t,n){}};const h=[{syscallNames:[`NtCreateFile`,`openat`,`open_nocancel`],jsFunction:`fs.open`,baseConfidence:.8,explanation:`File open syscalls commonly originate from Node.js file-system entry points.`},{syscallNames:[`NtReadFile`,`read`,`read_nocancel`],jsFunction:`fs.readFile`,baseConfidence:.78,explanation:`Read-oriented syscalls usually map back to file or stream reads in JavaScript.`},{syscallNames:[`NtWriteFile`,`write`,`write_nocancel`],jsFunction:`fs.writeFile`,baseConfidence:.78,explanation:`Write-oriented syscalls are strongly associated with Node.js file writes.`},{syscallNames:[`NtDeviceIoControlFile`,`ioctl`],jsFunction:`child_process.spawn`,baseConfidence:.55,explanation:`Device and control syscalls are often triggered by child processes or native helpers.`},{syscallNames:[`connect`,`sendto`,`recvfrom`],jsFunction:`fetch`,baseConfidence:.7,explanation:`Socket syscalls generally indicate outbound network activity from fetch-like APIs.`}];function g(e){return h.find(t=>t.syscallNames.includes(e))}function _(e){return e<0?0:e>1?1:e}function v(e,t){return e.some(e=>t.some(t=>e.toLowerCase().includes(t)))}var y=class{map(e){let t=this.findJSFunction(e.syscall);if(!t)return null;let n=g(e.syscall);if(!n)return null;let r=n.baseConfidence;return t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&(r+=.08),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&(r+=.1),{syscall:{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration},jsFunction:t,confidence:_(r),reasoning:this.getCorrelationReason(e,t)}}findJSFunction(e){let t=g(e);return t?t.jsFunction:null}getCorrelationReason(e,t){let n=g(e.syscall),r=[];return n&&r.push(n.explanation),t.startsWith(`fs.`)&&v(e.args,[`.js`,`.json`,`.node`])&&r.push(`The syscall arguments reference module-like file extensions, which strengthens the fs correlation.`),t===`fetch`&&v(e.args,[`80`,`443`,`http`,`https`])&&r.push(`The syscall arguments look like network endpoints, which aligns with fetch or low-level HTTP clients.`),r.length===0&&r.push(`Mapped ${e.syscall} to ${t} using the default syscall-to-JS heuristic table.`),r.join(` `)}};function b(e){return typeof e==`object`&&!!e}function x(e){if(typeof e==`number`&&Number.isFinite(e))return e}function S(e){if(typeof e==`boolean`)return e}function C(e){if(typeof e==`string`)return e}function w(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(typeof n!=`string`)return;t.push(n)}return t}const T=/^[a-z][a-z0-9_]*$/;function E(e){return T.test(e)&&e.length<=64}function D(e){if(e===`etw`||e===`strace`||e===`dtrace`)return e}function O(e){if(!b(e))return;let t={},n=w(e.name),r=x(e.pid);return n&&(t.name=n),r!==void 0&&(t.pid=r),t}function k(e){if(!b(e))return!1;let t=x(e.timestamp),n=x(e.pid),r=C(e.syscall),i=w(e.args),a=e.returnValue,o=e.duration,s=a===void 0||x(a)!==void 0,c=o===void 0||x(o)!==void 0;return t!==void 0&&n!==void 0&&r!==void 0&&i!==void 0&&s&&c}function A(e){return{timestamp:e.timestamp,pid:e.pid,syscall:e.syscall,args:[...e.args],returnValue:e.returnValue,duration:e.duration}}function j(e){return e instanceof Error?e.message:`Unknown syscall-hook error`}var M=class{monitor;mapper;eventBus;constructor(e,t,n){this.monitor=e,this.mapper=t,this.eventBus=n}async handleSyscallStartMonitor(e){let t=D(e.backend);if(!t)return{ok:!1,error:`backend must be one of: etw, strace, dtrace`};let n=x(e.pid),r=S(e.simulate)??!1;if(e.pid!==void 0&&e.pid!==null&&(n===void 0||!Number.isInteger(n)||n<0))return{ok:!1,error:`pid must be a non-negative integer when provided`};let i=n,a=this.ensureMonitor();try{return await a.start({backend:t,pid:i,simulate:r}),this.eventBus?.emit(`syscall:trace_started`,{backend:t,pid:i,simulate:r,timestamp:new Date().toISOString()}),{ok:!0,started:!0,backend:t,pid:i,simulate:r,stats:a.getStats()}}catch(e){return{ok:!1,error:j(e),requestedBackend:t,supportedBackends:a.getSupportedBackends()}}}async handleSyscallStopMonitor(){let e=this.ensureMonitor();try{return await e.stop(),{ok:!0,stopped:!0,stats:e.getStats()}}catch(e){return{ok:!1,error:j(e)}}}async handleSyscallCaptureEvents(e){let t=this.ensureMonitor(),n=O(e.filter),r=await t.captureEvents(n);return{ok:!0,events:r,count:r.length,stats:t.getStats()}}async handleSyscallCorrelateJs(e){let t=e.syscallEvents;if(!Array.isArray(t)||!t.every(e=>k(e)))return{ok:!1,error:`syscallEvents must be an array of valid SyscallEvent objects`};let n=this.ensureMapper(),r=[],i=[];for(let e of t){let t=A(e),a=n.map(t);a?r.push(a):i.push(t)}return{ok:!0,correlations:r,matched:r.length,unmatched:i}}async handleSyscallFilter(e){let t=w(e.names);if(e.names!==void 0&&t===void 0)return{ok:!1,error:`names must be an array of strings when provided`};let n=await this.ensureMonitor().captureEvents(t&&t.length>0?{name:t}:void 0);return{ok:!0,names:t,events:n,count:n.length}}async handleSyscallGetStats(){let e=this.ensureMonitor();return{ok:!0,...e.getStats(),running:e.isRunning(),supportedBackends:e.getSupportedBackends()}}async handleSyscallEbpfTrace(r){let i=x(r.pid),a=w(r.syscalls),o=x(r.durationSec)??n,s=S(r.simulate)??!1;if(r.pid!==void 0&&r.pid!==null&&(i===void 0||!Number.isInteger(i)||i<0))return{ok:!1,error:`pid must be a non-negative integer (0 for all processes)`};let c=i??0;if(o<t||o>e)return{ok:!1,error:`durationSec must be between ${t} and ${e}`};if(a?.length){let e=a.filter(e=>!E(e));if(e.length>0)return{ok:!1,error:`Invalid syscall names (must be lowercase alphanumeric with underscores): ${e.join(`, `)}`}}if(s){let e=[],t=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`],n=o*50;for(let r=0;r<20;r++)e.push({timestamp:r*n,pid:c||1234,syscall:t[r%t.length]??`read`,args:[`fd=${r%5+3}`,`count=${(r+1)*64}`],returnValue:r%3==0?-1:(r+1)*64,duration:Math.random()*2});return{ok:!0,backend:`ebpf`,simulated:!0,pid:c,durationSec:o,events:e,count:e.length,syscallsTraced:t}}let l=a?.length?a:[`read`,`write`,`openat`,`close`,`fstat`,`mmap`,`mprotect`,`munmap`,`brk`,`ioctl`,`connect`,`sendto`,`recvfrom`,`clone`,`execve`],u=c>0?`/pid == ${c}/`:``,d=l.map(e=>`tracepoint:syscalls:sys_enter_${e}`).join(`, `),f=l.map(e=>`tracepoint:syscalls:sys_exit_${e}`).join(`, `),p=`#!/usr/bin/env bpftrace
|
|
8
8
|
// Generated by jshookmcp syscall_ebpf_trace
|
|
9
9
|
// Target PID: ${c||`all`} | Duration: ${o}s | Syscalls: ${l.join(`, `)}
|
|
10
10
|
|