spana-test 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +1 -1
  2. package/dist/agent/index.js +28 -10
  3. package/dist/agent/index.js.map +1 -1
  4. package/dist/api/app.d.ts +40 -0
  5. package/dist/api/app.d.ts.map +1 -1
  6. package/dist/api/expect.d.ts +13 -0
  7. package/dist/api/expect.d.ts.map +1 -1
  8. package/dist/app-JTWXTFDY.js +13 -0
  9. package/dist/appium-CC77BJNK.js +935 -0
  10. package/dist/appium-CC77BJNK.js.map +1 -0
  11. package/dist/bridge-server-S3DHK7XE.js +12 -0
  12. package/dist/channels/cdp-client.d.ts +65 -0
  13. package/dist/channels/cdp-client.d.ts.map +1 -1
  14. package/dist/channels/dom-channel.d.ts +10 -1
  15. package/dist/channels/dom-channel.d.ts.map +1 -1
  16. package/dist/{chunk-OQRGR542.js → chunk-2SJNPLLU.js} +7 -7
  17. package/dist/chunk-2SJNPLLU.js.map +1 -0
  18. package/dist/chunk-4LJ3KYCX.js +94 -0
  19. package/dist/chunk-4LJ3KYCX.js.map +1 -0
  20. package/dist/{chunk-GAWJL6Q3.js → chunk-63OBFF2I.js} +601 -95
  21. package/dist/chunk-63OBFF2I.js.map +1 -0
  22. package/dist/{screenshot-compare-V4JQG73R.js → chunk-6C2EILMC.js} +185 -6
  23. package/dist/chunk-6C2EILMC.js.map +1 -0
  24. package/dist/{chunk-LQQNE2OE.js → chunk-7EMHU56B.js} +397 -44
  25. package/dist/chunk-7EMHU56B.js.map +1 -0
  26. package/dist/chunk-7WC7NPRU.js +1186 -0
  27. package/dist/chunk-7WC7NPRU.js.map +1 -0
  28. package/dist/chunk-A7Z52TDQ.js +97 -0
  29. package/dist/chunk-A7Z52TDQ.js.map +1 -0
  30. package/dist/chunk-DMF2BPPA.js +547 -0
  31. package/dist/chunk-DMF2BPPA.js.map +1 -0
  32. package/dist/chunk-E2JJOVPP.js +1962 -0
  33. package/dist/chunk-E2JJOVPP.js.map +1 -0
  34. package/dist/{chunk-QOL44BNJ.js → chunk-GDVHJBR2.js} +4 -4
  35. package/dist/chunk-GLNTGHR6.js +330 -0
  36. package/dist/chunk-GLNTGHR6.js.map +1 -0
  37. package/dist/chunk-HNQLWFHL.js +40 -0
  38. package/dist/chunk-HNQLWFHL.js.map +1 -0
  39. package/dist/chunk-HUYC4OAL.js +72 -0
  40. package/dist/chunk-HUYC4OAL.js.map +1 -0
  41. package/dist/chunk-HWS3XUEF.js +109 -0
  42. package/dist/chunk-HWS3XUEF.js.map +1 -0
  43. package/dist/chunk-IWGRZNKU.js +845 -0
  44. package/dist/chunk-IWGRZNKU.js.map +1 -0
  45. package/dist/chunk-JHJSAIPG.js +1114 -0
  46. package/dist/chunk-JHJSAIPG.js.map +1 -0
  47. package/dist/chunk-K4K2ACT2.js +179 -0
  48. package/dist/chunk-K4K2ACT2.js.map +1 -0
  49. package/dist/chunk-KWIB77C7.js +654 -0
  50. package/dist/chunk-KWIB77C7.js.map +1 -0
  51. package/dist/chunk-MPJCUL2B.js +154 -0
  52. package/dist/chunk-MPJCUL2B.js.map +1 -0
  53. package/dist/{chunk-F3AFZ6UX.js → chunk-MTCRATOA.js} +3 -1
  54. package/dist/chunk-MTCRATOA.js.map +1 -0
  55. package/dist/chunk-MUMIMDRJ.js +24 -0
  56. package/dist/chunk-MUMIMDRJ.js.map +1 -0
  57. package/dist/chunk-NMN2ENQZ.js +1046 -0
  58. package/dist/chunk-NMN2ENQZ.js.map +1 -0
  59. package/dist/{chunk-XQRXQBDQ.js → chunk-NWGA3R2E.js} +2 -19
  60. package/dist/chunk-NWGA3R2E.js.map +1 -0
  61. package/dist/chunk-PCVXXIEJ.js +529 -0
  62. package/dist/chunk-PCVXXIEJ.js.map +1 -0
  63. package/dist/chunk-RGLPQNJG.js +272 -0
  64. package/dist/chunk-RGLPQNJG.js.map +1 -0
  65. package/dist/{chunk-F2YUBD4E.js → chunk-RQ5TJJZU.js} +3 -3
  66. package/dist/{chunk-BWEQ4XT2.js → chunk-T4FCROSE.js} +458 -1180
  67. package/dist/chunk-T4FCROSE.js.map +1 -0
  68. package/dist/{chunk-AMBU26PB.js → chunk-U7633AII.js} +5 -4
  69. package/dist/chunk-U7633AII.js.map +1 -0
  70. package/dist/{chunk-53TGNQTM.js → chunk-WKN6ZW7V.js} +32 -18
  71. package/dist/{chunk-53TGNQTM.js.map → chunk-WKN6ZW7V.js.map} +1 -1
  72. package/dist/chunk-X5FRYDZ3.js +91 -0
  73. package/dist/chunk-X5FRYDZ3.js.map +1 -0
  74. package/dist/chunk-YFTHJRDO.js +37 -0
  75. package/dist/chunk-YFTHJRDO.js.map +1 -0
  76. package/dist/cli/config-loader.d.ts +1 -0
  77. package/dist/cli/config-loader.d.ts.map +1 -1
  78. package/dist/cli/test-command.d.ts +2 -0
  79. package/dist/cli/test-command.d.ts.map +1 -1
  80. package/dist/cli.js +18 -18
  81. package/dist/config-loader-4X7R7XDL.js +10 -0
  82. package/dist/core/engine.d.ts.map +1 -1
  83. package/dist/{discover-43C3BE7I.js → discover-6ULCTB5T.js} +3 -3
  84. package/dist/{doctor-command-CLKEEOAX.js → doctor-command-BYKRBS4V.js} +16 -9
  85. package/dist/{doctor-command-CLKEEOAX.js.map → doctor-command-BYKRBS4V.js.map} +1 -1
  86. package/dist/driver-GOPO5ZZP.js +19 -0
  87. package/dist/driver-HK4HQAYL.js +19 -0
  88. package/dist/drivers/cdp-browser.d.ts +31 -3
  89. package/dist/drivers/cdp-browser.d.ts.map +1 -1
  90. package/dist/drivers/electron.d.ts +1 -1
  91. package/dist/drivers/electron.d.ts.map +1 -1
  92. package/dist/drivers/playwright.d.ts +1 -5
  93. package/dist/drivers/playwright.d.ts.map +1 -1
  94. package/dist/drivers/raw-driver.d.ts +4 -0
  95. package/dist/drivers/raw-driver.d.ts.map +1 -1
  96. package/dist/drivers/wasm-utils.d.ts +100 -0
  97. package/dist/drivers/wasm-utils.d.ts.map +1 -0
  98. package/dist/drivers/wasm.d.ts +57 -0
  99. package/dist/drivers/wasm.d.ts.map +1 -0
  100. package/dist/electrobun-65Z6KOVN.js +15 -0
  101. package/dist/electrobun-65Z6KOVN.js.map +1 -0
  102. package/dist/electron-SQACDON3.js +9 -0
  103. package/dist/electron-SQACDON3.js.map +1 -0
  104. package/dist/index.d.ts +6 -1
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +409 -53
  107. package/dist/index.js.map +1 -1
  108. package/dist/installer-KL2NCILK.js +17 -0
  109. package/dist/installer-KL2NCILK.js.map +1 -0
  110. package/dist/{local-RH5EFGYF.js → local-6NRVD5VP.js} +8 -9
  111. package/dist/local-6NRVD5VP.js.map +1 -0
  112. package/dist/pagesource-KIQ5T5MA.js +9 -0
  113. package/dist/pagesource-KIQ5T5MA.js.map +1 -0
  114. package/dist/pagesource-KKG7WMFJ.js +9 -0
  115. package/dist/pagesource-KKG7WMFJ.js.map +1 -0
  116. package/dist/playwright-JUAD3TT4.js +28 -0
  117. package/dist/playwright-JUAD3TT4.js.map +1 -0
  118. package/dist/runtime/local.d.ts +2 -2
  119. package/dist/runtime/local.d.ts.map +1 -1
  120. package/dist/schemas/config.d.ts +37 -4
  121. package/dist/schemas/config.d.ts.map +1 -1
  122. package/dist/schemas/device.d.ts +1 -1
  123. package/dist/schemas/device.d.ts.map +1 -1
  124. package/dist/screenshot-compare-BJRJHKNQ.js +12 -0
  125. package/dist/screenshot-compare-BJRJHKNQ.js.map +1 -0
  126. package/dist/{server-D45AO34E.js → server-2RCONJCW.js} +30 -12
  127. package/dist/{server-D45AO34E.js.map → server-2RCONJCW.js.map} +1 -1
  128. package/dist/{server-KLZBJOMQ.js → server-UJ3RDZWT.js} +2 -2
  129. package/dist/server-UJ3RDZWT.js.map +1 -0
  130. package/dist/session-7N5XYDXQ.js +39 -0
  131. package/dist/session-7N5XYDXQ.js.map +1 -0
  132. package/dist/smart/auto-wait.d.ts +2 -0
  133. package/dist/smart/auto-wait.d.ts.map +1 -1
  134. package/dist/smart/coordinator.d.ts.map +1 -1
  135. package/dist/{studio-command-TNSJGTFA.js → studio-command-ZCR64XWV.js} +2 -2
  136. package/dist/{test-command-EXPYFDTF.js → test-command-ENL3DRN4.js} +74 -1041
  137. package/dist/test-command-ENL3DRN4.js.map +1 -0
  138. package/dist/watch-mode-NR5MHNNL.js +10 -0
  139. package/dist/watch-mode-NR5MHNNL.js.map +1 -0
  140. package/native/win32-x64/spana_native.dll +0 -0
  141. package/package.json +2 -2
  142. package/dist/app-CBHH5GMB.js +0 -10
  143. package/dist/chunk-AMBU26PB.js.map +0 -1
  144. package/dist/chunk-BWEQ4XT2.js.map +0 -1
  145. package/dist/chunk-F3AFZ6UX.js.map +0 -1
  146. package/dist/chunk-GAWJL6Q3.js.map +0 -1
  147. package/dist/chunk-GDDCZ2PL.js +0 -2619
  148. package/dist/chunk-GDDCZ2PL.js.map +0 -1
  149. package/dist/chunk-LQQNE2OE.js.map +0 -1
  150. package/dist/chunk-OQRGR542.js.map +0 -1
  151. package/dist/chunk-PPAPRKQU.js +0 -4739
  152. package/dist/chunk-PPAPRKQU.js.map +0 -1
  153. package/dist/chunk-VOYJQDSI.js +0 -188
  154. package/dist/chunk-VOYJQDSI.js.map +0 -1
  155. package/dist/chunk-XQRXQBDQ.js.map +0 -1
  156. package/dist/config-loader-V26XXHPH.js +0 -10
  157. package/dist/screenshot-compare-V4JQG73R.js.map +0 -1
  158. package/dist/session-N6DEYVPM.js +0 -21
  159. package/dist/test-command-EXPYFDTF.js.map +0 -1
  160. /package/dist/{app-CBHH5GMB.js.map → app-JTWXTFDY.js.map} +0 -0
  161. /package/dist/{config-loader-V26XXHPH.js.map → bridge-server-S3DHK7XE.js.map} +0 -0
  162. /package/dist/{chunk-QOL44BNJ.js.map → chunk-GDVHJBR2.js.map} +0 -0
  163. /package/dist/{chunk-F2YUBD4E.js.map → chunk-RQ5TJJZU.js.map} +0 -0
  164. /package/dist/{discover-43C3BE7I.js.map → config-loader-4X7R7XDL.js.map} +0 -0
  165. /package/dist/{local-RH5EFGYF.js.map → discover-6ULCTB5T.js.map} +0 -0
  166. /package/dist/{server-KLZBJOMQ.js.map → driver-GOPO5ZZP.js.map} +0 -0
  167. /package/dist/{session-N6DEYVPM.js.map → driver-HK4HQAYL.js.map} +0 -0
  168. /package/dist/{studio-command-TNSJGTFA.js.map → studio-command-ZCR64XWV.js.map} +0 -0
@@ -0,0 +1,654 @@
1
+ import {
2
+ buildDomQueryScript,
3
+ buildDomScrollIntoViewScript,
4
+ buildDomTapScript,
5
+ buildEvaluateExpression
6
+ } from "./chunk-63OBFF2I.js";
7
+ import {
8
+ init_esm_shims
9
+ } from "./chunk-FTXUQMGH.js";
10
+
11
+ // src/channels/apple-webinspector.ts
12
+ init_esm_shims();
13
+ import { execSync } from "child_process";
14
+ import { randomUUID } from "crypto";
15
+ import { existsSync, readdirSync } from "fs";
16
+ import { createConnection } from "net";
17
+ import { join } from "path";
18
+ function escapeXml(value) {
19
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
20
+ }
21
+ function encodePlistValue(value) {
22
+ if (typeof value === "string") {
23
+ return `<string>${escapeXml(value)}</string>`;
24
+ }
25
+ if (typeof value === "number") {
26
+ return Number.isInteger(value) ? `<integer>${value}</integer>` : `<real>${value}</real>`;
27
+ }
28
+ if (typeof value === "boolean") {
29
+ return value ? "<true/>" : "<false/>";
30
+ }
31
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
32
+ return `<data>${Buffer.from(value).toString("base64")}</data>`;
33
+ }
34
+ if (Array.isArray(value)) {
35
+ return `<array>${value.map(encodePlistValue).join("")}</array>`;
36
+ }
37
+ if (value && typeof value === "object") {
38
+ const entries = Object.entries(value).map(([k, v]) => `<key>${escapeXml(k)}</key>${encodePlistValue(v)}`).join("");
39
+ return `<dict>${entries}</dict>`;
40
+ }
41
+ return "<string></string>";
42
+ }
43
+ function encodeWebInspectorPacket(selector, args) {
44
+ const xml = [
45
+ '<?xml version="1.0" encoding="UTF-8"?>',
46
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
47
+ '<plist version="1.0">',
48
+ "<dict>",
49
+ "<key>__selector</key>",
50
+ `<string>${escapeXml(selector)}</string>`,
51
+ "<key>__argument</key>",
52
+ encodePlistValue(args),
53
+ "</dict>",
54
+ "</plist>"
55
+ ].join("");
56
+ const payload = Buffer.from(xml, "utf-8");
57
+ const header = Buffer.alloc(4);
58
+ header.writeUInt32BE(payload.length, 0);
59
+ return Buffer.concat([header, payload]);
60
+ }
61
+ function decodeWebInspectorFrames(buffer) {
62
+ const frames = [];
63
+ let offset = 0;
64
+ while (buffer.length - offset >= 4) {
65
+ const len = buffer.readUInt32BE(offset);
66
+ if (buffer.length - offset < 4 + len) break;
67
+ const payload = buffer.subarray(offset + 4, offset + 4 + len);
68
+ frames.push(payload.toString("utf-8"));
69
+ offset += 4 + len;
70
+ }
71
+ return {
72
+ frames,
73
+ remaining: buffer.subarray(offset)
74
+ };
75
+ }
76
+ function parseWebInspectorXmlFrame(xml) {
77
+ const selectorMatch = xml.match(/<key>__selector<\/key>\s*<string>([^<]+)<\/string>/);
78
+ const selector = selectorMatch?.[1] ?? null;
79
+ const appIdMatch = xml.match(
80
+ /<key>WIRApplicationIdentifierKey<\/key>\s*<string>([^<]+)<\/string>/
81
+ );
82
+ const appId = appIdMatch?.[1];
83
+ let messageDataJson;
84
+ const dataMatch = xml.match(/<key>WIRMessageDataKey<\/key>\s*<data>([\s\S]*?)<\/data>/);
85
+ if (dataMatch?.[1]) {
86
+ try {
87
+ const decoded = Buffer.from(dataMatch[1].replaceAll(/\s+/g, ""), "base64").toString("utf-8");
88
+ messageDataJson = JSON.parse(decoded);
89
+ } catch {
90
+ }
91
+ }
92
+ let pages;
93
+ if (selector === "_rpc_applicationSentListing:" && appId) {
94
+ pages = [];
95
+ const pageIdMatches = [
96
+ ...xml.matchAll(/<key>WIRPageIdentifierKey<\/key>\s*<integer>(\d+)<\/integer>/g)
97
+ ];
98
+ const urlMatches = [...xml.matchAll(/<key>WIRURLKey<\/key>\s*<string>([^<]*)<\/string>/g)];
99
+ const titleMatches = [...xml.matchAll(/<key>WIRTitleKey<\/key>\s*<string>([^<]*)<\/string>/g)];
100
+ for (let i = 0; i < pageIdMatches.length; i++) {
101
+ pages.push({
102
+ appId,
103
+ pageId: Number.parseInt(pageIdMatches[i][1], 10),
104
+ url: urlMatches[i]?.[1],
105
+ title: titleMatches[i]?.[1],
106
+ type: "WIRTypeWebPage"
107
+ });
108
+ }
109
+ }
110
+ return { selector, appId, messageDataJson, pages };
111
+ }
112
+ function findSimulatorWebInspectorSocket(udid) {
113
+ if (process.env["SIMULATOR_WEBINSPECTOR_SOCKET"]) {
114
+ const envSock = process.env["SIMULATOR_WEBINSPECTOR_SOCKET"];
115
+ if (existsSync(envSock)) return envSock;
116
+ }
117
+ try {
118
+ const out = execSync("launchctl getenv SIMULATOR_WEBINSPECTOR_SOCKET 2>/dev/null || true", {
119
+ encoding: "utf-8",
120
+ timeout: 2e3
121
+ }).trim();
122
+ if (out && existsSync(out)) return out;
123
+ } catch {
124
+ }
125
+ if (udid && process.env["HOME"]) {
126
+ const tmpDir = join(
127
+ process.env["HOME"],
128
+ "Library/Developer/CoreSimulator/Devices",
129
+ udid,
130
+ "data/tmp"
131
+ );
132
+ if (existsSync(tmpDir)) {
133
+ try {
134
+ const entry = readdirSync(tmpDir).find((f) => f.includes("webinspector"));
135
+ if (entry) return join(tmpDir, entry);
136
+ } catch {
137
+ }
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+ var AppleWebInspectorClient = class {
143
+ socketPath;
144
+ bundleId;
145
+ timeoutMs;
146
+ connectSocket;
147
+ connectionId = randomUUID().toUpperCase();
148
+ senderKey = randomUUID().toUpperCase();
149
+ socket = null;
150
+ readBuffer = Buffer.alloc(0);
151
+ connected = false;
152
+ nextRpcId = 1;
153
+ pages = [];
154
+ activePage = null;
155
+ pendingRpc = /* @__PURE__ */ new Map();
156
+ listingWaiters = [];
157
+ constructor(options) {
158
+ this.socketPath = options.socketPath;
159
+ this.bundleId = options.bundleId;
160
+ this.timeoutMs = options.timeoutMs ?? 8e3;
161
+ this.connectSocket = options.connectSocket ?? ((p) => createConnection(p));
162
+ }
163
+ isConnected() {
164
+ return this.connected && this.socket !== null && !this.socket.destroyed;
165
+ }
166
+ async connect() {
167
+ if (this.isConnected()) return;
168
+ await new Promise((resolve, reject) => {
169
+ const sock = this.connectSocket(this.socketPath);
170
+ this.socket = sock;
171
+ let settled = false;
172
+ const timer = setTimeout(() => {
173
+ if (settled) return;
174
+ settled = true;
175
+ sock.destroy();
176
+ reject(new Error(`Apple webinspectord socket connect timed out (${this.socketPath})`));
177
+ }, this.timeoutMs);
178
+ sock.once("connect", () => {
179
+ if (settled) return;
180
+ settled = true;
181
+ clearTimeout(timer);
182
+ this.connected = true;
183
+ sock.write(
184
+ encodeWebInspectorPacket("_rpc_reportIdentifier:", {
185
+ WIRConnectionIdentifierKey: this.connectionId
186
+ })
187
+ );
188
+ resolve();
189
+ });
190
+ sock.once("error", (err) => {
191
+ if (!settled) {
192
+ settled = true;
193
+ clearTimeout(timer);
194
+ reject(err);
195
+ }
196
+ });
197
+ sock.on("data", (chunk) => {
198
+ this.readBuffer = Buffer.concat([this.readBuffer, chunk]);
199
+ const { frames, remaining } = decodeWebInspectorFrames(this.readBuffer);
200
+ this.readBuffer = remaining;
201
+ for (const frame of frames) {
202
+ this.handleFrame(frame);
203
+ }
204
+ });
205
+ sock.on("close", () => {
206
+ this.connected = false;
207
+ for (const [, p] of this.pendingRpc) {
208
+ clearTimeout(p.timer);
209
+ p.reject(new Error("Apple webinspectord socket closed"));
210
+ }
211
+ this.pendingRpc.clear();
212
+ });
213
+ });
214
+ }
215
+ handleFrame(xml) {
216
+ const parsed = parseWebInspectorXmlFrame(xml);
217
+ if (parsed.pages && parsed.pages.length > 0) {
218
+ this.pages = parsed.pages;
219
+ while (this.listingWaiters.length > 0) {
220
+ this.listingWaiters.shift()(this.pages);
221
+ }
222
+ return;
223
+ }
224
+ const msg = parsed.messageDataJson;
225
+ if (msg && typeof msg["id"] === "number") {
226
+ const entry = this.pendingRpc.get(msg["id"]);
227
+ if (!entry) return;
228
+ this.pendingRpc.delete(msg["id"]);
229
+ clearTimeout(entry.timer);
230
+ if (msg["error"]) {
231
+ entry.reject(new Error(msg["error"].message ?? JSON.stringify(msg["error"])));
232
+ } else {
233
+ entry.resolve(msg["result"]);
234
+ }
235
+ }
236
+ }
237
+ async listPages() {
238
+ if (!this.isConnected()) await this.connect();
239
+ if (this.pages.length > 0) return this.pages;
240
+ if (this.bundleId) {
241
+ this.socket.write(
242
+ encodeWebInspectorPacket("_rpc_forwardGetListing:", {
243
+ WIRConnectionIdentifierKey: this.connectionId,
244
+ WIRApplicationIdentifierKey: this.bundleId
245
+ })
246
+ );
247
+ }
248
+ return new Promise((resolve) => {
249
+ const timer = setTimeout(() => resolve(this.pages), 1500);
250
+ this.listingWaiters.push((pages) => {
251
+ clearTimeout(timer);
252
+ resolve(pages);
253
+ });
254
+ });
255
+ }
256
+ async ensurePageAttached() {
257
+ if (this.activePage) return this.activePage;
258
+ const pages = await this.listPages();
259
+ const chosen = pages.find((p) => p.url && p.url !== "about:blank") ?? pages[0];
260
+ if (!chosen) {
261
+ throw new Error(
262
+ `No inspectable WKWebView pages reported by webinspectord (${this.socketPath})`
263
+ );
264
+ }
265
+ this.activePage = chosen;
266
+ this.socket.write(
267
+ encodeWebInspectorPacket("_rpc_forwardSocketSetup:", {
268
+ WIRConnectionIdentifierKey: this.connectionId,
269
+ WIRApplicationIdentifierKey: chosen.appId,
270
+ WIRPageIdentifierKey: chosen.pageId,
271
+ WIRSenderKey: this.senderKey,
272
+ WIRAutomaticallyPause: false
273
+ })
274
+ );
275
+ return chosen;
276
+ }
277
+ async sendInspectorCommand(method, params = {}) {
278
+ const page = await this.ensurePageAttached();
279
+ const id = this.nextRpcId++;
280
+ const payload = Buffer.from(JSON.stringify({ id, method, params }), "utf-8");
281
+ return new Promise((resolve, reject) => {
282
+ const timer = setTimeout(() => {
283
+ this.pendingRpc.delete(id);
284
+ reject(new Error(`webinspectord command "${method}" timed out after ${this.timeoutMs}ms`));
285
+ }, this.timeoutMs);
286
+ this.pendingRpc.set(id, { resolve, reject, timer });
287
+ this.socket.write(
288
+ encodeWebInspectorPacket("_rpc_forwardSocketData:", {
289
+ WIRConnectionIdentifierKey: this.connectionId,
290
+ WIRApplicationIdentifierKey: page.appId,
291
+ WIRPageIdentifierKey: page.pageId,
292
+ WIRSenderKey: this.senderKey,
293
+ WIRSocketDataKey: payload
294
+ })
295
+ );
296
+ });
297
+ }
298
+ async disconnect() {
299
+ this.connected = false;
300
+ this.activePage = null;
301
+ if (this.socket) {
302
+ this.socket.destroy();
303
+ this.socket = null;
304
+ }
305
+ }
306
+ };
307
+
308
+ // src/channels/webkit-inspector.ts
309
+ init_esm_shims();
310
+ import { execSync as execSync2, spawn } from "child_process";
311
+ var WS_OPEN = 1;
312
+ function defaultWebSocketFactory(url) {
313
+ return new WebSocket(url);
314
+ }
315
+ function parseWebKitTargetListing(payload) {
316
+ if (!Array.isArray(payload)) return [];
317
+ const results = [];
318
+ for (const item of payload) {
319
+ if (!item || typeof item !== "object") continue;
320
+ const obj = item;
321
+ const id = String(obj["id"] ?? obj["pageId"] ?? obj["devtoolsFrontendUrl"] ?? "");
322
+ const wsUrl = typeof obj["webSocketDebuggerUrl"] === "string" ? obj["webSocketDebuggerUrl"] : typeof obj["wsUrl"] === "string" ? obj["wsUrl"] : void 0;
323
+ if (!id && !wsUrl) continue;
324
+ results.push({
325
+ id: id || wsUrl,
326
+ title: typeof obj["title"] === "string" ? obj["title"] : void 0,
327
+ url: typeof obj["url"] === "string" ? obj["url"] : void 0,
328
+ type: typeof obj["type"] === "string" ? obj["type"] : "page",
329
+ webSocketDebuggerUrl: wsUrl,
330
+ appId: typeof obj["appId"] === "string" ? obj["appId"] : void 0
331
+ });
332
+ }
333
+ return results;
334
+ }
335
+ function selectWebKitTarget(targets, bundleId) {
336
+ const attachable = targets.filter((t) => Boolean(t.webSocketDebuggerUrl));
337
+ if (attachable.length === 0) return void 0;
338
+ if (bundleId) {
339
+ const byBundle = attachable.find(
340
+ (t) => t.appId === bundleId || (t.url ?? "").includes(bundleId) || (t.title ?? "").includes(bundleId)
341
+ );
342
+ if (byBundle) return byBundle;
343
+ }
344
+ const nonBlank = attachable.find(
345
+ (t) => t.url && t.url !== "about:blank" && !t.url.startsWith("webkit-")
346
+ );
347
+ return nonBlank ?? attachable[0];
348
+ }
349
+ function isWebKitDebugProxyInstalled() {
350
+ try {
351
+ execSync2("which ios_webkit_debug_proxy", { stdio: "ignore" });
352
+ return true;
353
+ } catch {
354
+ return false;
355
+ }
356
+ }
357
+ var WebKitInspectorChannel = class {
358
+ kind = "webkit-inspector";
359
+ endpointUrl;
360
+ explicitWsUrl;
361
+ udid;
362
+ bundleId;
363
+ port;
364
+ autoStartProxy;
365
+ timeoutMs;
366
+ fetchFn;
367
+ createWebSocket;
368
+ ws = null;
369
+ nativeInspector = null;
370
+ proxyProcess = null;
371
+ connected = false;
372
+ nextId = 1;
373
+ pending = /* @__PURE__ */ new Map();
374
+ currentTargetId = null;
375
+ constructor(options = {}) {
376
+ this.port = options.port ?? 9221;
377
+ this.endpointUrl = (options.endpointUrl ?? `http://127.0.0.1:${this.port}`).replace(/\/+$/, "");
378
+ this.explicitWsUrl = options.webSocketUrl;
379
+ this.udid = options.udid;
380
+ this.bundleId = options.bundleId;
381
+ this.autoStartProxy = options.autoStartProxy ?? false;
382
+ this.timeoutMs = options.timeoutMs ?? 1e4;
383
+ this.fetchFn = options.fetchFn ?? fetch;
384
+ this.createWebSocket = options.createWebSocket ?? defaultWebSocketFactory;
385
+ }
386
+ isConnected() {
387
+ return this.connected && this.ws !== null && this.ws.readyState === WS_OPEN || (this.nativeInspector?.isConnected() ?? false);
388
+ }
389
+ async ensureProxyIfNeeded() {
390
+ if (!this.autoStartProxy || this.proxyProcess || !this.udid) return;
391
+ if (!isWebKitDebugProxyInstalled()) return;
392
+ try {
393
+ const probe = await this.fetchFn(`${this.endpointUrl}/json`);
394
+ if (probe.ok) return;
395
+ } catch {
396
+ }
397
+ const proc = spawn("ios_webkit_debug_proxy", ["-c", `${this.udid}:${this.port}`, "-d"], {
398
+ stdio: "ignore",
399
+ detached: true
400
+ });
401
+ proc.unref();
402
+ this.proxyProcess = proc;
403
+ const deadline = Date.now() + 3e3;
404
+ while (Date.now() < deadline) {
405
+ try {
406
+ const res = await this.fetchFn(`${this.endpointUrl}/json`);
407
+ if (res.ok) return;
408
+ } catch {
409
+ }
410
+ await new Promise((r) => setTimeout(r, 150));
411
+ }
412
+ }
413
+ async fetchTargets() {
414
+ for (const path of ["/json", "/json/list"]) {
415
+ try {
416
+ const res = await this.fetchFn(`${this.endpointUrl}${path}`);
417
+ if (!res.ok) continue;
418
+ const data = await res.json();
419
+ const parsed = parseWebKitTargetListing(data);
420
+ if (parsed.length > 0 || Array.isArray(data)) {
421
+ return parsed;
422
+ }
423
+ } catch {
424
+ }
425
+ }
426
+ throw new Error(
427
+ `WebKit Inspector unreachable at ${this.endpointUrl}. Ensure WKWebView.isInspectable = true (iOS 16.4+) and start ios_webkit_debug_proxy (or use spana-bridge for zero-protocol DOM access).`
428
+ );
429
+ }
430
+ async listTargets() {
431
+ await this.ensureProxyIfNeeded();
432
+ const targets = await this.fetchTargets();
433
+ return targets.map((t) => ({
434
+ id: t.id,
435
+ title: t.title,
436
+ url: t.url,
437
+ type: t.type
438
+ }));
439
+ }
440
+ async selectTarget(targetId) {
441
+ const targets = await this.fetchTargets();
442
+ const match = targets.find((t) => t.id === targetId && t.webSocketDebuggerUrl);
443
+ if (!match?.webSocketDebuggerUrl) {
444
+ throw new Error(`WebKit Inspector: target "${targetId}" not found`);
445
+ }
446
+ await this.disconnectSocketOnly();
447
+ this.currentTargetId = match.id;
448
+ await this.openSocket(match.webSocketDebuggerUrl);
449
+ }
450
+ async connect() {
451
+ if (this.isConnected()) return;
452
+ let wsUrl = this.explicitWsUrl;
453
+ if (!wsUrl) {
454
+ await this.ensureProxyIfNeeded();
455
+ try {
456
+ const targets = await this.fetchTargets();
457
+ const chosen = selectWebKitTarget(targets, this.bundleId);
458
+ if (!chosen?.webSocketDebuggerUrl) {
459
+ throw new Error(
460
+ `WebKit Inspector: no inspectable WKWebView page found at ${this.endpointUrl}. Verify webView.isInspectable = true on iOS 16.4+.`
461
+ );
462
+ }
463
+ this.currentTargetId = chosen.id;
464
+ wsUrl = chosen.webSocketDebuggerUrl;
465
+ } catch (proxyErr) {
466
+ const nativeSock = findSimulatorWebInspectorSocket(this.udid);
467
+ if (!nativeSock) {
468
+ throw proxyErr;
469
+ }
470
+ this.nativeInspector = new AppleWebInspectorClient({
471
+ socketPath: nativeSock,
472
+ bundleId: this.bundleId,
473
+ timeoutMs: this.timeoutMs
474
+ });
475
+ await this.nativeInspector.connect();
476
+ await this.nativeInspector.ensurePageAttached();
477
+ return;
478
+ }
479
+ }
480
+ await this.openSocket(wsUrl);
481
+ }
482
+ async openSocket(wsUrl) {
483
+ await new Promise((resolve, reject) => {
484
+ const ws = this.createWebSocket(wsUrl);
485
+ this.ws = ws;
486
+ let settled = false;
487
+ const timer = setTimeout(() => {
488
+ if (settled) return;
489
+ settled = true;
490
+ reject(
491
+ new Error(`WebKit Inspector connection to ${wsUrl} timed out after ${this.timeoutMs}ms`)
492
+ );
493
+ }, this.timeoutMs);
494
+ const onOpen = () => {
495
+ if (settled) return;
496
+ settled = true;
497
+ clearTimeout(timer);
498
+ this.connected = true;
499
+ resolve();
500
+ };
501
+ const onError = (err) => {
502
+ const error = new Error(
503
+ `WebKit Inspector WebSocket error: ${err instanceof Error ? err.message : String(err)}`
504
+ );
505
+ if (!settled) {
506
+ settled = true;
507
+ clearTimeout(timer);
508
+ reject(error);
509
+ }
510
+ };
511
+ const onClose = () => {
512
+ this.connected = false;
513
+ this.rejectAllPending(new Error("WebKit Inspector WebSocket closed"));
514
+ };
515
+ const onMessage = (event) => {
516
+ const raw = typeof event.data === "string" ? event.data : String(event.data ?? "");
517
+ let parsed;
518
+ try {
519
+ parsed = JSON.parse(raw);
520
+ } catch {
521
+ return;
522
+ }
523
+ const id = parsed["id"];
524
+ if (typeof id === "number") {
525
+ const entry = this.pending.get(id);
526
+ if (!entry) return;
527
+ this.pending.delete(id);
528
+ clearTimeout(entry.timer);
529
+ if (parsed["error"]) {
530
+ const msg = parsed["error"].message ?? JSON.stringify(parsed["error"]);
531
+ entry.reject(new Error(`WebKit Inspector error: ${msg}`));
532
+ } else {
533
+ entry.resolve(parsed["result"]);
534
+ }
535
+ }
536
+ };
537
+ ws.addEventListener("open", onOpen);
538
+ ws.addEventListener("error", onError);
539
+ ws.addEventListener("close", onClose);
540
+ ws.addEventListener("message", onMessage);
541
+ if (ws.readyState === WS_OPEN) {
542
+ onOpen();
543
+ }
544
+ });
545
+ }
546
+ rejectAllPending(error) {
547
+ for (const [, entry] of this.pending) {
548
+ clearTimeout(entry.timer);
549
+ entry.reject(error);
550
+ }
551
+ this.pending.clear();
552
+ }
553
+ async sendCommand(method, params = {}) {
554
+ if (!this.isConnected()) {
555
+ await this.connect();
556
+ }
557
+ if (this.nativeInspector?.isConnected()) {
558
+ return this.nativeInspector.sendInspectorCommand(method, params);
559
+ }
560
+ const ws = this.ws;
561
+ const id = this.nextId++;
562
+ return new Promise((resolve, reject) => {
563
+ const timer = setTimeout(() => {
564
+ this.pending.delete(id);
565
+ reject(
566
+ new Error(`WebKit Inspector command "${method}" timed out after ${this.timeoutMs}ms`)
567
+ );
568
+ }, this.timeoutMs);
569
+ this.pending.set(id, { resolve, reject, timer });
570
+ ws.send(JSON.stringify({ id, method, params }));
571
+ });
572
+ }
573
+ async evaluate(script, ...args) {
574
+ const expression = buildEvaluateExpression(script, args);
575
+ const response = await this.sendCommand("Runtime.evaluate", {
576
+ expression,
577
+ returnByValue: true,
578
+ awaitPromise: true,
579
+ includeCommandLineAPI: false
580
+ });
581
+ if (response?.wasThrown) {
582
+ throw new Error(
583
+ `WebKit Inspector evaluate failed: ${response.result?.description ?? "Evaluation threw"}`
584
+ );
585
+ }
586
+ if (response?.exceptionDetails) {
587
+ const detail = response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? "Evaluation threw";
588
+ throw new Error(`WebKit Inspector evaluate failed: ${detail}`);
589
+ }
590
+ return response?.result?.value;
591
+ }
592
+ async query(selector) {
593
+ const result = await this.evaluate(buildDomQueryScript(selector));
594
+ return Array.isArray(result) ? result : [];
595
+ }
596
+ async tapDom(selector) {
597
+ const result = await this.evaluate(buildDomTapScript(selector));
598
+ return Boolean(result);
599
+ }
600
+ async scrollIntoView(selector) {
601
+ const result = await this.evaluate(
602
+ buildDomScrollIntoViewScript(selector)
603
+ );
604
+ return result ?? null;
605
+ }
606
+ async reload() {
607
+ await this.sendCommand("Page.reload", { ignoreCache: false }).catch(async () => {
608
+ await this.evaluate("window.location.reload()");
609
+ });
610
+ }
611
+ async disconnectSocketOnly() {
612
+ this.connected = false;
613
+ this.rejectAllPending(new Error("WebKit Inspector disconnected"));
614
+ if (this.ws) {
615
+ try {
616
+ this.ws.close();
617
+ } catch {
618
+ }
619
+ this.ws = null;
620
+ }
621
+ if (this.nativeInspector) {
622
+ await this.nativeInspector.disconnect();
623
+ this.nativeInspector = null;
624
+ }
625
+ }
626
+ async disconnect() {
627
+ await this.disconnectSocketOnly();
628
+ if (this.proxyProcess) {
629
+ try {
630
+ this.proxyProcess.kill();
631
+ } catch {
632
+ }
633
+ this.proxyProcess = null;
634
+ }
635
+ }
636
+ get targetId() {
637
+ return this.currentTargetId;
638
+ }
639
+ };
640
+ function createWebKitInspectorChannel(options = {}) {
641
+ return new WebKitInspectorChannel(options);
642
+ }
643
+
644
+ export {
645
+ encodeWebInspectorPacket,
646
+ decodeWebInspectorFrames,
647
+ parseWebInspectorXmlFrame,
648
+ findSimulatorWebInspectorSocket,
649
+ AppleWebInspectorClient,
650
+ isWebKitDebugProxyInstalled,
651
+ WebKitInspectorChannel,
652
+ createWebKitInspectorChannel
653
+ };
654
+ //# sourceMappingURL=chunk-KWIB77C7.js.map