@snap/valdi 1.1.7 → 1.2.1

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 (96) hide show
  1. package/.metadata/.bazelrc.template +9 -7
  2. package/.metadata/AGENTS.md.template +7 -0
  3. package/.metadata/MODULE.bazel.template +47 -3
  4. package/.metadata/README.md.template +2 -2
  5. package/.metadata/bzl/patches/rules_python/1.9.0/BUILD.bazel.template +1 -0
  6. package/.metadata/bzl/patches/rules_python/1.9.0/remove_setuptools_spaces.patch.template +96 -0
  7. package/.metadata/skill-tests-README.md.template +1 -1
  8. package/README.md +47 -14
  9. package/bundled-skills/registry.json +2 -1
  10. package/bundled-skills/skills/valdi-animations/skill.md +49 -0
  11. package/bundled-skills/skills/valdi-async/skill.md +3 -2
  12. package/bundled-skills/skills/valdi-async/tests/README.md +1 -1
  13. package/bundled-skills/skills/valdi-bazel/skill.md +2 -6
  14. package/bundled-skills/skills/valdi-component-tests/tests/README.md +1 -1
  15. package/bundled-skills/skills/valdi-cpp-runtime/skill.md +18 -0
  16. package/bundled-skills/skills/valdi-custom-view/skill.md +1 -1
  17. package/bundled-skills/skills/valdi-error-handling/skill.md +1 -1
  18. package/bundled-skills/skills/valdi-gestures/skill.md +3 -3
  19. package/bundled-skills/skills/valdi-migrate/skill.md +2 -1
  20. package/bundled-skills/skills/valdi-migrate/tests/README.md +2 -2
  21. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +4 -4
  22. package/bundled-skills/skills/valdi-mock-to-module/skill.md +9 -6
  23. package/bundled-skills/skills/valdi-overview/skill.md +2 -1
  24. package/bundled-skills/skills/valdi-perf/skill.md +121 -5
  25. package/bundled-skills/skills/valdi-perf/tests/README.md +1 -1
  26. package/bundled-skills/skills/valdi-pr-review/skill.md +189 -0
  27. package/bundled-skills/skills/valdi-profile/skill.md +5 -3
  28. package/bundled-skills/skills/valdi-setup/skill.md +3 -6
  29. package/bundled-skills/skills/valdi-testing/skill.md +1 -1
  30. package/bundled-skills/skills/valdi-tsx/skill.md +47 -11
  31. package/bundled-skills/skills/valdi-tsx/tests/README.md +1 -1
  32. package/debugger/README.md +356 -0
  33. package/debugger/debugger-actions.js +373 -0
  34. package/debugger/debugger-api.js +225 -0
  35. package/debugger/debugger-bootstrap.js +295 -0
  36. package/debugger/debugger-model.js +790 -0
  37. package/debugger/debugger-performance.js +573 -0
  38. package/debugger/debugger-preview-html.js +676 -0
  39. package/debugger/debugger-providers.js +389 -0
  40. package/debugger/debugger-render.js +529 -0
  41. package/debugger/debugger-runtime.js +387 -0
  42. package/debugger/debugger-session.js +188 -0
  43. package/debugger/debugger-settings.js +209 -0
  44. package/debugger/debugger-state.js +221 -0
  45. package/debugger/debugger-tree-model.js +539 -0
  46. package/debugger/debugger.css +1865 -0
  47. package/debugger/devtools-panel.css +1318 -0
  48. package/debugger/devtools-panel.html +273 -0
  49. package/debugger/devtools-panel.js +3329 -0
  50. package/debugger/index.html +279 -0
  51. package/dist/commands/bootstrap.js +7 -6
  52. package/dist/commands/build.js +7 -1
  53. package/dist/commands/debugger.js +163 -0
  54. package/dist/commands/doctor.js +3 -62
  55. package/dist/commands/export.js +47 -16
  56. package/dist/commands/hotreload.js +247 -27
  57. package/dist/commands/inspect.js +5 -2
  58. package/dist/commands/inspect_commands/input.js +176 -0
  59. package/dist/commands/inspect_commands/snapshot.js +1 -1
  60. package/dist/commands/inspect_commands/tree.js +1 -1
  61. package/dist/commands/install.js +79 -2
  62. package/dist/commands/projectsync.js +15 -0
  63. package/dist/commands/webHotreload.js +31 -0
  64. package/dist/core/constants.js +34 -7
  65. package/dist/debugger/chromiumConsole.js +279 -0
  66. package/dist/debugger/inputClient.js +473 -0
  67. package/dist/debugger/server.js +3801 -0
  68. package/dist/debugger/targetRegistry.js +436 -0
  69. package/dist/debugger/webPreviewPerformance.js +864 -0
  70. package/dist/index.js +0 -0
  71. package/dist/utils/BazelClient.js +34 -5
  72. package/dist/utils/applicationUtils.js +20 -2
  73. package/dist/utils/buildInfo.js +5 -1
  74. package/dist/utils/chromiumDevToolsClient.js +350 -0
  75. package/dist/utils/cliUtils.js +2 -2
  76. package/dist/utils/daemonClient.js +364 -44
  77. package/dist/utils/directorySync.js +153 -0
  78. package/dist/utils/githubUtils.js +1 -1
  79. package/dist/utils/hermesClient.js +82 -176
  80. package/dist/utils/loopbackHost.js +14 -0
  81. package/dist/utils/owlCdpClient.js +282 -0
  82. package/dist/utils/owlDevToolsExtension.js +142 -0
  83. package/dist/utils/processUtils.js +14 -0
  84. package/dist/utils/stringUtils.js +13 -1
  85. package/dist/utils/webApplicationSession.js +58 -0
  86. package/dist/utils/webHotReloadSession.js +212 -0
  87. package/dist/utils/webServerUtils.js +195 -0
  88. package/dist/utils/zipUtils.js +20 -2
  89. package/package.json +4 -2
  90. package/dist/commands/inspect_commands/snapshot.spec.js +0 -105
  91. package/dist/core/packageFiles.spec.js +0 -29
  92. package/dist/preview/previewGenerator.spec.js +0 -203
  93. package/dist/preview/viewModelParser.spec.js +0 -171
  94. package/dist/utils/linuxDistro.spec.js +0 -122
  95. package/dist/utils/skillsAdapters.spec.js +0 -141
  96. package/dist/utils/stringUtils.spec.js +0 -81
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.syncDirectoryContents = syncDirectoryContents;
4
+ const tslib_1 = require("tslib");
5
+ const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
6
+ const node_path_1 = tslib_1.__importDefault(require("node:path"));
7
+ let temporaryFileCounter = 0;
8
+ function isPathInside(parentPath, childPath) {
9
+ const relativePath = node_path_1.default.relative(parentPath, childPath);
10
+ return (relativePath === '' ||
11
+ (!relativePath.startsWith(`..${node_path_1.default.sep}`) && relativePath !== '..' && !node_path_1.default.isAbsolute(relativePath)));
12
+ }
13
+ async function countFiles(directoryPath) {
14
+ const entries = await node_fs_1.default.promises.readdir(directoryPath, { withFileTypes: true });
15
+ let count = 0;
16
+ for (const entry of entries) {
17
+ const entryPath = node_path_1.default.join(directoryPath, entry.name);
18
+ count += entry.isDirectory() ? await countFiles(entryPath) : 1;
19
+ }
20
+ return count;
21
+ }
22
+ async function makeTreeWritable(entryPath) {
23
+ const stats = await node_fs_1.default.promises.lstat(entryPath);
24
+ if (stats.isDirectory()) {
25
+ await node_fs_1.default.promises.chmod(entryPath, (stats.mode & 0o777) | 0o700);
26
+ const entries = await node_fs_1.default.promises.readdir(entryPath);
27
+ for (const entry of entries) {
28
+ await makeTreeWritable(node_path_1.default.join(entryPath, entry));
29
+ }
30
+ }
31
+ else if (stats.isFile()) {
32
+ await node_fs_1.default.promises.chmod(entryPath, (stats.mode & 0o777) | 0o600);
33
+ }
34
+ }
35
+ async function removeTree(entryPath) {
36
+ await makeTreeWritable(entryPath);
37
+ await node_fs_1.default.promises.rm(entryPath, { force: true, recursive: true });
38
+ }
39
+ async function filesHaveEqualContents(sourcePath, destinationPath) {
40
+ const [sourceStats, destinationStats] = await Promise.all([
41
+ node_fs_1.default.promises.stat(sourcePath),
42
+ node_fs_1.default.promises.stat(destinationPath),
43
+ ]);
44
+ if (sourceStats.size !== destinationStats.size) {
45
+ return false;
46
+ }
47
+ const [sourceContents, destinationContents] = await Promise.all([
48
+ node_fs_1.default.promises.readFile(sourcePath),
49
+ node_fs_1.default.promises.readFile(destinationPath),
50
+ ]);
51
+ return sourceContents.equals(destinationContents);
52
+ }
53
+ async function replaceFile(sourcePath, destinationPath, sourceMode) {
54
+ const temporaryPath = `${destinationPath}.valdi-export-${process.pid}-${temporaryFileCounter++}`;
55
+ try {
56
+ await node_fs_1.default.promises.copyFile(sourcePath, temporaryPath);
57
+ await node_fs_1.default.promises.chmod(temporaryPath, sourceMode);
58
+ await node_fs_1.default.promises.rename(temporaryPath, destinationPath);
59
+ }
60
+ finally {
61
+ await node_fs_1.default.promises.rm(temporaryPath, { force: true });
62
+ }
63
+ }
64
+ async function syncFile(sourcePath, destinationPath, destinationEntry, result) {
65
+ const sourceStats = await node_fs_1.default.promises.stat(sourcePath);
66
+ const sourceMode = sourceStats.mode & 0o777;
67
+ if (destinationEntry?.isFile() && (await filesHaveEqualContents(sourcePath, destinationPath))) {
68
+ result.unchanged += 1;
69
+ return;
70
+ }
71
+ if (destinationEntry?.isDirectory()) {
72
+ const removedFileCount = await countFiles(destinationPath);
73
+ result.removed += removedFileCount;
74
+ await removeTree(destinationPath);
75
+ }
76
+ else if (destinationEntry?.isSymbolicLink()) {
77
+ result.removed += 1;
78
+ await node_fs_1.default.promises.rm(destinationPath);
79
+ }
80
+ await replaceFile(sourcePath, destinationPath, sourceMode);
81
+ if (destinationEntry) {
82
+ result.updated += 1;
83
+ }
84
+ else {
85
+ result.added += 1;
86
+ }
87
+ }
88
+ async function syncDirectory(sourceDirectory, destinationDirectory, result) {
89
+ if (node_fs_1.default.existsSync(destinationDirectory)) {
90
+ const destinationStats = await node_fs_1.default.promises.lstat(destinationDirectory);
91
+ if (destinationStats.isDirectory()) {
92
+ const destinationMode = destinationStats.mode & 0o777;
93
+ const writableDestinationMode = destinationMode | 0o700;
94
+ if (destinationMode !== writableDestinationMode) {
95
+ await node_fs_1.default.promises.chmod(destinationDirectory, writableDestinationMode);
96
+ }
97
+ }
98
+ else {
99
+ result.removed += 1;
100
+ await removeTree(destinationDirectory);
101
+ await node_fs_1.default.promises.mkdir(destinationDirectory, { recursive: true });
102
+ }
103
+ }
104
+ else {
105
+ await node_fs_1.default.promises.mkdir(destinationDirectory, { recursive: true });
106
+ }
107
+ const [sourceEntries, destinationEntries] = await Promise.all([
108
+ node_fs_1.default.promises.readdir(sourceDirectory, { withFileTypes: true }),
109
+ node_fs_1.default.promises.readdir(destinationDirectory, { withFileTypes: true }),
110
+ ]);
111
+ const remainingDestinationEntries = new Map(destinationEntries.map(entry => [entry.name, entry]));
112
+ await Promise.all(sourceEntries.map(async (sourceEntry) => {
113
+ const sourcePath = node_path_1.default.join(sourceDirectory, sourceEntry.name);
114
+ const destinationPath = node_path_1.default.join(destinationDirectory, sourceEntry.name);
115
+ const destinationEntry = remainingDestinationEntries.get(sourceEntry.name);
116
+ remainingDestinationEntries.delete(sourceEntry.name);
117
+ if (sourceEntry.isDirectory()) {
118
+ await syncDirectory(sourcePath, destinationPath, result);
119
+ }
120
+ else if (sourceEntry.isFile() || sourceEntry.isSymbolicLink()) {
121
+ await syncFile(sourcePath, destinationPath, destinationEntry, result);
122
+ }
123
+ else {
124
+ throw new Error(`Unsupported entry in exported web package: ${sourcePath}`);
125
+ }
126
+ }));
127
+ await Promise.all(Array.from(remainingDestinationEntries.values(), async (destinationEntry) => {
128
+ const destinationPath = node_path_1.default.join(destinationDirectory, destinationEntry.name);
129
+ const removedFileCount = destinationEntry.isDirectory() ? await countFiles(destinationPath) : 1;
130
+ result.removed += removedFileCount;
131
+ await removeTree(destinationPath);
132
+ }));
133
+ }
134
+ async function syncDirectoryContents(sourceDirectory, destinationDirectory) {
135
+ const resolvedSourceDirectory = node_path_1.default.resolve(sourceDirectory);
136
+ const resolvedDestinationDirectory = node_path_1.default.resolve(destinationDirectory);
137
+ if (isPathInside(resolvedSourceDirectory, resolvedDestinationDirectory) ||
138
+ isPathInside(resolvedDestinationDirectory, resolvedSourceDirectory)) {
139
+ throw new Error('Source and destination directories must not overlap');
140
+ }
141
+ const sourceStats = await node_fs_1.default.promises.stat(resolvedSourceDirectory);
142
+ if (!sourceStats.isDirectory()) {
143
+ throw new Error(`Directory export source is not a directory: ${resolvedSourceDirectory}`);
144
+ }
145
+ const result = {
146
+ added: 0,
147
+ updated: 0,
148
+ removed: 0,
149
+ unchanged: 0,
150
+ };
151
+ await syncDirectory(resolvedSourceDirectory, resolvedDestinationDirectory, result);
152
+ return result;
153
+ }
@@ -11,7 +11,7 @@ function parseGitHubRepoSlug(repoUrl) {
11
11
  }
12
12
  return `${match[1]}/${match[2]}`;
13
13
  }
14
- const LATEST_RELEASE_HINT = 'Use --valdiVersion=latest to retry, or --valdiVersion=<tag> (e.g. main or v1.0.0) to pin a version.';
14
+ const LATEST_RELEASE_HINT = 'Use --valdiVersion=latest to retry, or --valdiVersion=<tag> (e.g. main or beta-0.2.0) to pin a version.';
15
15
  async function getLatestReleaseTag(repoUrl) {
16
16
  const slug = parseGitHubRepoSlug(repoUrl);
17
17
  let response;
@@ -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
+ }