@jshookmcp/jshook 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +36 -5
  2. package/README.zh.md +36 -5
  3. package/dist/{AntiCheatDetector-S8VRj-dD.mjs → AntiCheatDetector-BNk-EoBt.mjs} +3 -3
  4. package/dist/{CodeInjector-4Z3ngPoX.mjs → CodeInjector-Cq8q01kp.mjs} +5 -5
  5. package/dist/ConsoleMonitor-CPVQW1Y-.mjs +2201 -0
  6. package/dist/{DarwinAPI-B8hg_yhz.mjs → DarwinAPI-BNPxu0RH.mjs} +1 -1
  7. package/dist/DetailedDataManager-BQQcxh64.mjs +217 -0
  8. package/dist/EventBus-DgPmwpeu.mjs +141 -0
  9. package/dist/EvidenceGraphBridge-SFesNera.mjs +153 -0
  10. package/dist/{ExtensionManager-CZ6IveoV.mjs → ExtensionManager-CWYgw0YW.mjs} +13 -6
  11. package/dist/{FingerprintManager-BVxFJL2-.mjs → FingerprintManager-gzWtkKuf.mjs} +1 -1
  12. package/dist/{HardwareBreakpoint-DK1yjWkV.mjs → HardwareBreakpoint-B9gZCdFP.mjs} +3 -3
  13. package/dist/{HeapAnalyzer-CEbo10xU.mjs → HeapAnalyzer-BLDH0dCv.mjs} +4 -4
  14. package/dist/HookGeneratorBuilders.core.generators.storage-CtcdK78Q.mjs +639 -0
  15. package/dist/InstrumentationSession-CvPC7Jwy.mjs +244 -0
  16. package/dist/{MemoryController-DdtnBdD4.mjs → MemoryController-CbVdCIJF.mjs} +3 -3
  17. package/dist/{MemoryScanSession-RMixN3bX.mjs → MemoryScanSession-BsDZbLYm.mjs} +81 -78
  18. package/dist/{MemoryScanner-QjK4ld0B.mjs → MemoryScanner-Bcpml6II.mjs} +44 -18
  19. package/dist/{NativeMemoryManager.impl-CB6gJ0NM.mjs → NativeMemoryManager.impl-dZtA1ZGn.mjs} +14 -53
  20. package/dist/{NativeMemoryManager.utils-BML4q1ry.mjs → NativeMemoryManager.utils-B-FjA2mJ.mjs} +1 -1
  21. package/dist/{PEAnalyzer-CK0xe0Fs.mjs → PEAnalyzer-D1lzJ_VG.mjs} +2 -2
  22. package/dist/PageController-Bqm2kZ_X.mjs +417 -0
  23. package/dist/{PointerChainEngine-Cd73qu5b.mjs → PointerChainEngine-BOhyVsjx.mjs} +4 -4
  24. package/dist/PrerequisiteError-Dl33Svkz.mjs +20 -0
  25. package/dist/ResponseBuilder-D3iFYx2N.mjs +143 -0
  26. package/dist/ReverseEvidenceGraph-Dlsk94LC.mjs +269 -0
  27. package/dist/ScriptManager-aHHq0X7U.mjs +3000 -0
  28. package/dist/{Speedhack-CeF0XmEz.mjs → Speedhack-CqdIFlQl.mjs} +2 -2
  29. package/dist/{StructureAnalyzer-D4GkMduU.mjs → StructureAnalyzer-DhFaPvRO.mjs} +3 -3
  30. package/dist/ToolCatalog-C0JGZoOm.mjs +582 -0
  31. package/dist/ToolError-jh9whhMd.mjs +15 -0
  32. package/dist/ToolProbe-oC7aPrkv.mjs +45 -0
  33. package/dist/ToolRegistry-BjaF4oNz.mjs +131 -0
  34. package/dist/ToolRouter.policy-BWV67ZK-.mjs +304 -0
  35. package/dist/TraceRecorder-DgxyVbdQ.mjs +519 -0
  36. package/dist/{Win32API-Bc0QnQsN.mjs → Win32API-CePkipZY.mjs} +1 -1
  37. package/dist/{Win32Debug-DUHt9XUn.mjs → Win32Debug-BvKs-gxc.mjs} +2 -2
  38. package/dist/WorkflowEngine-CuvkZtWu.mjs +598 -0
  39. package/dist/analysis-CL9uACt9.mjs +463 -0
  40. package/dist/antidebug-CqDTB_uk.mjs +1081 -0
  41. package/dist/artifactRetention-CFEprwPw.mjs +591 -0
  42. package/dist/artifacts-Bk2-_uPq.mjs +59 -0
  43. package/dist/betterSqlite3-0pqusHHH.mjs +74 -0
  44. package/dist/binary-instrument-CXfpx6fT.mjs +979 -0
  45. package/dist/bind-helpers-xFfRF-qm.mjs +22 -0
  46. package/dist/boringssl-inspector-BH2D3VKc.mjs +180 -0
  47. package/dist/browser-BpOr5PEx.mjs +4082 -0
  48. package/dist/concurrency-Bt0yv1kJ.mjs +41 -0
  49. package/dist/{constants-CCvsN80K.mjs → constants-B0OANIBL.mjs} +88 -46
  50. package/dist/coordination-qUbyF8KU.mjs +259 -0
  51. package/dist/debugger-gnKxRSN0.mjs +1271 -0
  52. package/dist/definitions-6M-eejaT.mjs +53 -0
  53. package/dist/definitions-B18eyf0B.mjs +18 -0
  54. package/dist/definitions-B3QdlrHv.mjs +34 -0
  55. package/dist/definitions-B4rAvHNZ.mjs +63 -0
  56. package/dist/definitions-BB_4jnmy.mjs +37 -0
  57. package/dist/definitions-BMfYXoNC.mjs +43 -0
  58. package/dist/definitions-Beid2EB3.mjs +27 -0
  59. package/dist/definitions-C1UvM5Iy.mjs +126 -0
  60. package/dist/definitions-CXEI7QC72.mjs +216 -0
  61. package/dist/definitions-C_4r7Fo-2.mjs +14 -0
  62. package/dist/definitions-CkFDALoa.mjs +26 -0
  63. package/dist/definitions-Cke7zEb8.mjs +94 -0
  64. package/dist/definitions-ClJLzsJQ.mjs +25 -0
  65. package/dist/definitions-Cq-zroAU.mjs +28 -0
  66. package/dist/definitions-Cy3Sl6gV.mjs +34 -0
  67. package/dist/definitions-D3VsGcvz.mjs +47 -0
  68. package/dist/definitions-DVGfrn7y.mjs +96 -0
  69. package/dist/definitions-LKpC3-nL.mjs +9 -0
  70. package/dist/definitions-bAhHQJq9.mjs +359 -0
  71. package/dist/encoding-Bvz5jLRv.mjs +1065 -0
  72. package/dist/evidence-graph-bridge-C_fv9PuC.mjs +135 -0
  73. package/dist/{factory-CibqTNC8.mjs → factory-DxlGh9Xf.mjs} +37 -52
  74. package/dist/graphql-DYWzJ29s.mjs +1026 -0
  75. package/dist/handlers-9sAbfIg-.mjs +2552 -0
  76. package/dist/handlers-Bl8zkwz1.mjs +2716 -0
  77. package/dist/handlers-C67ktuRN.mjs +710 -0
  78. package/dist/handlers-C87g8oCe.mjs +276 -0
  79. package/dist/handlers-CTsDAO6p.mjs +681 -0
  80. package/dist/handlers-Cgyg6c0U.mjs +645 -0
  81. package/dist/handlers-D6j6yka7.mjs +2124 -0
  82. package/dist/handlers-DdFzXLvF.mjs +446 -0
  83. package/dist/handlers-DeLOCd5m.mjs +799 -0
  84. package/dist/handlers-DlCJN4Td.mjs +757 -0
  85. package/dist/handlers-DxGIq15_2.mjs +917 -0
  86. package/dist/handlers-U6L4xhuF.mjs +585 -0
  87. package/dist/handlers-tB9Mp9ZK.mjs +84 -0
  88. package/dist/handlers-tiy7EIBp.mjs +572 -0
  89. package/dist/handlers.impl-DS0d9fUw.mjs +761 -0
  90. package/dist/hooks-CzCWByww.mjs +898 -0
  91. package/dist/index.mjs +384 -155
  92. package/dist/{logger-BmWzC2lM.mjs → logger-Dh_xb7_2.mjs} +14 -6
  93. package/dist/maintenance-P7ePRXQC.mjs +830 -0
  94. package/dist/manifest-2ToTpjv8.mjs +106 -0
  95. package/dist/manifest-3g71z6Bg.mjs +79 -0
  96. package/dist/manifest-82baTv4U.mjs +45 -0
  97. package/dist/manifest-B3QVVeBS.mjs +82 -0
  98. package/dist/manifest-BB2J8IMJ.mjs +149 -0
  99. package/dist/manifest-BKbgbSiY.mjs +60 -0
  100. package/dist/manifest-Bcf-TJzH.mjs +848 -0
  101. package/dist/manifest-BmtZzQiQ2.mjs +45 -0
  102. package/dist/manifest-Bnd7kqEY.mjs +55 -0
  103. package/dist/manifest-BqQX6OQC2.mjs +65 -0
  104. package/dist/manifest-BqrQ4Tpj.mjs +81 -0
  105. package/dist/manifest-Br4RPFt5.mjs +370 -0
  106. package/dist/manifest-C5qDjysN.mjs +107 -0
  107. package/dist/manifest-C9RT5nk32.mjs +34 -0
  108. package/dist/manifest-CAhOuvSl.mjs +204 -0
  109. package/dist/manifest-CBYWCUBJ.mjs +51 -0
  110. package/dist/manifest-CFADCRa1.mjs +37 -0
  111. package/dist/manifest-CQVhavRF.mjs +114 -0
  112. package/dist/manifest-CT7zZBV1.mjs +48 -0
  113. package/dist/manifest-CV12bcrF.mjs +121 -0
  114. package/dist/manifest-CXsRWjjI.mjs +224 -0
  115. package/dist/manifest-CZLUCfG02.mjs +95 -0
  116. package/dist/manifest-D6phHKFd.mjs +131 -0
  117. package/dist/manifest-DCyjf4n2.mjs +294 -0
  118. package/dist/manifest-DHsnKgP6.mjs +60 -0
  119. package/dist/manifest-Df_dliIe.mjs +55 -0
  120. package/dist/manifest-Dh8WBmEW.mjs +129 -0
  121. package/dist/manifest-DhKRAT8_.mjs +92 -0
  122. package/dist/manifest-DlpTj4ic2.mjs +193 -0
  123. package/dist/manifest-DrbmZcFl2.mjs +253 -0
  124. package/dist/manifest-DuwHjUa5.mjs +70 -0
  125. package/dist/manifest-DzwvxPJX.mjs +38 -0
  126. package/dist/manifest-NXctwWQq.mjs +68 -0
  127. package/dist/manifest-Sc_0JQ13.mjs +418 -0
  128. package/dist/manifest-gZ4s_UtG.mjs +96 -0
  129. package/dist/manifest-qSleDqdO.mjs +1023 -0
  130. package/dist/modules-C184v-S9.mjs +11365 -0
  131. package/dist/mojo-ipc-B_H61Afw.mjs +525 -0
  132. package/dist/network-671Cw6hV.mjs +3346 -0
  133. package/dist/{artifacts-BbdOMET5.mjs → outputPaths-B1uGmrWZ.mjs} +219 -212
  134. package/dist/parse-args-BlRjqlkL.mjs +39 -0
  135. package/dist/platform-WmNn8Sxb.mjs +2070 -0
  136. package/dist/process-QcbIy5Zq.mjs +1401 -0
  137. package/dist/proxy-DqNs0bAd.mjs +170 -0
  138. package/dist/registry-D-6e18lB.mjs +34 -0
  139. package/dist/response-BQVP-xUn.mjs +28 -0
  140. package/dist/server/plugin-api.mjs +2 -2
  141. package/dist/shared-state-board-DV-dpHFJ.mjs +586 -0
  142. package/dist/sourcemap-Dq8ez8vS.mjs +650 -0
  143. package/dist/ssrf-policy-ZaUfvhq7.mjs +166 -0
  144. package/dist/streaming-BUQ0VJsg.mjs +725 -0
  145. package/dist/tool-builder-DCbIC5Eo.mjs +186 -0
  146. package/dist/transform-CiYJfNX0.mjs +1007 -0
  147. package/dist/types-Bx92KJfT.mjs +4 -0
  148. package/dist/wasm-DQTnHDs4.mjs +531 -0
  149. package/dist/workflow-f3xJOcjx.mjs +725 -0
  150. package/package.json +48 -78
  151. package/dist/ExtensionManager-DqUSOamB.mjs +0 -2
  152. package/dist/ToolCatalog-CnwmMIw3.mjs +0 -61483
  153. package/dist/{CacheAdapters-CzFNpD9a.mjs → CacheAdapters-CDe5WPSV.mjs} +0 -0
  154. package/dist/{StealthVerifier-BzBCFiwx.mjs → StealthVerifier-Bo4T3bz8.mjs} +0 -0
  155. package/dist/{VersionDetector-CNXcvD46.mjs → VersionDetector-CwVLVdDM.mjs} +0 -0
  156. package/dist/{formatAddress-ChCSIRWT.mjs → formatAddress-DVkj9kpI.mjs} +0 -0
  157. package/dist/{types-BBjOqye-.mjs → types-CPhOReNX.mjs} +1 -1
@@ -0,0 +1,650 @@
1
+ import { tr as SOURCEMAP_EXT_TIMEOUT_MS } from "./constants-B0OANIBL.mjs";
2
+ import { i as resolveArtifactPath } from "./artifacts-Bk2-_uPq.mjs";
3
+ import { s as evaluateWithTimeout } from "./PageController-Bqm2kZ_X.mjs";
4
+ import "./definitions-LKpC3-nL.mjs";
5
+ import { dirname, resolve } from "node:path";
6
+ import { mkdir, writeFile } from "node:fs/promises";
7
+ //#region src/server/domains/sourcemap/handlers/shared.ts
8
+ const BASE64_DECODE_MAP = new Map(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((char, index) => [char, index]));
9
+ function fromVlqSigned(value) {
10
+ const isNegative = (value & 1) === 1;
11
+ const shifted = value >> 1;
12
+ return isNegative ? -shifted : shifted;
13
+ }
14
+ function decodeVlqSegment(segment) {
15
+ const values = [];
16
+ let index = 0;
17
+ while (index < segment.length) {
18
+ let result = 0;
19
+ let shift = 0;
20
+ let continuation = true;
21
+ while (continuation) {
22
+ const char = segment.charAt(index);
23
+ if (!char) throw new Error(`Unexpected end of VLQ segment: "${segment}"`);
24
+ index += 1;
25
+ const digit = BASE64_DECODE_MAP.get(char);
26
+ if (digit === void 0) throw new Error(`Invalid VLQ base64 char "${char}" in segment "${segment}"`);
27
+ continuation = (digit & 32) !== 0;
28
+ const digitValue = digit & 31;
29
+ result += digitValue << shift;
30
+ shift += 5;
31
+ }
32
+ values.push(fromVlqSigned(result));
33
+ }
34
+ return values;
35
+ }
36
+ function decodeMappings(mappings) {
37
+ if (!mappings) return [];
38
+ const decoded = [];
39
+ let previousSource = 0;
40
+ let previousOriginalLine = 0;
41
+ let previousOriginalColumn = 0;
42
+ let previousName = 0;
43
+ const lines = mappings.split(";");
44
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
45
+ const line = lines[lineIndex] ?? "";
46
+ let generatedColumn = 0;
47
+ if (!line) continue;
48
+ const segments = line.split(",");
49
+ for (const segment of segments) {
50
+ if (!segment) continue;
51
+ const values = decodeVlqSegment(segment);
52
+ const generatedDelta = values[0];
53
+ if (generatedDelta === void 0) continue;
54
+ generatedColumn += generatedDelta;
55
+ const mapping = {
56
+ generatedLine: lineIndex + 1,
57
+ generatedColumn
58
+ };
59
+ if (values.length >= 4) {
60
+ previousSource += values[1] ?? 0;
61
+ previousOriginalLine += values[2] ?? 0;
62
+ previousOriginalColumn += values[3] ?? 0;
63
+ mapping.sourceIndex = previousSource;
64
+ mapping.originalLine = previousOriginalLine + 1;
65
+ mapping.originalColumn = previousOriginalColumn;
66
+ if (values.length >= 5) {
67
+ previousName += values[4] ?? 0;
68
+ mapping.nameIndex = previousName;
69
+ }
70
+ }
71
+ decoded.push(mapping);
72
+ }
73
+ }
74
+ return decoded;
75
+ }
76
+ function countMappingsStats(mappings) {
77
+ if (!mappings) return {
78
+ mappingsCount: 0,
79
+ segmentCount: 0
80
+ };
81
+ let mappingsCount = 0;
82
+ let segmentCount = 0;
83
+ let inNonEmptyLine = false;
84
+ for (let i = 0; i < mappings.length; i++) {
85
+ const ch = mappings[i];
86
+ if (ch === ";") {
87
+ if (inNonEmptyLine) mappingsCount++;
88
+ inNonEmptyLine = false;
89
+ } else if (ch === ",") segmentCount++;
90
+ else if (!inNonEmptyLine) {
91
+ inNonEmptyLine = true;
92
+ segmentCount++;
93
+ }
94
+ }
95
+ if (inNonEmptyLine) mappingsCount++;
96
+ return {
97
+ mappingsCount,
98
+ segmentCount
99
+ };
100
+ }
101
+ function json(payload) {
102
+ return { content: [{
103
+ type: "text",
104
+ text: JSON.stringify(payload, null, 2)
105
+ }] };
106
+ }
107
+ function fail(tool, error) {
108
+ return json({
109
+ success: false,
110
+ tool,
111
+ error: error instanceof Error ? error.message : String(error)
112
+ });
113
+ }
114
+ function asRecord(value) {
115
+ return typeof value === "object" && value !== null ? value : {};
116
+ }
117
+ function asString(value) {
118
+ return typeof value === "string" ? value : void 0;
119
+ }
120
+ function hasProtocol(value) {
121
+ return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);
122
+ }
123
+ function parseBooleanArg(value, defaultValue) {
124
+ return typeof value === "boolean" ? value : defaultValue;
125
+ }
126
+ function requiredStringArg(value, fieldName) {
127
+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${fieldName} is required`);
128
+ return value.trim();
129
+ }
130
+ function optionalStringArg(value) {
131
+ if (typeof value !== "string") return void 0;
132
+ const trimmed = value.trim();
133
+ return trimmed.length > 0 ? trimmed : void 0;
134
+ }
135
+ async function safeDetach(session) {
136
+ if (!session.detach) return;
137
+ try {
138
+ await session.detach();
139
+ } catch {}
140
+ }
141
+ async function trySend(session, method, params) {
142
+ try {
143
+ await session.send(method, params);
144
+ } catch {}
145
+ }
146
+ async function delay(ms) {
147
+ await new Promise((r) => setTimeout(() => r(), ms));
148
+ }
149
+ //#endregion
150
+ //#region src/server/domains/sourcemap/handlers/extension-handlers.ts
151
+ /**
152
+ * Extension-related sub-handler for sourcemap domain.
153
+ */
154
+ var ExtensionHandlers = class {
155
+ state;
156
+ constructor(state) {
157
+ this.state = state;
158
+ }
159
+ async handleExtensionListInstalled(_args) {
160
+ const session = await (await this.state.collector.getActivePage()).createCDPSession();
161
+ try {
162
+ return json((await this.getExtensionTargets(session)).map((target) => ({
163
+ extensionId: target.extensionId,
164
+ name: target.name,
165
+ type: target.type,
166
+ url: target.url
167
+ })));
168
+ } catch (error) {
169
+ return fail("extension_list_installed", error);
170
+ } finally {
171
+ await safeDetach(session);
172
+ }
173
+ }
174
+ async handleExtensionExecuteInContext(args) {
175
+ const extensionId = requiredStringArg(args.extensionId, "extensionId");
176
+ const code = requiredStringArg(args.code, "code");
177
+ const returnByValue = parseBooleanArg(args.returnByValue, true);
178
+ const session = await (await this.state.collector.getActivePage()).createCDPSession();
179
+ let attachedSessionId = "";
180
+ try {
181
+ const targets = await this.getExtensionTargets(session, extensionId);
182
+ if (targets.length === 0) throw new Error(`No background target found for extension: ${extensionId}`);
183
+ const preferred = this.pickPreferredExtensionTarget(targets);
184
+ attachedSessionId = requiredStringArg(asRecord(await session.send("Target.attachToTarget", {
185
+ targetId: preferred.targetId,
186
+ flatten: true
187
+ })).sessionId, "sessionId");
188
+ const evaluation = await this.evaluateInAttachedTarget(session, attachedSessionId, code, returnByValue);
189
+ return json({
190
+ extensionId,
191
+ target: {
192
+ type: preferred.type,
193
+ url: preferred.url,
194
+ name: preferred.name
195
+ },
196
+ result: evaluation.result,
197
+ exceptionDetails: evaluation.exceptionDetails
198
+ });
199
+ } catch (error) {
200
+ return fail("extension_execute_in_context", error);
201
+ } finally {
202
+ if (attachedSessionId) await trySend(session, "Target.detachFromTarget", { sessionId: attachedSessionId });
203
+ await safeDetach(session);
204
+ }
205
+ }
206
+ async getExtensionTargets(session, expectedExtensionId) {
207
+ const response = asRecord(await session.send("Target.getTargets"));
208
+ const targetInfos = Array.isArray(response.targetInfos) ? response.targetInfos : [];
209
+ const allowedTypes = new Set(["service_worker", "background_page"]);
210
+ const result = [];
211
+ for (const item of targetInfos) {
212
+ const record = asRecord(item);
213
+ const targetId = asString(record.targetId);
214
+ const type = asString(record.type);
215
+ const url = asString(record.url);
216
+ if (!targetId || !type || !url) continue;
217
+ if (!allowedTypes.has(type)) continue;
218
+ const extensionId = this.extractExtensionId(url);
219
+ if (!extensionId) continue;
220
+ if (expectedExtensionId && extensionId !== expectedExtensionId) continue;
221
+ const title = asString(record.title) ?? "";
222
+ result.push({
223
+ targetId,
224
+ extensionId,
225
+ name: title || extensionId,
226
+ type,
227
+ url
228
+ });
229
+ }
230
+ result.sort((left, right) => {
231
+ const leftScore = left.type === "service_worker" ? 0 : 1;
232
+ const rightScore = right.type === "service_worker" ? 0 : 1;
233
+ if (leftScore !== rightScore) return leftScore - rightScore;
234
+ return left.extensionId.localeCompare(right.extensionId);
235
+ });
236
+ return result;
237
+ }
238
+ pickPreferredExtensionTarget(targets) {
239
+ return targets.find((target) => target.type === "service_worker") ?? targets[0];
240
+ }
241
+ extractExtensionId(url) {
242
+ return url.match(/^chrome-extension:\/\/([a-p]{32})(?:\/|$)/i)?.[1] ?? null;
243
+ }
244
+ async evaluateInAttachedTarget(session, sessionId, code, returnByValue) {
245
+ if (!session.on) throw new Error("CDP session does not support event listeners");
246
+ const commandId = Date.now() % 1e9;
247
+ const commandMessage = JSON.stringify({
248
+ id: commandId,
249
+ method: "Runtime.evaluate",
250
+ params: {
251
+ expression: code,
252
+ returnByValue,
253
+ awaitPromise: true
254
+ }
255
+ });
256
+ const responseMessage = await new Promise((resolvePromise, rejectPromise) => {
257
+ const timeout = setTimeout(() => {
258
+ cleanup();
259
+ rejectPromise(/* @__PURE__ */ new Error("Runtime.evaluate timed out"));
260
+ }, SOURCEMAP_EXT_TIMEOUT_MS);
261
+ const onMessage = (payload) => {
262
+ const record = asRecord(payload);
263
+ if (asString(record.sessionId) !== sessionId) return;
264
+ const rawMessage = asString(record.message);
265
+ if (!rawMessage) return;
266
+ let parsed;
267
+ try {
268
+ parsed = JSON.parse(rawMessage);
269
+ } catch {
270
+ return;
271
+ }
272
+ const parsedRecord = asRecord(parsed);
273
+ if (parsedRecord.id !== commandId) return;
274
+ cleanup();
275
+ resolvePromise(parsedRecord);
276
+ };
277
+ const cleanup = () => {
278
+ clearTimeout(timeout);
279
+ session.off?.("Target.receivedMessageFromTarget", onMessage);
280
+ };
281
+ session.on?.("Target.receivedMessageFromTarget", onMessage);
282
+ session.send("Target.sendMessageToTarget", {
283
+ sessionId,
284
+ message: commandMessage
285
+ }).catch((error) => {
286
+ cleanup();
287
+ rejectPromise(error);
288
+ });
289
+ });
290
+ const errorRecord = asRecord(responseMessage.error);
291
+ if (Object.keys(errorRecord).length > 0) throw new Error(asString(errorRecord.message) ?? asString(errorRecord.data) ?? "Runtime.evaluate failed");
292
+ const resultEnvelope = asRecord(responseMessage.result);
293
+ return {
294
+ result: resultEnvelope.result !== void 0 ? resultEnvelope.result : null,
295
+ exceptionDetails: resultEnvelope.exceptionDetails !== void 0 ? resultEnvelope.exceptionDetails : null
296
+ };
297
+ }
298
+ };
299
+ //#endregion
300
+ //#region src/server/domains/sourcemap/handlers/sourcemap-parsing.ts
301
+ /**
302
+ * Sourcemap parsing, URL resolution, and path normalization functions.
303
+ */
304
+ function parseSourceMap(sourceMapUrl, scriptUrl, collector) {
305
+ return loadSourceMap(sourceMapUrl, scriptUrl, collector).then((loaded) => {
306
+ const mappings = decodeMappings(loaded.map.mappings);
307
+ const generatedLines = new Set(mappings.map((item) => item.generatedLine));
308
+ return {
309
+ resolvedUrl: loaded.resolvedUrl,
310
+ map: loaded.map,
311
+ mappings,
312
+ mappingsCount: generatedLines.size,
313
+ segmentCount: mappings.length
314
+ };
315
+ });
316
+ }
317
+ function parseSourceMapStats(sourceMapUrl, scriptUrl, collector) {
318
+ return loadSourceMap(sourceMapUrl, scriptUrl, collector).then((loaded) => {
319
+ const { mappingsCount, segmentCount } = countMappingsStats(loaded.map.mappings);
320
+ return {
321
+ resolvedUrl: loaded.resolvedUrl,
322
+ map: loaded.map,
323
+ mappingsCount,
324
+ segmentCount
325
+ };
326
+ });
327
+ }
328
+ async function loadSourceMap(sourceMapUrl, scriptUrl, collector) {
329
+ const resolvedUrl = resolveSourceMapUrl(sourceMapUrl, scriptUrl ?? "");
330
+ let sourceMapText = "";
331
+ if (resolvedUrl.startsWith("data:")) sourceMapText = decodeDataUriJson(resolvedUrl);
332
+ else sourceMapText = await fetchSourceMapText(resolvedUrl, collector);
333
+ let parsedJson;
334
+ try {
335
+ parsedJson = JSON.parse(sourceMapText);
336
+ } catch {
337
+ throw new Error(`Invalid SourceMap JSON: ${resolvedUrl}`);
338
+ }
339
+ return {
340
+ resolvedUrl,
341
+ map: normalizeSourceMap(parsedJson)
342
+ };
343
+ }
344
+ function normalizeSourceMap(value) {
345
+ const record = asRecord(value);
346
+ if (record.version !== 3) throw new Error("Only SourceMap version 3 is supported");
347
+ const mappings = asString(record.mappings);
348
+ if (mappings === void 0) throw new Error("SourceMap.mappings is required");
349
+ const sources = (Array.isArray(record.sources) ? record.sources : []).map((item) => asString(item)).filter((item) => typeof item === "string");
350
+ const names = (Array.isArray(record.names) ? record.names : []).map((item) => asString(item)).filter((item) => typeof item === "string");
351
+ const sourceRoot = asString(record.sourceRoot);
352
+ let sourcesContent;
353
+ if (Array.isArray(record.sourcesContent)) sourcesContent = record.sourcesContent.map((item) => typeof item === "string" ? item : null);
354
+ return {
355
+ version: 3,
356
+ sources,
357
+ sourcesContent,
358
+ mappings,
359
+ names,
360
+ sourceRoot
361
+ };
362
+ }
363
+ async function fetchSourceMapText(resolvedUrl, collector) {
364
+ validateFetchUrl(resolvedUrl);
365
+ {
366
+ const ac = new AbortController();
367
+ const t = setTimeout(() => ac.abort(), 1e4);
368
+ try {
369
+ const response = await fetch(resolvedUrl, { signal: ac.signal });
370
+ if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
371
+ return await response.text();
372
+ } catch (err) {
373
+ if (err.name === "AbortError") throw new Error(`SourceMap fetch timed out after 10s: ${resolvedUrl}`, { cause: err });
374
+ } finally {
375
+ clearTimeout(t);
376
+ }
377
+ }
378
+ const fetched = await evaluateWithTimeout(await collector.getActivePage(), async (url) => {
379
+ const ac = new AbortController();
380
+ const t = setTimeout(() => ac.abort(), 1e4);
381
+ try {
382
+ const resp = await fetch(url, { signal: ac.signal });
383
+ if (!resp.ok) return `__FETCH_ERROR__HTTP ${resp.status} ${resp.statusText}`;
384
+ return await resp.text();
385
+ } catch (error) {
386
+ return `__FETCH_ERROR__${error instanceof Error ? error.message : String(error)}`;
387
+ } finally {
388
+ clearTimeout(t);
389
+ }
390
+ }, resolvedUrl);
391
+ if (typeof fetched !== "string") throw new Error("Failed to fetch SourceMap content");
392
+ if (fetched.startsWith("__FETCH_ERROR__")) throw new Error(fetched.slice(15) || "Failed to fetch SourceMap content");
393
+ return fetched;
394
+ }
395
+ function validateFetchUrl(url) {
396
+ let parsed;
397
+ try {
398
+ parsed = new URL(url);
399
+ } catch {
400
+ throw new Error(`Invalid URL: ${url}`);
401
+ }
402
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`Blocked: unsupported protocol "${parsed.protocol}"`);
403
+ const hostname = parsed.hostname.toLowerCase();
404
+ const blockedPatterns = [
405
+ /^127\./,
406
+ /^10\./,
407
+ /^172\.(1[6-9]|2\d|3[01])\./,
408
+ /^192\.168\./,
409
+ /^0\./,
410
+ /^169\.254\./,
411
+ /^\[?::1\]?$/,
412
+ /^\[?fe80:/i,
413
+ /^\[?fc00:/i,
414
+ /^\[?fd/i
415
+ ];
416
+ if ([
417
+ "localhost",
418
+ "metadata.google.internal",
419
+ "metadata"
420
+ ].includes(hostname)) throw new Error(`SSRF blocked: hostname "${hostname}" is not allowed`);
421
+ for (const pattern of blockedPatterns) if (pattern.test(hostname)) throw new Error(`SSRF blocked: protected/reserved IP "${hostname}" is not allowed`);
422
+ }
423
+ function decodeDataUriJson(dataUri) {
424
+ const commaIndex = dataUri.indexOf(",");
425
+ if (commaIndex === -1) throw new Error("Invalid data URI source map");
426
+ const metadata = dataUri.slice(0, commaIndex);
427
+ const dataPart = dataUri.slice(commaIndex + 1);
428
+ if (/;base64/i.test(metadata)) return Buffer.from(dataPart, "base64").toString("utf-8");
429
+ return decodeURIComponent(dataPart);
430
+ }
431
+ function resolveSourceMapUrl(sourceMapUrl, scriptUrl) {
432
+ const trimmed = sourceMapUrl.trim();
433
+ if (!trimmed) return "";
434
+ if (trimmed.startsWith("data:")) return trimmed;
435
+ if (hasProtocol(trimmed)) return trimmed;
436
+ if (!scriptUrl) return trimmed;
437
+ try {
438
+ return new URL(trimmed, scriptUrl).toString();
439
+ } catch {
440
+ return trimmed;
441
+ }
442
+ }
443
+ function extractSourceMappingUrlFromScript(scriptSource) {
444
+ const tail = scriptSource.slice(-8192);
445
+ const regex = /(?:\/\/[@#]\s*sourceMappingURL=([^\s]+)|\/\*[@#]\s*sourceMappingURL=([^*]+)\*\/)/g;
446
+ let match;
447
+ let found = null;
448
+ while (true) {
449
+ match = regex.exec(tail);
450
+ if (!match) break;
451
+ const candidate = (match[1] ?? match[2] ?? "").trim();
452
+ if (candidate) found = candidate;
453
+ }
454
+ return found;
455
+ }
456
+ function combineSourceRoot(sourceRoot, sourcePath) {
457
+ if (!sourceRoot) return sourcePath;
458
+ if (!sourcePath) return sourceRoot;
459
+ if (hasProtocol(sourcePath) || sourcePath.startsWith("/")) return sourcePath;
460
+ if (hasProtocol(sourceRoot)) try {
461
+ const base = sourceRoot.endsWith("/") ? sourceRoot : `${sourceRoot}/`;
462
+ return new URL(sourcePath, base).toString();
463
+ } catch {
464
+ return `${sourceRoot.replace(/\/+$/g, "")}/${sourcePath.replace(/^\/+/g, "")}`;
465
+ }
466
+ return `${sourceRoot.replace(/\/+$/g, "")}/${sourcePath.replace(/^\/+/g, "")}`;
467
+ }
468
+ function normalizeSourcePath(sourcePath, index) {
469
+ let candidate = sourcePath.trim();
470
+ if (!candidate) return `source_${index + 1}.js`;
471
+ if (candidate.startsWith("webpack://")) candidate = candidate.slice(10);
472
+ if (candidate.startsWith("data:")) return `inline/source_${index + 1}.txt`;
473
+ if (hasProtocol(candidate)) try {
474
+ const parsed = new URL(candidate);
475
+ candidate = `${parsed.hostname}${parsed.pathname}`;
476
+ } catch {
477
+ candidate = candidate.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
478
+ }
479
+ candidate = candidate.replace(/[?#].*$/g, "");
480
+ candidate = candidate.replace(/^[A-Za-z]:[\\/]/, "");
481
+ candidate = candidate.replace(/^\/+/, "");
482
+ const parts = candidate.split(/[\\/]+/).map((seg) => sanitizePathSegment(seg)).filter((seg) => seg !== "" && seg !== "." && seg !== "..");
483
+ if (parts.length === 0) return `source_${index + 1}.js`;
484
+ return parts.join("/");
485
+ }
486
+ function sanitizePathSegment(segment) {
487
+ const sanitized = Array.from(segment, (char) => {
488
+ const codePoint = char.codePointAt(0);
489
+ return codePoint !== void 0 && (codePoint <= 31 || "<>:\"|?*".includes(char)) ? "_" : char;
490
+ }).join("").replace(/\s+/g, " ").trim();
491
+ if (!sanitized || sanitized === "." || sanitized === "..") return "_";
492
+ return sanitized;
493
+ }
494
+ function safeTarget(value) {
495
+ return value.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").replace(/[^a-zA-Z0-9_-]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "").slice(0, 48);
496
+ }
497
+ //#endregion
498
+ //#region src/server/domains/sourcemap/handlers/sourcemap-handlers.ts
499
+ /**
500
+ * Main sourcemap sub-handler — discover, fetch/parse, reconstruct tree.
501
+ */
502
+ var SourcemapHandlers = class {
503
+ state;
504
+ constructor(state) {
505
+ this.state = state;
506
+ }
507
+ async handleSourcemapDiscover(args) {
508
+ const includeInline = parseBooleanArg(args.includeInline, true);
509
+ const session = await (await this.state.collector.getActivePage()).createCDPSession();
510
+ const scripts = /* @__PURE__ */ new Map();
511
+ const onScriptParsed = (payload) => {
512
+ const record = asRecord(payload);
513
+ const scriptId = asString(record.scriptId);
514
+ if (!scriptId) return;
515
+ const scriptUrl = asString(record.url) ?? "";
516
+ const sourceMapUrlRaw = asString(record.sourceMapURL) ?? "";
517
+ const existing = scripts.get(scriptId);
518
+ const sourceMapUrlResolved = sourceMapUrlRaw ? resolveSourceMapUrl(sourceMapUrlRaw, scriptUrl) : existing?.sourceMapUrl ?? "";
519
+ scripts.set(scriptId, {
520
+ scriptId,
521
+ scriptUrl: scriptUrl || existing?.scriptUrl || "",
522
+ sourceMapUrl: sourceMapUrlResolved,
523
+ isInline: sourceMapUrlResolved.startsWith("data:")
524
+ });
525
+ };
526
+ try {
527
+ session.on?.("Debugger.scriptParsed", onScriptParsed);
528
+ await session.send("Debugger.enable");
529
+ await delay(250);
530
+ for (const item of scripts.values()) {
531
+ if (item.sourceMapUrl) continue;
532
+ if (!item.scriptId || !item.scriptUrl) continue;
533
+ try {
534
+ const scriptSource = asString(asRecord(await session.send("Debugger.getScriptSource", { scriptId: item.scriptId })).scriptSource);
535
+ if (!scriptSource) continue;
536
+ const extracted = extractSourceMappingUrlFromScript(scriptSource);
537
+ if (!extracted) continue;
538
+ const resolvedSourceMap = resolveSourceMapUrl(extracted, item.scriptUrl);
539
+ item.sourceMapUrl = resolvedSourceMap;
540
+ item.isInline = resolvedSourceMap.startsWith("data:");
541
+ } catch {
542
+ continue;
543
+ }
544
+ }
545
+ return json(Array.from(scripts.values()).filter((item) => item.sourceMapUrl.length > 0).filter((item) => includeInline || !item.isInline).toSorted((left, right) => {
546
+ const leftKey = `${left.scriptUrl}|${left.scriptId}`;
547
+ const rightKey = `${right.scriptUrl}|${right.scriptId}`;
548
+ return leftKey.localeCompare(rightKey);
549
+ }).map((item) => ({
550
+ scriptUrl: item.scriptUrl,
551
+ sourceMapUrl: item.sourceMapUrl,
552
+ isInline: item.isInline,
553
+ scriptId: item.scriptId
554
+ })));
555
+ } catch (error) {
556
+ return fail("sourcemap_discover", error);
557
+ } finally {
558
+ session.off?.("Debugger.scriptParsed", onScriptParsed);
559
+ await trySend(session, "Debugger.disable");
560
+ await safeDetach(session);
561
+ }
562
+ }
563
+ async handleSourcemapFetchAndParse(args) {
564
+ try {
565
+ const parsed = await parseSourceMap(requiredStringArg(args.sourceMapUrl, "sourceMapUrl"), optionalStringArg(args.scriptUrl), this.state.collector);
566
+ const responsePayload = {
567
+ sources: parsed.map.sources,
568
+ mappingsCount: parsed.mappingsCount,
569
+ segmentCount: parsed.segmentCount
570
+ };
571
+ if (Array.isArray(parsed.map.sourcesContent)) responsePayload.sourcesContent = parsed.map.sourcesContent;
572
+ return json(responsePayload);
573
+ } catch (error) {
574
+ return fail("sourcemap_fetch_and_parse", error);
575
+ }
576
+ }
577
+ async handleSourcemapReconstructTree(args) {
578
+ try {
579
+ const sourceMapUrl = requiredStringArg(args.sourceMapUrl, "sourceMapUrl");
580
+ const outputDir = optionalStringArg(args.outputDir);
581
+ const parsed = await parseSourceMapStats(sourceMapUrl, void 0, this.state.collector);
582
+ const artifactPath = await resolveArtifactPath({
583
+ category: "reports",
584
+ toolName: "sourcemap-tree",
585
+ target: safeTarget(parsed.resolvedUrl),
586
+ ext: "tmp",
587
+ ...outputDir ? { customDir: outputDir } : {}
588
+ });
589
+ const outputRoot = artifactPath.absolutePath.replace(/\.tmp$/i, "");
590
+ const outputRootDisplay = artifactPath.displayPath.replace(/\.tmp$/i, "");
591
+ await mkdir(outputRoot, { recursive: true });
592
+ const writtenFiles = [];
593
+ let skippedFiles = 0;
594
+ for (let index = 0; index < parsed.map.sources.length; index += 1) {
595
+ const rawSourcePath = parsed.map.sources[index] ?? "";
596
+ const sourcePath = combineSourceRoot(parsed.map.sourceRoot, rawSourcePath);
597
+ const relativePath = normalizeSourcePath(sourcePath, index);
598
+ const absolutePath = resolve(outputRoot, relativePath);
599
+ const sourceContent = parsed.map.sourcesContent && index < parsed.map.sourcesContent.length ? parsed.map.sourcesContent[index] : null;
600
+ const fileContent = typeof sourceContent === "string" ? sourceContent : `/* source content missing in source map: ${sourcePath} */\n`;
601
+ try {
602
+ await mkdir(dirname(absolutePath), { recursive: true });
603
+ await writeFile(absolutePath, fileContent, "utf-8");
604
+ writtenFiles.push(relativePath);
605
+ } catch {
606
+ skippedFiles += 1;
607
+ }
608
+ }
609
+ return json({
610
+ outputDir: outputRootDisplay,
611
+ totalSources: parsed.map.sources.length,
612
+ writtenFiles: writtenFiles.length,
613
+ skippedFiles,
614
+ files: writtenFiles
615
+ });
616
+ } catch (error) {
617
+ return fail("sourcemap_reconstruct_tree", error);
618
+ }
619
+ }
620
+ };
621
+ //#endregion
622
+ //#region src/server/domains/sourcemap/handlers.impl.core.ts
623
+ var SourcemapToolHandlers = class {
624
+ collector;
625
+ extension;
626
+ sourcemap;
627
+ constructor(collector) {
628
+ this.collector = collector;
629
+ const state = { collector };
630
+ this.extension = new ExtensionHandlers(state);
631
+ this.sourcemap = new SourcemapHandlers(state);
632
+ }
633
+ handleExtensionListInstalled(args) {
634
+ return this.extension.handleExtensionListInstalled(args);
635
+ }
636
+ handleExtensionExecuteInContext(args) {
637
+ return this.extension.handleExtensionExecuteInContext(args);
638
+ }
639
+ handleSourcemapDiscover(args) {
640
+ return this.sourcemap.handleSourcemapDiscover(args);
641
+ }
642
+ handleSourcemapFetchAndParse(args) {
643
+ return this.sourcemap.handleSourcemapFetchAndParse(args);
644
+ }
645
+ handleSourcemapReconstructTree(args) {
646
+ return this.sourcemap.handleSourcemapReconstructTree(args);
647
+ }
648
+ };
649
+ //#endregion
650
+ export { SourcemapToolHandlers };