@jetpack-desktop/client 0.0.0-stage → 0.1.2-rc.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.
package/dist/client.js ADDED
@@ -0,0 +1,864 @@
1
+ import { JetPackControlBar } from './control-bar.js';
2
+ import { JetPackLogTerminal } from './log-terminal.js';
3
+ import { JetPackClientError, } from './types.js';
4
+ const DEFAULT_DAEMON_PORT = 9470;
5
+ const DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2000;
6
+ const DEFAULT_PAIRING_POLL_MS = 1500;
7
+ const DEFAULT_PAIRING_TIMEOUT_MS = 60_000;
8
+ export const DEFAULT_JETPACK_DOWNLOAD_URL = 'https://github.com/jetpack-desktop/releases/releases/latest';
9
+ function delay(ms) {
10
+ return new Promise((resolve) => setTimeout(resolve, ms));
11
+ }
12
+ function isNoActiveWorkerError(err) {
13
+ const msg = err instanceof Error ? err.message : String(err ?? '');
14
+ return (msg.includes('No active worker job for current session') ||
15
+ msg.includes('Worker job not found') ||
16
+ msg.includes('Worker IPC channel closed'));
17
+ }
18
+ function formatStopDetail(reason) {
19
+ switch (reason) {
20
+ case 'idle_timeout':
21
+ return 'Idle timeout — perform an action or click Relaunch';
22
+ case 'process_exited':
23
+ return 'Worker exited unexpectedly';
24
+ case 'terminated':
25
+ default:
26
+ return 'Stopped';
27
+ }
28
+ }
29
+ function sanitizeDownloadUrl(rawUrl) {
30
+ if (typeof rawUrl === 'string') {
31
+ const trimmed = rawUrl.trim();
32
+ if (trimmed && !/[\s\u0000-\u001f\u007f]/.test(trimmed)) {
33
+ try {
34
+ const parsed = new URL(trimmed);
35
+ if (parsed.protocol === 'https:' && !parsed.username && !parsed.password) {
36
+ return parsed.toString();
37
+ }
38
+ }
39
+ catch {
40
+ // Fall through to default download URL
41
+ }
42
+ }
43
+ }
44
+ return DEFAULT_JETPACK_DOWNLOAD_URL;
45
+ }
46
+ function resolveHealthProbeUrl(wsUrl, daemonPort) {
47
+ try {
48
+ const parsed = new URL(wsUrl);
49
+ if (parsed.protocol === 'wss:') {
50
+ parsed.protocol = 'https:';
51
+ }
52
+ else if (parsed.protocol === 'ws:') {
53
+ parsed.protocol = 'http:';
54
+ }
55
+ parsed.pathname = '/health';
56
+ parsed.search = '';
57
+ parsed.hash = '';
58
+ return parsed.toString();
59
+ }
60
+ catch {
61
+ return `http://127.0.0.1:${daemonPort}/health`;
62
+ }
63
+ }
64
+ function isSameHttpOrigin(healthUrl, origin) {
65
+ try {
66
+ return new URL(healthUrl).origin === new URL(origin).origin;
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ async function probeDaemonHealth(healthUrl, timeoutMs, fetchImpl) {
73
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
74
+ let timer = null;
75
+ try {
76
+ const fetchPromise = fetchImpl(healthUrl, {
77
+ method: 'GET',
78
+ cache: 'no-store',
79
+ signal: controller?.signal,
80
+ });
81
+ const timeoutPromise = new Promise((_, reject) => {
82
+ timer = setTimeout(() => {
83
+ controller?.abort();
84
+ reject(new Error(`Health check timed out after ${timeoutMs}ms`));
85
+ }, timeoutMs);
86
+ });
87
+ const response = await Promise.race([fetchPromise, timeoutPromise]);
88
+ if (!response || !response.ok) {
89
+ return { reachable: false, originPaired: null };
90
+ }
91
+ let originPaired = null;
92
+ if (typeof response.json === 'function') {
93
+ try {
94
+ const payload = (await response.json());
95
+ if (payload && typeof payload.origin_paired === 'boolean') {
96
+ originPaired = payload.origin_paired;
97
+ }
98
+ }
99
+ catch {
100
+ originPaired = null;
101
+ }
102
+ }
103
+ return { reachable: true, originPaired };
104
+ }
105
+ catch {
106
+ return { reachable: false, originPaired: null };
107
+ }
108
+ finally {
109
+ if (timer !== null) {
110
+ clearTimeout(timer);
111
+ }
112
+ }
113
+ }
114
+ function resolveDefaultOrigin() {
115
+ if (typeof globalThis !== 'undefined') {
116
+ const loc = globalThis.location;
117
+ if (loc && typeof loc.origin === 'string' && loc.origin !== 'null' && loc.origin.length > 0) {
118
+ return loc.origin;
119
+ }
120
+ }
121
+ return 'http://127.0.0.1';
122
+ }
123
+ function triggerBrowserDeepLink(uri) {
124
+ if (typeof document === 'undefined' || !document.body) {
125
+ return;
126
+ }
127
+ try {
128
+ const link = document.createElement('a');
129
+ link.href = uri;
130
+ link.style.display = 'none';
131
+ document.body.appendChild(link);
132
+ link.click();
133
+ document.body.removeChild(link);
134
+ }
135
+ catch {
136
+ // Non-fatal in restricted/headless DOM environments
137
+ }
138
+ }
139
+ /**
140
+ * High-level SDK client wrapping `jetpack-wasm` (`WasmClientIdentity` + `JetPackWasmClient`)
141
+ * to provide automatic `jetpack://pair` onboarding, catalog/install/launch orchestration,
142
+ * correlated `request()` RPCs, multiplexed `onStream()` subscriptions, and an auto-mounted
143
+ * Shadow-DOM `JetPackControlBar`.
144
+ *
145
+ * Optionally pass a codegen-generated `JetPackOpcodeMap` generic parameter
146
+ * (`new JetPackAppClient<JetPackOpcodeMap>()`) for compile-time opcode, metadata,
147
+ * binary payload, and stream contract enforcement.
148
+ */
149
+ export class JetPackAppClient {
150
+ wasmClient = null;
151
+ identity = null;
152
+ appId = null;
153
+ lastPairingUri = null;
154
+ closed = false;
155
+ workerRunning = false;
156
+ lastStopReason = null;
157
+ ensureWorkerPromise = null;
158
+ lastProgressCallback = null;
159
+ resetVolumesOnRelaunch = false;
160
+ initializedWasmModules = new WeakSet();
161
+ streamListeners = new Map();
162
+ workerStoppedListeners = new Set();
163
+ workerStartedListeners = new Set();
164
+ inFlightRequests = new Set();
165
+ controlBar = null;
166
+ logTerminal = null;
167
+ /** Returns `true` when an authenticated daemon session is open and bound to an app. */
168
+ isConnected() {
169
+ return !this.closed && this.wasmClient !== null && this.wasmClient.is_connected() && this.appId !== null;
170
+ }
171
+ /** Returns `true` when the session is connected and the app worker is currently active. */
172
+ isWorkerRunning() {
173
+ return this.isConnected() && this.workerRunning;
174
+ }
175
+ /** Returns the most recent worker stop reason observed on this session, if stopped. */
176
+ getLastStopReason() {
177
+ return this.lastStopReason;
178
+ }
179
+ /** Returns the currently ensured `appId`, or `null` if disconnected. */
180
+ getAppId() {
181
+ return this.appId;
182
+ }
183
+ /** Returns the active `WasmClientIdentity` instance, if initialized. */
184
+ getIdentity() {
185
+ return this.identity;
186
+ }
187
+ /** Returns the last generated `jetpack://pair?...` URI if pairing was triggered. */
188
+ getLastPairingUri() {
189
+ return this.lastPairingUri;
190
+ }
191
+ /** Returns the underlying `JetPackWasmClient` instance for advanced control-plane calls. */
192
+ getRawClient() {
193
+ return this.wasmClient;
194
+ }
195
+ /** Returns the auto-mounted `JetPackControlBar` instance, or `null` when disabled or headless. */
196
+ getControlBar() {
197
+ return this.controlBar;
198
+ }
199
+ /** Returns the Developer Mode `JetPackLogTerminal` instance, or `null` when disabled or unmounted. */
200
+ getLogTerminal() {
201
+ return this.logTerminal;
202
+ }
203
+ /**
204
+ * Registers a callback invoked when the daemon reports `"app.worker.stopped"` for this app
205
+ * (e.g. idle timeout, manual Stop, or unexpected process exit). Returns an unsubscribe closure.
206
+ */
207
+ onWorkerStopped(callback) {
208
+ this.workerStoppedListeners.add(callback);
209
+ return () => {
210
+ this.workerStoppedListeners.delete(callback);
211
+ };
212
+ }
213
+ /**
214
+ * Registers a callback invoked when `ensureWorkerRunning()` successfully launches or wakes
215
+ * the worker for this app (including via the `JetPackControlBar` `"Relaunch"` button or
216
+ * transparent `request()` auto-wake). Returns an unsubscribe closure.
217
+ */
218
+ onWorkerStarted(callback) {
219
+ this.workerStartedListeners.add(callback);
220
+ return () => {
221
+ this.workerStartedListeners.delete(callback);
222
+ };
223
+ }
224
+ /**
225
+ * Ensures the sandboxed worker for the connected app is running, relaunching it via
226
+ * `launch_app` if it was stopped due to idle timeout or user termination. Concurrent calls
227
+ * share a single in-flight launch operation.
228
+ */
229
+ async ensureWorkerRunning() {
230
+ if (this.closed) {
231
+ throw new JetPackClientError('CLIENT_CLOSED', 'Cannot launch worker after JetPackAppClient.close()');
232
+ }
233
+ const client = this.wasmClient;
234
+ const appId = this.appId;
235
+ if (!client || !client.is_connected() || !appId) {
236
+ throw new JetPackClientError('NOT_CONNECTED', 'JetPackAppClient is not connected. Call connectAndEnsureApp() first.');
237
+ }
238
+ if (this.workerRunning) {
239
+ return;
240
+ }
241
+ if (this.ensureWorkerPromise) {
242
+ return this.ensureWorkerPromise;
243
+ }
244
+ let launchPromise;
245
+ launchPromise = (async () => {
246
+ this.controlBar?.setStatus('Connecting');
247
+ try {
248
+ await client.launch_app(appId, this.resetVolumesOnRelaunch, this.lastProgressCallback);
249
+ if (this.closed || this.wasmClient !== client || !client.is_connected()) {
250
+ throw new JetPackClientError(this.closed ? 'CLIENT_CLOSED' : 'NOT_CONNECTED', 'Session closed while relaunching worker');
251
+ }
252
+ this.workerRunning = true;
253
+ this.lastStopReason = null;
254
+ this.controlBar?.setStatus('Running');
255
+ const startedEvent = { app_id: appId };
256
+ for (const cb of Array.from(this.workerStartedListeners)) {
257
+ cb(startedEvent);
258
+ }
259
+ }
260
+ catch (err) {
261
+ if (!this.closed) {
262
+ const msg = err instanceof Error ? err.message : String(err);
263
+ this.controlBar?.setStatus('Error', msg);
264
+ }
265
+ throw err;
266
+ }
267
+ finally {
268
+ if (this.ensureWorkerPromise === launchPromise) {
269
+ this.ensureWorkerPromise = null;
270
+ }
271
+ }
272
+ })();
273
+ this.ensureWorkerPromise = launchPromise;
274
+ return launchPromise;
275
+ }
276
+ /**
277
+ * Connects to the local JetPack daemon (triggering `jetpack://pair` approval if unpaired),
278
+ * verifies `appId` is installed (pulling from `SignedAppCatalog` with progress if absent),
279
+ * ensures the worker process is running inside its sandbox, and mounts `JetPackControlBar`
280
+ * in browser DOM environments unless `controlBar: false`.
281
+ */
282
+ async connectAndEnsureApp(options) {
283
+ if (!options || typeof options.appId !== 'string' || options.appId.trim().length === 0) {
284
+ throw new JetPackClientError('INVALID_OPTIONS', 'connectAndEnsureApp requires a non-empty appId');
285
+ }
286
+ // Reset any prior session state cleanly
287
+ if (this.wasmClient) {
288
+ this.cleanupConnectionOnly();
289
+ }
290
+ this.closed = false;
291
+ const appId = options.appId.trim();
292
+ const daemonPort = options.daemonPort ?? DEFAULT_DAEMON_PORT;
293
+ const wsUrl = options.wsUrl ?? `ws://127.0.0.1:${daemonPort}`;
294
+ const origin = options.origin ?? resolveDefaultOrigin();
295
+ const autoPair = options.autoPair ?? true;
296
+ const pollIntervalMs = Math.max(50, options.pairingPollIntervalMs ?? DEFAULT_PAIRING_POLL_MS);
297
+ const timeoutMs = Math.max(pollIntervalMs, options.pairingTimeoutMs ?? DEFAULT_PAIRING_TIMEOUT_MS);
298
+ const downloadUrl = sanitizeDownloadUrl(options.downloadUrl);
299
+ const healthProbeTimeoutMs = options.healthProbeTimeoutMs === 0
300
+ ? 0
301
+ : Math.max(50, options.healthProbeTimeoutMs ?? DEFAULT_HEALTH_PROBE_TIMEOUT_MS);
302
+ const fetchImpl = options.fetchFn ??
303
+ (typeof globalThis !== 'undefined' && typeof globalThis.fetch === 'function'
304
+ ? globalThis.fetch.bind(globalThis)
305
+ : null);
306
+ const barConfig = options.controlBar === false || typeof document === 'undefined'
307
+ ? null
308
+ : {
309
+ ...(typeof options.controlBar === 'object' && options.controlBar !== null
310
+ ? options.controlBar
311
+ : {}),
312
+ appId,
313
+ appName: (typeof options.controlBar === 'object' && options.controlBar?.appName) || appId,
314
+ controlCenterUrl: (typeof options.controlBar === 'object' && options.controlBar?.controlCenterUrl) ||
315
+ `http://127.0.0.1:${daemonPort}/#apps`,
316
+ initialStatus: 'Connecting',
317
+ onStop: () => this.stopApp(),
318
+ onRelaunch: () => this.ensureWorkerRunning(),
319
+ };
320
+ if (options.controlBar === false && this.controlBar) {
321
+ this.controlBar.unmount();
322
+ this.controlBar = null;
323
+ }
324
+ else if (barConfig) {
325
+ if (!this.controlBar) {
326
+ this.controlBar = new JetPackControlBar(barConfig);
327
+ }
328
+ else {
329
+ this.controlBar.updateOptions(barConfig);
330
+ this.controlBar.mount(barConfig.mountTarget);
331
+ }
332
+ this.controlBar.setStatus('Connecting');
333
+ }
334
+ try {
335
+ let skipInitialConnect = false;
336
+ if (healthProbeTimeoutMs > 0 && fetchImpl) {
337
+ const healthUrl = resolveHealthProbeUrl(wsUrl, daemonPort);
338
+ const health = await probeDaemonHealth(healthUrl, healthProbeTimeoutMs, fetchImpl);
339
+ if (!health.reachable) {
340
+ throw new JetPackClientError('DAEMON_NOT_RUNNING', `JetPack daemon is not running or unreachable at ${healthUrl}. Download and start JetPack from ${downloadUrl}`, { downloadUrl });
341
+ }
342
+ // Browsers omit the HTTP Origin header on same-origin GET /health requests, so
343
+ // origin_paired is reported as false even when the client is already paired.
344
+ if (health.originPaired === false && autoPair && !isSameHttpOrigin(healthUrl, origin)) {
345
+ skipInitialConnect = true;
346
+ }
347
+ }
348
+ const wasm = await this.loadWasmBindings(options);
349
+ if (typeof wasm.default === 'function' && !this.initializedWasmModules.has(wasm)) {
350
+ try {
351
+ await wasm.default(options.wasmBinaryOrUrl);
352
+ }
353
+ catch (initErr) {
354
+ const metaUrl = typeof import.meta !== 'undefined' ? import.meta.url : '';
355
+ const viteDepsIdx = typeof metaUrl === 'string' ? metaUrl.indexOf('/.vite/deps/') : -1;
356
+ if (options.wasmBinaryOrUrl === undefined &&
357
+ !options.wasmModule &&
358
+ !options.wasmModulePath &&
359
+ viteDepsIdx !== -1) {
360
+ const fallbackWasmUrl = `${metaUrl.slice(0, viteDepsIdx)}/@jetpack-desktop/client/wasm/jetpack_wasm_bg.wasm`;
361
+ await wasm.default(fallbackWasmUrl);
362
+ }
363
+ else {
364
+ throw initErr;
365
+ }
366
+ }
367
+ this.initializedWasmModules.add(wasm);
368
+ }
369
+ const identity = new wasm.WasmClientIdentity();
370
+ this.identity = identity;
371
+ const client = await this.connectWithAutoPair({
372
+ wasm,
373
+ identity,
374
+ wsUrl,
375
+ origin,
376
+ autoPair,
377
+ skipInitialConnect,
378
+ pollIntervalMs,
379
+ timeoutMs,
380
+ disableAutoDeepLink: options.disableAutoDeepLink ?? false,
381
+ onPairingUri: options.onPairingUri,
382
+ });
383
+ if (this.closed) {
384
+ try {
385
+ client.close();
386
+ }
387
+ catch {
388
+ // ignore
389
+ }
390
+ throw new JetPackClientError('CLIENT_CLOSED', 'JetPackAppClient was closed during connection');
391
+ }
392
+ this.wasmClient = client;
393
+ this.appId = appId;
394
+ const apps = (await client.list_apps());
395
+ let targetApp = Array.isArray(apps) ? apps.find((a) => a.id === appId) : undefined;
396
+ const progressAdapter = options.onProgress
397
+ ? (prog) => options.onProgress?.(prog)
398
+ : null;
399
+ this.lastProgressCallback = progressAdapter;
400
+ this.resetVolumesOnRelaunch = options.resetVolumes ?? false;
401
+ if (!targetApp) {
402
+ let ociRef = options.ociReference?.trim();
403
+ if (!ociRef) {
404
+ const catalog = (await client.get_catalog());
405
+ const entry = Array.isArray(catalog)
406
+ ? catalog.find((c) => c.app_id === appId)
407
+ : undefined;
408
+ if (!entry || !entry.oci_reference) {
409
+ throw new JetPackClientError('APP_NOT_IN_CATALOG', `Application '${appId}' is not installed and was not found in the verified JetPack catalog`);
410
+ }
411
+ ociRef = entry.oci_reference;
412
+ }
413
+ await client.pull_app(ociRef, progressAdapter, appId);
414
+ const refreshed = (await client.list_apps());
415
+ targetApp = Array.isArray(refreshed) ? refreshed.find((a) => a.id === appId) : undefined;
416
+ }
417
+ const explicitName = typeof options.controlBar === 'object' && options.controlBar !== null
418
+ ? options.controlBar.appName?.trim()
419
+ : undefined;
420
+ const resolvedAppName = explicitName || targetApp?.name?.trim() || appId;
421
+ this.controlBar?.setAppName(resolvedAppName);
422
+ const status = String(targetApp?.status ?? '').toLowerCase();
423
+ if (status !== 'running') {
424
+ await client.launch_app(appId, this.resetVolumesOnRelaunch, progressAdapter);
425
+ }
426
+ client.on_worker_frame((opcode, payload, correlationId) => {
427
+ this.dispatchStreamFrame(opcode, payload, correlationId ?? null);
428
+ });
429
+ client.on_worker_stopped?.((event) => {
430
+ this.handleWorkerStopped(event);
431
+ });
432
+ this.workerRunning = true;
433
+ this.lastStopReason = null;
434
+ await this.syncLogTerminalForSession(client, resolvedAppName, options.logTerminal);
435
+ this.controlBar?.setStatus('Running');
436
+ return this;
437
+ }
438
+ catch (err) {
439
+ const msg = err instanceof Error ? err.message : String(err);
440
+ const errDownloadUrl = err instanceof JetPackClientError && err.downloadUrl ? err.downloadUrl : undefined;
441
+ this.controlBar?.setStatus('Error', msg, errDownloadUrl ? { downloadUrl: errDownloadUrl } : undefined);
442
+ this.cleanupConnectionOnly();
443
+ throw err;
444
+ }
445
+ }
446
+ /**
447
+ * Stops the active sandboxed worker process via `terminate_app(appId)` while keeping
448
+ * any mounted `JetPackControlBar` visible with `'Stopped'` status.
449
+ */
450
+ async stopApp() {
451
+ if (this.closed) {
452
+ throw new JetPackClientError('CLIENT_CLOSED', 'Cannot stop app after JetPackAppClient.close()');
453
+ }
454
+ if (!this.wasmClient || !this.wasmClient.is_connected() || !this.appId) {
455
+ throw new JetPackClientError('NOT_CONNECTED', 'JetPackAppClient is not connected. Call connectAndEnsureApp() first.');
456
+ }
457
+ const activeAppId = this.appId;
458
+ let result;
459
+ try {
460
+ result = await this.wasmClient.terminate_app(activeAppId);
461
+ }
462
+ catch (err) {
463
+ const msg = err instanceof Error ? err.message : String(err);
464
+ if (msg.includes('JOB_NOT_FOUND') || msg.includes('is not currently running')) {
465
+ result = { terminated: false, id: activeAppId, already_stopped: true };
466
+ }
467
+ else {
468
+ throw err;
469
+ }
470
+ }
471
+ this.workerRunning = false;
472
+ this.lastStopReason = this.lastStopReason ?? 'terminated';
473
+ const pending = Array.from(this.inFlightRequests);
474
+ this.inFlightRequests.clear();
475
+ for (const req of pending) {
476
+ req.reject(new JetPackClientError('NOT_CONNECTED', `Worker '${activeAppId}' was stopped`));
477
+ }
478
+ this.controlBar?.setStatus('Stopped');
479
+ return result;
480
+ }
481
+ /**
482
+ * Sends a correlated zero-copy binary hybrid frame to the ensured worker and resolves
483
+ * with `{ opcode, payload, correlationId }` when the matching reply arrives.
484
+ *
485
+ * Automatically relaunches the worker once via `ensureWorkerRunning()` if it was stopped
486
+ * due to idle timeout or if the daemon returns a no-active-worker `system.error`.
487
+ */
488
+ async request(opcode, ...args) {
489
+ if (this.closed) {
490
+ throw new JetPackClientError('CLIENT_CLOSED', 'Cannot send request after JetPackAppClient.close()');
491
+ }
492
+ if (!this.wasmClient || !this.wasmClient.is_connected() || !this.appId) {
493
+ throw new JetPackClientError('NOT_CONNECTED', 'JetPackAppClient is not connected. Call connectAndEnsureApp() first.');
494
+ }
495
+ const [meta = null, binaryPayload = new Uint8Array(0), options] = args;
496
+ const payload = binaryPayload ?? new Uint8Array(0);
497
+ const totalTimeoutMs = options?.timeoutMs && options.timeoutMs > 0 ? options.timeoutMs : undefined;
498
+ const deadlineMs = totalTimeoutMs !== undefined ? Date.now() + totalTimeoutMs : undefined;
499
+ const getRemainingTimeoutMs = () => {
500
+ if (deadlineMs === undefined)
501
+ return undefined;
502
+ const remaining = deadlineMs - Date.now();
503
+ if (remaining <= 0) {
504
+ throw new JetPackClientError('REQUEST_TIMEOUT', `Worker request '${opcode}' timed out after ${totalTimeoutMs}ms`);
505
+ }
506
+ return remaining;
507
+ };
508
+ const awaitWithRemainingTimeout = async (promise) => {
509
+ const remaining = getRemainingTimeoutMs();
510
+ if (remaining === undefined) {
511
+ return promise;
512
+ }
513
+ let timer = null;
514
+ try {
515
+ return await Promise.race([
516
+ promise,
517
+ new Promise((_, reject) => {
518
+ timer = setTimeout(() => {
519
+ reject(new JetPackClientError('REQUEST_TIMEOUT', `Worker request '${opcode}' timed out after ${totalTimeoutMs}ms`));
520
+ }, remaining);
521
+ }),
522
+ ]);
523
+ }
524
+ finally {
525
+ if (timer !== null)
526
+ clearTimeout(timer);
527
+ }
528
+ };
529
+ const executeSingleAttempt = async () => {
530
+ if (this.closed) {
531
+ throw new JetPackClientError('CLIENT_CLOSED', 'Cannot send request after JetPackAppClient.close()');
532
+ }
533
+ if (!this.wasmClient || !this.wasmClient.is_connected() || !this.appId) {
534
+ throw new JetPackClientError('NOT_CONNECTED', 'JetPackAppClient is not connected. Call connectAndEnsureApp() first.');
535
+ }
536
+ const remaining = getRemainingTimeoutMs();
537
+ const rpcPromise = this.wasmClient.request_worker_frame(this.appId, opcode, (meta ?? null), payload);
538
+ return new Promise((resolve, reject) => {
539
+ let settled = false;
540
+ let timer = null;
541
+ const rejector = {
542
+ reject: (err) => {
543
+ if (settled)
544
+ return;
545
+ settled = true;
546
+ if (timer !== null)
547
+ clearTimeout(timer);
548
+ this.inFlightRequests.delete(rejector);
549
+ reject(err);
550
+ },
551
+ };
552
+ this.inFlightRequests.add(rejector);
553
+ if (remaining !== undefined) {
554
+ timer = setTimeout(() => {
555
+ rejector.reject(new JetPackClientError('REQUEST_TIMEOUT', `Worker request '${opcode}' timed out after ${totalTimeoutMs}ms`));
556
+ }, remaining);
557
+ }
558
+ rpcPromise.then((res) => {
559
+ if (settled)
560
+ return;
561
+ settled = true;
562
+ if (timer !== null)
563
+ clearTimeout(timer);
564
+ this.inFlightRequests.delete(rejector);
565
+ resolve(res);
566
+ }, (err) => {
567
+ if (settled)
568
+ return;
569
+ settled = true;
570
+ if (timer !== null)
571
+ clearTimeout(timer);
572
+ this.inFlightRequests.delete(rejector);
573
+ reject(err instanceof Error ? err : new Error(String(err)));
574
+ });
575
+ });
576
+ };
577
+ if (!this.workerRunning) {
578
+ await awaitWithRemainingTimeout(this.ensureWorkerRunning());
579
+ }
580
+ try {
581
+ return await executeSingleAttempt();
582
+ }
583
+ catch (err) {
584
+ if (!this.closed &&
585
+ this.wasmClient?.is_connected() &&
586
+ this.appId !== null &&
587
+ isNoActiveWorkerError(err)) {
588
+ this.workerRunning = false;
589
+ await awaitWithRemainingTimeout(this.ensureWorkerRunning());
590
+ return await executeSingleAttempt();
591
+ }
592
+ throw err;
593
+ }
594
+ }
595
+ /**
596
+ * Registers a listener for streaming or unsolicited worker frames matching `opcode`
597
+ * (or `'*'` to subscribe to all stream frames). Returns an idempotent unsubscribe closure.
598
+ */
599
+ onStream(opcode, callback) {
600
+ const key = opcode;
601
+ const listener = callback;
602
+ let bucket = this.streamListeners.get(key);
603
+ if (!bucket) {
604
+ bucket = new Set();
605
+ this.streamListeners.set(key, bucket);
606
+ }
607
+ bucket.add(listener);
608
+ return () => {
609
+ const existing = this.streamListeners.get(key);
610
+ if (!existing)
611
+ return;
612
+ existing.delete(listener);
613
+ if (existing.size === 0) {
614
+ this.streamListeners.delete(key);
615
+ }
616
+ };
617
+ }
618
+ /**
619
+ * Subscribes to live sanitized daemon & worker log entries (`logs.entry`) when
620
+ * Developer Mode is enabled on the local daemon.
621
+ */
622
+ async subscribeLogs(onEntry) {
623
+ if (this.closed) {
624
+ throw new JetPackClientError('CLIENT_CLOSED', 'Cannot subscribe to logs after JetPackAppClient.close()');
625
+ }
626
+ if (!this.wasmClient || !this.wasmClient.is_connected()) {
627
+ throw new JetPackClientError('NOT_CONNECTED', 'JetPackAppClient is not connected. Call connectAndEnsureApp() first.');
628
+ }
629
+ if (typeof this.wasmClient.subscribe_logs !== 'function') {
630
+ throw new JetPackClientError('INVALID_OPTIONS', 'Underlying WASM client does not expose subscribe_logs()');
631
+ }
632
+ return this.wasmClient.subscribe_logs(onEntry);
633
+ }
634
+ /**
635
+ * Unsubscribes from live log streaming (`logs.unsubscribe`). Safe to call repeatedly.
636
+ */
637
+ async unsubscribeLogs() {
638
+ if (!this.wasmClient || !this.wasmClient.is_connected()) {
639
+ return;
640
+ }
641
+ if (typeof this.wasmClient.unsubscribe_logs === 'function') {
642
+ await this.wasmClient.unsubscribe_logs();
643
+ }
644
+ }
645
+ /**
646
+ * Closes the WebSocket session, rejects any in-flight `request()` calls,
647
+ * clears all registered `onStream()` listeners, unsubscribes from live logs,
648
+ * and transitions any mounted `JetPackControlBar` to `'Stopped'`.
649
+ */
650
+ close() {
651
+ this.closed = true;
652
+ this.streamListeners.clear();
653
+ this.workerStoppedListeners.clear();
654
+ this.workerStartedListeners.clear();
655
+ const pending = Array.from(this.inFlightRequests);
656
+ this.inFlightRequests.clear();
657
+ for (const req of pending) {
658
+ req.reject(new JetPackClientError('CLIENT_CLOSED', 'JetPackAppClient was closed'));
659
+ }
660
+ this.cleanupConnectionOnly();
661
+ this.logTerminal?.setDeveloperMode(false);
662
+ this.controlBar?.setStatus('Stopped');
663
+ }
664
+ /**
665
+ * Closes the WebSocket session and unmounts any auto-mounted `JetPackControlBar`
666
+ * and `JetPackLogTerminal`.
667
+ */
668
+ destroy() {
669
+ this.close();
670
+ if (this.controlBar) {
671
+ this.controlBar.unmount();
672
+ this.controlBar = null;
673
+ }
674
+ if (this.logTerminal) {
675
+ this.logTerminal.unmount();
676
+ this.logTerminal = null;
677
+ }
678
+ }
679
+ async syncLogTerminalForSession(client, resolvedAppName, logTerminalOpt) {
680
+ if (logTerminalOpt === false || typeof document === 'undefined') {
681
+ if (this.logTerminal) {
682
+ this.logTerminal.unmount();
683
+ this.logTerminal = null;
684
+ }
685
+ return;
686
+ }
687
+ let devMode = false;
688
+ if (typeof client.get_settings === 'function') {
689
+ try {
690
+ const settings = await client.get_settings();
691
+ devMode = Boolean(settings?.developer_mode);
692
+ }
693
+ catch {
694
+ devMode = false;
695
+ }
696
+ }
697
+ else if (typeof logTerminalOpt === 'object' && logTerminalOpt !== null) {
698
+ devMode = Boolean(logTerminalOpt.developerMode);
699
+ }
700
+ if (!devMode) {
701
+ if (this.logTerminal) {
702
+ this.logTerminal.setDeveloperMode(false);
703
+ this.logTerminal.unmount();
704
+ this.logTerminal = null;
705
+ }
706
+ return;
707
+ }
708
+ const customOpts = typeof logTerminalOpt === 'object' && logTerminalOpt !== null ? logTerminalOpt : {};
709
+ const mergedOpts = {
710
+ title: `${resolvedAppName} · Live Logs`,
711
+ ...customOpts,
712
+ developerMode: true,
713
+ };
714
+ if (!this.logTerminal) {
715
+ this.logTerminal = new JetPackLogTerminal(mergedOpts);
716
+ }
717
+ else {
718
+ this.logTerminal.updateOptions(mergedOpts);
719
+ if (mergedOpts.mountTarget !== null) {
720
+ this.logTerminal.mount(mergedOpts.mountTarget);
721
+ }
722
+ }
723
+ if (typeof client.subscribe_logs === 'function') {
724
+ try {
725
+ await client.subscribe_logs((entry) => {
726
+ this.logTerminal?.appendEntry(entry);
727
+ });
728
+ }
729
+ catch {
730
+ this.logTerminal.setDeveloperMode(false);
731
+ }
732
+ }
733
+ }
734
+ cleanupConnectionOnly() {
735
+ this.workerRunning = false;
736
+ this.lastStopReason = null;
737
+ this.ensureWorkerPromise = null;
738
+ this.lastProgressCallback = null;
739
+ this.resetVolumesOnRelaunch = false;
740
+ if (this.wasmClient) {
741
+ if (typeof this.wasmClient.unsubscribe_logs === 'function' && this.wasmClient.is_connected()) {
742
+ try {
743
+ void this.wasmClient.unsubscribe_logs().catch(() => { });
744
+ }
745
+ catch {
746
+ // ignore unsubscribe errors on teardown
747
+ }
748
+ }
749
+ try {
750
+ this.wasmClient.close();
751
+ }
752
+ catch {
753
+ // ignore close errors
754
+ }
755
+ this.wasmClient = null;
756
+ }
757
+ this.appId = null;
758
+ }
759
+ handleWorkerStopped(event) {
760
+ if (this.closed || !this.appId || event.app_id !== this.appId) {
761
+ return;
762
+ }
763
+ this.workerRunning = false;
764
+ this.lastStopReason = event.reason;
765
+ this.controlBar?.setStatus('Stopped', formatStopDetail(event.reason));
766
+ if (event.reason === 'terminated' || event.reason === 'process_exited') {
767
+ const pending = Array.from(this.inFlightRequests);
768
+ this.inFlightRequests.clear();
769
+ const errMessage = event.reason === 'process_exited'
770
+ ? `Worker '${this.appId}' exited unexpectedly`
771
+ : `Worker '${this.appId}' was stopped`;
772
+ for (const req of pending) {
773
+ req.reject(new JetPackClientError('NOT_CONNECTED', errMessage));
774
+ }
775
+ }
776
+ for (const cb of Array.from(this.workerStoppedListeners)) {
777
+ cb(event);
778
+ }
779
+ }
780
+ dispatchStreamFrame(opcode, payload, correlationId) {
781
+ const context = { opcode, correlationId };
782
+ const exactListeners = this.streamListeners.get(opcode);
783
+ if (exactListeners) {
784
+ for (const cb of Array.from(exactListeners)) {
785
+ cb(payload, context);
786
+ }
787
+ }
788
+ const wildcardListeners = this.streamListeners.get('*');
789
+ if (wildcardListeners) {
790
+ for (const cb of Array.from(wildcardListeners)) {
791
+ cb(payload, context);
792
+ }
793
+ }
794
+ }
795
+ async loadWasmBindings(options) {
796
+ if (options.wasmModule) {
797
+ return options.wasmModule;
798
+ }
799
+ if (options.wasmModulePath) {
800
+ const modulePath = options.wasmModulePath;
801
+ try {
802
+ const mod = (await import(/* @vite-ignore */ modulePath));
803
+ if (!mod || !mod.WasmClientIdentity || !mod.JetPackWasmClient) {
804
+ throw new Error('Loaded module does not export WasmClientIdentity and JetPackWasmClient');
805
+ }
806
+ return mod;
807
+ }
808
+ catch (err) {
809
+ const msg = err instanceof Error ? err.message : String(err);
810
+ throw new JetPackClientError('WASM_LOAD_FAILED', `Failed to load jetpack-wasm bindings from '${modulePath}': ${msg}`);
811
+ }
812
+ }
813
+ try {
814
+ const mod = (await import('../wasm/jetpack_wasm.js'));
815
+ if (!mod || !mod.WasmClientIdentity || !mod.JetPackWasmClient) {
816
+ throw new Error('Loaded module does not export WasmClientIdentity and JetPackWasmClient');
817
+ }
818
+ return mod;
819
+ }
820
+ catch (err) {
821
+ const msg = err instanceof Error ? err.message : String(err);
822
+ throw new JetPackClientError('WASM_LOAD_FAILED', `Failed to load bundled jetpack-wasm bindings: ${msg}`);
823
+ }
824
+ }
825
+ async connectWithAutoPair(params) {
826
+ if (!params.skipInitialConnect) {
827
+ try {
828
+ return await params.wasm.JetPackWasmClient.connect(params.wsUrl, params.identity, params.origin);
829
+ }
830
+ catch (initialErr) {
831
+ if (!params.autoPair || this.closed) {
832
+ throw initialErr instanceof Error ? initialErr : new Error(String(initialErr));
833
+ }
834
+ }
835
+ }
836
+ const pairingUri = params.identity.generate_pairing_uri(params.origin);
837
+ this.lastPairingUri = pairingUri;
838
+ params.onPairingUri?.(pairingUri);
839
+ if (!params.disableAutoDeepLink) {
840
+ triggerBrowserDeepLink(pairingUri);
841
+ }
842
+ const deadline = Date.now() + params.timeoutMs;
843
+ let lastError = null;
844
+ while (Date.now() < deadline) {
845
+ if (this.closed) {
846
+ throw new JetPackClientError('CLIENT_CLOSED', 'JetPackAppClient closed during pairing');
847
+ }
848
+ const remaining = deadline - Date.now();
849
+ await delay(Math.min(params.pollIntervalMs, Math.max(1, remaining)));
850
+ if (this.closed) {
851
+ throw new JetPackClientError('CLIENT_CLOSED', 'JetPackAppClient closed during pairing');
852
+ }
853
+ try {
854
+ return await params.wasm.JetPackWasmClient.connect(params.wsUrl, params.identity, params.origin);
855
+ }
856
+ catch (err) {
857
+ lastError = err;
858
+ }
859
+ }
860
+ const detail = lastError instanceof Error ? lastError.message : String(lastError ?? 'No approval');
861
+ throw new JetPackClientError('PAIRING_TIMEOUT', `Timed out waiting for jetpack://pair approval after ${params.timeoutMs}ms (${detail})`);
862
+ }
863
+ }
864
+ //# sourceMappingURL=client.js.map