@player-devtools/client-flipper 0.14.3--canary.24.1132 → 0.15.1--canary.29.1254

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/src/transport.ts CHANGED
@@ -3,9 +3,7 @@ import {
3
3
  FlipperServerState,
4
4
  type FlipperServer,
5
5
  } from "flipper-server-client";
6
- import type { InstalledPluginDetails } from "flipper-common";
7
6
  import { spawn } from "child_process";
8
- import open from "open";
9
7
  import * as net from "net";
10
8
  import * as fs from "fs";
11
9
  import * as os from "os";
@@ -30,7 +28,6 @@ type MessageCallback = (
30
28
  ) => void;
31
29
 
32
30
  const PLUGIN_API = "player-ui-devtools";
33
- const PLUGIN_NPM_NAME = "flipper-plugin-player-ui-devtools";
34
31
 
35
32
  /**
36
33
  * All diagnostics go to stderr.
@@ -54,12 +51,6 @@ type FlipperExecuteMessage = {
54
51
  };
55
52
  };
56
53
 
57
- /** Wire shape of the `init`/`deinit` plugin-activation handshake (`js-flipper`'s `FlipperClient.onMessageReceived`) */
58
- type FlipperPluginLifecycleMessage = {
59
- method: "init" | "deinit";
60
- params: { plugin: string };
61
- };
62
-
63
54
  /**
64
55
  * Flipper headless transport
65
56
  *
@@ -155,6 +146,14 @@ class FlipperRefcount {
155
146
  }
156
147
  }
157
148
 
149
+ /**
150
+ * Read the current refcount state without mutating it. Still goes through
151
+ * `withLock` so a concurrent acquire/release can't be observed mid-write.
152
+ */
153
+ peek(): RefcountFile | null {
154
+ return this.withLock(() => this.read());
155
+ }
156
+
158
157
  private write(state: RefcountFile): void {
159
158
  fs.writeFileSync(this.file, JSON.stringify(state));
160
159
  }
@@ -227,12 +226,15 @@ export class FlipperServerTransport implements Transport {
227
226
  */
228
227
  private activeClientIds = new Set<string>();
229
228
 
229
+ /** Resolved connection target, set at the top of `connect()`. */
230
+ private host = "localhost";
231
+ private port = 52342;
232
+
230
233
  /**
231
- * Client IDs currently connected to flipper-server, regardless of whether
232
- * the devtools plugin has been activated for them. Used by `enablePlugin`'s
233
- * "all connected clients" convenience.
234
+ * Whether this instance started the shared daemon (vs. attaching to one
235
+ * another instance started). Only an owner may consider restarting it.
234
236
  */
235
- private connectedClientIds = new Set<string>();
237
+ private owns = false;
236
238
 
237
239
  constructor(
238
240
  private options: {
@@ -240,47 +242,22 @@ export class FlipperServerTransport implements Transport {
240
242
  host?: string;
241
243
  /** Flipper server WebSocket port; defaults to 52342 */
242
244
  port?: number;
243
- /**
244
- * Whether to open a browser/PWA UI once the server is up. Defaults to
245
- * `false` — an agent driving this transport has no use for a browser
246
- * tab, unlike a human running `flipper-server` directly.
247
- */
248
- open?: boolean;
249
- /**
250
- * URL to open in the browser when `open` is true. Defaults to
251
- * `http://localhost:{port}`. `flipper-server` itself always binds to
252
- * localhost regardless of this value — this only controls what URL
253
- * gets opened, so a custom host (e.g. a branded domain) must already
254
- * resolve to this machine (e.g. via `/etc/hosts`) for it to work.
255
- */
256
- url?: string;
257
- /**
258
- * Activate the devtools plugin automatically for every client that
259
- * connects, instead of requiring an explicit `enablePlugin()` call per
260
- * client. Off by default so a caller can choose when/whether to
261
- * activate a given device; turn this on for a fully hands-off session
262
- * where every connecting device should be watched immediately.
263
- */
264
- autoEnablePlugin?: boolean;
265
245
  } = {},
266
246
  ) {}
267
247
 
268
248
  async connect(): Promise<void> {
269
- const host = this.options.host ?? "localhost";
270
- const port = this.options.port ?? 52342;
249
+ const host = (this.host = this.options.host ?? "localhost");
250
+ const port = (this.port = this.options.port ?? 52342);
271
251
 
272
252
  // Register interest in the shared daemon. The first instance to do so is
273
253
  // told to start it; the rest just attach. The daemon outlives any single
274
254
  // MCP process and is only torn down when the last instance detaches.
275
255
  const { shouldStart, commit } = this.refcount.acquire();
256
+ this.owns = shouldStart;
276
257
 
277
258
  if (shouldStart) {
278
259
  log("[FlipperServerTransport] Starting flipper-server...");
279
260
  const serverScript = require.resolve("flipper-server/server.js");
280
- // We always pass --open=false and drive any browser-open ourselves
281
- // (below) so we control both whether it happens and what URL is used —
282
- // flipper-server's own --open only ever opens http://localhost:{port}.
283
- //
284
261
  // Detached + unref'd: the daemon must survive this process exiting so
285
262
  // other instances keep their connections. We never kill it directly —
286
263
  // shutdown is driven by the refcount in close().
@@ -288,7 +265,7 @@ export class FlipperServerTransport implements Transport {
288
265
  // The daemon must never inherit our fd 1: it outlives this process and
289
266
  // would write into a later session's JSON-RPC stream. Its stderr stays
290
267
  // inherited so daemon diagnostics remain visible.
291
- const child = spawn(process.execPath, [serverScript, "--open=false"], {
268
+ const child = spawn(process.execPath, [serverScript, "--open=true"], {
292
269
  stdio: ["ignore", "ignore", "inherit"],
293
270
  detached: true,
294
271
  });
@@ -299,7 +276,20 @@ export class FlipperServerTransport implements Transport {
299
276
  );
300
277
  });
301
278
  child.unref();
302
- await waitForPort(host, port);
279
+ try {
280
+ await waitForPort(host, port);
281
+ } catch (err) {
282
+ // Nothing has recorded this PID in the refcount file yet, so nobody
283
+ // else can track or kill it — if we leave it running here it becomes
284
+ // an orphan daemon that a later connect() would compete with on the
285
+ // same port instead of detecting. Wait for it to actually exit (via
286
+ // the same bounded kill-and-confirm mechanism used everywhere else in
287
+ // this file) before rethrowing, so a caller that retries connect()
288
+ // right away doesn't spawn a second daemon racing this one for the
289
+ // port during teardown.
290
+ await this.killAndWait(child.pid!);
291
+ throw err;
292
+ }
303
293
  commit(child.pid!);
304
294
  log("[FlipperServerTransport] flipper-server ready.");
305
295
  } else {
@@ -309,16 +299,6 @@ export class FlipperServerTransport implements Transport {
309
299
  log("[FlipperServerTransport] Attached to flipper-server.");
310
300
  }
311
301
 
312
- if (this.options.open) {
313
- const url = this.options.url ?? `http://localhost:${port}`;
314
- log(`[FlipperServerTransport] Opening ${url}`);
315
- try {
316
- await open(url);
317
- } catch (err) {
318
- console.warn("[FlipperServerTransport] Failed to open UI:", err);
319
- }
320
- }
321
-
322
302
  // Read the auth token the flipper-server wrote during startup
323
303
  const { getAuthToken } =
324
304
  // eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -349,20 +329,10 @@ export class FlipperServerTransport implements Transport {
349
329
  // Track client connects/disconnects
350
330
  this.server.on("client-connected", (info) => {
351
331
  log("[FlipperServerTransport] client-connected:", JSON.stringify(info));
352
- this.connectedClientIds.add(info.id);
353
- if (this.options.autoEnablePlugin) {
354
- this.enablePlugin(info.id).catch((err) => {
355
- console.warn(
356
- `[FlipperServerTransport] Failed to auto-enable plugin for client ${info.id}:`,
357
- err,
358
- );
359
- });
360
- }
361
332
  });
362
333
  this.server.on("client-disconnected", ({ id }) => {
363
334
  log("[FlipperServerTransport] client-disconnected:", id);
364
335
  this.activeClientIds.delete(id);
365
- this.connectedClientIds.delete(id);
366
336
  });
367
337
 
368
338
  // Route inbound device messages to our Messenger listeners
@@ -426,91 +396,6 @@ export class FlipperServerTransport implements Transport {
426
396
  );
427
397
  };
428
398
 
429
- /**
430
- * Ensures `flipper-plugin-player-ui-devtools` is installed on the attached
431
- * flipper-server, installing the published npm package if it's missing.
432
- *
433
- * This is Flipper's own documented plugin-install RPC (the same
434
- * `exec(...)` commands the desktop UI's "Install Plugin" button calls) —
435
- * not a filesystem workaround. It's opt-in: callers that manage plugin
436
- * installation themselves (or run against a flipper-server that already
437
- * has it) can skip calling this.
438
- */
439
- async ensurePluginInstalled(): Promise<InstalledPluginDetails> {
440
- if (!this.server) {
441
- throw new Error("FlipperServerTransport is not connected");
442
- }
443
-
444
- const installed = await this.server.exec("plugins-get-installed-plugins");
445
- const existing = installed.find((p) => p.name === PLUGIN_NPM_NAME);
446
- if (existing) {
447
- log(
448
- `[FlipperServerTransport] ${PLUGIN_NPM_NAME}@${existing.version} already installed.`,
449
- );
450
- return existing;
451
- }
452
-
453
- log(`[FlipperServerTransport] Installing ${PLUGIN_NPM_NAME} from npm...`);
454
- const details = await this.server.exec(
455
- "plugins-install-from-npm",
456
- PLUGIN_NPM_NAME,
457
- );
458
- log(
459
- `[FlipperServerTransport] Installed ${PLUGIN_NPM_NAME}@${details.version}.`,
460
- );
461
- return details;
462
- }
463
-
464
- /**
465
- * Activates the devtools plugin for a connected client by sending the
466
- * `init` handshake `js-flipper`'s device SDK requires before it will open
467
- * a live plugin connection (`onConnect`/`FlipperConnection`) and start
468
- * relaying `client-message`s for our api. Nothing in flipper-server itself
469
- * sends this automatically for a non-background plugin like ours unless a
470
- * full Flipper desktop app is attached and its tab is selected — this
471
- * method lets a caller trigger the same handshake directly, without
472
- * needing a desktop UI at all.
473
- *
474
- * Pass a specific `clientId`, or omit it to enable for every client
475
- * currently connected to flipper-server.
476
- */
477
- async enablePlugin(clientId?: string): Promise<void> {
478
- await this.sendLifecycleMessage("init", clientId);
479
- }
480
-
481
- /** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */
482
- async disablePlugin(clientId?: string): Promise<void> {
483
- await this.sendLifecycleMessage("deinit", clientId);
484
- }
485
-
486
- private async sendLifecycleMessage(
487
- method: "init" | "deinit",
488
- clientId?: string,
489
- ): Promise<void> {
490
- if (!this.server) {
491
- throw new Error("FlipperServerTransport is not connected");
492
- }
493
-
494
- const targets = clientId ? [clientId] : [...this.connectedClientIds];
495
- const payload: FlipperPluginLifecycleMessage = {
496
- method,
497
- params: { plugin: PLUGIN_API },
498
- };
499
-
500
- await Promise.all(
501
- targets.map((id) =>
502
- this.server!.exec("client-request-response", id, payload).catch(
503
- (err) => {
504
- console.warn(
505
- `[FlipperServerTransport] Failed to ${method} plugin for client ${id}:`,
506
- err,
507
- );
508
- },
509
- ),
510
- ),
511
- );
512
- }
513
-
514
399
  addListener: CommunicationLayerMethods["addListener"] = (callback) => {
515
400
  this.listeners.add(callback);
516
401
  };
@@ -519,10 +404,26 @@ export class FlipperServerTransport implements Transport {
519
404
  this.listeners.delete(callback);
520
405
  };
521
406
 
407
+ /**
408
+ * In-flight `close()` promise, if one is currently running on this
409
+ * instance. Guards `refcount.release()` and `killAndWait()` against being
410
+ * invoked twice for a single logical close — e.g. `restart()`'s internal
411
+ * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
412
+ */
413
+ private closing: Promise<void> | null = null;
414
+
522
415
  async close(): Promise<void> {
416
+ if (this.closing) return this.closing;
417
+
418
+ this.closing = this.doClose().finally(() => {
419
+ this.closing = null;
420
+ });
421
+ return this.closing;
422
+ }
423
+
424
+ private async doClose(): Promise<void> {
523
425
  this.listeners.clear();
524
426
  this.activeClientIds.clear();
525
- this.connectedClientIds.clear();
526
427
  this.server?.close();
527
428
  this.server = null;
528
429
 
@@ -531,12 +432,158 @@ export class FlipperServerTransport implements Transport {
531
432
  // running for the remaining instances.
532
433
  const pidToKill = this.refcount.release();
533
434
  if (pidToKill !== null) {
435
+ await this.killAndWait(pidToKill);
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Send SIGTERM and wait for the process to actually exit (or a bounded
441
+ * timeout) before resolving, so callers — notably `restart()` — can rely on
442
+ * the port being free once `close()` returns instead of racing a new child
443
+ * for it.
444
+ */
445
+ private killAndWait(pid: number, timeoutMs = 5_000): Promise<void> {
446
+ return new Promise((resolve) => {
534
447
  try {
535
- process.kill(pidToKill);
536
- log("[FlipperServerTransport] Shut down flipper-server.");
448
+ process.kill(pid);
537
449
  } catch {
538
- /* already gone */
450
+ // Already gone.
451
+ resolve();
452
+ return;
539
453
  }
454
+
455
+ const deadline = Date.now() + timeoutMs;
456
+ const poll = () => {
457
+ if (!this.isPidAlive(pid)) {
458
+ log("[FlipperServerTransport] Shut down flipper-server.");
459
+ resolve();
460
+ return;
461
+ }
462
+ if (Date.now() >= deadline) {
463
+ log(
464
+ "[FlipperServerTransport] Timed out waiting for flipper-server to exit.",
465
+ );
466
+ resolve();
467
+ return;
468
+ }
469
+ setTimeout(poll, 100);
470
+ };
471
+ poll();
472
+ });
473
+ }
474
+
475
+ private isPidAlive(pid: number): boolean {
476
+ try {
477
+ process.kill(pid, 0);
478
+ return true;
479
+ } catch {
480
+ return false;
481
+ }
482
+ }
483
+
484
+ /** Read-only snapshot of this transport's connection to the shared daemon. */
485
+ getDiagnostics(): {
486
+ connected: boolean;
487
+ host: string;
488
+ port: number;
489
+ owns: boolean;
490
+ refs: number | null;
491
+ activeClientIds: string[];
492
+ } {
493
+ const state = this.refcount.peek();
494
+ return {
495
+ connected: this.server !== null,
496
+ host: this.host,
497
+ port: this.port,
498
+ owns: this.owns,
499
+ refs: state?.refs ?? null,
500
+ activeClientIds: [...this.activeClientIds],
501
+ };
502
+ }
503
+
504
+ /**
505
+ * Restart the shared daemon. Only ever acts when this instance both owns
506
+ * the daemon (started it) and is its sole remaining consumer — otherwise
507
+ * this soft-errors without touching the daemon, since killing it out from
508
+ * under other attached instances would break their connections.
509
+ */
510
+ async restart(): Promise<
511
+ { ok: true; host: string; port: number } | { ok: false; reason: string }
512
+ > {
513
+ if (!this.owns) {
514
+ return {
515
+ ok: false,
516
+ reason: "this instance does not own the flipper-server daemon",
517
+ };
518
+ }
519
+
520
+ const state = this.refcount.peek();
521
+ if (state?.refs !== 1) {
522
+ return {
523
+ ok: false,
524
+ reason: "other consumers are attached to this daemon",
525
+ };
526
+ }
527
+
528
+ // Re-verify immediately before the destructive close(): another instance
529
+ // could have called connect()/acquire() between the check above and here,
530
+ // bumping refs to 2+. This narrows but does not eliminate the race — a
531
+ // consumer could still slip in between this re-check and close() itself;
532
+ // a fully atomic fix would need close()+connect() to run inside
533
+ // refcount.withLock(), which isn't reentrant-safe with connect()'s own
534
+ // internal use of the lock, so we accept this narrow residual window.
535
+ const recheck = this.refcount.peek();
536
+ if (recheck?.refs !== 1) {
537
+ return {
538
+ ok: false,
539
+ reason: "other consumers attached to this daemon just before restart",
540
+ };
541
+ }
542
+
543
+ try {
544
+ await this.close();
545
+ await this.connect();
546
+ } catch (err) {
547
+ // The daemon this instance owned/attempted to own is now in an unknown
548
+ // or dead state — don't leave `owns` set, or a later restart() call
549
+ // will misreport "other consumers are attached" against a stale
550
+ // refcount for a daemon that no longer exists.
551
+ this.owns = false;
552
+ return {
553
+ ok: false,
554
+ reason: err instanceof Error ? err.message : String(err),
555
+ };
556
+ }
557
+ return { ok: true, host: this.host, port: this.port };
558
+ }
559
+
560
+ /** Whether the devtools Flipper plugin is installed, per the live daemon. */
561
+ async getPluginInstallStatus(): Promise<{
562
+ installed: boolean;
563
+ version?: string;
564
+ reason?: string;
565
+ }> {
566
+ if (!this.server) return { installed: false, reason: "not connected" };
567
+
568
+ try {
569
+ const plugins = (await this.server.exec(
570
+ "plugins-get-installed-plugins",
571
+ )) as Array<{ id?: string; name?: string; version?: string }>;
572
+
573
+ const plugin = plugins.find(
574
+ (candidate) =>
575
+ candidate.id === PLUGIN_API || candidate.name === PLUGIN_API,
576
+ );
577
+
578
+ if (!plugin) return { installed: false };
579
+ return plugin.version
580
+ ? { installed: true, version: plugin.version }
581
+ : { installed: true };
582
+ } catch (err) {
583
+ return {
584
+ installed: false,
585
+ reason: err instanceof Error ? err.message : String(err),
586
+ };
540
587
  }
541
588
  }
542
589
  }
@@ -1,4 +1,3 @@
1
- import type { InstalledPluginDetails } from "flipper-common";
2
1
  import type { CommunicationLayerMethods, Transport } from "@player-devtools/types";
3
2
  export declare class FlipperServerTransport implements Transport {
4
3
  private options;
@@ -10,72 +9,69 @@ export declare class FlipperServerTransport implements Transport {
10
9
  * plugin — these are the clients we send outbound messages to.
11
10
  */
12
11
  private activeClientIds;
12
+ /** Resolved connection target, set at the top of `connect()`. */
13
+ private host;
14
+ private port;
13
15
  /**
14
- * Client IDs currently connected to flipper-server, regardless of whether
15
- * the devtools plugin has been activated for them. Used by `enablePlugin`'s
16
- * "all connected clients" convenience.
16
+ * Whether this instance started the shared daemon (vs. attaching to one
17
+ * another instance started). Only an owner may consider restarting it.
17
18
  */
18
- private connectedClientIds;
19
+ private owns;
19
20
  constructor(options?: {
20
21
  /** Flipper server host; defaults to "localhost" */
21
22
  host?: string;
22
23
  /** Flipper server WebSocket port; defaults to 52342 */
23
24
  port?: number;
24
- /**
25
- * Whether to open a browser/PWA UI once the server is up. Defaults to
26
- * `false` — an agent driving this transport has no use for a browser
27
- * tab, unlike a human running `flipper-server` directly.
28
- */
29
- open?: boolean;
30
- /**
31
- * URL to open in the browser when `open` is true. Defaults to
32
- * `http://localhost:{port}`. `flipper-server` itself always binds to
33
- * localhost regardless of this value — this only controls what URL
34
- * gets opened, so a custom host (e.g. a branded domain) must already
35
- * resolve to this machine (e.g. via `/etc/hosts`) for it to work.
36
- */
37
- url?: string;
38
- /**
39
- * Activate the devtools plugin automatically for every client that
40
- * connects, instead of requiring an explicit `enablePlugin()` call per
41
- * client. Off by default so a caller can choose when/whether to
42
- * activate a given device; turn this on for a fully hands-off session
43
- * where every connecting device should be watched immediately.
44
- */
45
- autoEnablePlugin?: boolean;
46
25
  });
47
26
  connect(): Promise<void>;
48
27
  sendMessage: CommunicationLayerMethods["sendMessage"];
28
+ addListener: CommunicationLayerMethods["addListener"];
29
+ removeListener: CommunicationLayerMethods["removeListener"];
49
30
  /**
50
- * Ensures `flipper-plugin-player-ui-devtools` is installed on the attached
51
- * flipper-server, installing the published npm package if it's missing.
52
- *
53
- * This is Flipper's own documented plugin-install RPC (the same
54
- * `exec(...)` commands the desktop UI's "Install Plugin" button calls) —
55
- * not a filesystem workaround. It's opt-in: callers that manage plugin
56
- * installation themselves (or run against a flipper-server that already
57
- * has it) can skip calling this.
31
+ * In-flight `close()` promise, if one is currently running on this
32
+ * instance. Guards `refcount.release()` and `killAndWait()` against being
33
+ * invoked twice for a single logical close — e.g. `restart()`'s internal
34
+ * `close()` racing an external `MCPServer.stop()` -> `transport.close()`.
58
35
  */
59
- ensurePluginInstalled(): Promise<InstalledPluginDetails>;
36
+ private closing;
37
+ close(): Promise<void>;
38
+ private doClose;
60
39
  /**
61
- * Activates the devtools plugin for a connected client by sending the
62
- * `init` handshake `js-flipper`'s device SDK requires before it will open
63
- * a live plugin connection (`onConnect`/`FlipperConnection`) and start
64
- * relaying `client-message`s for our api. Nothing in flipper-server itself
65
- * sends this automatically for a non-background plugin like ours unless a
66
- * full Flipper desktop app is attached and its tab is selected — this
67
- * method lets a caller trigger the same handshake directly, without
68
- * needing a desktop UI at all.
69
- *
70
- * Pass a specific `clientId`, or omit it to enable for every client
71
- * currently connected to flipper-server.
40
+ * Send SIGTERM and wait for the process to actually exit (or a bounded
41
+ * timeout) before resolving, so callers — notably `restart()` — can rely on
42
+ * the port being free once `close()` returns instead of racing a new child
43
+ * for it.
72
44
  */
73
- enablePlugin(clientId?: string): Promise<void>;
74
- /** Symmetric counterpart to `enablePlugin` — releases the plugin connection without disconnecting the client from flipper-server. */
75
- disablePlugin(clientId?: string): Promise<void>;
76
- private sendLifecycleMessage;
77
- addListener: CommunicationLayerMethods["addListener"];
78
- removeListener: CommunicationLayerMethods["removeListener"];
79
- close(): Promise<void>;
45
+ private killAndWait;
46
+ private isPidAlive;
47
+ /** Read-only snapshot of this transport's connection to the shared daemon. */
48
+ getDiagnostics(): {
49
+ connected: boolean;
50
+ host: string;
51
+ port: number;
52
+ owns: boolean;
53
+ refs: number | null;
54
+ activeClientIds: string[];
55
+ };
56
+ /**
57
+ * Restart the shared daemon. Only ever acts when this instance both owns
58
+ * the daemon (started it) and is its sole remaining consumer — otherwise
59
+ * this soft-errors without touching the daemon, since killing it out from
60
+ * under other attached instances would break their connections.
61
+ */
62
+ restart(): Promise<{
63
+ ok: true;
64
+ host: string;
65
+ port: number;
66
+ } | {
67
+ ok: false;
68
+ reason: string;
69
+ }>;
70
+ /** Whether the devtools Flipper plugin is installed, per the live daemon. */
71
+ getPluginInstallStatus(): Promise<{
72
+ installed: boolean;
73
+ version?: string;
74
+ reason?: string;
75
+ }>;
80
76
  }
81
77
  //# sourceMappingURL=transport.d.ts.map