@speedkit/cli 4.40.0 → 4.41.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/CHANGELOG.md CHANGED
@@ -1,3 +1,24 @@
1
+ ## [4.41.1](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.41.0...v4.41.1) (2026-10-05)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **onboarding:** keep the debugging pipe when a debug port is set ([df363cc](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/df363cc7339465a3072168d4b04c6f7bd4d6b859))
7
+
8
+ # [4.41.0](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.40.0...v4.41.0) (2026-10-05)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **onboarding:** keep the devtools panel updated after the extension's worker stops ([e3386f8](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/e3386f88c9c6ff4c79ae437ef235c37044e05dc9))
14
+
15
+
16
+ ### Features
17
+
18
+ * **onboarding:** open DevTools on the Speed Kit panel when a headed run starts ([2c77b38](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/2c77b38e7d984be8f62aedd0dd016d78bdc7c512))
19
+ * **onboarding:** send swPath and scope to the devtools panel ([61ad30f](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/61ad30f198d9d1121d2350ba0f3836dca115cd67))
20
+ * send sessionInfo to devtools ([eb3b888](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/eb3b888ba2d39019e5fa0f1f455a285487e83509))
21
+
1
22
  # [4.40.0](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.39.0...v4.40.0) (2026-10-02)
2
23
 
3
24
 
@@ -57,7 +57,7 @@ export class ExecutableValidator {
57
57
  // on windows executing chrome to gather the version will spawn a chromeProcess
58
58
  // so we use a powershell instead. Emit `<ProductName> <FileVersion>` so the
59
59
  // output is shape-compatible with `chrome --version` on macOS/Linux —
60
- // downstream consumers (isChromeBrowser, log lines) can stay OS-agnostic.
60
+ // downstream consumers (the headed user agent, log lines) can stay OS-agnostic.
61
61
  if (this.environment.oclif.windows) {
62
62
  return this.cli.execSync(`$i = (Get-Item '${this.environment.settings.chromePath}').VersionInfo; "$($i.ProductName) $($i.FileVersion)"`, { shell: "powershell.exe" });
63
63
  }
@@ -0,0 +1,36 @@
1
+ import { Page } from "puppeteer";
2
+ export interface ShownPanel {
3
+ /** The DevTools tab id, `chrome-extension://<id><panel title>`. */
4
+ panel: string;
5
+ /** DevTools was closed and this opened it, rather than switching tabs. */
6
+ openedDevTools: boolean;
7
+ }
8
+ export declare class PanelNotFoundError extends Error {
9
+ /** The tabs DevTools did show, so a missing panel can be told from a renamed one. */
10
+ readonly tabs: string[];
11
+ constructor(message: string,
12
+ /** The tabs DevTools did show, so a missing panel can be told from a renamed one. */
13
+ tabs: string[]);
14
+ }
15
+ /**
16
+ * Open DevTools for `page` and bring the devtools extension's panel to the
17
+ * front.
18
+ *
19
+ * There is no public way to do this. `chrome.devtools.panels` cannot select a
20
+ * panel, and CDP can open DevTools but knows nothing about what is in it. So
21
+ * this reaches into the DevTools frontend itself — `page.openDevTools()` hands
22
+ * back the DevTools window as a page, and its own `InspectorView` does the
23
+ * switching. That is internal API and may move in a Chrome update, which is why
24
+ * every caller treats a failure here as a missing convenience, never as a
25
+ * failed run.
26
+ *
27
+ * `openDevTools` returns the window already open for the page when there is
28
+ * one, so this never stacks a second DevTools on a headed run, where
29
+ * `devtools: true` has opened one for every tab.
30
+ *
31
+ * Polls, for two things that each take a moment on a DevTools window this has
32
+ * just opened: its frontend has to initialise before `InspectorView` exists at
33
+ * all — asking earlier throws — and the extension registers its panel only
34
+ * once its devtools page has loaded, after that.
35
+ */
36
+ export declare function showDevtoolsPanel(page: Page, extensionId: string, timeoutMs?: number): Promise<ShownPanel>;
@@ -0,0 +1,82 @@
1
+ const POLL_INTERVAL_MS = 200;
2
+ const DEFAULT_TIMEOUT_MS = 10_000;
3
+ export class PanelNotFoundError extends Error {
4
+ tabs;
5
+ constructor(message,
6
+ /** The tabs DevTools did show, so a missing panel can be told from a renamed one. */
7
+ tabs) {
8
+ super(message);
9
+ this.tabs = tabs;
10
+ }
11
+ }
12
+ /**
13
+ * Open DevTools for `page` and bring the devtools extension's panel to the
14
+ * front.
15
+ *
16
+ * There is no public way to do this. `chrome.devtools.panels` cannot select a
17
+ * panel, and CDP can open DevTools but knows nothing about what is in it. So
18
+ * this reaches into the DevTools frontend itself — `page.openDevTools()` hands
19
+ * back the DevTools window as a page, and its own `InspectorView` does the
20
+ * switching. That is internal API and may move in a Chrome update, which is why
21
+ * every caller treats a failure here as a missing convenience, never as a
22
+ * failed run.
23
+ *
24
+ * `openDevTools` returns the window already open for the page when there is
25
+ * one, so this never stacks a second DevTools on a headed run, where
26
+ * `devtools: true` has opened one for every tab.
27
+ *
28
+ * Polls, for two things that each take a moment on a DevTools window this has
29
+ * just opened: its frontend has to initialise before `InspectorView` exists at
30
+ * all — asking earlier throws — and the extension registers its panel only
31
+ * once its devtools page has loaded, after that.
32
+ */
33
+ export async function showDevtoolsPanel(page, extensionId, timeoutMs = DEFAULT_TIMEOUT_MS) {
34
+ const openedDevTools = !(await page.hasDevTools());
35
+ const devtools = await page.openDevTools();
36
+ const prefix = `chrome-extension://${extensionId}`;
37
+ const deadline = Date.now() + timeoutMs;
38
+ let tabs = [];
39
+ let notReady;
40
+ // Puppeteer drops the arguments of a string expression, so the prefix is
41
+ // spliced in rather than passed.
42
+ const expression = `(${SELECT_PANEL})(${JSON.stringify(prefix)})`;
43
+ for (;;) {
44
+ try {
45
+ const answer = (await devtools.evaluate(expression));
46
+ notReady = null;
47
+ tabs = answer.tabs;
48
+ if (answer.selected) {
49
+ return { panel: answer.selected, openedDevTools };
50
+ }
51
+ }
52
+ catch (error) {
53
+ notReady = error;
54
+ }
55
+ if (Date.now() >= deadline)
56
+ break;
57
+ await sleep(POLL_INTERVAL_MS);
58
+ }
59
+ // Still throwing at the deadline is not a frontend that is starting: it is
60
+ // one whose internals are not the ones this was written against.
61
+ if (notReady) {
62
+ throw notReady;
63
+ }
64
+ throw new PanelNotFoundError(`the Speed Kit panel did not appear in DevTools within ${timeoutMs}ms`, tabs);
65
+ }
66
+ /**
67
+ * Runs inside the DevTools frontend, whose modules resolve relative to
68
+ * `devtools://devtools/bundled/`. A string, because TypeScript would try to
69
+ * resolve the import against this repository.
70
+ */
71
+ const SELECT_PANEL = `async (prefix) => {
72
+ const { InspectorView } = await import("./ui/legacy/legacy.js");
73
+ const view = InspectorView.InspectorView.instance();
74
+ const tabs = view.tabbedPane.tabIds();
75
+ const panel = tabs.find((id) => id.startsWith(prefix));
76
+ if (!panel) return { tabs, selected: null };
77
+ await view.showPanel(panel);
78
+ return { tabs, selected: view.tabbedPane.selectedTabId };
79
+ }`;
80
+ function sleep(ms) {
81
+ return new Promise((resolve) => setTimeout(resolve, ms));
82
+ }
@@ -3,27 +3,41 @@ import { DevelopmentToolsMessage } from "../../onboarding-model.js";
3
3
  import { CliServiceInterface } from "../../../cli/index.js";
4
4
  /**
5
5
  * Name heuristic for the devtools extension, shared by ExtensionValidator
6
- * (is one among the loaded extensions?) and the service-worker lookup below.
6
+ * (is one among the loaded extensions?) and the extension lookup below.
7
7
  */
8
8
  export declare function isDevtoolsExtensionName(name: string): boolean;
9
9
  /**
10
10
  * Writes onboarding state (messages, status) into the devtools extension's
11
- * chrome.storage.local via a CDP session against the extension's MV3
12
- * service-worker target. The devtools extension subscribes via
11
+ * chrome.storage.local, which the panel subscribes to via
13
12
  * chrome.storage.onChanged. Replaces the legacy `window.skCliMessages` page
14
13
  * injection — no more customer-visible global state.
15
14
  *
15
+ * **The write does not go through the extension's service worker.** It used
16
+ * to, and an MV3 worker that has stopped is not a target anyone can attach to:
17
+ * nothing restarted it, so every write after it stopped failed for the rest of
18
+ * the run and the panel kept showing whatever it had last received.
19
+ * `Extensions.setStorageItems` writes the storage from the browser side, works
20
+ * whether the worker runs or not, and restarts it as a side effect. It has to
21
+ * be sent from a session on a page the extension can access — an http(s) page,
22
+ * given its `<all_urls>` — because a browser-level session is refused. The
23
+ * worker stays as the fallback for a Chrome that refuses the command.
24
+ *
16
25
  * Lifecycle: construct once per browser, call `init()` after the browser is
17
- * launched and the devtools extension has loaded, then call `writeMessages`
18
- * whenever the message list changes. Constructed with
19
- * `devtoolsExtensionLoaded: false` (no devtools extension among the browser's
20
- * extensions) the bridge stays unavailable and never looks for a target.
26
+ * launched, then call `writeMessages` whenever the message list changes.
27
+ * Constructed with `devtoolsExtensionLoaded: false` (no devtools extension
28
+ * among the browser's extensions) the bridge stays unavailable and never
29
+ * looks for one.
21
30
  */
22
31
  export declare class ExtensionBridge {
23
32
  private readonly cli;
24
33
  private readonly devtoolsExtensionLoaded;
25
34
  private browser;
26
35
  private extensionId;
36
+ /** The newest snapshot not yet stored. Older ones are never worth writing. */
37
+ private pending;
38
+ private writing;
39
+ /** Set while writes fail, so an outage is reported once, not per write. */
40
+ private failing;
27
41
  constructor(cli: CliServiceInterface, devtoolsExtensionLoaded: boolean);
28
42
  /**
29
43
  * false when the browser is started without a devtools extension, so there
@@ -31,33 +45,50 @@ export declare class ExtensionBridge {
31
45
  */
32
46
  get isAvailable(): boolean;
33
47
  /**
34
- * Bind the bridge to a freshly-launched browser, discover the
35
- * devtools-extension's service-worker target, and cache its extension ID.
36
- * Polls for ~INIT_POLL_TIMEOUT_MS because MV3 service workers are
37
- * sometimes not registered as targets until Chrome has finished loading
38
- * the extension. Throws if no matching SW target is found in time.
48
+ * Bind the bridge to a freshly-launched browser and find the devtools
49
+ * extension's ID.
50
+ *
51
+ * Polls, because Puppeteer's `launch` returns before `enableExtensions` has
52
+ * finished installing. Throws if the extension does not show up in time.
39
53
  */
40
54
  init(browser: Browser): Promise<void>;
41
55
  /**
42
- * Write the current messages snapshot into chrome.storage.local. One retry
43
- * on transient failures (MV3 service workers can briefly disappear during
44
- * respawn). Failures are surfaced via `cli.writeError` but do not throw —
45
- * a missed write is degraded UX, not a fatal onboarding failure.
56
+ * Store the current messages snapshot in chrome.storage.local.
57
+ *
58
+ * Only the newest snapshot is written: one write is in flight at a time, and
59
+ * a snapshot that arrives meanwhile replaces the one waiting behind it, so an
60
+ * older snapshot can never land after a newer one. A snapshot that fails
61
+ * stays pending and is retried on the next page load. Failures are reported
62
+ * but never thrown — a missed write is degraded UX, not a fatal onboarding
63
+ * failure.
46
64
  */
47
65
  writeMessages(messages: DevelopmentToolsMessage[]): Promise<void>;
48
- private evaluateInServiceWorker;
66
+ /** Whether the bridge found an extension to talk to at all. */
67
+ get available(): boolean;
68
+ /** The devtools extension's ID, once `init()` has found it. */
69
+ get devtoolsExtensionId(): string | null;
70
+ private drain;
71
+ private writePending;
72
+ private store;
73
+ private reportFailure;
74
+ private reportRecovery;
75
+ private setStorageItems;
76
+ private findWebPage;
49
77
  /**
50
- * Look up the service-worker target by cached extension ID. Returns null
51
- * when the SW is dormant — callers handle that via retry.
78
+ * Run an expression inside the devtools extension's service worker, waiting
79
+ * briefly for one when none is running. Only the fallback: waiting does not
80
+ * start a worker, it only catches one that is starting anyway.
52
81
  */
53
- private getServiceWorkerTarget;
82
+ private evaluateInServiceWorker;
54
83
  /**
55
- * Scan service-worker targets, evaluate `chrome.runtime.getManifest().name`
56
- * on each, and return the first whose name matches the devtools-extension
57
- * heuristic. We discover the extension by name (not by computing the ID
58
- * from the unpacked path) because unpacked-extension IDs depend on the
84
+ * The devtools extension's ID, from `Extensions.getExtensions` — which needs
85
+ * no running worker — or, when Chrome refuses that, from the manifest name
86
+ * of a running extension worker. Discovered by name rather than computed
87
+ * from the unpacked path, because unpacked-extension IDs depend on the
59
88
  * absolute path and OS path normalization.
60
89
  */
90
+ private findExtensionId;
91
+ private listExtensions;
61
92
  private findDevtoolsServiceWorker;
62
93
  private readManifestName;
63
94
  private extractExtensionId;
@@ -1,13 +1,13 @@
1
1
  import { safe } from "../../../../helpers/safe.js";
2
2
  const STORAGE_KEY = "skCli";
3
3
  const PROTOCOL_VERSION = 1;
4
- const SW_LOOKUP_RETRY_MS = 250;
4
+ const SW_WAIT_MS = 2000;
5
5
  const INIT_POLL_INTERVAL_MS = 200;
6
- const INIT_POLL_TIMEOUT_MS = 4000;
6
+ const INIT_POLL_TIMEOUT_MS = 10000;
7
7
  const EXTENSION_NAME_MATCHERS = ["speed-kit devtools", "devtools extension"];
8
8
  /**
9
9
  * Name heuristic for the devtools extension, shared by ExtensionValidator
10
- * (is one among the loaded extensions?) and the service-worker lookup below.
10
+ * (is one among the loaded extensions?) and the extension lookup below.
11
11
  */
12
12
  export function isDevtoolsExtensionName(name) {
13
13
  const lower = name.toLowerCase();
@@ -15,22 +15,36 @@ export function isDevtoolsExtensionName(name) {
15
15
  }
16
16
  /**
17
17
  * Writes onboarding state (messages, status) into the devtools extension's
18
- * chrome.storage.local via a CDP session against the extension's MV3
19
- * service-worker target. The devtools extension subscribes via
18
+ * chrome.storage.local, which the panel subscribes to via
20
19
  * chrome.storage.onChanged. Replaces the legacy `window.skCliMessages` page
21
20
  * injection — no more customer-visible global state.
22
21
  *
22
+ * **The write does not go through the extension's service worker.** It used
23
+ * to, and an MV3 worker that has stopped is not a target anyone can attach to:
24
+ * nothing restarted it, so every write after it stopped failed for the rest of
25
+ * the run and the panel kept showing whatever it had last received.
26
+ * `Extensions.setStorageItems` writes the storage from the browser side, works
27
+ * whether the worker runs or not, and restarts it as a side effect. It has to
28
+ * be sent from a session on a page the extension can access — an http(s) page,
29
+ * given its `<all_urls>` — because a browser-level session is refused. The
30
+ * worker stays as the fallback for a Chrome that refuses the command.
31
+ *
23
32
  * Lifecycle: construct once per browser, call `init()` after the browser is
24
- * launched and the devtools extension has loaded, then call `writeMessages`
25
- * whenever the message list changes. Constructed with
26
- * `devtoolsExtensionLoaded: false` (no devtools extension among the browser's
27
- * extensions) the bridge stays unavailable and never looks for a target.
33
+ * launched, then call `writeMessages` whenever the message list changes.
34
+ * Constructed with `devtoolsExtensionLoaded: false` (no devtools extension
35
+ * among the browser's extensions) the bridge stays unavailable and never
36
+ * looks for one.
28
37
  */
29
38
  export class ExtensionBridge {
30
39
  cli;
31
40
  devtoolsExtensionLoaded;
32
41
  browser = null;
33
42
  extensionId = null;
43
+ /** The newest snapshot not yet stored. Older ones are never worth writing. */
44
+ pending = null;
45
+ writing = null;
46
+ /** Set while writes fail, so an outage is reported once, not per write. */
47
+ failing = false;
34
48
  constructor(cli, devtoolsExtensionLoaded) {
35
49
  this.cli = cli;
36
50
  this.devtoolsExtensionLoaded = devtoolsExtensionLoaded;
@@ -43,11 +57,11 @@ export class ExtensionBridge {
43
57
  return this.devtoolsExtensionLoaded;
44
58
  }
45
59
  /**
46
- * Bind the bridge to a freshly-launched browser, discover the
47
- * devtools-extension's service-worker target, and cache its extension ID.
48
- * Polls for ~INIT_POLL_TIMEOUT_MS because MV3 service workers are
49
- * sometimes not registered as targets until Chrome has finished loading
50
- * the extension. Throws if no matching SW target is found in time.
60
+ * Bind the bridge to a freshly-launched browser and find the devtools
61
+ * extension's ID.
62
+ *
63
+ * Polls, because Puppeteer's `launch` returns before `enableExtensions` has
64
+ * finished installing. Throws if the extension does not show up in time.
51
65
  */
52
66
  async init(browser) {
53
67
  if (!this.isAvailable) {
@@ -55,61 +69,143 @@ export class ExtensionBridge {
55
69
  }
56
70
  this.browser = browser;
57
71
  const deadline = Date.now() + INIT_POLL_TIMEOUT_MS;
58
- let target = await this.findDevtoolsServiceWorker();
59
- while (!target && Date.now() < deadline) {
72
+ let id = await this.findExtensionId();
73
+ while (!id && Date.now() < deadline) {
60
74
  await sleep(INIT_POLL_INTERVAL_MS);
61
- target = await this.findDevtoolsServiceWorker();
75
+ id = await this.findExtensionId();
62
76
  }
63
- if (!target) {
64
- throw new Error("ExtensionBridge: no devtools-extension service-worker target found " +
65
- `within ${INIT_POLL_TIMEOUT_MS} ms. Confirm the extension is loaded ` +
66
- "and its name matches one of: " +
77
+ if (!id) {
78
+ throw new Error(`ExtensionBridge: no devtools extension found within ${INIT_POLL_TIMEOUT_MS} ms. ` +
79
+ "Confirm the extension is loaded and its name matches one of: " +
67
80
  EXTENSION_NAME_MATCHERS.join(", "));
68
81
  }
69
- this.extensionId = this.extractExtensionId(target.url());
82
+ this.extensionId = id;
83
+ // A snapshot that could not be stored waits for the next page load. That
84
+ // is when an http(s) page to send it from is most likely to exist, and
85
+ // when the panel is most likely to be looked at.
86
+ browser.on("targetchanged", (target) => {
87
+ if (this.pending && target.type() === "page" && isWebUrl(target.url())) {
88
+ void this.drain();
89
+ }
90
+ });
70
91
  }
71
92
  /**
72
- * Write the current messages snapshot into chrome.storage.local. One retry
73
- * on transient failures (MV3 service workers can briefly disappear during
74
- * respawn). Failures are surfaced via `cli.writeError` but do not throw —
75
- * a missed write is degraded UX, not a fatal onboarding failure.
93
+ * Store the current messages snapshot in chrome.storage.local.
94
+ *
95
+ * Only the newest snapshot is written: one write is in flight at a time, and
96
+ * a snapshot that arrives meanwhile replaces the one waiting behind it, so an
97
+ * older snapshot can never land after a newer one. A snapshot that fails
98
+ * stays pending and is retried on the next page load. Failures are reported
99
+ * but never thrown — a missed write is degraded UX, not a fatal onboarding
100
+ * failure.
76
101
  */
77
102
  async writeMessages(messages) {
78
- if (!this.browser || !this.extensionId) {
103
+ if (!this.available) {
79
104
  this.cli.writeWarning("ExtensionBridge.writeMessages called before init()");
80
105
  return;
81
106
  }
82
- const payload = {
107
+ this.pending = {
83
108
  protocolVersion: PROTOCOL_VERSION,
84
109
  writtenAt: new Date().toISOString(),
85
110
  messages,
86
111
  };
87
- const first = await safe(this.evaluateInServiceWorker(payload));
88
- if (first.success === true)
112
+ await this.drain();
113
+ }
114
+ /** Whether the bridge found an extension to talk to at all. */
115
+ get available() {
116
+ return Boolean(this.browser && this.extensionId);
117
+ }
118
+ /** The devtools extension's ID, once `init()` has found it. */
119
+ get devtoolsExtensionId() {
120
+ return this.extensionId;
121
+ }
122
+ drain() {
123
+ this.writing ??= this.writePending().finally(() => {
124
+ this.writing = null;
125
+ });
126
+ return this.writing;
127
+ }
128
+ async writePending() {
129
+ while (this.pending) {
130
+ const payload = this.pending;
131
+ const result = await safe(this.store({ [STORAGE_KEY]: payload }));
132
+ if (result.success !== true) {
133
+ this.reportFailure(result.error);
134
+ return;
135
+ }
136
+ if (this.pending === payload) {
137
+ this.pending = null;
138
+ }
139
+ this.reportRecovery();
140
+ }
141
+ }
142
+ async store(values) {
143
+ const direct = await safe(this.setStorageItems(values));
144
+ if (direct.success === true)
89
145
  return;
90
- await sleep(SW_LOOKUP_RETRY_MS);
91
- const retry = await safe(this.evaluateInServiceWorker(payload));
92
- if (retry.success !== true) {
93
- this.cli.writeError(`ExtensionBridge.writeMessages failed: ${retry.error}`);
146
+ const viaWorker = await safe(this.evaluateInServiceWorker(`chrome.storage.local.set(${JSON.stringify(values)})`));
147
+ if (viaWorker.success === true)
148
+ return;
149
+ throw new Error(`${direct.error} (through the service worker: ${viaWorker.error})`);
150
+ }
151
+ reportFailure(error) {
152
+ if (this.failing)
153
+ return;
154
+ this.failing = true;
155
+ this.cli.writeWarning(`The devtools panel is not receiving updates: ${error}. Retrying on the next page load.`);
156
+ }
157
+ reportRecovery() {
158
+ if (!this.failing)
159
+ return;
160
+ this.failing = false;
161
+ this.cli.writeSuccess("The devtools panel is receiving updates again.");
162
+ }
163
+ async setStorageItems(values) {
164
+ const page = await this.findWebPage();
165
+ if (!page) {
166
+ throw new Error("no http(s) page is open to write the storage from");
94
167
  }
168
+ const session = await page.createCDPSession();
169
+ try {
170
+ await session.send("Extensions.setStorageItems", {
171
+ id: this.extensionId,
172
+ storageArea: "local",
173
+ values,
174
+ });
175
+ }
176
+ finally {
177
+ await safe(session.detach());
178
+ }
179
+ }
180
+ async findWebPage() {
181
+ const pages = await this.browser.pages();
182
+ return pages.find((page) => isWebUrl(page.url())) ?? null;
95
183
  }
96
- async evaluateInServiceWorker(payload) {
97
- const target = await this.getServiceWorkerTarget();
184
+ /**
185
+ * Run an expression inside the devtools extension's service worker, waiting
186
+ * briefly for one when none is running. Only the fallback: waiting does not
187
+ * start a worker, it only catches one that is starting anyway.
188
+ */
189
+ async evaluateInServiceWorker(expression) {
190
+ const prefix = `chrome-extension://${this.extensionId}/`;
191
+ const isWorker = (target) => target.type() === "service_worker" && target.url().startsWith(prefix);
192
+ const target = this.browser.targets().find(isWorker) ??
193
+ (await this.browser
194
+ .waitForTarget(isWorker, { timeout: SW_WAIT_MS })
195
+ .catch(() => null));
98
196
  if (!target) {
99
197
  throw new Error("service-worker target not found");
100
198
  }
101
199
  const session = await target.createCDPSession();
102
200
  try {
103
- const expression = `chrome.storage.local.set(${JSON.stringify({
104
- [STORAGE_KEY]: payload,
105
- })})`;
106
201
  const evalResult = await session.send("Runtime.evaluate", {
107
202
  expression,
108
203
  awaitPromise: true,
109
204
  returnByValue: true,
110
205
  });
111
206
  if (evalResult.exceptionDetails) {
112
- throw new Error(evalResult.exceptionDetails.text ||
207
+ throw new Error(evalResult.exceptionDetails.exception?.description ||
208
+ evalResult.exceptionDetails.text ||
113
209
  "Runtime.evaluate threw an unknown exception");
114
210
  }
115
211
  }
@@ -118,31 +214,31 @@ export class ExtensionBridge {
118
214
  }
119
215
  }
120
216
  /**
121
- * Look up the service-worker target by cached extension ID. Returns null
122
- * when the SW is dormant — callers handle that via retry.
217
+ * The devtools extension's ID, from `Extensions.getExtensions` — which needs
218
+ * no running worker — or, when Chrome refuses that, from the manifest name
219
+ * of a running extension worker. Discovered by name rather than computed
220
+ * from the unpacked path, because unpacked-extension IDs depend on the
221
+ * absolute path and OS path normalization.
123
222
  */
124
- async getServiceWorkerTarget() {
125
- if (!this.browser || !this.extensionId)
126
- return null;
127
- const prefix = `chrome-extension://${this.extensionId}/`;
128
- for (const target of this.browser.targets()) {
129
- if (target.type() === "service_worker" &&
130
- target.url().startsWith(prefix)) {
131
- return target;
132
- }
223
+ async findExtensionId() {
224
+ const listed = await safe(this.listExtensions());
225
+ if (listed.success === true) {
226
+ return (listed.data.find((e) => isDevtoolsExtensionName(e.name))?.id ?? null);
227
+ }
228
+ const worker = await this.findDevtoolsServiceWorker();
229
+ return worker ? this.extractExtensionId(worker.url()) : null;
230
+ }
231
+ async listExtensions() {
232
+ const session = await this.browser.target().createCDPSession();
233
+ try {
234
+ const { extensions } = await session.send("Extensions.getExtensions");
235
+ return extensions;
236
+ }
237
+ finally {
238
+ await safe(session.detach());
133
239
  }
134
- return null;
135
240
  }
136
- /**
137
- * Scan service-worker targets, evaluate `chrome.runtime.getManifest().name`
138
- * on each, and return the first whose name matches the devtools-extension
139
- * heuristic. We discover the extension by name (not by computing the ID
140
- * from the unpacked path) because unpacked-extension IDs depend on the
141
- * absolute path and OS path normalization.
142
- */
143
241
  async findDevtoolsServiceWorker() {
144
- if (!this.browser)
145
- return null;
146
242
  const swTargets = this.browser
147
243
  .targets()
148
244
  .filter((t) => t.type() === "service_worker");
@@ -173,13 +269,12 @@ export class ExtensionBridge {
173
269
  }
174
270
  }
175
271
  extractExtensionId(url) {
176
- const match = url.match(/^chrome-extension:\/\/([a-p]{32})\//);
177
- if (!match) {
178
- throw new Error(`Could not extract extension ID from URL: ${url}`);
179
- }
180
- return match[1];
272
+ return url.match(/^chrome-extension:\/\/([a-p]{32})\//)?.[1] ?? null;
181
273
  }
182
274
  }
275
+ function isWebUrl(url) {
276
+ return /^https?:\/\//.test(url);
277
+ }
183
278
  function sleep(ms) {
184
279
  return new Promise((resolve) => setTimeout(resolve, ms));
185
280
  }
@@ -55,7 +55,6 @@ export declare class BrowserContext {
55
55
  * refetch would still leak the headless token and re-poison the merged body.
56
56
  */
57
57
  private getHeadlessParityArgs;
58
- private isChromeBrowser;
59
58
  private getBrowserExtensionPath;
60
59
  /** The system-specific chromeFlags of the user config, appended to every other arg. */
61
60
  private getSystemChromeFlags;
@@ -119,9 +118,38 @@ export interface SpeedKitServerConfig {
119
118
  };
120
119
  }
121
120
  export interface SkCliInfo {
121
+ /** The CLI that wrote this — the writer, not the run, so it stays outside. */
122
122
  version: string;
123
+ /** What this run is for and how it was started. */
124
+ session: SkCliSessionInfo;
125
+ }
126
+ export interface SkCliSessionInfo {
123
127
  app: string;
124
128
  customerConfigPath: string;
129
+ /**
130
+ * The customer config's `origins`. The extension marks only tabs on these,
131
+ * so a second customer opened in the same browser is not drawn into this
132
+ * run's tab group.
133
+ */
134
+ origins: string[];
135
+ /** The customer config's `swPath`: where the Speed Kit service worker is served. */
136
+ swPath: string;
137
+ /** The customer config's `scope`: the URL prefix that service worker controls. */
138
+ scope: string;
139
+ /** `--local`: the documentHandler is built and served from this machine. */
140
+ local: boolean;
141
+ /** The customer config's `forceInstall`: Speed Kit is installed on every page. */
142
+ forceInstall: boolean;
143
+ /**
144
+ * The SOCKS proxy every origin request goes through, or null for a direct
145
+ * connection. `source` says whether `SK_PROXY_SERVER` set it or the
146
+ * customer config's `chromeFlags` did — the environment overrides the exit
147
+ * region the customer pinned, and that is worth seeing.
148
+ */
149
+ proxy: {
150
+ url: string;
151
+ source: "environment" | "chromeFlags";
152
+ } | null;
125
153
  }
126
154
  export interface AthenaInfo {
127
155
  client: boolean;