@rezkam/browser-tools 0.3.0 → 1.0.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.
@@ -0,0 +1,27 @@
1
+ ObjC.import('AppKit');
2
+
3
+ function run(argv) {
4
+ const applicationURL = $.NSURL.fileURLWithPath($(argv[0]));
5
+ const options = Number($.NSWorkspaceLaunchWithoutAddingToRecents)
6
+ | Number($.NSWorkspaceLaunchWithoutActivation)
7
+ | Number($.NSWorkspaceLaunchNewInstance)
8
+ | Number($.NSWorkspaceLaunchAndHide);
9
+ const configuration = $.NSMutableDictionary.dictionary;
10
+ configuration.setObjectForKey($(argv.slice(1)), $.NSWorkspaceLaunchConfigurationArguments);
11
+ configuration.setObjectForKey(
12
+ $.NSProcessInfo.processInfo.environment,
13
+ $.NSWorkspaceLaunchConfigurationEnvironment,
14
+ );
15
+ const error = Ref();
16
+ const launched = $.NSWorkspace.sharedWorkspace.launchApplicationAtURLOptionsConfigurationError(
17
+ applicationURL,
18
+ options,
19
+ configuration,
20
+ error,
21
+ );
22
+ if (!launched || launched.isNil()) {
23
+ const detail = error[0] ? error[0].localizedDescription.js : 'unknown error';
24
+ throw new Error(`NSWorkspace launch failed: ${detail}`);
25
+ }
26
+ return Number(launched.processIdentifier);
27
+ }
package/scripts/start.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
  * BROWSER_TOOLS_OWNER_TOKEN="<owner token>" scripts/start.mjs
14
14
  */
15
15
 
16
- import { hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome } from './browser-control.mjs';
16
+ import { CLI_OWNER_ID, hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome } from './browser-control.mjs';
17
17
 
18
18
  const args = process.argv.slice(2);
19
19
  const profileName = requiredOptionValue(args, '--profile', null);
@@ -24,7 +24,7 @@ const includeGoogle = hasFlag(args, '--include-google');
24
24
  const explicitPort = args.includes('--port');
25
25
  const port = parsePort(args);
26
26
  const ownerToken = parseOwnerToken(args);
27
- const ownerId = parseOwnerId(args);
27
+ const ownerId = parseOwnerId(args) || CLI_OWNER_ID;
28
28
 
29
29
  try {
30
30
  const result = await startChrome({ port, profileName, taskName, forceProfileSync, autoAllocatePort: !explicitPort, ownerToken, ownerId, headless, includeGoogle });
package/scripts/stop.mjs CHANGED
@@ -8,11 +8,24 @@
8
8
  * scripts/stop.mjs --port 9223
9
9
  * scripts/stop.mjs --clean
10
10
  * scripts/stop.mjs --dry-run
11
- * scripts/stop.mjs --prune (remove all cached clones not in use)
11
+ * scripts/stop.mjs --prune (reap orphans, then remove all cached clones not in use)
12
+ * scripts/stop.mjs --reap (kill managed browsers no lifecycle file tracks)
13
+ * scripts/stop.mjs --reap --dry-run (list them without killing anything)
14
+ * scripts/stop.mjs --status (show how many managed browsers are running)
12
15
  * scripts/stop.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
13
16
  */
14
17
 
15
- import { hasFlag, parseOwnerToken, parsePort, pruneChromeClones, stopChrome } from './browser-control.mjs';
18
+ import {
19
+ hasFlag,
20
+ managedBrowserCapacity,
21
+ managedBrowserStartupWarnings,
22
+ parseOwnerToken,
23
+ parsePort,
24
+ pruneChromeClones,
25
+ reapExitCode,
26
+ reapOrphanedChromes,
27
+ stopChrome,
28
+ } from './browser-control.mjs';
16
29
 
17
30
  const args = process.argv.slice(2);
18
31
  const port = parsePort(args);
@@ -20,8 +33,48 @@ const clean = hasFlag(args, '--clean');
20
33
  const dryRun = hasFlag(args, '--dry-run');
21
34
  const ownerToken = parseOwnerToken(args);
22
35
 
36
+ function reportReaped(reaped, wasDryRun) {
37
+ if (!reaped.length) {
38
+ console.log('No untracked managed browsers found.');
39
+ return;
40
+ }
41
+ for (const entry of reaped) {
42
+ const verb = wasDryRun ? 'Would reap' : entry.status === 'failed' ? '✗ Failed to reap' : '✓ Reaped';
43
+ console.log(`${verb} :${entry.port} (PID ${entry.pid})`);
44
+ }
45
+ }
46
+
47
+ if (hasFlag(args, '--status')) {
48
+ const capacity = managedBrowserCapacity();
49
+ console.log(`${capacity.count} of ${capacity.max} managed Chrome browsers running, ${capacity.remaining} slot(s) free`);
50
+ for (const entry of capacity.processes) {
51
+ const hours = Number.isFinite(entry.ageMs) ? (entry.ageMs / 3600000).toFixed(1) : '?';
52
+ console.log(` :${entry.port} PID ${entry.pid} up ${hours}h`);
53
+ }
54
+ for (const warning of managedBrowserStartupWarnings({ processes: capacity.processes, max: capacity.max })) {
55
+ console.log(`⚠ ${warning}`);
56
+ }
57
+ process.exit(0);
58
+ }
59
+
60
+ if (hasFlag(args, '--reap')) {
61
+ const result = reapOrphanedChromes({ dryRun });
62
+ reportReaped(result.reaped, dryRun);
63
+ // A caller reaping to free a slot must be able to tell that a browser survived.
64
+ process.exit(reapExitCode(result.reaped));
65
+ }
66
+
23
67
  if (hasFlag(args, '--prune')) {
24
- const prune = pruneChromeClones({ dryRun });
68
+ // Reap first: a clone dir held open by an untracked browser is otherwise unreclaimable, which is
69
+ // how 2.4 GB of clones survived every prune during the leak.
70
+ const reaped = reapOrphanedChromes({ dryRun });
71
+ reportReaped(reaped.reaped, dryRun);
72
+ // A real prune reclaims the clones of the browsers just reaped. Tell the dry run to assume the
73
+ // same, otherwise the preview reports those clones as in use and understates what will be removed.
74
+ const freedPorts = reaped.reaped
75
+ .filter((entry) => entry.status === 'would-reap' || entry.status === 'reaped' || entry.status === 'killed' || entry.status === 'already-gone')
76
+ .map((entry) => entry.port);
77
+ const prune = pruneChromeClones({ dryRun, assumeStoppedPorts: dryRun ? freedPorts : [] });
25
78
  if (!prune.removed.length && !prune.kept.length) {
26
79
  console.log('No cached Chrome clones found.');
27
80
  }
@@ -32,7 +85,7 @@ if (hasFlag(args, '--prune')) {
32
85
  const count = entry.paths.length;
33
86
  console.log(`${dryRun ? '• Would remove' : '✓ Removed'} clone for :${entry.port} (${count} item${count === 1 ? '' : 's'})`);
34
87
  }
35
- process.exit(0);
88
+ process.exit(reapExitCode(reaped.reaped));
36
89
  }
37
90
 
38
91
  const result = stopChrome({ port, clean, dryRun, ownerToken });
@@ -45,7 +98,8 @@ if (result.status === 'missing') {
45
98
  if (result.status === 'would-stop') {
46
99
  console.log(`✓ Dry run: would stop managed Chrome (PID ${result.pid}) on :${port}`);
47
100
  } else if (result.status === 'stopped') {
48
- console.log(`✓ Stopped managed Chrome (PID ${result.pid}) on :${port}`);
101
+ const reclaimed = result.reclaimedUnowned ? ' (reclaimed: nothing owned it)' : '';
102
+ console.log(`✓ Stopped managed Chrome (PID ${result.pid}) on :${port}${reclaimed}`);
49
103
  } else if (result.status === 'killed') {
50
104
  console.log(`✓ Killed managed Chrome (PID ${result.pid}) on :${port} after SIGTERM did not exit`);
51
105
  } else if (result.status === 'already-gone') {
@@ -54,6 +108,7 @@ if (result.status === 'would-stop') {
54
108
  const target = result.pid ? `PID ${result.pid}` : `port ${port}`;
55
109
  console.error(`✗ Refusing to stop ${target}: ${result.reason}`);
56
110
  console.error(' Safety rule: stop.mjs only kills Chrome processes launched by start.mjs.');
111
+ if (result.hint) console.error(` ${result.hint}`);
57
112
  process.exit(1);
58
113
  } else if (result.status === 'not-owned') {
59
114
  const owner = result.ownerId ? ` owned by ${result.ownerId}` : '';
@@ -66,6 +121,7 @@ if (result.status === 'would-stop') {
66
121
  process.exit(1);
67
122
  } else {
68
123
  console.error(`✗ Failed to stop Chrome: ${result.error?.message || 'unknown error'}`);
124
+ process.exit(1);
69
125
  }
70
126
 
71
127
  if (result.cleaned) console.log('✓ Cleaned up cached profile copy');