@limrun/api 0.79.0 → 0.79.2

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 (59) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/destination-tunnel-dialer.d.mts.map +1 -1
  3. package/destination-tunnel-dialer.d.ts.map +1 -1
  4. package/destination-tunnel-dialer.js +23 -14
  5. package/destination-tunnel-dialer.js.map +1 -1
  6. package/destination-tunnel-dialer.mjs +23 -14
  7. package/destination-tunnel-dialer.mjs.map +1 -1
  8. package/internal/app-log-events.d.mts +21 -0
  9. package/internal/app-log-events.d.mts.map +1 -0
  10. package/internal/app-log-events.d.ts +21 -0
  11. package/internal/app-log-events.d.ts.map +1 -0
  12. package/internal/app-log-events.js +73 -0
  13. package/internal/app-log-events.js.map +1 -0
  14. package/internal/app-log-events.mjs +69 -0
  15. package/internal/app-log-events.mjs.map +1 -0
  16. package/internal/signaling-transport.d.mts +79 -0
  17. package/internal/signaling-transport.d.mts.map +1 -0
  18. package/internal/signaling-transport.d.ts +79 -0
  19. package/internal/signaling-transport.d.ts.map +1 -0
  20. package/internal/signaling-transport.js +320 -0
  21. package/internal/signaling-transport.js.map +1 -0
  22. package/internal/signaling-transport.mjs +316 -0
  23. package/internal/signaling-transport.mjs.map +1 -0
  24. package/ios-client.d.mts +4 -9
  25. package/ios-client.d.mts.map +1 -1
  26. package/ios-client.d.ts +4 -9
  27. package/ios-client.d.ts.map +1 -1
  28. package/ios-client.js +172 -412
  29. package/ios-client.js.map +1 -1
  30. package/ios-client.mjs +173 -413
  31. package/ios-client.mjs.map +1 -1
  32. package/log-stream.d.mts +11 -4
  33. package/log-stream.d.mts.map +1 -1
  34. package/log-stream.d.ts +11 -4
  35. package/log-stream.d.ts.map +1 -1
  36. package/log-stream.js +45 -8
  37. package/log-stream.js.map +1 -1
  38. package/log-stream.mjs +45 -8
  39. package/log-stream.mjs.map +1 -1
  40. package/package.json +1 -1
  41. package/resources/macos-instances-helpers.d.mts +12 -0
  42. package/resources/macos-instances-helpers.d.mts.map +1 -1
  43. package/resources/macos-instances-helpers.d.ts +12 -0
  44. package/resources/macos-instances-helpers.d.ts.map +1 -1
  45. package/resources/macos-instances-helpers.js +118 -141
  46. package/resources/macos-instances-helpers.js.map +1 -1
  47. package/resources/macos-instances-helpers.mjs +118 -141
  48. package/resources/macos-instances-helpers.mjs.map +1 -1
  49. package/src/destination-tunnel-dialer.ts +23 -14
  50. package/src/internal/app-log-events.ts +76 -0
  51. package/src/internal/signaling-transport.ts +454 -0
  52. package/src/ios-client.ts +193 -471
  53. package/src/log-stream.ts +54 -11
  54. package/src/resources/macos-instances-helpers.ts +153 -136
  55. package/src/version.ts +1 -1
  56. package/version.d.mts +1 -1
  57. package/version.d.ts +1 -1
  58. package/version.js +1 -1
  59. package/version.mjs +1 -1
@@ -0,0 +1,454 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { WebSocket, Data } from 'ws';
3
+ import { nodeProxyTransport } from './proxy-transport';
4
+ import { isNonRetryableError } from '../tunnel';
5
+
6
+ /**
7
+ * Connection state of an instance's signaling WebSocket.
8
+ */
9
+ export type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'reconnecting';
10
+
11
+ /**
12
+ * Callback function for connection state changes
13
+ */
14
+ export type ConnectionStateCallback = (state: ConnectionState) => void;
15
+
16
+ /** A message the instance sends on the signaling socket. Replies carry the request's `id`. */
17
+ export type SignalingMessage = { type: string; id: string; error?: string | null } & Record<string, any>;
18
+
19
+ export interface SignalingLogger {
20
+ debug: (...args: any[]) => void;
21
+ info: (...args: any[]) => void;
22
+ warn: (...args: any[]) => void;
23
+ error: (...args: any[]) => void;
24
+ }
25
+
26
+ export interface SignalingTransportOptions {
27
+ /** The instance's API URL; the socket opens at its `/signaling` path. */
28
+ apiUrl: string;
29
+ token: string;
30
+ logger: SignalingLogger;
31
+ /** Reconnect attempts after the socket drops. Defaults to 6. */
32
+ maxReconnectAttempts?: number;
33
+ /** First reconnect delay in milliseconds, doubled per attempt. Defaults to 1000. */
34
+ reconnectDelay?: number;
35
+ /** Longest reconnect delay in milliseconds. Defaults to 30000. */
36
+ maxReconnectDelay?: number;
37
+ /** Turns a reply into a request's result, by reply type. Unknown types resolve with the message. */
38
+ responseHandlers?: Record<string, (message: SignalingMessage) => unknown>;
39
+ /** Turns a reply's `error` into the error its request rejects with. Defaults to an Error with that text. */
40
+ replyError?: (message: SignalingMessage) => Error;
41
+ /** Consumes messages that are not replies, such as notifications and streams. True when handled. */
42
+ handleMessage?: (message: SignalingMessage) => boolean;
43
+ /** Called when the socket closes, with the reason pending requests failed for. */
44
+ onConnectionLost?: (reason: string) => void;
45
+ /** Called once the client is closed for good: on disconnect, or when reconnecting gives up. */
46
+ onClosed?: () => void;
47
+ /** What a request looks like in debug logs, for requests that carry secrets. */
48
+ redactRequest?: (request: Record<string, unknown>) => Record<string, unknown>;
49
+ /** Runs on the first open before the transport resolves; a failure rejects it. */
50
+ onFirstOpen?: (transport: SignalingTransport) => Promise<void>;
51
+ }
52
+
53
+ /**
54
+ * SignalingTransport is an instance's signaling WebSocket: requests matched to replies by `id`,
55
+ * reconnects with exponential backoff, and keepAlive. The iOS and macOS clients share it.
56
+ */
57
+ export interface SignalingTransport {
58
+ /** The signaling WebSocket URL, token included. */
59
+ readonly url: string;
60
+ /**
61
+ * Send `{type, id, ...params}` and resolve with the reply with the same `id`. A `timeoutMs` of
62
+ * zero waits until the reply or the connection ends. Pass `id` (from {@link nextId}) to match
63
+ * messages the instance sends before the reply, such as progress.
64
+ */
65
+ request<T>(
66
+ type: string,
67
+ params?: Record<string, unknown>,
68
+ transform?: (message: SignalingMessage) => T,
69
+ timeoutMs?: number,
70
+ id?: string,
71
+ ): Promise<T>;
72
+ /** A new request ID. */
73
+ nextId(): string;
74
+ /** Send a message without waiting for a reply. False when the socket is not open. */
75
+ send(message: Record<string, unknown>, callback?: (err?: Error) => void): boolean;
76
+ isOpen(): boolean;
77
+ /** Send an application-level keepAlive message. */
78
+ keepAlive(): void;
79
+ /** Close the socket for good and fail pending requests. */
80
+ disconnect(): void;
81
+ getConnectionState(): ConnectionState;
82
+ onConnectionStateChange(callback: ConnectionStateCallback): () => void;
83
+ }
84
+
85
+ type PendingRequest = {
86
+ resolve: (value: any) => void;
87
+ reject: (reason: Error) => void;
88
+ timeout: NodeJS.Timeout | undefined;
89
+ transform?: (message: SignalingMessage) => unknown;
90
+ };
91
+
92
+ /** The WebSocket close code for a policy violation, as the instance closes a refused session. */
93
+ const POLICY_VIOLATION = 1008;
94
+
95
+ /** signalingUrl is the signaling WebSocket URL of an instance API URL. */
96
+ export function signalingUrl(apiUrl: string, token: string): string {
97
+ return `${apiUrl.replace('https://', 'wss://').replace('http://', 'ws://')}/signaling?token=${token}`;
98
+ }
99
+
100
+ /**
101
+ * Open an instance's signaling WebSocket. Resolves once it is open and `onFirstOpen` finished.
102
+ * Only the opening handshake is retried before it resolves, once, when the failure is transient.
103
+ */
104
+ export function openSignalingTransport(options: SignalingTransportOptions): Promise<SignalingTransport> {
105
+ const url = signalingUrl(options.apiUrl, options.token);
106
+ const logger = options.logger;
107
+ const maxReconnectAttempts = options.maxReconnectAttempts ?? 6;
108
+ const reconnectDelay = options.reconnectDelay ?? 1000;
109
+ const maxReconnectDelay = options.maxReconnectDelay ?? 30000;
110
+ const responseHandlers = options.responseHandlers ?? {};
111
+
112
+ let ws: WebSocket | undefined = undefined;
113
+ let connectionState: ConnectionState = 'connecting';
114
+ let reconnectAttempts = 0;
115
+ let reconnectTimeout: NodeJS.Timeout | undefined;
116
+ let handshakeDeadline: NodeJS.Timeout | undefined;
117
+ let pingInterval: NodeJS.Timeout | undefined;
118
+ let intentionalDisconnect = false;
119
+ let lastError: string | undefined;
120
+ // What the instance said in an error frame before closing, such as a message above the grant.
121
+ let instanceError: string | undefined;
122
+ const pendingRequests: Map<string, PendingRequest> = new Map();
123
+ const stateChangeCallbacks: Set<ConnectionStateCallback> = new Set();
124
+ const keepAliveSessionId =
125
+ Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
126
+
127
+ const updateConnectionState = (newState: ConnectionState): void => {
128
+ if (connectionState !== newState) {
129
+ connectionState = newState;
130
+ logger.debug(`Connection state changed to: ${newState}`);
131
+ stateChangeCallbacks.forEach((callback) => {
132
+ try {
133
+ callback(newState);
134
+ } catch (err) {
135
+ logger.error('Error in connection state callback:', err);
136
+ }
137
+ });
138
+ }
139
+ };
140
+
141
+ const failPendingRequests = (reason: string): void => {
142
+ pendingRequests.forEach((request) => {
143
+ clearTimeout(request.timeout);
144
+ request.reject(new Error(reason));
145
+ });
146
+ pendingRequests.clear();
147
+ options.onConnectionLost?.(reason);
148
+ };
149
+
150
+ const cleanupConnection = (): void => {
151
+ clearTimeout(handshakeDeadline);
152
+ if (reconnectTimeout) {
153
+ clearTimeout(reconnectTimeout);
154
+ reconnectTimeout = undefined;
155
+ }
156
+ if (pingInterval) {
157
+ clearInterval(pingInterval);
158
+ pingInterval = undefined;
159
+ }
160
+ if (ws) {
161
+ ws.removeAllListeners();
162
+ // A retired socket can emit an error when an unfinished handshake is cancelled.
163
+ ws.on('error', () => {});
164
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
165
+ ws.close();
166
+ }
167
+ ws = undefined;
168
+ }
169
+ };
170
+
171
+ const isOpen = (): boolean => !!ws && ws.readyState === WebSocket.OPEN;
172
+
173
+ const generateId = (): string => `ts-client-${randomUUID()}`;
174
+
175
+ const request = <T>(
176
+ type: string,
177
+ params: Record<string, unknown> = {},
178
+ transform?: (message: SignalingMessage) => T,
179
+ timeoutMs: number = 30000,
180
+ id: string = generateId(),
181
+ ): Promise<T> => {
182
+ return new Promise((resolve, reject) => {
183
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
184
+ reject(new Error('WebSocket is not connected or connection is not open.'));
185
+ return;
186
+ }
187
+
188
+ const timeout =
189
+ timeoutMs > 0 ?
190
+ setTimeout(() => {
191
+ pendingRequests.delete(id);
192
+ reject(new Error(`Request ${type} timed out`));
193
+ }, timeoutMs)
194
+ : undefined;
195
+
196
+ pendingRequests.set(
197
+ id,
198
+ transform ? { resolve, reject, timeout, transform } : { resolve, reject, timeout },
199
+ );
200
+
201
+ const message = { type, id, ...params };
202
+ logger.debug('Sending request:', options.redactRequest ? options.redactRequest(message) : message);
203
+
204
+ ws.send(JSON.stringify(message), (err?: Error) => {
205
+ if (err) {
206
+ clearTimeout(timeout);
207
+ pendingRequests.delete(id);
208
+ logger.error(`Failed to send ${type} request:`, err);
209
+ reject(err);
210
+ }
211
+ });
212
+ });
213
+ };
214
+
215
+ const send = (message: Record<string, unknown>, callback?: (err?: Error) => void): boolean => {
216
+ if (!ws || ws.readyState !== WebSocket.OPEN) return false;
217
+ ws.send(JSON.stringify(message), callback);
218
+ return true;
219
+ };
220
+
221
+ const keepAlive = (): void => {
222
+ send({ type: 'keepAlive', sessionId: keepAliveSessionId });
223
+ };
224
+
225
+ const disconnect = (): void => {
226
+ intentionalDisconnect = true;
227
+ cleanupConnection();
228
+ updateConnectionState('disconnected');
229
+ failPendingRequests('Intentional disconnect');
230
+ options.onClosed?.();
231
+ logger.debug('Intentionally disconnected from WebSocket.');
232
+ };
233
+
234
+ const transport: SignalingTransport = {
235
+ url,
236
+ request,
237
+ nextId: generateId,
238
+ send,
239
+ isOpen,
240
+ keepAlive,
241
+ disconnect,
242
+ getConnectionState: () => connectionState,
243
+ onConnectionStateChange: (callback) => {
244
+ stateChangeCallbacks.add(callback);
245
+ return () => {
246
+ stateChangeCallbacks.delete(callback);
247
+ };
248
+ },
249
+ };
250
+
251
+ return new Promise<SignalingTransport>((resolveConnection, rejectConnection) => {
252
+ let hasResolved = false;
253
+ let retriedHandshake = false;
254
+
255
+ // Reconnection logic with exponential backoff
256
+ const scheduleReconnect = (): void => {
257
+ if (intentionalDisconnect) {
258
+ logger.debug('Skipping reconnection (intentional disconnect)');
259
+ return;
260
+ }
261
+
262
+ if (isNonRetryableError(lastError ?? '')) {
263
+ logger.error(`Skipping reconnection (non-retryable error): ${lastError}`);
264
+ updateConnectionState('disconnected');
265
+ options.onClosed?.();
266
+ return;
267
+ }
268
+
269
+ if (reconnectAttempts >= maxReconnectAttempts) {
270
+ logger.error(`Max reconnection attempts (${maxReconnectAttempts}) reached. Giving up.`);
271
+ updateConnectionState('disconnected');
272
+ options.onClosed?.();
273
+ return;
274
+ }
275
+
276
+ const currentDelay = Math.min(reconnectDelay * Math.pow(2, reconnectAttempts), maxReconnectDelay);
277
+
278
+ reconnectAttempts++;
279
+ logger.debug(`Scheduling reconnection attempt ${reconnectAttempts} in ${currentDelay}ms...`);
280
+ updateConnectionState('reconnecting');
281
+
282
+ reconnectTimeout = setTimeout(() => {
283
+ logger.debug(`Attempting to reconnect (attempt ${reconnectAttempts})...`);
284
+ setupWebSocket();
285
+ }, currentDelay);
286
+ };
287
+
288
+ const setupWebSocket = (): void => {
289
+ cleanupConnection();
290
+ updateConnectionState('connecting');
291
+
292
+ const proxyAgent = nodeProxyTransport.getWebSocketAgent(url);
293
+ let opened = false;
294
+ let handshakeError: Error | undefined;
295
+ const socket = new WebSocket(url, proxyAgent ? { agent: proxyAgent } : {});
296
+ ws = socket;
297
+ // A socket inactivity timeout allows a slow TLS peer to keep the first command waiting.
298
+ handshakeDeadline = setTimeout(() => {
299
+ handshakeError = Object.assign(new Error('Opening handshake has timed out'), { code: 'ETIMEDOUT' });
300
+ socket.terminate();
301
+ }, 5000);
302
+
303
+ socket.on('message', (data: Data) => {
304
+ let message: SignalingMessage;
305
+ try {
306
+ message = JSON.parse(data.toString());
307
+ } catch (e) {
308
+ logger.error({ data, error: e }, 'Failed to parse JSON message');
309
+ return;
310
+ }
311
+
312
+ if (options.handleMessage?.(message)) {
313
+ return;
314
+ }
315
+
316
+ const pending = pendingRequests.get(message.id);
317
+ if (!pending) {
318
+ if (message.type === 'error' && message['message']) {
319
+ // The instance explains a policy close, such as a message above the token's grant.
320
+ instanceError = String(message['message']);
321
+ logger.error('Instance error:', instanceError);
322
+ return;
323
+ }
324
+ logger.debug(`Received response for unknown or already handled request: ${message.id}`);
325
+ return;
326
+ }
327
+
328
+ clearTimeout(pending.timeout);
329
+ pendingRequests.delete(message.id);
330
+
331
+ if (message.error) {
332
+ logger.debug(`Server error for ${message.type}: ${message.error}`);
333
+ pending.reject(options.replyError ? options.replyError(message) : new Error(message.error));
334
+ return;
335
+ }
336
+
337
+ // Use handler to transform response, or resolve with raw message
338
+ const handler = pending.transform ?? responseHandlers[message.type];
339
+ if (handler) {
340
+ try {
341
+ pending.resolve(handler(message));
342
+ } catch (err) {
343
+ pending.reject(err as Error);
344
+ }
345
+ } else {
346
+ logger.warn('Received unexpected message type:', message.type);
347
+ pending.resolve(message);
348
+ }
349
+ });
350
+
351
+ socket.on('error', (err: Error) => {
352
+ lastError = err.message;
353
+ logger.error('WebSocket error:', err.message);
354
+ if (!opened) handshakeError ??= err;
355
+ });
356
+
357
+ socket.on('close', (code: number) => {
358
+ clearTimeout(handshakeDeadline);
359
+ if (pingInterval) {
360
+ clearInterval(pingInterval);
361
+ pingInterval = undefined;
362
+ }
363
+
364
+ // A policy close, or the instance's error frame before it, refuses the token for good,
365
+ // such as a command above its grant, so reconnecting cannot help.
366
+ const refusal =
367
+ instanceError ?? (code === POLICY_VIOLATION ? 'the instance closed the session' : undefined);
368
+ instanceError = undefined;
369
+ const shouldReconnect =
370
+ !intentionalDisconnect &&
371
+ !refusal &&
372
+ !isNonRetryableError(lastError ?? '') &&
373
+ connectionState !== 'disconnected';
374
+ updateConnectionState('disconnected');
375
+
376
+ logger.debug('Disconnected from server.');
377
+
378
+ failPendingRequests(refusal ? `Connection closed: ${refusal}` : 'Connection closed');
379
+
380
+ if (!hasResolved) {
381
+ // Settle before onFirstOpen sees its request fail, with the instance's reason.
382
+ const err =
383
+ refusal ?
384
+ new Error(refusal)
385
+ : handshakeError ?? new Error('Connection closed before the client was ready');
386
+ // Retry only the opening handshake. Once open, onFirstOpen owns its failure.
387
+ const code = (err as NodeJS.ErrnoException).code;
388
+ const transient =
389
+ ['ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN'].includes(
390
+ code ?? '',
391
+ ) ||
392
+ /^(Opening handshake has timed out|socket hang up|Unexpected server response: 50[234])$/.test(
393
+ err.message,
394
+ );
395
+ if (!refusal && !opened && !retriedHandshake && maxReconnectAttempts > 0 && transient) {
396
+ retriedHandshake = true;
397
+ updateConnectionState('reconnecting');
398
+ reconnectTimeout = setTimeout(setupWebSocket, 100 + Math.floor(Math.random() * 151));
399
+ } else {
400
+ cleanupConnection();
401
+ rejectConnection(err);
402
+ }
403
+ return;
404
+ }
405
+ if (shouldReconnect) {
406
+ scheduleReconnect();
407
+ } else if (refusal && !intentionalDisconnect) {
408
+ logger.error(`The instance closed the session: ${refusal}`);
409
+ cleanupConnection();
410
+ options.onClosed?.();
411
+ } else if (isNonRetryableError(lastError ?? '')) {
412
+ logger.error(`Closing connection due to non-retryable error: ${lastError}`);
413
+ cleanupConnection();
414
+ updateConnectionState('disconnected');
415
+ failPendingRequests('Non-retryable error');
416
+ options.onClosed?.();
417
+ logger.debug('Non-retryable error. Closing connection.');
418
+ }
419
+ });
420
+
421
+ socket.on('open', async () => {
422
+ clearTimeout(handshakeDeadline);
423
+ opened = true;
424
+ logger.debug('WebSocket connected');
425
+ reconnectAttempts = 0;
426
+ lastError = undefined;
427
+ updateConnectionState('connected');
428
+
429
+ pingInterval = setInterval(() => {
430
+ if (ws && ws.readyState === WebSocket.OPEN) {
431
+ ws.ping();
432
+ }
433
+ }, 30_000);
434
+
435
+ if (!hasResolved) {
436
+ try {
437
+ await options.onFirstOpen?.(transport);
438
+ } catch (err) {
439
+ logger.error('Failed to prepare the client:', err);
440
+ cleanupConnection();
441
+ updateConnectionState('disconnected');
442
+ rejectConnection(err as Error);
443
+ return;
444
+ }
445
+
446
+ hasResolved = true;
447
+ resolveConnection(transport);
448
+ }
449
+ });
450
+ };
451
+
452
+ setupWebSocket();
453
+ });
454
+ }