screen-relay 0.0.0-stage → 0.1.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 (88) hide show
  1. package/LICENSE +201 -0
  2. package/Makefile +165 -0
  3. package/README.md +113 -2
  4. package/THIRD-PARTY-NOTICES.md +75 -0
  5. package/dist/cli/client.d.ts +28 -0
  6. package/dist/cli/commands.d.ts +52 -0
  7. package/dist/cli/config.d.ts +32 -0
  8. package/dist/cli/format.d.ts +15 -0
  9. package/dist/cli/help.d.ts +5 -0
  10. package/dist/cli/host/common.d.ts +23 -0
  11. package/dist/cli/host/doctor.d.ts +2 -0
  12. package/dist/cli/host/packages.d.ts +13 -0
  13. package/dist/cli/host/session_commands.d.ts +8 -0
  14. package/dist/cli/host/setup.d.ts +22 -0
  15. package/dist/cli/host/state.d.ts +23 -0
  16. package/dist/cli/host/supervisor.d.ts +91 -0
  17. package/dist/cli/host/watcher.d.ts +4 -0
  18. package/dist/cli/main.d.ts +3 -0
  19. package/dist/cli/mode.d.ts +14 -0
  20. package/dist/cli/output.d.ts +24 -0
  21. package/dist/cli/parser.d.ts +6 -0
  22. package/dist/cli/relay.mjs +12247 -0
  23. package/dist/cli/skills.d.ts +21 -0
  24. package/dist/cli/theme.d.ts +14 -0
  25. package/dist/protocol/errors.d.ts +155 -0
  26. package/dist/protocol/index.d.ts +119 -0
  27. package/dist/protocol/index.js +418 -0
  28. package/dist/sdk/index.d.ts +77 -0
  29. package/dist/sdk/index.js +724 -0
  30. package/dist/viewer/index.html +96 -0
  31. package/dist/viewer/viewer.js +1052 -0
  32. package/package.json +50 -4
  33. package/packages.tsv +38 -0
  34. package/skills/core/SKILL.md +169 -0
  35. package/skills/core/references/cli.md +119 -0
  36. package/skills/core/references/config.md +48 -0
  37. package/skills/core/references/macos.md +50 -0
  38. package/skills/core/references/sdk.md +69 -0
  39. package/skills/core/references/troubleshooting.md +33 -0
  40. package/skills/core/references/wayland.md +47 -0
  41. package/skills/screen-relay/SKILL.md +24 -0
  42. package/skills/vercel-sandbox/SKILL.md +68 -0
  43. package/src/engine/backends/linux/keycodes.hpp +35 -0
  44. package/src/engine/backends/linux/wayland/capture.cpp +298 -0
  45. package/src/engine/backends/linux/wayland/input.cpp +559 -0
  46. package/src/engine/backends/linux/wayland/keymap.cpp +118 -0
  47. package/src/engine/backends/linux/wayland/keymap.hpp +54 -0
  48. package/src/engine/backends/linux/wayland/protocols/virtual-keyboard-unstable-v1.xml +112 -0
  49. package/src/engine/backends/linux/wayland/protocols/wlr-screencopy-unstable-v1.xml +234 -0
  50. package/src/engine/backends/linux/wayland/protocols/wlr-virtual-pointer-unstable-v1.xml +152 -0
  51. package/src/engine/backends/linux/wayland/wayland.cpp +166 -0
  52. package/src/engine/backends/linux/wayland/wayland.hpp +60 -0
  53. package/src/engine/backends/linux/x11/capture.cpp +206 -0
  54. package/src/engine/backends/linux/x11/input.cpp +266 -0
  55. package/src/engine/backends/macos/capture.mm +367 -0
  56. package/src/engine/backends/macos/display.hpp +20 -0
  57. package/src/engine/backends/macos/display.mm +84 -0
  58. package/src/engine/backends/macos/input.mm +287 -0
  59. package/src/engine/backends/macos/keys.hpp +34 -0
  60. package/src/engine/backends/windows/capture.cpp +393 -0
  61. package/src/engine/backends/windows/input.cpp +274 -0
  62. package/src/engine/backends/windows/output.cpp +65 -0
  63. package/src/engine/backends/windows/output.hpp +26 -0
  64. package/src/engine/core/capture-bucket.hpp +40 -0
  65. package/src/engine/core/capture-source.hpp +59 -0
  66. package/src/engine/core/capture.cpp +565 -0
  67. package/src/engine/core/capture.hpp +58 -0
  68. package/src/engine/core/color.cpp +176 -0
  69. package/src/engine/core/color.hpp +16 -0
  70. package/src/engine/core/cpu-budget.hpp +196 -0
  71. package/src/engine/core/flow.hpp +317 -0
  72. package/src/engine/core/input.cpp +98 -0
  73. package/src/engine/core/input.hpp +115 -0
  74. package/src/engine/core/wait.cpp +125 -0
  75. package/src/engine/core/wait.hpp +41 -0
  76. package/src/engine/server/backend.cpp +65 -0
  77. package/src/engine/server/backend.hpp +18 -0
  78. package/src/engine/server/config.cpp +257 -0
  79. package/src/engine/server/config.hpp +24 -0
  80. package/src/engine/server/main.cpp +82 -0
  81. package/src/engine/server/metrics.cpp +47 -0
  82. package/src/engine/server/metrics.hpp +10 -0
  83. package/src/engine/server/screenshot.cpp +108 -0
  84. package/src/engine/server/screenshot.hpp +31 -0
  85. package/src/engine/server/server.cpp +531 -0
  86. package/src/engine/server/server.hpp +88 -0
  87. package/src/engine/server/wire.cpp +65 -0
  88. package/src/engine/server/wire.hpp +27 -0
@@ -0,0 +1,418 @@
1
+ // src/protocol/errors.ts
2
+ var ERROR_REASONS = {
3
+ invalid_input: { class: "usage", code: "INVALID_ARGUMENT", exitCode: 2 },
4
+ invalid_option: { class: "usage", code: "INVALID_ARGUMENT", exitCode: 2 },
5
+ unknown_command: { class: "usage", code: "INVALID_ARGUMENT", exitCode: 2 },
6
+ missing_input: { class: "missing_input", code: "INVALID_ARGUMENT", exitCode: 2 },
7
+ missing_command: { class: "missing_input", code: "INVALID_ARGUMENT", exitCode: 2 },
8
+ not_found: { class: "not_found", code: "NOT_FOUND", exitCode: 1 },
9
+ not_running: { class: "not_found", code: "NOT_FOUND", exitCode: 1 },
10
+ already_running: { class: "conflict", code: "BUSY", exitCode: 1 },
11
+ port_in_use: { class: "conflict", code: "BUSY", exitCode: 1 },
12
+ busy: { class: "conflict", code: "BUSY", exitCode: 1 },
13
+ unreachable: { class: "network", code: "NETWORK_ERROR", exitCode: 1 },
14
+ timeout: { class: "network", code: "TIMEOUT", exitCode: 1 },
15
+ disconnected: { class: "network", code: "DISCONNECTED", exitCode: 1 },
16
+ unauthorized: { class: "permission", code: "UNAUTHORIZED", exitCode: 1 },
17
+ forbidden: { class: "permission", code: "UNAUTHORIZED", exitCode: 1 },
18
+ unsupported_input: { class: "platform", code: "UNSUPPORTED", exitCode: 1 },
19
+ unsupported_platform: { class: "platform", code: "UNSUPPORTED", exitCode: 1 },
20
+ missing_dependency: { class: "platform", code: "UNSUPPORTED", exitCode: 1 },
21
+ component_failed: { class: "platform", code: "HTTP_ERROR", exitCode: 1 },
22
+ spawn_failed: { class: "platform", code: "IO_ERROR", exitCode: 1 },
23
+ io_error: { class: "platform", code: "IO_ERROR", exitCode: 1 },
24
+ protocol_error: { class: "platform", code: "PROTOCOL_ERROR", exitCode: 1 },
25
+ invalid_config: { class: "config", code: "CONFIG_ERROR", exitCode: 1 },
26
+ internal: { class: "bug", code: "INTERNAL", exitCode: 1 },
27
+ canceled: { class: "canceled", code: "CANCELED", exitCode: 130 }
28
+ };
29
+ var LEGACY_REASONS = {
30
+ INVALID_ARGUMENT: "invalid_input",
31
+ NOT_FOUND: "not_found",
32
+ BUSY: "busy",
33
+ NETWORK_ERROR: "unreachable",
34
+ TIMEOUT: "timeout",
35
+ DISCONNECTED: "disconnected",
36
+ UNAUTHORIZED: "unauthorized",
37
+ UNSUPPORTED: "unsupported_input",
38
+ HTTP_ERROR: "component_failed",
39
+ IO_ERROR: "io_error",
40
+ PROTOCOL_ERROR: "protocol_error",
41
+ CONFIG_ERROR: "invalid_config",
42
+ INTERNAL: "internal",
43
+ CANCELED: "canceled"
44
+ };
45
+ var RelayError = class extends Error {
46
+ code;
47
+ reason;
48
+ class;
49
+ exitCode;
50
+ hint;
51
+ data;
52
+ next;
53
+ status;
54
+ label;
55
+ constructor(reason, message, options = {}) {
56
+ super(message);
57
+ this.name = "RelayError";
58
+ this.reason = Object.hasOwn(ERROR_REASONS, reason) ? reason : Object.hasOwn(LEGACY_REASONS, reason) ? LEGACY_REASONS[reason] : "internal";
59
+ const definition = ERROR_REASONS[this.reason];
60
+ this.code = definition.code;
61
+ this.class = definition.class;
62
+ this.exitCode = definition.exitCode;
63
+ const details = typeof options === "string" ? { hint: options } : options;
64
+ this.hint = details.hint;
65
+ this.data = details.data;
66
+ this.next = details.next;
67
+ this.label = details.label;
68
+ this.status = details.status ?? "error";
69
+ }
70
+ };
71
+ function errorCodes(error, seen = /* @__PURE__ */ new Set()) {
72
+ if (!error || typeof error !== "object" || seen.has(error)) return [];
73
+ seen.add(error);
74
+ const record = error;
75
+ const codes = [];
76
+ if (typeof record.code === "string") codes.push(record.code);
77
+ if (Array.isArray(record.errors)) for (const inner of record.errors) codes.push(...errorCodes(inner, seen));
78
+ if (record.cause !== void 0) codes.push(...errorCodes(record.cause, seen));
79
+ return codes;
80
+ }
81
+ function errorText(error, seen = /* @__PURE__ */ new Set()) {
82
+ if (!error || typeof error !== "object" || seen.has(error)) return "";
83
+ seen.add(error);
84
+ const record = error;
85
+ const parts = [];
86
+ if (typeof record.message === "string") parts.push(record.message);
87
+ if (Array.isArray(record.errors)) for (const inner of record.errors) parts.push(errorText(inner, seen));
88
+ if (record.cause !== void 0) parts.push(errorText(record.cause, seen));
89
+ return parts.join(" ");
90
+ }
91
+ var CAUSES = {
92
+ ECONNREFUSED: "Connection refused.",
93
+ ENOTFOUND: "The host name did not resolve.",
94
+ EAI_AGAIN: "The host name did not resolve.",
95
+ ETIMEDOUT: "The request timed out.",
96
+ ESOCKETTIMEDOUT: "The request timed out.",
97
+ UND_ERR_CONNECT_TIMEOUT: "The request timed out.",
98
+ UND_ERR_HEADERS_TIMEOUT: "The request timed out.",
99
+ UND_ERR_BODY_TIMEOUT: "The request timed out.",
100
+ ABORT_ERR: "The request timed out.",
101
+ ECONNRESET: "The connection was reset.",
102
+ EPIPE: "The connection was closed.",
103
+ EHOSTUNREACH: "The host was unreachable.",
104
+ ENETUNREACH: "The network was unreachable."
105
+ };
106
+ var TLS_CODES = /TLS|SSL|CERT/;
107
+ var TIMEOUT_CODES = /* @__PURE__ */ new Set(["ETIMEDOUT", "ESOCKETTIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "ABORT_ERR", "TimeoutError"]);
108
+ function networkError(error) {
109
+ const codes = errorCodes(error);
110
+ const text = errorText(error);
111
+ if (codes.some((code) => TLS_CODES.test(code)) || /certificate/i.test(text)) return new RelayError("unreachable", "The TLS certificate was rejected.");
112
+ const timedOut = codes.some((code) => TIMEOUT_CODES.has(code)) || typeof error === "object" && error !== null && error.name === "AbortError" || /timed? ?out/i.test(text);
113
+ const blocked = /bad port/i.test(text);
114
+ const message = blocked ? "Connection refused." : codes.map((code) => CAUSES[code]).find(Boolean) ?? (timedOut ? "The request timed out." : "The connection failed.");
115
+ return new RelayError(timedOut ? "timeout" : "unreachable", message);
116
+ }
117
+ function responseError(status, detail) {
118
+ const body = detail && typeof detail === "object" ? detail : {};
119
+ const reason = status === 401 ? "unauthorized" : status === 403 ? "forbidden" : status === 404 ? "not_found" : status === 409 || status === 429 || status === 503 && body.error === "busy" || body.error === "busy" ? "busy" : status === 422 || body.error === "unsupported_input" ? "unsupported_input" : status === 400 || status === 413 || body.error === "invalid_input" ? "invalid_input" : "component_failed";
120
+ const messages = {
121
+ unauthorized: "The engine rejected the token.",
122
+ forbidden: "The engine rejected the connection origin.",
123
+ not_found: "The engine endpoint was not found.",
124
+ busy: "Another controller holds control of the desktop.",
125
+ unsupported_input: "The engine does not support this input.",
126
+ invalid_input: "The engine rejected the input."
127
+ };
128
+ const index = Number.isInteger(body.index) && Number(body.index) >= 0 ? Number(body.index) : void 0;
129
+ const applied = Number.isInteger(body.applied) && Number(body.applied) >= 0 ? Number(body.applied) : void 0;
130
+ const message = body.error === "screenshot_unavailable" ? "The engine could not take a screenshot. Read the engine log with screen-relay logs engine." : messages[reason] ?? "The engine could not complete the request.";
131
+ return new RelayError(reason, message, {
132
+ data: { httpStatus: status, ...index === void 0 ? {} : { index }, ...applied === void 0 ? {} : { applied } }
133
+ });
134
+ }
135
+
136
+ // src/protocol/index.ts
137
+ var MAGIC = 1314081841;
138
+ var VERSION = 1;
139
+ var HEADER_SIZE = 20;
140
+ var INPUT_SIZE = 16;
141
+ var MAX_INPUT_BATCH = 256;
142
+ var MAX_INPUT_PENDING = 32;
143
+ var MAX_WIDTH = 65535;
144
+ var MAX_HEIGHT = 65535;
145
+ var MAX_BYTES_IN_FLIGHT = 8388608;
146
+ var SUBPROTOCOL = "nsl1";
147
+ var MESSAGE_TYPES = { frame: 1, ack: 2, input: 3, controlReady: 4, inputResponse: 5, cursor: 6 };
148
+ var INPUT_TYPES = { keyDown: 1, keyUp: 2, pointerMove: 3, buttonDown: 4, buttonUp: 5, wheel: 6, releaseAll: 7, text: 8 };
149
+ function integer(value, min, max, name) {
150
+ if (!Number.isInteger(value) || value < min || value > max) throw new RelayError("invalid_input", `Invalid ${name}`);
151
+ return value;
152
+ }
153
+ function coordinate(value, name) {
154
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) throw new RelayError("invalid_input", `Invalid ${name}`);
155
+ return Math.round(value * 65535);
156
+ }
157
+ function encodeInputRecord(event) {
158
+ if (!event || typeof event !== "object" || !Object.hasOwn(INPUT_TYPES, event.type)) throw new RelayError("invalid_input", "Unknown input type");
159
+ const bytes = new Uint8Array(INPUT_SIZE);
160
+ const view = new DataView(bytes.buffer);
161
+ view.setUint8(0, INPUT_TYPES[event.type]);
162
+ const buttons = integer(event.buttons ?? 0, 0, 31, "buttons");
163
+ const modifiers = integer(event.modifiers ?? 0, 0, 255, "modifiers");
164
+ if ((event.type === "releaseAll" || event.type === "text") && (buttons || modifiers)) throw new RelayError("invalid_input", "Release and text events require zero masks");
165
+ view.setUint16(12, buttons);
166
+ view.setUint16(14, modifiers);
167
+ if (event.type === "pointerMove" || event.type === "buttonDown" || event.type === "buttonUp" || event.type === "wheel") {
168
+ view.setUint16(8, coordinate(event.x, "x"));
169
+ view.setUint16(10, coordinate(event.y, "y"));
170
+ }
171
+ if (event.type === "keyDown" || event.type === "keyUp") view.setUint16(2, integer(event.key, 0, 231, "key"));
172
+ if (event.type === "buttonDown" || event.type === "buttonUp") view.setUint16(2, integer(event.button, 1, 3, "button"));
173
+ if (event.type === "wheel") {
174
+ if (event.axis !== "vertical" && event.axis !== "horizontal") throw new RelayError("invalid_input", "Invalid wheel axis");
175
+ const delta = integer(event.delta, -1200, 1200, "wheel delta");
176
+ if (delta % 120) throw new RelayError("invalid_input", "Wheel delta must be a multiple of 120");
177
+ view.setUint16(2, event.axis === "horizontal" ? 1 : 0);
178
+ view.setInt32(4, delta);
179
+ }
180
+ if (event.type === "text") {
181
+ const codepoint = integer(event.codepoint, 1, 1114111, "Unicode scalar");
182
+ if (codepoint >= 55296 && codepoint <= 57343) throw new RelayError("invalid_input", "Invalid Unicode scalar");
183
+ view.setInt32(4, codepoint);
184
+ view.setUint16(8, 0);
185
+ view.setUint16(10, 0);
186
+ }
187
+ return bytes;
188
+ }
189
+ function encodeInputBatch(events) {
190
+ if (!Array.isArray(events)) throw new RelayError("invalid_input", "Input must be an array");
191
+ integer(events.length, 1, MAX_INPUT_BATCH, "input batch length");
192
+ const bytes = new Uint8Array(events.length * INPUT_SIZE);
193
+ for (let index = 0; index < events.length; index++) bytes.set(encodeInputRecord(events[index]), index * INPUT_SIZE);
194
+ return bytes;
195
+ }
196
+ function batches(groups, limit = MAX_INPUT_BATCH) {
197
+ integer(limit, 1, MAX_INPUT_BATCH, "input batch limit");
198
+ const result = [];
199
+ let batch = [];
200
+ for (const group of groups) {
201
+ if (group.length > limit) throw new RelayError("invalid_input", `An input group has more than ${limit} events`);
202
+ if (batch.length + group.length > limit) {
203
+ result.push(batch);
204
+ batch = [];
205
+ }
206
+ batch.push(...group);
207
+ }
208
+ if (batch.length) result.push(batch);
209
+ return result;
210
+ }
211
+ function header(type, generation, sequence, size) {
212
+ integer(type, 1, 6, "message type");
213
+ integer(generation, 1, 4294967295, "generation");
214
+ integer(sequence, 0, 4294967295, "sequence");
215
+ integer(size, 0, 8388620, "payload length");
216
+ const bytes = new Uint8Array(HEADER_SIZE + size);
217
+ const view = new DataView(bytes.buffer);
218
+ view.setUint32(0, MAGIC);
219
+ view.setUint8(4, VERSION);
220
+ view.setUint8(5, type);
221
+ view.setUint32(8, generation);
222
+ view.setUint32(12, sequence);
223
+ view.setUint32(16, size);
224
+ return bytes;
225
+ }
226
+ function encodeInput(event, generation, sequence) {
227
+ const bytes = header(MESSAGE_TYPES.input, generation, sequence, INPUT_SIZE);
228
+ bytes.set(encodeInputRecord(event), HEADER_SIZE);
229
+ return bytes;
230
+ }
231
+ function encodeAck(generation, sequence, viewerWaitMs) {
232
+ if (viewerWaitMs === void 0) return header(MESSAGE_TYPES.ack, generation, sequence, 0);
233
+ const bytes = header(MESSAGE_TYPES.ack, generation, sequence, 4);
234
+ const micros = Number.isFinite(viewerWaitMs) ? Math.min(4294967295, Math.max(0, Math.round(viewerWaitMs * 1e3))) : 0;
235
+ new DataView(bytes.buffer).setUint32(HEADER_SIZE, micros);
236
+ return bytes;
237
+ }
238
+ function parseHeader(bytes) {
239
+ const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
240
+ if (data.byteLength < HEADER_SIZE || data.byteLength > HEADER_SIZE + 12 + MAX_BYTES_IN_FLIGHT) throw new RelayError("protocol_error", "Invalid message length");
241
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
242
+ const type = view.getUint8(5), flags = view.getUint16(6), generation = view.getUint32(8);
243
+ if (view.getUint32(0) !== MAGIC || view.getUint8(4) !== VERSION || type < 1 || type > 6 || flags > (type === MESSAGE_TYPES.frame ? 1 : 0) || !generation || view.getUint32(16) !== data.byteLength - HEADER_SIZE) {
244
+ throw new RelayError("protocol_error", "Invalid message envelope");
245
+ }
246
+ return { type, flags, generation, sequence: view.getUint32(12), payloadLength: view.getUint32(16) };
247
+ }
248
+ function parseMessage(bytes) {
249
+ const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
250
+ const { type, flags, generation, sequence, payloadLength: size } = parseHeader(data);
251
+ const view = new DataView(data.buffer, data.byteOffset + HEADER_SIZE, size);
252
+ const invalid = (what) => new RelayError("protocol_error", `Invalid ${what}`);
253
+ if (type === MESSAGE_TYPES.frame) {
254
+ if (size < 13 || !sequence) throw invalid("frame header");
255
+ const width = view.getUint16(0), height = view.getUint16(2), timestamp = view.getBigUint64(4);
256
+ if (!width || !height || timestamp > BigInt(Number.MAX_SAFE_INTEGER)) throw invalid("frame header");
257
+ return { type: "frame", generation, sequence, keyframe: flags === 1, width, height, timestamp: Number(timestamp), data: data.subarray(HEADER_SIZE + 12) };
258
+ }
259
+ if (type === MESSAGE_TYPES.cursor) {
260
+ if (size < 8 || sequence) throw invalid("cursor envelope");
261
+ const width = view.getUint16(0), height = view.getUint16(2), hotX = view.getUint16(4), hotY = view.getUint16(6);
262
+ if (width > 256 || height > 256 || size !== 8 + width * height * 4 || (width && height ? hotX >= width || hotY >= height : width || height || hotX || hotY)) throw invalid("cursor image");
263
+ return { type: "cursor", generation, width, height, hotX, hotY, pixels: new Uint8ClampedArray(data.buffer, data.byteOffset + HEADER_SIZE + 8, size - 8) };
264
+ }
265
+ if (type === MESSAGE_TYPES.controlReady) {
266
+ if (size !== 4 || sequence || !view.getUint16(0) || !view.getUint16(2)) throw invalid("ready message");
267
+ return { type: "controlReady", generation, width: view.getUint16(0), height: view.getUint16(2) };
268
+ }
269
+ if (type === MESSAGE_TYPES.inputResponse) {
270
+ if (size !== 1 || !sequence || view.getUint8(0) > 2) throw invalid("input response");
271
+ return { type: "inputResponse", generation, sequence, status: view.getUint8(0) };
272
+ }
273
+ throw invalid("message type");
274
+ }
275
+ function h264Codec(bytes) {
276
+ for (let i = 0; i + 7 < bytes.length; i++) {
277
+ let n = 0;
278
+ if (bytes[i] === 0 && bytes[i + 1] === 0 && bytes[i + 2] === 1) n = i + 3;
279
+ else if (bytes[i] === 0 && bytes[i + 1] === 0 && bytes[i + 2] === 0 && bytes[i + 3] === 1) n = i + 4;
280
+ if (n && n + 3 < bytes.length && (bytes[n] & 31) === 7) {
281
+ return `avc1.${[bytes[n + 1], bytes[n + 2], bytes[n + 3]].map((v) => v.toString(16).padStart(2, "0")).join("")}`;
282
+ }
283
+ }
284
+ throw new RelayError("protocol_error", "Keyframe is missing SPS");
285
+ }
286
+ function socketTarget(origin, path, token) {
287
+ const url = new URL(path, origin);
288
+ url.protocol = origin.protocol === "https:" ? "wss:" : "ws:";
289
+ return { url, protocols: token ? [SUBPROTOCOL, `bearer.${token}`] : [SUBPROTOCOL] };
290
+ }
291
+ var HID_KEYS = {};
292
+ function assignKeys(first, names) {
293
+ names.forEach((name, index) => {
294
+ HID_KEYS[name] = first + index;
295
+ });
296
+ }
297
+ assignKeys(4, Array.from({ length: 26 }, (_, index) => `Key${String.fromCharCode(65 + index)}`));
298
+ assignKeys(30, "Digit1 Digit2 Digit3 Digit4 Digit5 Digit6 Digit7 Digit8 Digit9 Digit0".split(" "));
299
+ assignKeys(40, "Enter Escape Backspace Tab Space Minus Equal BracketLeft BracketRight Backslash".split(" "));
300
+ assignKeys(51, "Semicolon Quote Backquote Comma Period Slash CapsLock".split(" "));
301
+ assignKeys(58, Array.from({ length: 12 }, (_, index) => `F${index + 1}`));
302
+ assignKeys(70, "PrintScreen ScrollLock Pause Insert Home PageUp Delete End PageDown ArrowRight ArrowLeft ArrowDown ArrowUp NumLock".split(" "));
303
+ assignKeys(84, "NumpadDivide NumpadMultiply NumpadSubtract NumpadAdd NumpadEnter Numpad1 Numpad2 Numpad3 Numpad4 Numpad5 Numpad6 Numpad7 Numpad8 Numpad9 Numpad0 NumpadDecimal".split(" "));
304
+ HID_KEYS.IntlBackslash = 100;
305
+ HID_KEYS.ContextMenu = 101;
306
+ assignKeys(104, Array.from({ length: 12 }, (_, index) => `F${index + 13}`));
307
+ assignKeys(224, "ControlLeft ShiftLeft AltLeft MetaLeft ControlRight ShiftRight AltRight MetaRight".split(" "));
308
+ Object.freeze(HID_KEYS);
309
+ var MODIFIERS = Object.freeze({ ctrl: 224, control: 224, shift: 225, alt: 226, super: 227, meta: 227, cmd: 227, win: 227 });
310
+ var NAMED_KEYS = Object.freeze({
311
+ ...Object.fromEntries(Object.entries(HID_KEYS).filter(([name]) => !name.startsWith("Key") && !name.startsWith("Digit")).map(([name, code]) => [name.toLowerCase(), code])),
312
+ return: 40,
313
+ esc: 41,
314
+ right: 79,
315
+ left: 80,
316
+ down: 81,
317
+ up: 82,
318
+ menu: 101
319
+ });
320
+ var characters = "abcdefghijklmnopqrstuvwxyz1234567890";
321
+ var punctuation = "-=[]\\";
322
+ var punctuationTail = ";'`,./";
323
+ var shifted = '!@#$%^&*()_+{}|:"~<>?';
324
+ var unshifted = "1234567890-=[]\\;'`,./";
325
+ function comboEvents(spec) {
326
+ if (typeof spec !== "string" || !spec) throw new RelayError("invalid_input", "Invalid key combo");
327
+ const split = spec === "+" || spec.endsWith("++") ? spec.length - 2 : spec.lastIndexOf("+");
328
+ if (split === 0 && spec !== "+") throw new RelayError("invalid_input", `Invalid key combo "${spec}"`);
329
+ const held = split > 0 ? spec.slice(0, split).split("+") : [];
330
+ const key = spec === "+" || spec.endsWith("++") ? "+" : spec.slice(split + 1);
331
+ const modifiers = [];
332
+ for (const name of held) {
333
+ if (!Object.hasOwn(MODIFIERS, name.toLowerCase())) throw new RelayError("invalid_input", `Invalid key combo "${spec}"`);
334
+ const code2 = MODIFIERS[name.toLowerCase()];
335
+ if (!modifiers.includes(code2)) modifiers.push(code2);
336
+ }
337
+ const lower = key.toLowerCase();
338
+ let code = Object.hasOwn(NAMED_KEYS, lower) ? NAMED_KEYS[lower] : Object.hasOwn(MODIFIERS, lower) ? MODIFIERS[lower] : void 0;
339
+ if (code === void 0 && key.length === 1) {
340
+ const shiftedIndex = shifted.indexOf(key);
341
+ const plain = shiftedIndex >= 0 ? unshifted[shiftedIndex] : lower;
342
+ const index = characters.indexOf(plain);
343
+ if (index >= 0) code = index + 4;
344
+ else if (punctuation.includes(plain)) code = punctuation.indexOf(plain) + 45;
345
+ else if (punctuationTail.includes(plain)) code = punctuationTail.indexOf(plain) + 51;
346
+ else code = { "\n": 40, " ": 43, " ": 44 }[plain];
347
+ if ((shiftedIndex >= 0 || /[A-Z]/.test(key)) && !modifiers.includes(225)) modifiers.push(225);
348
+ }
349
+ if (code === void 0 || !key) throw new RelayError("invalid_input", `Unknown key "${key}"`);
350
+ const keys = [...modifiers.filter((modifier) => modifier !== code), code];
351
+ return [...keys.map((key2) => ({ type: "keyDown", key: key2 })), ...keys.reverse().map((key2) => ({ type: "keyUp", key: key2 }))];
352
+ }
353
+ function textEvents(text) {
354
+ if (typeof text !== "string") throw new RelayError("invalid_input", "Text must be a string");
355
+ return Array.from(text, (character) => {
356
+ const codepoint = character.codePointAt(0);
357
+ if (!codepoint || codepoint >= 55296 && codepoint <= 57343) throw new RelayError("invalid_input", "Invalid Unicode scalar");
358
+ return { type: "text", codepoint };
359
+ });
360
+ }
361
+ function isLoopback(hostname) {
362
+ return hostname === "localhost" || hostname === "127.0.0.1";
363
+ }
364
+ function validToken(token) {
365
+ return typeof token === "string" && /^[0-9a-f]{64}$/.test(token);
366
+ }
367
+ function baseUrl(url, token) {
368
+ let parsed;
369
+ try {
370
+ parsed = new URL(url);
371
+ } catch {
372
+ throw new RelayError("invalid_input", "Invalid server URL");
373
+ }
374
+ const local = isLoopback(parsed.hostname);
375
+ if (!["http:", "https:"].includes(parsed.protocol) || !local && parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) {
376
+ throw new RelayError("invalid_input", "Server URL must be an HTTPS origin or loopback HTTP origin");
377
+ }
378
+ if (token !== void 0 && !validToken(token) || !local && !token) throw new RelayError("invalid_input", "Remote connections require a 64-character hexadecimal token");
379
+ return parsed;
380
+ }
381
+ export {
382
+ ERROR_REASONS,
383
+ HEADER_SIZE,
384
+ HID_KEYS,
385
+ INPUT_SIZE,
386
+ INPUT_TYPES,
387
+ MAGIC,
388
+ MAX_BYTES_IN_FLIGHT,
389
+ MAX_HEIGHT,
390
+ MAX_INPUT_BATCH,
391
+ MAX_INPUT_PENDING,
392
+ MAX_WIDTH,
393
+ MESSAGE_TYPES,
394
+ MODIFIERS,
395
+ NAMED_KEYS,
396
+ RelayError,
397
+ SUBPROTOCOL,
398
+ VERSION,
399
+ baseUrl,
400
+ batches,
401
+ comboEvents,
402
+ coordinate,
403
+ encodeAck,
404
+ encodeInput,
405
+ encodeInputBatch,
406
+ encodeInputRecord,
407
+ h264Codec,
408
+ header,
409
+ integer,
410
+ isLoopback,
411
+ networkError,
412
+ parseHeader,
413
+ parseMessage,
414
+ responseError,
415
+ socketTarget,
416
+ textEvents,
417
+ validToken
418
+ };
@@ -0,0 +1,77 @@
1
+ import { type InputEvent } from '../protocol/index.js';
2
+ export { RelayError, ERROR_REASONS } from '../protocol/index.js';
3
+ export type { ErrorClass, ErrorReason, ErrorOptions, NextCommand } from '../protocol/index.js';
4
+ export type { InputEvent };
5
+ export type Input = InputEvent;
6
+ /** Connection settings. `url` is the engine origin (default `http://127.0.0.1:8080`), `token` is the 64-character session token that remote hosts require, and `timeout` is in milliseconds (default 10000). */
7
+ export interface ClientOptions {
8
+ url?: string;
9
+ token?: string;
10
+ timeout?: number;
11
+ ca?: string;
12
+ connect?: string;
13
+ signal?: AbortSignal;
14
+ }
15
+ export type Options = ClientOptions;
16
+ export interface InputResult {
17
+ events: number;
18
+ }
19
+ export type Status = Record<string, unknown>;
20
+ export interface Capabilities {
21
+ version: number;
22
+ backend: string;
23
+ width: number;
24
+ height: number;
25
+ fps: number;
26
+ input: {
27
+ keyboard: boolean;
28
+ pointer: boolean;
29
+ buttons: boolean;
30
+ wheel: boolean;
31
+ };
32
+ screenshot: string;
33
+ control: string;
34
+ wayland: boolean;
35
+ max_input_pending: number;
36
+ input_endpoint: string;
37
+ max_input_batch: number;
38
+ cursor: boolean;
39
+ audio: boolean;
40
+ clipboard: boolean;
41
+ resize: boolean;
42
+ ime: boolean;
43
+ }
44
+ /** Sends each call as its own request. Coordinates are fractions of the screen from 0 to 1, and `screenshot` resolves to PNG bytes. */
45
+ export interface Client {
46
+ status(): Promise<Status>;
47
+ capabilities(): Promise<Capabilities>;
48
+ screenshot(): Promise<Uint8Array>;
49
+ click(x: number, y: number, options?: {
50
+ button?: 'left' | 'middle' | 'right';
51
+ }): Promise<InputResult>;
52
+ move(x: number, y: number): Promise<InputResult>;
53
+ scroll(x: number, y: number, options?: {
54
+ dx?: number;
55
+ dy?: number;
56
+ }): Promise<InputResult>;
57
+ key(...combos: string[]): Promise<InputResult>;
58
+ type(text: string): Promise<InputResult>;
59
+ input(events: InputEvent[]): Promise<InputResult>;
60
+ }
61
+ /** A control connection that owns input until `close()`. `input` sends one raw event. */
62
+ export interface Session {
63
+ surface: {
64
+ width: number;
65
+ height: number;
66
+ };
67
+ capabilities(): Promise<Capabilities>;
68
+ status(): Promise<Status>;
69
+ screenshot(path?: string): Promise<Uint8Array>;
70
+ input(event: InputEvent): Promise<void>;
71
+ close(): void;
72
+ }
73
+ export declare function capabilities(options?: ClientOptions): Promise<Capabilities>;
74
+ export declare function status(options?: ClientOptions): Promise<Status>;
75
+ export declare function screenshot(options?: ClientOptions, path?: string): Promise<Uint8Array>;
76
+ export declare function createClient(options?: ClientOptions): Client;
77
+ export declare function connect(options?: ClientOptions): Promise<Session>;