@snap/valdi 1.1.7 → 1.2.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 (74) hide show
  1. package/.metadata/.bazelrc.template +8 -2
  2. package/.metadata/MODULE.bazel.template +20 -3
  3. package/.metadata/bzl/patches/rules_python/1.9.0/BUILD.bazel.template +1 -0
  4. package/.metadata/bzl/patches/rules_python/1.9.0/remove_setuptools_spaces.patch.template +96 -0
  5. package/README.md +35 -1
  6. package/bundled-skills/registry.json +2 -1
  7. package/bundled-skills/skills/valdi-animations/skill.md +49 -0
  8. package/bundled-skills/skills/valdi-async/skill.md +3 -2
  9. package/bundled-skills/skills/valdi-bazel/skill.md +2 -6
  10. package/bundled-skills/skills/valdi-cpp-runtime/skill.md +18 -0
  11. package/bundled-skills/skills/valdi-error-handling/skill.md +1 -1
  12. package/bundled-skills/skills/valdi-gestures/skill.md +3 -3
  13. package/bundled-skills/skills/valdi-migrate/skill.md +2 -1
  14. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +4 -4
  15. package/bundled-skills/skills/valdi-mock-to-module/skill.md +9 -6
  16. package/bundled-skills/skills/valdi-overview/skill.md +2 -1
  17. package/bundled-skills/skills/valdi-perf/skill.md +121 -5
  18. package/bundled-skills/skills/valdi-pr-review/skill.md +189 -0
  19. package/bundled-skills/skills/valdi-profile/skill.md +5 -3
  20. package/bundled-skills/skills/valdi-setup/skill.md +3 -6
  21. package/bundled-skills/skills/valdi-testing/skill.md +1 -1
  22. package/bundled-skills/skills/valdi-tsx/skill.md +47 -11
  23. package/debugger/README.md +356 -0
  24. package/debugger/debugger-actions.js +373 -0
  25. package/debugger/debugger-api.js +225 -0
  26. package/debugger/debugger-bootstrap.js +295 -0
  27. package/debugger/debugger-model.js +790 -0
  28. package/debugger/debugger-performance.js +573 -0
  29. package/debugger/debugger-preview-html.js +676 -0
  30. package/debugger/debugger-providers.js +389 -0
  31. package/debugger/debugger-render.js +529 -0
  32. package/debugger/debugger-runtime.js +387 -0
  33. package/debugger/debugger-session.js +188 -0
  34. package/debugger/debugger-settings.js +209 -0
  35. package/debugger/debugger-state.js +221 -0
  36. package/debugger/debugger-tree-model.js +539 -0
  37. package/debugger/debugger.css +1865 -0
  38. package/debugger/devtools-panel.css +1318 -0
  39. package/debugger/devtools-panel.html +273 -0
  40. package/debugger/devtools-panel.js +3329 -0
  41. package/debugger/index.html +279 -0
  42. package/dist/commands/bootstrap.js +6 -5
  43. package/dist/commands/debugger.js +163 -0
  44. package/dist/commands/doctor.js +3 -62
  45. package/dist/commands/inspect.js +5 -2
  46. package/dist/commands/inspect_commands/input.js +176 -0
  47. package/dist/commands/inspect_commands/snapshot.js +1 -1
  48. package/dist/commands/inspect_commands/tree.js +1 -1
  49. package/dist/commands/projectsync.js +15 -0
  50. package/dist/commands/webHotreload.js +31 -0
  51. package/dist/core/constants.js +22 -6
  52. package/dist/debugger/chromiumConsole.js +279 -0
  53. package/dist/debugger/inputClient.js +473 -0
  54. package/dist/debugger/server.js +3801 -0
  55. package/dist/debugger/targetRegistry.js +436 -0
  56. package/dist/debugger/webPreviewPerformance.js +864 -0
  57. package/dist/index.js +0 -0
  58. package/dist/utils/BazelClient.js +34 -5
  59. package/dist/utils/applicationUtils.js +3 -0
  60. package/dist/utils/chromiumDevToolsClient.js +350 -0
  61. package/dist/utils/daemonClient.js +364 -44
  62. package/dist/utils/hermesClient.js +82 -176
  63. package/dist/utils/loopbackHost.js +14 -0
  64. package/dist/utils/owlCdpClient.js +282 -0
  65. package/dist/utils/owlDevToolsExtension.js +142 -0
  66. package/dist/utils/stringUtils.js +13 -1
  67. package/package.json +4 -2
  68. package/dist/commands/inspect_commands/snapshot.spec.js +0 -105
  69. package/dist/core/packageFiles.spec.js +0 -29
  70. package/dist/preview/previewGenerator.spec.js +0 -203
  71. package/dist/preview/viewModelParser.spec.js +0 -171
  72. package/dist/utils/linuxDistro.spec.js +0 -122
  73. package/dist/utils/skillsAdapters.spec.js +0 -141
  74. package/dist/utils/stringUtils.spec.js +0 -81
@@ -4,11 +4,13 @@ exports.HermesConnection = exports.NotHermesError = exports.HERMES_BUILD_FLAG =
4
4
  exports.listHermesDevices = listHermesDevices;
5
5
  exports.normalizeHermesProfile = normalizeHermesProfile;
6
6
  const tslib_1 = require("tslib");
7
- const net = tslib_1.__importStar(require("net"));
8
- const crypto = tslib_1.__importStar(require("crypto"));
9
7
  const http = tslib_1.__importStar(require("http"));
8
+ const node_util_1 = require("node:util");
10
9
  const errors_1 = require("../core/errors");
11
- exports.HERMES_PORT = 13595;
10
+ const chromiumDevToolsClient_1 = require("./chromiumDevToolsClient");
11
+ exports.HERMES_PORT = 13_595;
12
+ const MAX_HERMES_DISCOVERY_BYTES = 1024 * 1024;
13
+ const FATAL_UTF8_DECODER = new node_util_1.TextDecoder('utf8', { fatal: true });
12
14
  exports.HERMES_BUILD_FLAG = '--@valdi//bzl/valdi:js_engine=hermes --@valdi//bzl/valdi:js_bytecode_format=hermes';
13
15
  class NotHermesError extends errors_1.CliError {
14
16
  constructor(port) {
@@ -24,58 +26,69 @@ class NotHermesError extends errors_1.CliError {
24
26
  exports.NotHermesError = NotHermesError;
25
27
  async function listHermesDevices(port) {
26
28
  return new Promise((resolve, reject) => {
29
+ let settled = false;
30
+ function fail(error) {
31
+ if (settled)
32
+ return;
33
+ settled = true;
34
+ reject(error);
35
+ }
27
36
  const timer = setTimeout(() => {
28
37
  req.destroy();
29
- reject(new NotHermesError(port));
30
- }, 3_000);
38
+ fail(new NotHermesError(port));
39
+ }, 3000);
31
40
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
32
- let body = '';
33
- res.on('data', (chunk) => { body += chunk; });
34
- res.on('end', () => {
41
+ const chunks = [];
42
+ let bodyBytes = 0;
43
+ res.on('data', (chunk) => {
44
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
45
+ if (buffer.length > MAX_HERMES_DISCOVERY_BYTES - bodyBytes) {
46
+ clearTimeout(timer);
47
+ fail(new errors_1.CliError(`Hermes discovery exceeded the ${MAX_HERMES_DISCOVERY_BYTES} byte response limit.`));
48
+ res.destroy();
49
+ req.destroy();
50
+ return;
51
+ }
52
+ bodyBytes += buffer.length;
53
+ chunks.push(buffer);
54
+ });
55
+ res.once('error', error => {
56
+ clearTimeout(timer);
57
+ fail(error);
58
+ });
59
+ res.once('end', () => {
60
+ if (settled)
61
+ return;
35
62
  clearTimeout(timer);
63
+ let body;
36
64
  try {
37
- resolve(JSON.parse(body));
65
+ body = FATAL_UTF8_DECODER.decode(Buffer.concat(chunks, bodyBytes));
38
66
  }
39
67
  catch {
40
- reject(new errors_1.CliError(`Invalid response from Hermes debug server on port ${port}`));
68
+ fail(new errors_1.CliError(`Hermes debug server on port ${port} returned malformed UTF-8`));
69
+ return;
70
+ }
71
+ try {
72
+ const devices = JSON.parse(body);
73
+ settled = true;
74
+ resolve(devices);
75
+ }
76
+ catch {
77
+ fail(new errors_1.CliError(`Invalid response from Hermes debug server on port ${port}`));
41
78
  }
42
79
  });
43
80
  });
44
81
  req.on('error', (err) => {
45
82
  clearTimeout(timer);
46
83
  if (err.code === 'ECONNREFUSED') {
47
- reject(new NotHermesError(port));
84
+ fail(new NotHermesError(port));
48
85
  }
49
86
  else {
50
- reject(err);
87
+ fail(err);
51
88
  }
52
89
  });
53
90
  });
54
91
  }
55
- function encodeWsFrame(text) {
56
- const payload = Buffer.from(text, 'utf8');
57
- const mask = crypto.randomBytes(4);
58
- const masked = Buffer.alloc(payload.length);
59
- for (let i = 0; i < payload.length; i++) {
60
- masked[i] = payload[i] ^ mask[i % 4];
61
- }
62
- const len = payload.length;
63
- let header;
64
- if (len < 126) {
65
- header = Buffer.alloc(6);
66
- header[0] = 0x81;
67
- header[1] = 0x80 | len;
68
- mask.copy(header, 2);
69
- }
70
- else {
71
- header = Buffer.alloc(8);
72
- header[0] = 0x81;
73
- header[1] = 0x80 | 126;
74
- header.writeUInt16BE(len, 2);
75
- mask.copy(header, 4);
76
- }
77
- return Buffer.concat([header, masked]);
78
- }
79
92
  function normalizeHermesProfile(profile) {
80
93
  const { samples = [], timeDeltas = [], startTime, endTime, nodes } = profile;
81
94
  if (samples.length < 2 || timeDeltas.length < 2)
@@ -96,157 +109,50 @@ function normalizeHermesProfile(profile) {
96
109
  return { nodes, startTime: realStart, endTime, samples: realSamples, timeDeltas: newDeltas };
97
110
  }
98
111
  class HermesConnection {
99
- socket;
100
- recvBuf = Buffer.alloc(0);
101
- callId = 0;
102
- pending = new Map();
103
- constructor(socket) {
104
- this.socket = socket;
105
- socket.on('data', (chunk) => this.onData(chunk));
106
- socket.on('close', () => {
107
- this.rejectAll(new Error('Hermes debug WebSocket closed unexpectedly'));
108
- });
109
- socket.on('error', (err) => this.rejectAll(err));
112
+ connection;
113
+ constructor(connection) {
114
+ this.connection = connection;
110
115
  }
111
- static connect(port, deviceId) {
112
- return new Promise((resolve, reject) => {
113
- const socket = net.createConnection({ port, host: '127.0.0.1' });
114
- const timer = setTimeout(() => {
115
- socket.destroy();
116
- reject(new errors_1.CliError(`Timeout connecting to Hermes debug socket on port ${port}.\n` +
117
- `Make sure the Valdi app is running and the hot-reloader is active.`));
118
- }, 5_000);
119
- socket.once('error', (err) => {
120
- clearTimeout(timer);
121
- if (err.code === 'ECONNREFUSED') {
122
- reject(new NotHermesError(port));
123
- }
124
- else {
125
- reject(err);
126
- }
127
- });
128
- socket.once('connect', () => {
129
- const key = crypto.randomBytes(16).toString('base64');
130
- const handshake = `GET /${deviceId} HTTP/1.1\r\n` +
131
- `Host: localhost:${port}\r\n` +
132
- `Upgrade: websocket\r\n` +
133
- `Connection: Upgrade\r\n` +
134
- `Sec-WebSocket-Key: ${key}\r\n` +
135
- `Sec-WebSocket-Version: 13\r\n` +
136
- `\r\n`;
137
- socket.write(handshake);
138
- let handshakeBuf = '';
139
- const onHandshakeData = (chunk) => {
140
- handshakeBuf += chunk.toString('utf8');
141
- if (handshakeBuf.includes('\r\n\r\n')) {
142
- socket.removeListener('data', onHandshakeData);
143
- clearTimeout(timer);
144
- if (!handshakeBuf.includes('101 Switching Protocols')) {
145
- socket.destroy();
146
- reject(new errors_1.CliError(`Hermes WebSocket handshake failed: ${handshakeBuf.slice(0, 100)}`));
147
- return;
148
- }
149
- resolve(new HermesConnection(socket));
150
- }
151
- };
152
- socket.on('data', onHandshakeData);
153
- });
154
- });
116
+ static encodeDeviceId(deviceId) {
117
+ if (!deviceId || deviceId === '.' || deviceId === '..') {
118
+ throw new errors_1.CliError('The Hermes debugger device id must be a non-empty WebSocket path segment.');
119
+ }
120
+ try {
121
+ return encodeURIComponent(deviceId);
122
+ }
123
+ catch {
124
+ throw new errors_1.CliError('The Hermes debugger device id contains invalid Unicode.');
125
+ }
126
+ }
127
+ static async connect(port, deviceId) {
128
+ const encodedDeviceId = HermesConnection.encodeDeviceId(deviceId);
129
+ try {
130
+ const connection = await chromiumDevToolsClient_1.ChromiumDevToolsConnection.connect(`ws://127.0.0.1:${port}/${encodedDeviceId}`, 5000);
131
+ return new HermesConnection(connection);
132
+ }
133
+ catch (error) {
134
+ if (error.code === 'ECONNREFUSED') {
135
+ throw new NotHermesError(port);
136
+ }
137
+ if (error instanceof Error && error.message === 'Timed out connecting to the Chromium DevTools target.') {
138
+ throw new errors_1.CliError(`Timeout connecting to Hermes debug socket on port ${port}. ` +
139
+ 'Make sure the Valdi app is running and the hot-reloader is active.');
140
+ }
141
+ throw error;
142
+ }
155
143
  }
156
144
  call(method, params = {}, timeoutMs = 10_000) {
157
- const id = ++this.callId;
158
- return new Promise((resolve, reject) => {
159
- const timer = setTimeout(() => {
160
- this.pending.delete(id);
161
- reject(new Error(`Timeout waiting for response to ${method}`));
162
- }, timeoutMs);
163
- this.pending.set(id, {
164
- resolve: (v) => { clearTimeout(timer); resolve(v); },
165
- reject: (e) => { clearTimeout(timer); reject(e); },
166
- });
167
- this.socket.write(encodeWsFrame(JSON.stringify({ id, method, params })));
168
- });
145
+ return this.connection.call(method, params, timeoutMs);
169
146
  }
170
147
  async startProfiling() {
171
148
  await this.call('Profiler.start');
172
149
  }
173
150
  async stopProfiling() {
174
- const result = await this.call('Profiler.stop', {}, 60_000);
151
+ const result = (await this.call('Profiler.stop', {}, 60_000));
175
152
  return normalizeHermesProfile(result.profile);
176
153
  }
177
154
  close() {
178
- this.socket.destroy();
179
- }
180
- rejectAll(err) {
181
- for (const pending of this.pending.values())
182
- pending.reject(err);
183
- this.pending.clear();
184
- }
185
- onData(chunk) {
186
- this.recvBuf = Buffer.concat([this.recvBuf, chunk]);
187
- this.drainBuffer();
188
- }
189
- drainBuffer() {
190
- for (;;) {
191
- if (this.recvBuf.length < 2)
192
- break;
193
- const firstByte = this.recvBuf[0];
194
- const secondByte = this.recvBuf[1];
195
- const opcode = firstByte & 0x0f;
196
- if (opcode === 0x08) {
197
- this.rejectAll(new Error('Hermes debug WebSocket closed by server'));
198
- return;
199
- }
200
- const isMasked = (secondByte & 0x80) !== 0;
201
- let payloadLen = secondByte & 0x7f;
202
- let offset = 2;
203
- if (payloadLen === 126) {
204
- if (this.recvBuf.length < 4)
205
- break;
206
- payloadLen = this.recvBuf.readUInt16BE(2);
207
- offset = 4;
208
- }
209
- else if (payloadLen === 127) {
210
- if (this.recvBuf.length < 10)
211
- break;
212
- payloadLen = this.recvBuf.readUInt32BE(6);
213
- offset = 10;
214
- }
215
- const maskLen = isMasked ? 4 : 0;
216
- const totalLen = offset + maskLen + payloadLen;
217
- if (this.recvBuf.length < totalLen)
218
- break;
219
- if (opcode !== 0x01 && opcode !== 0x02) {
220
- this.recvBuf = this.recvBuf.subarray(totalLen);
221
- continue;
222
- }
223
- let payload = this.recvBuf.subarray(offset + maskLen, totalLen);
224
- if (isMasked) {
225
- const mask = this.recvBuf.subarray(offset, offset + 4);
226
- payload = Buffer.from(payload.map((b, i) => b ^ mask[i % 4]));
227
- }
228
- this.recvBuf = this.recvBuf.subarray(totalLen);
229
- try {
230
- this.dispatchMessage(JSON.parse(payload.toString('utf8')));
231
- }
232
- catch {
233
- }
234
- }
235
- }
236
- dispatchMessage(msg) {
237
- if (typeof msg['id'] !== 'number')
238
- return;
239
- const pending = this.pending.get(msg['id']);
240
- if (!pending)
241
- return;
242
- this.pending.delete(msg['id']);
243
- if (msg['error']) {
244
- const err = msg['error'];
245
- pending.reject(new Error(String(err['message'] ?? 'Unknown CDP error')));
246
- }
247
- else {
248
- pending.resolve(msg['result']);
249
- }
155
+ this.connection.close();
250
156
  }
251
157
  }
252
158
  exports.HermesConnection = HermesConnection;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizedHostname = normalizedHostname;
4
+ exports.isLoopbackHost = isLoopbackHost;
5
+ const tslib_1 = require("tslib");
6
+ const node_net_1 = tslib_1.__importDefault(require("node:net"));
7
+ function normalizedHostname(hostname) {
8
+ const unwrapped = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
9
+ return unwrapped.toLowerCase();
10
+ }
11
+ function isLoopbackHost(hostname) {
12
+ const normalized = normalizedHostname(hostname);
13
+ return (normalized === 'localhost' || normalized === '::1' || (node_net_1.default.isIP(normalized) === 4 && normalized.startsWith('127.')));
14
+ }
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OwlChromiumConnection = exports.OWL_DEVTOOLS_TARGET_NONCE_PROPERTY = void 0;
4
+ exports.matchesOwlApplicationUrl = matchesOwlApplicationUrl;
5
+ exports.listOwlChromiumTargets = listOwlChromiumTargets;
6
+ exports.connectToOwlApplication = connectToOwlApplication;
7
+ exports.readOwlDebuggerSnapshot = readOwlDebuggerSnapshot;
8
+ exports.evaluateOwlApplicationExpression = evaluateOwlApplicationExpression;
9
+ const tslib_1 = require("tslib");
10
+ const node_http_1 = tslib_1.__importDefault(require("node:http"));
11
+ const node_util_1 = require("node:util");
12
+ const chromiumDevToolsClient_1 = require("./chromiumDevToolsClient");
13
+ const loopbackHost_1 = require("./loopbackHost");
14
+ const CHROMIUM_DISCOVERY_TIMEOUT_MS = 3000;
15
+ const CHROMIUM_COMMAND_TIMEOUT_MS = 8000;
16
+ const MAX_CHROMIUM_DISCOVERY_BYTES = 1024 * 1024;
17
+ const MAX_CHROMIUM_DISCOVERY_TARGETS = 256;
18
+ const VALDI_INJECTED_QUERY_PARAMETERS = ['valdiDebugger', 'valdiDevTools', 'valdiTrace'];
19
+ const FATAL_UTF8_DECODER = new node_util_1.TextDecoder('utf8', { fatal: true });
20
+ const GUARDED_TARGET_MATCH_PROPERTY = '__valdiDevToolsTargetMatched';
21
+ exports.OWL_DEVTOOLS_TARGET_NONCE_PROPERTY = '__VALDI_DEVTOOLS_TARGET_NONCE__';
22
+ function chromiumError(error, fallback) {
23
+ if (error instanceof Error)
24
+ return error;
25
+ if (typeof error === 'string' && error)
26
+ return new Error(error);
27
+ return new Error(fallback);
28
+ }
29
+ function isWebSocketForDiscoveryPort(value, port) {
30
+ try {
31
+ const url = new URL(value);
32
+ return (url.protocol === 'ws:' &&
33
+ (0, loopbackHost_1.isLoopbackHost)(url.hostname) &&
34
+ !url.username &&
35
+ !url.password &&
36
+ Number.parseInt(url.port || '80', 10) === port);
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ function canonicalApplicationUrl(value, removeInjectedParameters) {
43
+ const url = new URL(value);
44
+ if (removeInjectedParameters) {
45
+ for (const parameter of VALDI_INJECTED_QUERY_PARAMETERS)
46
+ url.searchParams.delete(parameter);
47
+ }
48
+ const entries = Array.from(url.searchParams.entries()).sort(([firstName], [secondName]) => {
49
+ if (firstName !== secondName)
50
+ return firstName < secondName ? -1 : 1;
51
+ return 0;
52
+ });
53
+ url.search = '';
54
+ for (const [name, value] of entries)
55
+ url.searchParams.append(name, value);
56
+ return `${url.origin}${url.pathname}${url.search}`;
57
+ }
58
+ function matchesOwlApplicationUrl(inspectedUrl, applicationUrl) {
59
+ try {
60
+ return canonicalApplicationUrl(inspectedUrl, true) === canonicalApplicationUrl(applicationUrl, false);
61
+ }
62
+ catch (error) {
63
+ console.warn('[Valdi Owl] Ignoring invalid Chromium target URL.', error);
64
+ return false;
65
+ }
66
+ }
67
+ async function listOwlChromiumTargets(port) {
68
+ return await new Promise((resolve, reject) => {
69
+ let settled = false;
70
+ let activeResponse;
71
+ function fail(error) {
72
+ if (settled)
73
+ return;
74
+ settled = true;
75
+ clearTimeout(deadline);
76
+ activeResponse?.destroy();
77
+ request.destroy();
78
+ reject(error);
79
+ }
80
+ function succeed(targets) {
81
+ if (settled)
82
+ return;
83
+ settled = true;
84
+ clearTimeout(deadline);
85
+ resolve(targets);
86
+ }
87
+ const request = node_http_1.default.get(`http://127.0.0.1:${port}/json/list`, response => {
88
+ activeResponse = response;
89
+ if (response.statusCode !== 200) {
90
+ fail(new Error(`Owl Chromium discovery returned HTTP ${String(response.statusCode)}.`));
91
+ return;
92
+ }
93
+ const chunks = [];
94
+ let bodyBytes = 0;
95
+ response.on('data', (chunk) => {
96
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
97
+ const chunkBytes = buffer.length;
98
+ if (chunkBytes > MAX_CHROMIUM_DISCOVERY_BYTES - bodyBytes) {
99
+ fail(new Error(`Owl Chromium discovery exceeded the ${MAX_CHROMIUM_DISCOVERY_BYTES} byte response limit.`));
100
+ return;
101
+ }
102
+ bodyBytes += chunkBytes;
103
+ chunks.push(buffer);
104
+ });
105
+ response.once('error', error => fail(error));
106
+ response.once('end', () => {
107
+ if (settled)
108
+ return;
109
+ let body;
110
+ try {
111
+ body = FATAL_UTF8_DECODER.decode(Buffer.concat(chunks, bodyBytes));
112
+ }
113
+ catch {
114
+ fail(new Error('Owl Chromium discovery returned malformed UTF-8.'));
115
+ return;
116
+ }
117
+ try {
118
+ const parsed = JSON.parse(body);
119
+ if (!Array.isArray(parsed)) {
120
+ fail(new Error('Owl Chromium discovery did not return a target list.'));
121
+ return;
122
+ }
123
+ if (parsed.length > MAX_CHROMIUM_DISCOVERY_TARGETS) {
124
+ fail(new Error(`Owl Chromium discovery returned more than ${MAX_CHROMIUM_DISCOVERY_TARGETS} targets.`));
125
+ return;
126
+ }
127
+ const targets = parsed.filter((item) => {
128
+ if (typeof item !== 'object' || item === null)
129
+ return false;
130
+ const target = item;
131
+ return (typeof target.id === 'string' &&
132
+ typeof target.title === 'string' &&
133
+ typeof target.type === 'string' &&
134
+ typeof target.url === 'string' &&
135
+ typeof target.webSocketDebuggerUrl === 'string' &&
136
+ isWebSocketForDiscoveryPort(target.webSocketDebuggerUrl, port));
137
+ });
138
+ succeed(targets);
139
+ }
140
+ catch (error) {
141
+ fail(chromiumError(error, 'Owl Chromium discovery returned invalid JSON.'));
142
+ }
143
+ });
144
+ });
145
+ const deadline = setTimeout(() => {
146
+ fail(new Error(`Timed out discovering Owl Chromium targets on port ${port}.`));
147
+ }, CHROMIUM_DISCOVERY_TIMEOUT_MS);
148
+ request.once('error', error => fail(error));
149
+ });
150
+ }
151
+ function guardedOwlExpression(applicationUrl, targetNonce, expression) {
152
+ const expectedUrl = canonicalApplicationUrl(applicationUrl, false);
153
+ return `(async () => {
154
+ const currentUrl = new URL(globalThis.location.href);
155
+ for (const parameter of ${JSON.stringify(VALDI_INJECTED_QUERY_PARAMETERS)}) currentUrl.searchParams.delete(parameter);
156
+ const entries = Array.from(currentUrl.searchParams.entries()).sort(([firstName], [secondName]) =>
157
+ firstName === secondName ? 0 : firstName < secondName ? -1 : 1
158
+ );
159
+ currentUrl.search = '';
160
+ for (const [name, value] of entries) currentUrl.searchParams.append(name, value);
161
+ const canonicalUrl = currentUrl.origin + currentUrl.pathname + currentUrl.search;
162
+ if (
163
+ globalThis[${JSON.stringify(exports.OWL_DEVTOOLS_TARGET_NONCE_PROPERTY)}] !== ${JSON.stringify(targetNonce)} ||
164
+ canonicalUrl !== ${JSON.stringify(expectedUrl)}
165
+ ) {
166
+ return { ${JSON.stringify(GUARDED_TARGET_MATCH_PROPERTY)}: false };
167
+ }
168
+ return {
169
+ ${JSON.stringify(GUARDED_TARGET_MATCH_PROPERTY)}: true,
170
+ value: await (${expression}),
171
+ };
172
+ })()`;
173
+ }
174
+ async function evaluateGuardedOwlExpression(connection, applicationUrl, targetNonce, expression) {
175
+ const result = await connection.evaluate(guardedOwlExpression(applicationUrl, targetNonce, expression));
176
+ if (typeof result !== 'object' || result === null || Array.isArray(result)) {
177
+ throw new Error('The running Owl page returned an invalid guarded evaluation result.');
178
+ }
179
+ const record = result;
180
+ if (record[GUARDED_TARGET_MATCH_PROPERTY] === false)
181
+ return { matched: false };
182
+ if (record[GUARDED_TARGET_MATCH_PROPERTY] !== true) {
183
+ throw new Error('The running Owl page omitted its guarded target identity.');
184
+ }
185
+ return { matched: true, value: record['value'] };
186
+ }
187
+ class OwlChromiumConnection {
188
+ connection;
189
+ constructor(connection) {
190
+ this.connection = connection;
191
+ }
192
+ static async connect(webSocketUrl) {
193
+ const parsed = new URL(webSocketUrl);
194
+ if (parsed.protocol !== 'ws:' || !(0, loopbackHost_1.isLoopbackHost)(parsed.hostname) || parsed.username || parsed.password) {
195
+ throw new Error('Owl Chromium inspection only allows unauthenticated loopback WebSocket targets.');
196
+ }
197
+ return new OwlChromiumConnection(await chromiumDevToolsClient_1.ChromiumDevToolsConnection.connect(webSocketUrl, CHROMIUM_DISCOVERY_TIMEOUT_MS));
198
+ }
199
+ async evaluate(expression) {
200
+ const result = (await this.connection.call('Runtime.evaluate', {
201
+ awaitPromise: true,
202
+ expression,
203
+ returnByValue: true,
204
+ }, CHROMIUM_COMMAND_TIMEOUT_MS));
205
+ if (result.exceptionDetails) {
206
+ throw new Error(result.exceptionDetails.text ?? 'Owl Chromium could not evaluate the Valdi inspection request.');
207
+ }
208
+ if (result.result?.type === 'undefined') {
209
+ throw new Error('The running Owl page has not registered the Valdi inspection bridge.');
210
+ }
211
+ return result.result?.value;
212
+ }
213
+ async call(method, params, timeoutMs) {
214
+ return await this.connection.call(method, params, timeoutMs);
215
+ }
216
+ async matchesTarget(applicationUrl, targetNonce) {
217
+ const evaluation = await evaluateGuardedOwlExpression(this, applicationUrl, targetNonce, 'true');
218
+ return evaluation.matched;
219
+ }
220
+ onClose(listener) {
221
+ return this.connection.onClose(listener);
222
+ }
223
+ onEvent(listener) {
224
+ return this.connection.onEvent(listener);
225
+ }
226
+ close() {
227
+ this.connection.close();
228
+ }
229
+ }
230
+ exports.OwlChromiumConnection = OwlChromiumConnection;
231
+ async function connectToOwlApplication(port, applicationUrl, targetNonce) {
232
+ const targets = await listOwlChromiumTargets(port);
233
+ const candidates = targets.filter(candidate => candidate.type === 'page' && matchesOwlApplicationUrl(candidate.url, applicationUrl));
234
+ if (candidates.length === 0) {
235
+ throw new Error('No running Owl Chromium page matches this Valdi application.');
236
+ }
237
+ let lastProbeError = null;
238
+ for (const candidate of candidates) {
239
+ let connection = null;
240
+ let matched = false;
241
+ try {
242
+ connection = await OwlChromiumConnection.connect(candidate.webSocketDebuggerUrl);
243
+ const probe = await evaluateGuardedOwlExpression(connection, applicationUrl, targetNonce, 'true');
244
+ if (!probe.matched)
245
+ continue;
246
+ matched = true;
247
+ return connection;
248
+ }
249
+ catch (error) {
250
+ lastProbeError = chromiumError(error, 'Could not inspect the candidate Owl Chromium page.');
251
+ }
252
+ finally {
253
+ if (connection && !matched)
254
+ connection.close();
255
+ }
256
+ }
257
+ if (candidates.length === 1 && lastProbeError)
258
+ throw lastProbeError;
259
+ throw new Error('No running Owl Chromium page matches the exact inspected DevTools tab.');
260
+ }
261
+ async function evaluateOnOwlApplication(port, applicationUrl, targetNonce, expression) {
262
+ const connection = await connectToOwlApplication(port, applicationUrl, targetNonce);
263
+ try {
264
+ const evaluation = await evaluateGuardedOwlExpression(connection, applicationUrl, targetNonce, expression);
265
+ if (evaluation.matched)
266
+ return evaluation.value;
267
+ throw new Error('The inspected Owl page changed while the debugger request was running.');
268
+ }
269
+ finally {
270
+ connection.close();
271
+ }
272
+ }
273
+ async function readOwlDebuggerSnapshot(port, applicationUrl, targetNonce) {
274
+ const snapshot = await evaluateOwlApplicationExpression(port, applicationUrl, targetNonce, 'globalThis.__VALDI_WEB_DEBUGGER__?.getSnapshot()');
275
+ if (typeof snapshot !== 'object' || snapshot === null || Array.isArray(snapshot)) {
276
+ throw new Error('The running Owl page returned an invalid Valdi debug snapshot.');
277
+ }
278
+ return snapshot;
279
+ }
280
+ async function evaluateOwlApplicationExpression(port, applicationUrl, targetNonce, expression) {
281
+ return await evaluateOnOwlApplication(port, applicationUrl, targetNonce, expression);
282
+ }