@speedkit/cli 4.50.5 → 4.51.0-run-control.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (432) hide show
  1. package/README.md +1425 -14
  2. package/dist/base/run-control-command.d.ts +15 -0
  3. package/dist/base/run-control-command.js +20 -0
  4. package/dist/build-info.json +6 -0
  5. package/dist/commands/diff.d.ts +7 -1
  6. package/dist/commands/diff.js +9 -3
  7. package/dist/commands/login.d.ts +3 -0
  8. package/dist/commands/login.js +14 -3
  9. package/dist/commands/onboarding/browser/click.d.ts +75 -0
  10. package/dist/commands/onboarding/browser/click.js +19 -0
  11. package/dist/commands/onboarding/browser/emulate.d.ts +105 -0
  12. package/dist/commands/onboarding/browser/emulate.js +26 -0
  13. package/dist/commands/onboarding/browser/navigate.d.ts +75 -0
  14. package/dist/commands/onboarding/browser/navigate.js +19 -0
  15. package/dist/commands/onboarding/browser/panel.d.ts +63 -0
  16. package/dist/commands/onboarding/browser/panel.js +12 -0
  17. package/dist/commands/onboarding/browser/reinstall-sw.d.ts +63 -0
  18. package/dist/commands/onboarding/browser/reinstall-sw.js +14 -0
  19. package/dist/commands/onboarding/browser/reset.d.ts +71 -0
  20. package/dist/commands/onboarding/browser/reset.js +18 -0
  21. package/dist/commands/onboarding/browser/screenshot.d.ts +77 -0
  22. package/dist/commands/onboarding/browser/screenshot.js +19 -0
  23. package/dist/commands/onboarding/browser/state.d.ts +63 -0
  24. package/dist/commands/onboarding/browser/state.js +12 -0
  25. package/dist/commands/onboarding/browser/tabs.d.ts +58 -0
  26. package/dist/commands/onboarding/browser/tabs.js +16 -0
  27. package/dist/commands/onboarding/cache/clear.d.ts +58 -0
  28. package/dist/commands/onboarding/cache/clear.js +12 -0
  29. package/dist/commands/onboarding/cache/errors.d.ts +58 -0
  30. package/dist/commands/onboarding/cache/errors.js +12 -0
  31. package/dist/commands/onboarding/cache/evict.d.ts +62 -0
  32. package/dist/commands/onboarding/cache/evict.js +15 -0
  33. package/dist/commands/onboarding/cache/get.d.ts +85 -0
  34. package/dist/commands/onboarding/cache/get.js +17 -0
  35. package/dist/commands/onboarding/cache/list.d.ts +58 -0
  36. package/dist/commands/onboarding/cache/list.js +15 -0
  37. package/dist/commands/onboarding/cache/prewarm.d.ts +73 -0
  38. package/dist/commands/onboarding/cache/prewarm.js +20 -0
  39. package/dist/commands/onboarding/cache/refresh.d.ts +62 -0
  40. package/dist/commands/onboarding/cache/refresh.js +18 -0
  41. package/dist/commands/onboarding/cdp.d.ts +81 -0
  42. package/dist/commands/onboarding/cdp.js +18 -0
  43. package/dist/commands/onboarding/debug/arm.d.ts +83 -0
  44. package/dist/commands/onboarding/debug/arm.js +19 -0
  45. package/dist/commands/onboarding/debug/await.d.ts +71 -0
  46. package/dist/commands/onboarding/debug/await.js +18 -0
  47. package/dist/commands/onboarding/debug/disarm.d.ts +63 -0
  48. package/dist/commands/onboarding/debug/disarm.js +12 -0
  49. package/dist/commands/onboarding/debug/eval.d.ts +75 -0
  50. package/dist/commands/onboarding/debug/eval.js +16 -0
  51. package/dist/commands/onboarding/debug/release.d.ts +63 -0
  52. package/dist/commands/onboarding/debug/release.js +12 -0
  53. package/dist/commands/onboarding/debug/resume.d.ts +63 -0
  54. package/dist/commands/onboarding/debug/resume.js +12 -0
  55. package/dist/commands/onboarding/debug/status.d.ts +63 -0
  56. package/dist/commands/onboarding/debug/status.js +12 -0
  57. package/dist/commands/onboarding/debug/step.d.ts +67 -0
  58. package/dist/commands/onboarding/debug/step.js +15 -0
  59. package/dist/commands/onboarding/files/list.d.ts +58 -0
  60. package/dist/commands/onboarding/files/list.js +12 -0
  61. package/dist/commands/onboarding/files/read.d.ts +73 -0
  62. package/dist/commands/onboarding/files/read.js +16 -0
  63. package/dist/commands/onboarding/files/rebuild.d.ts +63 -0
  64. package/dist/commands/onboarding/files/rebuild.js +18 -0
  65. package/dist/commands/onboarding/files/validate.d.ts +58 -0
  66. package/dist/commands/onboarding/files/validate.js +12 -0
  67. package/dist/commands/onboarding/fouc.d.ts +77 -0
  68. package/dist/commands/onboarding/fouc.js +16 -0
  69. package/dist/commands/onboarding/inject/add.d.ts +89 -0
  70. package/dist/commands/onboarding/inject/add.js +17 -0
  71. package/dist/commands/onboarding/inject/clear.d.ts +63 -0
  72. package/dist/commands/onboarding/inject/clear.js +12 -0
  73. package/dist/commands/onboarding/inject/list.d.ts +63 -0
  74. package/dist/commands/onboarding/inject/list.js +12 -0
  75. package/dist/commands/onboarding/inject/read.d.ts +75 -0
  76. package/dist/commands/onboarding/inject/read.js +18 -0
  77. package/dist/commands/onboarding/inject/recipes.d.ts +63 -0
  78. package/dist/commands/onboarding/inject/recipes.js +12 -0
  79. package/dist/commands/onboarding/inject/remove.d.ts +67 -0
  80. package/dist/commands/onboarding/inject/remove.js +15 -0
  81. package/dist/commands/onboarding/list.d.ts +13 -0
  82. package/dist/commands/onboarding/list.js +12 -0
  83. package/dist/commands/onboarding/logs.d.ts +41 -0
  84. package/dist/commands/onboarding/logs.js +257 -0
  85. package/dist/commands/onboarding/navwalk.d.ts +95 -0
  86. package/dist/commands/onboarding/navwalk.js +19 -0
  87. package/dist/commands/onboarding/response.d.ts +67 -0
  88. package/dist/commands/onboarding/response.js +18 -0
  89. package/dist/commands/onboarding/rum/beacons.d.ts +75 -0
  90. package/dist/commands/onboarding/rum/beacons.js +16 -0
  91. package/dist/commands/onboarding/rum/get.d.ts +77 -0
  92. package/dist/commands/onboarding/rum/get.js +18 -0
  93. package/dist/commands/onboarding/rum/key.d.ts +67 -0
  94. package/dist/commands/onboarding/rum/key.js +13 -0
  95. package/dist/commands/onboarding/rum/previous.d.ts +63 -0
  96. package/dist/commands/onboarding/rum/previous.js +12 -0
  97. package/dist/commands/onboarding/status.d.ts +13 -0
  98. package/dist/commands/onboarding/status.js +17 -0
  99. package/dist/commands/onboarding/stop.d.ts +13 -0
  100. package/dist/commands/onboarding/stop.js +17 -0
  101. package/dist/commands/onboarding/todo.d.ts +58 -0
  102. package/dist/commands/onboarding/todo.js +12 -0
  103. package/dist/commands/onboarding/viewport.d.ts +101 -0
  104. package/dist/commands/onboarding/viewport.js +18 -0
  105. package/dist/commands/onboarding/watch.d.ts +93 -0
  106. package/dist/commands/onboarding/watch.js +16 -0
  107. package/dist/commands/onboarding.d.ts +26 -0
  108. package/dist/commands/onboarding.js +221 -4
  109. package/dist/commands/origin-request.d.ts +4 -0
  110. package/dist/commands/origin-request.js +4 -0
  111. package/dist/commands/spec/onboarding.spec.d.ts +1 -0
  112. package/dist/commands/spec/onboarding.spec.js +127 -0
  113. package/dist/services/cli/build-info.d.ts +33 -0
  114. package/dist/services/cli/build-info.js +63 -0
  115. package/dist/services/cli/cli-environment-factory.d.ts +3 -0
  116. package/dist/services/cli/cli-environment-factory.js +1 -0
  117. package/dist/services/cli/cli-service-build-context.d.ts +3 -0
  118. package/dist/services/cli/cli-service-factory.js +1 -1
  119. package/dist/services/cli/cli-service-model.d.ts +29 -10
  120. package/dist/services/cli/cli-service.d.ts +60 -11
  121. package/dist/services/cli/cli-service.js +196 -32
  122. package/dist/services/cli/index.d.ts +2 -0
  123. package/dist/services/cli/index.js +2 -0
  124. package/dist/services/cli/sink.d.ts +47 -0
  125. package/dist/services/cli/sink.js +31 -0
  126. package/dist/services/cli/spec/build-identity.spec.d.ts +1 -0
  127. package/dist/services/cli/spec/build-identity.spec.js +85 -0
  128. package/dist/services/cli/spec/build-info.spec.d.ts +1 -0
  129. package/dist/services/cli/spec/build-info.spec.js +10 -0
  130. package/dist/services/cli/spec/cli-service-log.spec.d.ts +1 -0
  131. package/dist/services/cli/spec/cli-service-log.spec.js +133 -0
  132. package/dist/services/cli/spec/cli-service.spec.js +113 -50
  133. package/dist/services/cli/spec/memory-cli.d.ts +9 -0
  134. package/dist/services/cli/spec/memory-cli.js +9 -0
  135. package/dist/services/diff/config-at-ref.d.ts +20 -0
  136. package/dist/services/diff/config-at-ref.js +33 -0
  137. package/dist/services/diff/diff-service-build-context.d.ts +12 -0
  138. package/dist/services/diff/diff-service-build-context.js +45 -1
  139. package/dist/services/diff/diff-service-factory.d.ts +2 -0
  140. package/dist/services/diff/diff-service-factory.js +65 -25
  141. package/dist/services/diff/diff-service.d.ts +11 -0
  142. package/dist/services/diff/diff-service.js +37 -11
  143. package/dist/services/diff/page-source.d.ts +12 -0
  144. package/dist/services/diff/page-source.js +16 -11
  145. package/dist/services/diff/run-runtime-config.d.ts +33 -0
  146. package/dist/services/diff/run-runtime-config.js +74 -0
  147. package/dist/services/diff/sinks/tool-diff-sink.d.ts +3 -2
  148. package/dist/services/diff/sinks/tool-diff-sink.js +3 -2
  149. package/dist/services/diff/spec/config-at-ref.spec.d.ts +1 -0
  150. package/dist/services/diff/spec/config-at-ref.spec.js +46 -0
  151. package/dist/services/diff/spec/diff-service-build-context.spec.js +19 -0
  152. package/dist/services/diff/spec/diff-service.spec.js +95 -0
  153. package/dist/services/diff/spec/run-runtime-config.spec.d.ts +1 -0
  154. package/dist/services/diff/spec/run-runtime-config.spec.js +87 -0
  155. package/dist/services/git/git-repository.d.ts +2 -0
  156. package/dist/services/git/git-repository.js +6 -0
  157. package/dist/services/integration-api/customer-config-flags.js +1 -0
  158. package/dist/services/onboarding/browse/browse-service.d.ts +13 -1
  159. package/dist/services/onboarding/browse/browse-service.js +40 -7
  160. package/dist/services/onboarding/browser/answer-dialogs.d.ts +12 -0
  161. package/dist/services/onboarding/browser/answer-dialogs.js +25 -0
  162. package/dist/services/onboarding/browser/baqend-response.d.ts +17 -1
  163. package/dist/services/onboarding/browser/baqend-response.js +23 -0
  164. package/dist/services/onboarding/browser/console-log.d.ts +9 -0
  165. package/dist/services/onboarding/browser/console-log.js +27 -0
  166. package/dist/services/onboarding/browser/emulate-device.d.ts +12 -1
  167. package/dist/services/onboarding/browser/emulate-device.js +33 -6
  168. package/dist/services/onboarding/browser/executable/executable-validator.js +4 -2
  169. package/dist/services/onboarding/browser/extension/extension-bridge.js +5 -3
  170. package/dist/services/onboarding/browser/extension/extension-downloader.js +17 -8
  171. package/dist/services/onboarding/browser/extension/extension-validator.js +9 -4
  172. package/dist/services/onboarding/browser/launch-browser.d.ts +2 -1
  173. package/dist/services/onboarding/browser/launch-browser.js +3 -1
  174. package/dist/services/onboarding/control/body-inspect.d.ts +24 -0
  175. package/dist/services/onboarding/control/body-inspect.js +106 -0
  176. package/dist/services/onboarding/control/browser-session.d.ts +535 -0
  177. package/dist/services/onboarding/control/browser-session.js +1300 -0
  178. package/dist/services/onboarding/control/config-validation.d.ts +17 -0
  179. package/dist/services/onboarding/control/config-validation.js +46 -0
  180. package/dist/services/onboarding/control/control-protocol.d.ts +1428 -0
  181. package/dist/services/onboarding/control/control-protocol.js +58 -0
  182. package/dist/services/onboarding/control/control-server.d.ts +292 -0
  183. package/dist/services/onboarding/control/control-server.js +1629 -0
  184. package/dist/services/onboarding/control/debug-session.d.ts +219 -0
  185. package/dist/services/onboarding/control/debug-session.js +897 -0
  186. package/dist/services/onboarding/control/fouc.d.ts +23 -0
  187. package/dist/services/onboarding/control/fouc.js +151 -0
  188. package/dist/services/onboarding/control/index.d.ts +4 -0
  189. package/dist/services/onboarding/control/index.js +4 -0
  190. package/dist/services/onboarding/control/navigate-wait.d.ts +33 -0
  191. package/dist/services/onboarding/control/navigate-wait.js +56 -0
  192. package/dist/services/onboarding/control/navwalk.d.ts +65 -0
  193. package/dist/services/onboarding/control/navwalk.js +248 -0
  194. package/dist/services/onboarding/control/preload-registry.d.ts +150 -0
  195. package/dist/services/onboarding/control/preload-registry.js +829 -0
  196. package/dist/services/onboarding/control/response-explainer.d.ts +24 -0
  197. package/dist/services/onboarding/control/response-explainer.js +257 -0
  198. package/dist/services/onboarding/control/rum.d.ts +8 -0
  199. package/dist/services/onboarding/control/rum.js +220 -0
  200. package/dist/services/onboarding/control/service-worker-tracker.d.ts +68 -0
  201. package/dist/services/onboarding/control/service-worker-tracker.js +120 -0
  202. package/dist/services/onboarding/control/viewport.d.ts +45 -0
  203. package/dist/services/onboarding/control/viewport.js +344 -0
  204. package/dist/services/onboarding/control/watch.d.ts +26 -0
  205. package/dist/services/onboarding/control/watch.js +157 -0
  206. package/dist/services/onboarding/dashboard/diff-against-current-page.js +3 -1
  207. package/dist/services/onboarding/dashboard/index.js +7 -2
  208. package/dist/services/onboarding/fetch-event-handler.d.ts +24 -5
  209. package/dist/services/onboarding/fetch-event-handler.js +103 -32
  210. package/dist/services/onboarding/fetch-events/speed-kit-install-js.js +11 -2
  211. package/dist/services/onboarding/fetch-events/speed-kit-rum-pi-request.d.ts +14 -0
  212. package/dist/services/onboarding/fetch-events/speed-kit-rum-pi-request.js +30 -0
  213. package/dist/services/onboarding/fetch-events/speed-kit-service-worker-js.d.ts +13 -0
  214. package/dist/services/onboarding/fetch-events/speed-kit-service-worker-js.js +28 -1
  215. package/dist/services/onboarding/file-events/file-watcher.d.ts +42 -1
  216. package/dist/services/onboarding/file-events/file-watcher.js +117 -12
  217. package/dist/services/onboarding/inject/inject-service.js +1 -1
  218. package/dist/services/onboarding/onboarding-model.d.ts +30 -0
  219. package/dist/services/onboarding/onboarding-model.js +12 -1
  220. package/dist/services/onboarding/onboarding-service-build-context.d.ts +4 -0
  221. package/dist/services/onboarding/onboarding-service-build-context.js +7 -1
  222. package/dist/services/onboarding/onboarding-service-factory.d.ts +17 -1
  223. package/dist/services/onboarding/onboarding-service-factory.js +150 -23
  224. package/dist/services/onboarding/onboarding-service.d.ts +40 -1
  225. package/dist/services/onboarding/onboarding-service.js +136 -23
  226. package/dist/services/onboarding/request-cache/asset-key.d.ts +61 -0
  227. package/dist/services/onboarding/request-cache/asset-key.js +115 -0
  228. package/dist/services/onboarding/request-cache/cache.d.ts +62 -5
  229. package/dist/services/onboarding/request-cache/cache.js +128 -17
  230. package/dist/services/onboarding/spec/browser/answer-dialogs.spec.d.ts +1 -0
  231. package/dist/services/onboarding/spec/browser/answer-dialogs.spec.js +66 -0
  232. package/dist/services/onboarding/spec/browser/console-log.spec.d.ts +1 -0
  233. package/dist/services/onboarding/spec/browser/console-log.spec.js +42 -0
  234. package/dist/services/onboarding/spec/control/browser-session.spec.d.ts +1 -0
  235. package/dist/services/onboarding/spec/control/browser-session.spec.js +651 -0
  236. package/dist/services/onboarding/spec/control/control-server.spec.d.ts +1 -0
  237. package/dist/services/onboarding/spec/control/control-server.spec.js +371 -0
  238. package/dist/services/onboarding/spec/control/debug-session.spec.d.ts +1 -0
  239. package/dist/services/onboarding/spec/control/debug-session.spec.js +751 -0
  240. package/dist/services/onboarding/spec/control/fakes.d.ts +31 -0
  241. package/dist/services/onboarding/spec/control/fakes.js +66 -0
  242. package/dist/services/onboarding/spec/control/fouc.spec.d.ts +1 -0
  243. package/dist/services/onboarding/spec/control/fouc.spec.js +167 -0
  244. package/dist/services/onboarding/spec/control/navigate-wait.spec.d.ts +1 -0
  245. package/dist/services/onboarding/spec/control/navigate-wait.spec.js +47 -0
  246. package/dist/services/onboarding/spec/control/navwalk.spec.d.ts +1 -0
  247. package/dist/services/onboarding/spec/control/navwalk.spec.js +222 -0
  248. package/dist/services/onboarding/spec/control/preload-registry.spec.d.ts +1 -0
  249. package/dist/services/onboarding/spec/control/preload-registry.spec.js +432 -0
  250. package/dist/services/onboarding/spec/control/response-explainer.spec.d.ts +1 -0
  251. package/dist/services/onboarding/spec/control/response-explainer.spec.js +324 -0
  252. package/dist/services/onboarding/spec/control/rum.spec.d.ts +1 -0
  253. package/dist/services/onboarding/spec/control/rum.spec.js +222 -0
  254. package/dist/services/onboarding/spec/control/service-worker-tracker.spec.d.ts +1 -0
  255. package/dist/services/onboarding/spec/control/service-worker-tracker.spec.js +193 -0
  256. package/dist/services/onboarding/spec/control/viewport.spec.d.ts +1 -0
  257. package/dist/services/onboarding/spec/control/viewport.spec.js +200 -0
  258. package/dist/services/onboarding/spec/control/watch.spec.d.ts +1 -0
  259. package/dist/services/onboarding/spec/control/watch.spec.js +187 -0
  260. package/dist/services/onboarding/spec/fetch-event-handler.spec.d.ts +1 -0
  261. package/dist/services/onboarding/spec/fetch-event-handler.spec.js +219 -0
  262. package/dist/services/onboarding/spec/fetch-events/speed-kit-service-worker-js.spec.d.ts +1 -0
  263. package/dist/services/onboarding/spec/fetch-events/speed-kit-service-worker-js.spec.js +41 -0
  264. package/dist/services/onboarding/spec/onboarding-model.spec.js +39 -3
  265. package/dist/services/onboarding/spec/onboarding-service-factory.spec.js +25 -1
  266. package/dist/services/onboarding/spec/request-cache/cache.spec.d.ts +1 -0
  267. package/dist/services/onboarding/spec/request-cache/cache.spec.js +107 -0
  268. package/dist/services/onboarding/spec/todo-collector.spec.d.ts +1 -0
  269. package/dist/services/onboarding/spec/todo-collector.spec.js +136 -0
  270. package/dist/services/onboarding/spec/virtual-orestes-app/virtual-orestes-app.spec.d.ts +1 -0
  271. package/dist/services/onboarding/spec/virtual-orestes-app/virtual-orestes-app.spec.js +65 -0
  272. package/dist/services/onboarding/todo-collector.d.ts +7 -2
  273. package/dist/services/onboarding/todo-collector.js +49 -12
  274. package/dist/services/onboarding/virtual-orestes-app/index.d.ts +38 -0
  275. package/dist/services/onboarding/virtual-orestes-app/index.js +113 -27
  276. package/dist/services/origin-request/asset-variations.d.ts +14 -0
  277. package/dist/services/origin-request/asset-variations.js +11 -4
  278. package/dist/services/origin-request/origin-fetcher.d.ts +7 -0
  279. package/dist/services/origin-request/origin-fetcher.js +43 -5
  280. package/dist/services/origin-request/origin-request-service-build-context.d.ts +17 -0
  281. package/dist/services/origin-request/origin-request-service-build-context.js +8 -0
  282. package/dist/services/origin-request/origin-request-service-factory.d.ts +0 -5
  283. package/dist/services/origin-request/origin-request-service-factory.js +2 -30
  284. package/dist/services/origin-request/origin-request-service.d.ts +121 -6
  285. package/dist/services/origin-request/origin-request-service.js +273 -49
  286. package/dist/services/origin-request/runtime-config-source.d.ts +6 -0
  287. package/dist/services/origin-request/runtime-config-source.js +15 -4
  288. package/dist/services/origin-request/spec/asset-variations.spec.js +20 -0
  289. package/dist/services/origin-request/spec/origin-request-service.spec.js +329 -6
  290. package/dist/services/query-builder/rules/rule-match.d.ts +35 -0
  291. package/dist/services/query-builder/rules/rule-match.js +70 -0
  292. package/dist/services/query-builder/spec/rules/rule-match.spec.d.ts +1 -0
  293. package/dist/services/query-builder/spec/rules/rule-match.spec.js +121 -0
  294. package/dist/services/run-control/browser/run-browser-contexts.d.ts +557 -0
  295. package/dist/services/run-control/browser/run-browser-contexts.js +91 -0
  296. package/dist/services/run-control/browser/run-browser-service-factory.d.ts +5 -0
  297. package/dist/services/run-control/browser/run-browser-service-factory.js +7 -0
  298. package/dist/services/run-control/browser/run-browser-service.d.ts +68 -0
  299. package/dist/services/run-control/browser/run-browser-service.js +206 -0
  300. package/dist/services/run-control/cache/run-cache-contexts.d.ts +349 -0
  301. package/dist/services/run-control/cache/run-cache-contexts.js +51 -0
  302. package/dist/services/run-control/cache/run-cache-service-factory.d.ts +6 -0
  303. package/dist/services/run-control/cache/run-cache-service-factory.js +12 -0
  304. package/dist/services/run-control/cache/run-cache-service.d.ts +35 -0
  305. package/dist/services/run-control/cache/run-cache-service.js +151 -0
  306. package/dist/services/run-control/control-client.d.ts +36 -0
  307. package/dist/services/run-control/control-client.js +147 -0
  308. package/dist/services/run-control/debug/run-debug-contexts.d.ts +416 -0
  309. package/dist/services/run-control/debug/run-debug-contexts.js +47 -0
  310. package/dist/services/run-control/debug/run-debug-service-factory.d.ts +5 -0
  311. package/dist/services/run-control/debug/run-debug-service-factory.js +7 -0
  312. package/dist/services/run-control/debug/run-debug-service.d.ts +39 -0
  313. package/dist/services/run-control/debug/run-debug-service.js +164 -0
  314. package/dist/services/run-control/files/run-files-contexts.d.ts +238 -0
  315. package/dist/services/run-control/files/run-files-contexts.js +26 -0
  316. package/dist/services/run-control/files/run-files-service-factory.d.ts +5 -0
  317. package/dist/services/run-control/files/run-files-service-factory.js +7 -0
  318. package/dist/services/run-control/files/run-files-service.d.ts +29 -0
  319. package/dist/services/run-control/files/run-files-service.js +120 -0
  320. package/dist/services/run-control/index.d.ts +32 -0
  321. package/dist/services/run-control/index.js +31 -0
  322. package/dist/services/run-control/inject/run-inject-contexts.d.ts +319 -0
  323. package/dist/services/run-control/inject/run-inject-contexts.js +38 -0
  324. package/dist/services/run-control/inject/run-inject-service-factory.d.ts +5 -0
  325. package/dist/services/run-control/inject/run-inject-service-factory.js +7 -0
  326. package/dist/services/run-control/inject/run-inject-service.d.ts +31 -0
  327. package/dist/services/run-control/inject/run-inject-service.js +227 -0
  328. package/dist/services/run-control/live-run.d.ts +37 -0
  329. package/dist/services/run-control/live-run.js +56 -0
  330. package/dist/services/run-control/probe/run-probe-contexts.d.ts +333 -0
  331. package/dist/services/run-control/probe/run-probe-contexts.js +73 -0
  332. package/dist/services/run-control/probe/run-probe-service-factory.d.ts +5 -0
  333. package/dist/services/run-control/probe/run-probe-service-factory.js +7 -0
  334. package/dist/services/run-control/probe/run-probe-service.d.ts +54 -0
  335. package/dist/services/run-control/probe/run-probe-service.js +194 -0
  336. package/dist/services/run-control/rum/run-rum-contexts.d.ts +216 -0
  337. package/dist/services/run-control/rum/run-rum-contexts.js +34 -0
  338. package/dist/services/run-control/rum/run-rum-service-factory.d.ts +5 -0
  339. package/dist/services/run-control/rum/run-rum-service-factory.js +7 -0
  340. package/dist/services/run-control/rum/run-rum-service.d.ts +36 -0
  341. package/dist/services/run-control/rum/run-rum-service.js +122 -0
  342. package/dist/services/run-control/run-answer.d.ts +28 -0
  343. package/dist/services/run-control/run-answer.js +58 -0
  344. package/dist/services/run-control/run-control-context.d.ts +102 -0
  345. package/dist/services/run-control/run-control-context.js +36 -0
  346. package/dist/services/run-control/run-control-flags.d.ts +12 -0
  347. package/dist/services/run-control/run-control-flags.js +22 -0
  348. package/dist/services/run-control/run-control-model.d.ts +9 -0
  349. package/dist/services/run-control/run-control-model.js +1 -0
  350. package/dist/services/run-control/run-control-service-factory.d.ts +14 -0
  351. package/dist/services/run-control/run-control-service-factory.js +26 -0
  352. package/dist/services/run-control/session/run-session-contexts.d.ts +25 -0
  353. package/dist/services/run-control/session/run-session-contexts.js +20 -0
  354. package/dist/services/run-control/session/run-session-service-factory.d.ts +8 -0
  355. package/dist/services/run-control/session/run-session-service-factory.js +18 -0
  356. package/dist/services/run-control/session/run-session-service.d.ts +32 -0
  357. package/dist/services/run-control/session/run-session-service.js +151 -0
  358. package/dist/services/run-control/spec/browser/run-browser-service.spec.d.ts +1 -0
  359. package/dist/services/run-control/spec/browser/run-browser-service.spec.js +327 -0
  360. package/dist/services/run-control/spec/cache/run-cache-service.spec.d.ts +1 -0
  361. package/dist/services/run-control/spec/cache/run-cache-service.spec.js +454 -0
  362. package/dist/services/run-control/spec/debug/run-debug-service.spec.d.ts +1 -0
  363. package/dist/services/run-control/spec/debug/run-debug-service.spec.js +113 -0
  364. package/dist/services/run-control/spec/files/run-files-service.spec.d.ts +1 -0
  365. package/dist/services/run-control/spec/files/run-files-service.spec.js +234 -0
  366. package/dist/services/run-control/spec/inject/run-inject-service.spec.d.ts +1 -0
  367. package/dist/services/run-control/spec/inject/run-inject-service.spec.js +251 -0
  368. package/dist/services/run-control/spec/live-run-fixture.d.ts +32 -0
  369. package/dist/services/run-control/spec/live-run-fixture.js +109 -0
  370. package/dist/services/run-control/spec/probe/run-probe-service.spec.d.ts +1 -0
  371. package/dist/services/run-control/spec/probe/run-probe-service.spec.js +108 -0
  372. package/dist/services/run-control/spec/rum/run-rum-service.spec.d.ts +1 -0
  373. package/dist/services/run-control/spec/rum/run-rum-service.spec.js +47 -0
  374. package/dist/services/run-control/spec/run-answer.spec.d.ts +1 -0
  375. package/dist/services/run-control/spec/run-answer.spec.js +57 -0
  376. package/dist/services/run-control/spec/session/run-session-service.spec.d.ts +1 -0
  377. package/dist/services/run-control/spec/session/run-session-service.spec.js +150 -0
  378. package/dist/services/run-log/crash-mirror.d.ts +31 -0
  379. package/dist/services/run-log/crash-mirror.js +69 -0
  380. package/dist/services/run-log/index.d.ts +11 -0
  381. package/dist/services/run-log/index.js +11 -0
  382. package/dist/services/run-log/jsonl-appender.d.ts +46 -0
  383. package/dist/services/run-log/jsonl-appender.js +91 -0
  384. package/dist/services/run-log/log-event-model.d.ts +104 -0
  385. package/dist/services/run-log/log-event-model.js +56 -0
  386. package/dist/services/run-log/log-query-service-factory.d.ts +11 -0
  387. package/dist/services/run-log/log-query-service-factory.js +14 -0
  388. package/dist/services/run-log/log-query-service.d.ts +59 -0
  389. package/dist/services/run-log/log-query-service.js +111 -0
  390. package/dist/services/run-log/log-reader.d.ts +84 -0
  391. package/dist/services/run-log/log-reader.js +180 -0
  392. package/dist/services/run-log/log-summary.d.ts +72 -0
  393. package/dist/services/run-log/log-summary.js +208 -0
  394. package/dist/services/run-log/redaction.d.ts +34 -0
  395. package/dist/services/run-log/redaction.js +124 -0
  396. package/dist/services/run-log/request-log.d.ts +82 -0
  397. package/dist/services/run-log/request-log.js +69 -0
  398. package/dist/services/run-log/request-summary.d.ts +76 -0
  399. package/dist/services/run-log/request-summary.js +0 -0
  400. package/dist/services/run-log/run-log.d.ts +61 -0
  401. package/dist/services/run-log/run-log.js +102 -0
  402. package/dist/services/run-log/spec/log-query-service.spec.d.ts +1 -0
  403. package/dist/services/run-log/spec/log-query-service.spec.js +197 -0
  404. package/dist/services/run-log/spec/log-reader.spec.d.ts +1 -0
  405. package/dist/services/run-log/spec/log-reader.spec.js +109 -0
  406. package/dist/services/run-log/spec/log-summary.spec.d.ts +1 -0
  407. package/dist/services/run-log/spec/log-summary.spec.js +153 -0
  408. package/dist/services/run-log/spec/redaction.spec.d.ts +1 -0
  409. package/dist/services/run-log/spec/redaction.spec.js +61 -0
  410. package/dist/services/run-log/spec/request-log.spec.d.ts +1 -0
  411. package/dist/services/run-log/spec/request-log.spec.js +101 -0
  412. package/dist/services/run-log/spec/request-summary.spec.d.ts +1 -0
  413. package/dist/services/run-log/spec/request-summary.spec.js +171 -0
  414. package/dist/services/run-log/spec/run-log.spec.d.ts +1 -0
  415. package/dist/services/run-log/spec/run-log.spec.js +122 -0
  416. package/dist/services/run-registry/exit-classification.d.ts +39 -0
  417. package/dist/services/run-registry/exit-classification.js +42 -0
  418. package/dist/services/run-registry/index.d.ts +3 -0
  419. package/dist/services/run-registry/index.js +3 -0
  420. package/dist/services/run-registry/process-identity.d.ts +28 -0
  421. package/dist/services/run-registry/process-identity.js +80 -0
  422. package/dist/services/run-registry/run-registry-model.d.ts +128 -0
  423. package/dist/services/run-registry/run-registry-model.js +16 -0
  424. package/dist/services/run-registry/run-registry.d.ts +155 -0
  425. package/dist/services/run-registry/run-registry.js +430 -0
  426. package/dist/services/run-registry/spec/exit-classification.spec.d.ts +1 -0
  427. package/dist/services/run-registry/spec/exit-classification.spec.js +82 -0
  428. package/dist/services/run-registry/spec/run-registry.spec.d.ts +1 -0
  429. package/dist/services/run-registry/spec/run-registry.spec.js +526 -0
  430. package/dist/services/setup/os/tool-registry.js +2 -2
  431. package/oclif.manifest.json +3409 -288
  432. package/package.json +20 -2
@@ -0,0 +1,1629 @@
1
+ import { createServer } from "node:net";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { createHash } from "node:crypto";
4
+ import { join } from "node:path";
5
+ import { FILE_TYPE, } from "../../integration-api/index.js";
6
+ import { NoRebuildContextError } from "../file-events/file-watcher.js";
7
+ import { DEFAULT_VARIATION, decodeAssetKey, } from "../request-cache/asset-key.js";
8
+ import { grepText, selectInHtml } from "./body-inspect.js";
9
+ import { BadUrlError, NoBrowserError, NoPageError, CdpCallError, CdpRefusedError, NoSuchElementError, NoSuchTabError, PageEvaluationError, CdpTimeoutError, } from "./browser-session.js";
10
+ import { NoSuchBreakpointError, NotArmedError, NotPausedError, } from "./debug-session.js";
11
+ import { runWatch } from "./watch.js";
12
+ import { NoTriggerError, runNavwalk } from "./navwalk.js";
13
+ import { runFouc } from "./fouc.js";
14
+ import { BadRangeError, runViewportSweep } from "./viewport.js";
15
+ import { BadRecipeParamsError, InjectSourceRequiredError, NoSuchPreloadError, TooManyPreloadsError, UnknownRecipeError, } from "./preload-registry.js";
16
+ import { readRum } from "./rum.js";
17
+ import { explainResponse, hasAssetList } from "./response-explainer.js";
18
+ import { parseRuleSets } from "../../query-builder/rules/index.js";
19
+ import { CONTROL_ERRORS, CONTROL_PROTOCOL_VERSION, CONTROL_SOCKET, } from "./control-protocol.js";
20
+ /** Only the owner. This is an unauthenticated door into a live browser session. */
21
+ const SOCKET_MODE = 0o600;
22
+ /**
23
+ * Bodies are written here rather than sent back.
24
+ *
25
+ * Inside the run directory on purpose: the run's own retention prunes them, and
26
+ * a body from a finished run is still on disk when the post-mortem happens.
27
+ */
28
+ const ARTIFACTS_DIRECTORY = "artifacts";
29
+ /** How many candidates an ambiguous key names before it truncates. */
30
+ const CANDIDATE_LIMIT = 10;
31
+ /** Every place `key` appears in a beacon payload, as a dotted path. */
32
+ function findKey(data, key, path = "", depth = 0) {
33
+ if (!data || typeof data !== "object" || depth > 6) {
34
+ return [];
35
+ }
36
+ const found = [];
37
+ for (const [name, value] of Object.entries(data)) {
38
+ const here = path ? `${path}.${name}` : name;
39
+ if (name === key) {
40
+ found.push({ path: here, value });
41
+ }
42
+ found.push(...findKey(value, key, here, depth + 1));
43
+ }
44
+ return found;
45
+ }
46
+ /** The first list that matched something, so narrower rules win. */
47
+ function firstNonEmpty(...candidates) {
48
+ return candidates.find((list) => list.length > 0) ?? [];
49
+ }
50
+ /** So an artifact opens in an editor as what it is, rather than as html. */
51
+ function extensionFor(name) {
52
+ if (name.includes("orestes-config") || name.includes("json")) {
53
+ return "json";
54
+ }
55
+ return "js";
56
+ }
57
+ /**
58
+ * `decodeURI`, but a malformed escape returns the text rather than throwing.
59
+ *
60
+ * The collector encoded it, so it should always be valid — but a config file
61
+ * is customer-written, and a tool that throws on a stray `%` in a TODO would
62
+ * take out the whole list for one comment.
63
+ */
64
+ /** A body that cannot be read is an absent asset list, not a failed call. */
65
+ function safeRead(path) {
66
+ try {
67
+ return readFileSync(path, "utf8");
68
+ }
69
+ catch {
70
+ return "";
71
+ }
72
+ }
73
+ function safeDecode(text) {
74
+ try {
75
+ return decodeURI(text);
76
+ }
77
+ catch {
78
+ return text;
79
+ }
80
+ }
81
+ /**
82
+ * Ops that change what another caller would observe.
83
+ *
84
+ * These are the ones that take the run-wide queue. The list is by op except for
85
+ * one case that has to read the request: `rum.get` is a read until `flush` is
86
+ * set, and a flush ends the page impression being measured — which is a
87
+ * mutation of the most expensive kind, because the thing it destroys is the
88
+ * measurement someone else is in the middle of taking.
89
+ */
90
+ const MUTATING_OPS = new Set([
91
+ "cache.prewarm",
92
+ "cache.clear",
93
+ "cache.evict",
94
+ "cache.refresh",
95
+ "files.rebuild",
96
+ "browser.reset",
97
+ "browser.reinstall-sw",
98
+ "browser.navigate",
99
+ // Opening DevTools changes what a load does: a panel switch left lit pauses
100
+ // every load, and "Disable cache" applies, only while DevTools is open.
101
+ "browser.panel",
102
+ // Anything at all: a raw CDP call is as sharp as arbitrary JavaScript.
103
+ "cdp",
104
+ // A click is a visitor's action: a cart, a consent, a navigation.
105
+ "browser.click",
106
+ // The page is laid out, detected and served as another device from here on,
107
+ // and loaded again: every later measurement is of a different device.
108
+ "browser.emulate",
109
+ // A preload changes what every later navigation does, which is the widest
110
+ // blast radius on this list — it outlives the call, survives reloads, and is
111
+ // invisible to anyone who did not add it.
112
+ "inject.add",
113
+ "inject.remove",
114
+ "inject.clear",
115
+ // Arming installs a script and may reload; resuming and stepping move a page
116
+ // that another caller may be reading. `debug.eval` is here because arbitrary
117
+ // JavaScript is the widest mutation there is, even when it is usually a read.
118
+ "debug.arm",
119
+ "debug.disarm",
120
+ // Resumes a pause someone else is sitting in, and clears switches a person
121
+ // lit in the panel: the one op here that undoes a human's state, not an
122
+ // agent's.
123
+ "debug.release",
124
+ "debug.resume",
125
+ "debug.step",
126
+ "debug.eval",
127
+ // Injects a sampler and often reloads. It is also the slowest op on the
128
+ // socket, which is the other reason nothing else should interleave with it.
129
+ "watch",
130
+ // All three drive the page — a click into a login flow, two reloads, a
131
+ // viewport pinned to a width — and all three take long enough that anything
132
+ // interleaved would be measuring a different page than it thinks.
133
+ "navwalk",
134
+ "fouc",
135
+ "viewport",
136
+ ]);
137
+ function mutates(request) {
138
+ if (request.op === "rum.get") {
139
+ return Boolean(request.flush);
140
+ }
141
+ return MUTATING_OPS.has(request.op);
142
+ }
143
+ /** Lets a handler name the wire code its failure should carry. */
144
+ class ControlHandlerError extends Error {
145
+ code;
146
+ detail;
147
+ constructor(code, detail) {
148
+ super(detail.message);
149
+ this.code = code;
150
+ this.detail = detail;
151
+ }
152
+ }
153
+ /**
154
+ * Serves the control protocol on a unix socket inside the run directory.
155
+ *
156
+ * A unix socket rather than a TCP port, and 0600 rather than anything wider:
157
+ * what is on the other side of this is a live browser session with the
158
+ * customer's credentials in it. A local port is an unauthenticated RPC into
159
+ * that for every process on the machine.
160
+ */
161
+ export class ControlServer {
162
+ runDirectory;
163
+ runId;
164
+ collaborators;
165
+ server;
166
+ generation = 0;
167
+ connections = new Set();
168
+ /**
169
+ * One queue per run for the ops that change something.
170
+ *
171
+ * The per-connection queue below keeps one caller's requests in order, which
172
+ * is what stops a `browser.state` answering from before the `browser.reset`
173
+ * that preceded it. It says nothing about two callers, and two is not
174
+ * hypothetical: a run is asked from as many terminals and agents as are
175
+ * open. A `browser.reset` interleaved with a
176
+ * `cache.prewarm` leaves a half-built comparison that nothing reports as
177
+ * such.
178
+ *
179
+ * Reads stay concurrent, deliberately. They are the common case and the
180
+ * expensive ones wait on CDP; serialising them would make one slow read block
181
+ * every other caller for no correctness gain.
182
+ */
183
+ mutations = Promise.resolve();
184
+ constructor(runDirectory, runId, collaborators) {
185
+ this.runDirectory = runDirectory;
186
+ this.runId = runId;
187
+ this.collaborators = collaborators;
188
+ }
189
+ get socketPath() {
190
+ return join(this.runDirectory, CONTROL_SOCKET);
191
+ }
192
+ /**
193
+ * Start listening, and stop when the run does.
194
+ *
195
+ * Tied to the signal the onboarding run already threads through, so the
196
+ * socket cannot outlive the thing it controls.
197
+ */
198
+ async listen(signal) {
199
+ this.removeStaleSocket();
200
+ this.server = createServer((socket) => this.accept(socket));
201
+ await new Promise((resolve, reject) => {
202
+ this.server.once("error", reject);
203
+ this.server.listen(this.socketPath, () => {
204
+ this.server.off("error", reject);
205
+ resolve();
206
+ });
207
+ });
208
+ chmodSync(this.socketPath, SOCKET_MODE);
209
+ signal.addEventListener("abort", () => void this.close(), { once: true });
210
+ // `close()` is async, and a run that ends on a signal can exit before it
211
+ // finishes — leaving a live-looking socket in a dead run's directory. This
212
+ // is synchronous, so it lands whatever the exit path.
213
+ process.once("exit", this.unlinkOnExit);
214
+ }
215
+ /** Bound once, so it can be removed again rather than leaking per run. */
216
+ unlinkOnExit = () => this.removeStaleSocket();
217
+ async close() {
218
+ process.off("exit", this.unlinkOnExit);
219
+ for (const socket of this.connections) {
220
+ socket.destroy();
221
+ }
222
+ this.connections.clear();
223
+ await new Promise((resolve) => {
224
+ if (!this.server) {
225
+ resolve();
226
+ return;
227
+ }
228
+ this.server.close(() => resolve());
229
+ });
230
+ this.removeStaleSocket();
231
+ }
232
+ /** Bumped by any op that changes what a reader would observe. */
233
+ bumpGeneration() {
234
+ this.generation += 1;
235
+ return this.generation;
236
+ }
237
+ accept(socket) {
238
+ this.connections.add(socket);
239
+ socket.on("close", () => this.connections.delete(socket));
240
+ // A peer that goes away mid-request is ordinary, not an incident.
241
+ socket.on("error", () => socket.destroy());
242
+ let greeted = false;
243
+ let buffer = "";
244
+ /**
245
+ * One request at a time, in the order they arrived.
246
+ *
247
+ * Handlers are async — a browser op waits on CDP — and dispatching them as
248
+ * the lines arrive let a later request answer first. That is not merely
249
+ * untidy: a caller that sends `browser.reset` and then `browser.state`
250
+ * would get the state from *before* the reset, carrying the generation
251
+ * from before it too, and the correlation id would match so nothing would
252
+ * look wrong. The generation counter exists to catch exactly that class of
253
+ * stale reading, and it cannot catch one the server itself created.
254
+ */
255
+ let queue = Promise.resolve();
256
+ socket.on("data", (chunk) => {
257
+ buffer += chunk.toString();
258
+ // Newline-delimited JSON: one frame per line, so a partial read simply
259
+ // waits rather than corrupting the next request.
260
+ let newline = buffer.indexOf("\n");
261
+ while (newline !== -1) {
262
+ const line = buffer.slice(0, newline);
263
+ buffer = buffer.slice(newline + 1);
264
+ newline = buffer.indexOf("\n");
265
+ if (line.trim()) {
266
+ queue = queue.then(async () => {
267
+ greeted = await this.handleLine(socket, line, greeted);
268
+ });
269
+ }
270
+ }
271
+ });
272
+ }
273
+ /** @returns whether the connection has completed its handshake. */
274
+ async handleLine(socket, line, greeted) {
275
+ let request;
276
+ try {
277
+ request = JSON.parse(line);
278
+ }
279
+ catch {
280
+ this.reply(socket, {
281
+ id: "unknown",
282
+ status: "error",
283
+ generation: this.generation,
284
+ error: {
285
+ code: CONTROL_ERRORS.malformed,
286
+ message: "expected one JSON object per line",
287
+ },
288
+ });
289
+ return greeted;
290
+ }
291
+ if (request.op === "hello") {
292
+ this.replyToHello(socket, request);
293
+ return request.version === CONTROL_PROTOCOL_VERSION;
294
+ }
295
+ if (!greeted) {
296
+ // Version skew is real — `sk` gets upgraded while a run from the previous
297
+ // build is still going — so no op runs until both sides have agreed what
298
+ // the words mean.
299
+ this.reply(socket, {
300
+ id: request.id,
301
+ status: "error",
302
+ generation: this.generation,
303
+ error: {
304
+ code: CONTROL_ERRORS.helloRequired,
305
+ message: "send `hello` before anything else",
306
+ version: CONTROL_PROTOCOL_VERSION,
307
+ },
308
+ });
309
+ return greeted;
310
+ }
311
+ if (mutates(request)) {
312
+ await this.serialize(() => this.dispatch(socket, request));
313
+ }
314
+ else {
315
+ await this.dispatch(socket, request);
316
+ }
317
+ return greeted;
318
+ }
319
+ /**
320
+ * Run this after every mutation already queued, whatever became of them.
321
+ *
322
+ * `then(work, work)` rather than `then(work)`: a failed mutation must not
323
+ * strand every mutation behind it, and `dispatch` answers its own errors
324
+ * anyway. The chain is reduced to a settled promise before it is stored, so a
325
+ * rejection cannot surface later as an unhandled one.
326
+ */
327
+ serialize(work) {
328
+ const next = this.mutations.then(work, work);
329
+ this.mutations = next.then(() => undefined, () => undefined);
330
+ return next;
331
+ }
332
+ replyToHello(socket, request) {
333
+ if (request.version !== CONTROL_PROTOCOL_VERSION) {
334
+ this.reply(socket, {
335
+ id: request.id,
336
+ status: "error",
337
+ generation: this.generation,
338
+ error: {
339
+ code: CONTROL_ERRORS.versionMismatch,
340
+ message: `this run speaks control protocol ${CONTROL_PROTOCOL_VERSION}, the caller speaks ${request.version}`,
341
+ version: CONTROL_PROTOCOL_VERSION,
342
+ },
343
+ });
344
+ return;
345
+ }
346
+ const data = {
347
+ pid: process.pid,
348
+ runId: this.runId,
349
+ version: CONTROL_PROTOCOL_VERSION,
350
+ };
351
+ this.reply(socket, {
352
+ id: request.id,
353
+ status: "ok",
354
+ generation: this.generation,
355
+ data,
356
+ });
357
+ }
358
+ async dispatch(socket, request) {
359
+ try {
360
+ switch (request.op) {
361
+ case "cache.get": {
362
+ this.reply(socket, {
363
+ id: request.id,
364
+ status: "ok",
365
+ generation: this.generation,
366
+ data: this.getCacheEntry(request),
367
+ });
368
+ return;
369
+ }
370
+ case "rum.beacons": {
371
+ this.reply(socket, {
372
+ id: request.id,
373
+ status: "ok",
374
+ generation: this.generation,
375
+ data: this.readBeacons(request),
376
+ });
377
+ return;
378
+ }
379
+ case "rum.get":
380
+ case "rum.key":
381
+ case "rum.previous": {
382
+ this.reply(socket, {
383
+ id: request.id,
384
+ status: "ok",
385
+ generation: this.generation,
386
+ data: await this.readRum(request),
387
+ });
388
+ return;
389
+ }
390
+ case "files.list": {
391
+ this.reply(socket, {
392
+ id: request.id,
393
+ status: "ok",
394
+ generation: this.generation,
395
+ data: this.listFiles(),
396
+ });
397
+ return;
398
+ }
399
+ case "files.read": {
400
+ this.reply(socket, {
401
+ id: request.id,
402
+ status: "ok",
403
+ generation: this.generation,
404
+ data: this.readFile(request),
405
+ });
406
+ return;
407
+ }
408
+ case "cache.prewarm": {
409
+ const data = await this.prewarmCache(request);
410
+ // A mutating op, so the same rule the browser ops follow: bumped
411
+ // after, because a reader comparing generations is asking whether
412
+ // anything changed and a call that built nothing changed nothing.
413
+ this.reply(socket, {
414
+ id: request.id,
415
+ status: "ok",
416
+ generation: data.entries.some((entry) => entry.built)
417
+ ? this.bumpGeneration()
418
+ : this.generation,
419
+ data,
420
+ });
421
+ return;
422
+ }
423
+ case "cache.list": {
424
+ this.reply(socket, {
425
+ id: request.id,
426
+ status: "ok",
427
+ generation: this.generation,
428
+ data: this.listCache(),
429
+ });
430
+ return;
431
+ }
432
+ case "cache.errors": {
433
+ this.reply(socket, {
434
+ id: request.id,
435
+ status: "ok",
436
+ generation: this.generation,
437
+ data: this.listCacheErrors(),
438
+ });
439
+ return;
440
+ }
441
+ case "cache.clear": {
442
+ const data = this.clearCache();
443
+ this.reply(socket, {
444
+ id: request.id,
445
+ status: "ok",
446
+ // Same rule as the other mutating ops: bumped only when something
447
+ // actually changed, so a caller comparing generations across a
448
+ // clear of an already-empty cache is not told its measurements
449
+ // went stale when they did not.
450
+ generation: data.cleared > 0 ? this.bumpGeneration() : this.generation,
451
+ data,
452
+ });
453
+ return;
454
+ }
455
+ case "cache.evict": {
456
+ const data = this.evictCache(request);
457
+ this.reply(socket, {
458
+ id: request.id,
459
+ status: "ok",
460
+ generation: data.removed.length > 0 ? this.bumpGeneration() : this.generation,
461
+ data,
462
+ });
463
+ return;
464
+ }
465
+ case "cache.refresh": {
466
+ const data = await this.refreshCache(request);
467
+ // A rebuild replaces every entry it touched, whether or not the bytes
468
+ // differ — so anything holding a `bodyPath` from before is reading a
469
+ // file that has since been rewritten.
470
+ this.reply(socket, {
471
+ id: request.id,
472
+ status: "ok",
473
+ generation: data.entries.length > 0 ? this.bumpGeneration() : this.generation,
474
+ data,
475
+ });
476
+ return;
477
+ }
478
+ case "files.rebuild": {
479
+ const data = await this.rebuildFiles(request);
480
+ this.reply(socket, {
481
+ id: request.id,
482
+ status: "ok",
483
+ generation: this.bumpGeneration(),
484
+ data,
485
+ });
486
+ return;
487
+ }
488
+ case "files.validate": {
489
+ this.reply(socket, {
490
+ id: request.id,
491
+ status: "ok",
492
+ generation: this.generation,
493
+ data: this.validateFiles(),
494
+ });
495
+ return;
496
+ }
497
+ case "config.runtime": {
498
+ this.reply(socket, {
499
+ id: request.id,
500
+ status: "ok",
501
+ generation: this.generation,
502
+ data: this.readRuntimeConfig(),
503
+ });
504
+ return;
505
+ }
506
+ case "response.explain": {
507
+ this.reply(socket, {
508
+ id: request.id,
509
+ status: "ok",
510
+ generation: this.generation,
511
+ data: await this.explainResponse(request),
512
+ });
513
+ return;
514
+ }
515
+ case "todo.list": {
516
+ this.reply(socket, {
517
+ id: request.id,
518
+ status: "ok",
519
+ generation: this.generation,
520
+ data: this.listTodos(),
521
+ });
522
+ return;
523
+ }
524
+ case "browser.emulate": {
525
+ const data = await (await this.browser(request)).emulate(request);
526
+ this.reply(socket, {
527
+ id: request.id,
528
+ status: "ok",
529
+ generation: this.bumpGeneration(),
530
+ data,
531
+ });
532
+ return;
533
+ }
534
+ case "browser.click": {
535
+ const browser = await this.browser(request);
536
+ const data = await browser.click(request);
537
+ this.reply(socket, {
538
+ id: request.id,
539
+ status: "ok",
540
+ generation: this.bumpGeneration(),
541
+ data,
542
+ });
543
+ return;
544
+ }
545
+ case "browser.tabs": {
546
+ this.reply(socket, {
547
+ id: request.id,
548
+ status: "ok",
549
+ generation: this.generation,
550
+ data: {
551
+ tabs: await (await this.browser({ ...request, tab: undefined })).tabs(),
552
+ },
553
+ });
554
+ return;
555
+ }
556
+ case "cdp": {
557
+ const browser = await this.browser(request);
558
+ // Announced like an injection: a raw CDP call can change anything,
559
+ // and the person watching the run's terminal is the one who would
560
+ // otherwise never know.
561
+ this.collaborators.cli.comment(`an agent sent ${request.method} over CDP to ${browser.url() ?? "the page"}`);
562
+ this.reply(socket, {
563
+ id: request.id,
564
+ status: "ok",
565
+ generation: this.bumpGeneration(),
566
+ data: await browser.rawCdp(request.method, request.params),
567
+ });
568
+ return;
569
+ }
570
+ case "browser.screenshot": {
571
+ this.reply(socket, {
572
+ id: request.id,
573
+ status: "ok",
574
+ generation: this.generation,
575
+ data: await this.takeScreenshot(request),
576
+ });
577
+ return;
578
+ }
579
+ case "browser.state": {
580
+ this.reply(socket, {
581
+ id: request.id,
582
+ status: "ok",
583
+ generation: this.generation,
584
+ data: await (await this.browser(request)).state(),
585
+ });
586
+ return;
587
+ }
588
+ case "inject.recipes": {
589
+ this.reply(socket, {
590
+ id: request.id,
591
+ status: "ok",
592
+ generation: this.generation,
593
+ data: (await this.preloads(request)).recipes(),
594
+ });
595
+ return;
596
+ }
597
+ case "inject.list": {
598
+ this.reply(socket, {
599
+ id: request.id,
600
+ status: "ok",
601
+ generation: this.generation,
602
+ data: await (await this.preloads(request)).list(),
603
+ });
604
+ return;
605
+ }
606
+ case "inject.read": {
607
+ this.reply(socket, {
608
+ id: request.id,
609
+ status: "ok",
610
+ generation: this.generation,
611
+ data: await (await this.preloads(request)).read(request.preload, request.limit),
612
+ });
613
+ return;
614
+ }
615
+ case "inject.add": {
616
+ const data = await (await this.preloads(request)).add(request);
617
+ this.announceInjection(data);
618
+ this.reply(socket, {
619
+ id: request.id,
620
+ status: "ok",
621
+ generation: this.bumpGeneration(),
622
+ data,
623
+ });
624
+ return;
625
+ }
626
+ case "inject.remove":
627
+ case "inject.clear": {
628
+ const preloads = await this.preloads(request);
629
+ const data = request.op === "inject.clear"
630
+ ? await preloads.clear()
631
+ : await preloads.remove(request.preload);
632
+ if (data.removed.length > 0) {
633
+ this.collaborators.cli.note(`an agent removed ${data.removed.length} injected preload${data.removed.length === 1 ? "" : "s"} from this run (${data.removed.join(", ")})`);
634
+ }
635
+ this.reply(socket, {
636
+ id: request.id,
637
+ status: "ok",
638
+ // Same rule as the other mutating ops: bumped only when something
639
+ // actually changed.
640
+ generation: data.removed.length > 0 ? this.bumpGeneration() : this.generation,
641
+ data,
642
+ });
643
+ return;
644
+ }
645
+ case "debug.arm": {
646
+ const data = await (await this.browser(request)).debug.arm(request.bps, request.then, request.compared);
647
+ this.collaborators.cli.writeWarning(`an agent armed BP${data.armed.join(", BP")} on this run — the page will pause at the Speed Kit lifecycle marks until it is disarmed`);
648
+ this.reply(socket, {
649
+ id: request.id,
650
+ status: "ok",
651
+ generation: this.bumpGeneration(),
652
+ data,
653
+ });
654
+ return;
655
+ }
656
+ case "debug.status": {
657
+ this.reply(socket, {
658
+ id: request.id,
659
+ status: "ok",
660
+ generation: this.generation,
661
+ data: await (await this.browser(request)).debug.status(),
662
+ });
663
+ return;
664
+ }
665
+ case "debug.await": {
666
+ // Deliberately not a mutation: it waits, and queueing a wait would
667
+ // hold every other caller's mutation for the length of the timeout.
668
+ this.reply(socket, {
669
+ id: request.id,
670
+ status: "ok",
671
+ generation: this.generation,
672
+ data: await (await this.browser(request)).debug.awaitPause(request.timeoutMs),
673
+ });
674
+ return;
675
+ }
676
+ case "debug.eval": {
677
+ this.reply(socket, {
678
+ id: request.id,
679
+ status: "ok",
680
+ generation: this.generation,
681
+ data: await (await this.browser(request)).debug.evaluate(request.expression),
682
+ });
683
+ return;
684
+ }
685
+ case "debug.release": {
686
+ const data = await (await this.browser(request)).debug.release();
687
+ // In the terminal because the pause it ended may have been a
688
+ // developer's, deliberately — and they are the one person who would
689
+ // otherwise never learn why the page moved on.
690
+ this.collaborators.cli.writeWarning(`an agent released the page: ${data.did}`);
691
+ this.reply(socket, {
692
+ id: request.id,
693
+ status: "ok",
694
+ generation: this.bumpGeneration(),
695
+ data,
696
+ });
697
+ return;
698
+ }
699
+ case "debug.disarm":
700
+ case "debug.resume":
701
+ case "debug.step": {
702
+ const debug = (await this.browser(request)).debug;
703
+ const data = request.op === "debug.disarm"
704
+ ? await debug.disarm()
705
+ : request.op === "debug.resume"
706
+ ? await debug.resume()
707
+ : await debug.step(request.kind);
708
+ this.reply(socket, {
709
+ id: request.id,
710
+ status: "ok",
711
+ generation: this.bumpGeneration(),
712
+ data,
713
+ });
714
+ return;
715
+ }
716
+ case "watch": {
717
+ const browser = await this.browser(request);
718
+ const data = await runWatch(browser.preloads, () => browser.reload(), request);
719
+ this.reply(socket, {
720
+ id: request.id,
721
+ status: "ok",
722
+ // A watch that reloaded changed what everyone else is looking at;
723
+ // one that only sampled put the page back as it found it.
724
+ generation: data.reloaded ? this.bumpGeneration() : this.generation,
725
+ data,
726
+ });
727
+ return;
728
+ }
729
+ case "navwalk": {
730
+ this.reply(socket, {
731
+ id: request.id,
732
+ status: "ok",
733
+ generation: this.bumpGeneration(),
734
+ data: await runNavwalk(await this.browser(request), {
735
+ ...request,
736
+ knownPages: this.cachedPages(),
737
+ }),
738
+ });
739
+ return;
740
+ }
741
+ case "fouc": {
742
+ const browser = await this.browser(request);
743
+ this.reply(socket, {
744
+ id: request.id,
745
+ status: "ok",
746
+ generation: this.bumpGeneration(),
747
+ data: await runFouc(browser.preloads, () => browser.reload(), request),
748
+ });
749
+ return;
750
+ }
751
+ case "viewport": {
752
+ this.reply(socket, {
753
+ id: request.id,
754
+ status: "ok",
755
+ generation: this.bumpGeneration(),
756
+ data: await this.sweepViewport(request),
757
+ });
758
+ return;
759
+ }
760
+ case "browser.reset":
761
+ case "browser.reinstall-sw":
762
+ case "browser.navigate":
763
+ case "browser.panel": {
764
+ const data = await this.mutateBrowser(request);
765
+ // Bumped after the op, not before: a reader comparing generations is
766
+ // asking "did anything change since my last measurement", and a
767
+ // failed op changed nothing.
768
+ this.reply(socket, {
769
+ id: request.id,
770
+ status: "ok",
771
+ generation: this.bumpGeneration(),
772
+ data,
773
+ });
774
+ return;
775
+ }
776
+ default: {
777
+ this.reply(socket, {
778
+ id: request.id,
779
+ status: "error",
780
+ generation: this.generation,
781
+ error: {
782
+ code: CONTROL_ERRORS.unknownOp,
783
+ message: `no such op: ${request.op}`,
784
+ },
785
+ });
786
+ }
787
+ }
788
+ }
789
+ catch (error) {
790
+ if (error instanceof NoPageError ||
791
+ error instanceof PageEvaluationError ||
792
+ error instanceof CdpTimeoutError ||
793
+ error instanceof NoBrowserError ||
794
+ error instanceof BadUrlError ||
795
+ error instanceof NoSuchElementError ||
796
+ error instanceof CdpRefusedError ||
797
+ error instanceof CdpCallError) {
798
+ this.reply(socket, {
799
+ id: request.id,
800
+ status: "error",
801
+ generation: this.generation,
802
+ error: { code: error.code, message: error.message },
803
+ });
804
+ return;
805
+ }
806
+ // The tabs that do exist are the answer to "which did you mean".
807
+ if (error instanceof NoSuchTabError) {
808
+ this.reply(socket, {
809
+ id: request.id,
810
+ status: "error",
811
+ generation: this.generation,
812
+ error: {
813
+ code: error.code,
814
+ message: error.message,
815
+ candidates: error.tabs.map((tab) => `${tab.index} ${tab.url}`),
816
+ next: "Pass --tab with an index or part of a url from the list.",
817
+ },
818
+ });
819
+ return;
820
+ }
821
+ // Every one of these carries the thing the caller needs to fix its next
822
+ // attempt — the recipes that exist, the params one takes, the preloads
823
+ // already registered. A bare code and message would send an agent back
824
+ // to guessing at exactly the point it has been told it guessed wrong.
825
+ if (error instanceof NoSuchPreloadError ||
826
+ error instanceof InjectSourceRequiredError) {
827
+ this.reply(socket, {
828
+ id: request.id,
829
+ status: "error",
830
+ generation: this.generation,
831
+ error: { code: error.code, message: error.message },
832
+ });
833
+ return;
834
+ }
835
+ if (error instanceof UnknownRecipeError) {
836
+ this.reply(socket, {
837
+ id: request.id,
838
+ status: "error",
839
+ generation: this.generation,
840
+ error: {
841
+ code: error.code,
842
+ message: error.message,
843
+ recipes: error.recipes,
844
+ },
845
+ });
846
+ return;
847
+ }
848
+ if (error instanceof BadRecipeParamsError) {
849
+ this.reply(socket, {
850
+ id: request.id,
851
+ status: "error",
852
+ generation: this.generation,
853
+ error: {
854
+ code: error.code,
855
+ message: error.message,
856
+ params: error.params,
857
+ },
858
+ });
859
+ return;
860
+ }
861
+ if (error instanceof NoTriggerError || error instanceof BadRangeError) {
862
+ this.reply(socket, {
863
+ id: request.id,
864
+ status: "error",
865
+ generation: this.generation,
866
+ error: { code: error.code, message: error.message },
867
+ });
868
+ return;
869
+ }
870
+ if (error instanceof NotPausedError || error instanceof NotArmedError) {
871
+ this.reply(socket, {
872
+ id: request.id,
873
+ status: "error",
874
+ generation: this.generation,
875
+ error: { code: error.code, message: error.message },
876
+ });
877
+ return;
878
+ }
879
+ if (error instanceof NoSuchBreakpointError) {
880
+ this.reply(socket, {
881
+ id: request.id,
882
+ status: "error",
883
+ generation: this.generation,
884
+ error: {
885
+ code: error.code,
886
+ message: error.message,
887
+ breakpoints: error.breakpoints,
888
+ },
889
+ });
890
+ return;
891
+ }
892
+ if (error instanceof TooManyPreloadsError) {
893
+ this.reply(socket, {
894
+ id: request.id,
895
+ status: "error",
896
+ generation: this.generation,
897
+ error: {
898
+ code: error.code,
899
+ message: error.message,
900
+ registered: error.registered,
901
+ },
902
+ });
903
+ return;
904
+ }
905
+ const known = error instanceof ControlHandlerError;
906
+ this.reply(socket, {
907
+ id: request.id,
908
+ status: "error",
909
+ generation: this.generation,
910
+ error: known
911
+ ? { ...error.detail, code: error.code }
912
+ : {
913
+ code: CONTROL_ERRORS.handlerFailed,
914
+ message: error instanceof Error ? error.message : String(error),
915
+ },
916
+ });
917
+ }
918
+ }
919
+ listCache() {
920
+ const entries = [...this.collaborators.cache.getAll()].map(([key, entry]) => {
921
+ const { originUrl, variation } = decodeAssetKey(key);
922
+ return {
923
+ key,
924
+ originUrl,
925
+ variation,
926
+ status: entry.status,
927
+ contentType: entry.contentType,
928
+ bytes: entry.bytes,
929
+ };
930
+ });
931
+ return { entries };
932
+ }
933
+ /**
934
+ * One entry, by exact key or by an origin url that names exactly one.
935
+ *
936
+ * Matching by substring is what `Cache.removeEntry` does and it surprises
937
+ * people, so here an ambiguous key is an error listing what it matched rather
938
+ * than a silent pick of the first.
939
+ */
940
+ getCacheEntry(request) {
941
+ // A variation narrows before anything matches, so an origin url plus a
942
+ // variation names one entry without the caller ever handling a cache key.
943
+ const wanted = request.variation === "default" ? null : (request.variation ?? undefined);
944
+ const all = [...this.collaborators.cache.getAll()].filter(([key]) => wanted === undefined || decodeAssetKey(key).variation === wanted);
945
+ // Narrowest first. A site's homepage is a prefix of every url on the site,
946
+ // so a substring search for it matches the whole cache and the entry can
947
+ // never be asked for by its own origin url — the one thing a caller has in
948
+ // hand. Exact origin url is tried before substring for exactly that.
949
+ const matched = firstNonEmpty(all.filter(([key]) => key === request.key), all.filter(([key]) => decodeAssetKey(key).originUrl === request.key), all.filter(([key]) => key.includes(request.key)));
950
+ if (matched.length === 0) {
951
+ throw new ControlHandlerError(CONTROL_ERRORS.noSuchEntry, {
952
+ message: `nothing cached for "${request.key}"${request.variation ? ` in variation ${request.variation}` : ""}`,
953
+ cached: all.length,
954
+ });
955
+ }
956
+ if (matched.length > 1) {
957
+ const candidates = matched.slice(0, CANDIDATE_LIMIT).map(([key]) => key);
958
+ const variations = [
959
+ ...new Set(matched.map(([key]) => decodeAssetKey(key).variation ?? "default")),
960
+ ];
961
+ const urls = new Set(matched.map(([key]) => decodeAssetKey(key).originUrl));
962
+ throw new ControlHandlerError(CONTROL_ERRORS.ambiguousEntry, {
963
+ message: `"${request.key}" matches ${matched.length} entries`,
964
+ candidates,
965
+ variations,
966
+ // One url in several variations is settled by naming the variation;
967
+ // several urls need the narrower url, or a key from the list.
968
+ next: urls.size === 1
969
+ ? `Name the variation: --variation ${variations.join(" | ")}.`
970
+ : "Pass a narrower url, or one of the keys above.",
971
+ // Said out loud, the way `select` and `grep` say it. A list that is
972
+ // shorter than the count without saying so reads as the whole list.
973
+ truncated: matched.length > candidates.length,
974
+ total: matched.length,
975
+ });
976
+ }
977
+ const [key, entry] = matched[0];
978
+ const { originUrl, variation } = decodeAssetKey(key);
979
+ // The body is already on disk, written when it was cached — nothing to
980
+ // decode and nothing to copy. It is only read when something was asked
981
+ // *about* it, so a plain `get` costs no I/O at all.
982
+ const body = request.select || request.grep ? readFileSync(entry.path, "utf8") : "";
983
+ return {
984
+ key,
985
+ originUrl,
986
+ variation,
987
+ status: entry.status,
988
+ contentType: entry.contentType,
989
+ bytes: entry.bytes,
990
+ bodySha: entry.sha,
991
+ bodyPath: entry.path,
992
+ select: request.select
993
+ ? selectInHtml(body, request.select, request.maxMatches)
994
+ : undefined,
995
+ grep: request.grep
996
+ ? grepText(body, request.grep, request.maxMatches)
997
+ : undefined,
998
+ };
999
+ }
1000
+ /**
1001
+ * A caller's url against the origin this run is driving.
1002
+ *
1003
+ * Normalised the way `@speedkit/rules`' own `destructURL` does, so a base
1004
+ * without a scheme cannot take the whole op down. `new URL(input, base)`
1005
+ * parses the base first and throws when it is not absolute — even when the
1006
+ * input is — and the thrown error says nothing about which of the two was at
1007
+ * fault. That cost a testing session: every url form came back BAD_URL
1008
+ * blaming the url, while the base was a bare hostname.
1009
+ */
1010
+ resolveUrl(input) {
1011
+ const origin = this.collaborators.origin;
1012
+ const base = origin && !/^https?:\/\//.test(origin) ? `https://${origin}` : origin;
1013
+ try {
1014
+ return new URL(input ?? "", base || undefined);
1015
+ }
1016
+ catch {
1017
+ throw new ControlHandlerError(CONTROL_ERRORS.badUrl, {
1018
+ message: base
1019
+ ? `"${input}" is not a url, absolute or relative to ${base}`
1020
+ : `"${input}" is not an absolute url, and this run lent the control socket no origin to resolve it against`,
1021
+ // Said out loud, because the message above used to blame the input for
1022
+ // a base that was wrong.
1023
+ base: base || null,
1024
+ });
1025
+ }
1026
+ }
1027
+ /**
1028
+ * Build cache entries for a url that nothing has requested.
1029
+ *
1030
+ * The gap this closes: the dh-cache only ever fills as a side effect of the
1031
+ * browser asking for a page, and the browser is one device at a time. So the
1032
+ * comparison people actually want — mobile against desktop, or a url with a
1033
+ * parameter against the same url without — could not be set up at all, no
1034
+ * matter how the run was driven.
1035
+ *
1036
+ * Each variation is built independently and reported independently. One
1037
+ * variation failing is a fact about that variation, usually a transform that
1038
+ * throws on it, and it must not cost the caller the ones that worked.
1039
+ */
1040
+ async prewarmCache(request) {
1041
+ const prewarm = this.collaborators.prewarm;
1042
+ if (!prewarm) {
1043
+ throw new ControlHandlerError(CONTROL_ERRORS.noLocalCache, {
1044
+ message: "this run has no local documentHandler to build with — start it with `--local`",
1045
+ });
1046
+ }
1047
+ const url = this.resolveUrl(request.url).toString();
1048
+ // Deduplicated, because two names for one variation would build it twice
1049
+ // and report it twice, and the second build is a second origin request.
1050
+ const variations = [
1051
+ ...new Set(request.all
1052
+ ? this.everyVariation()
1053
+ : request.variations?.length
1054
+ ? request.variations
1055
+ : [DEFAULT_VARIATION]),
1056
+ ];
1057
+ const entries = [];
1058
+ const failed = [];
1059
+ for (const variation of variations) {
1060
+ // Asked before the build, so `built` distinguishes "this call fetched the
1061
+ // origin" from "it was already there" — which is the difference between a
1062
+ // fresh comparison and one of the two halves being minutes old.
1063
+ const before = this.cacheKeysNow();
1064
+ let key;
1065
+ try {
1066
+ key = await prewarm(url, variation);
1067
+ }
1068
+ catch (error) {
1069
+ failed.push({
1070
+ variation,
1071
+ error: error instanceof Error ? error.message : String(error),
1072
+ });
1073
+ continue;
1074
+ }
1075
+ const entry = this.collaborators.cache.getMeta(key);
1076
+ if (!entry) {
1077
+ // The build ran and cached nothing. A redirect and a non-html response
1078
+ // both do this legitimately, so it is reported rather than thrown —
1079
+ // but it is never an entry, and pretending otherwise would hand the
1080
+ // caller a path to a file that does not exist.
1081
+ failed.push({
1082
+ variation,
1083
+ error: `built without caching anything — the origin answered with a redirect, an error or a non-html body (key ${key})`,
1084
+ });
1085
+ continue;
1086
+ }
1087
+ entries.push({
1088
+ key,
1089
+ ...decodeAssetKey(key),
1090
+ status: entry.status,
1091
+ contentType: entry.contentType,
1092
+ bytes: entry.bytes,
1093
+ bodySha: entry.sha,
1094
+ bodyPath: entry.path,
1095
+ built: !before.has(key),
1096
+ alreadyCached: before.has(key),
1097
+ });
1098
+ }
1099
+ if (entries.length === 0 && failed.length > 0) {
1100
+ throw new ControlHandlerError(CONTROL_ERRORS.prewarmFailed, {
1101
+ message: `nothing could be built for ${url}: ${failed.map((one) => `${one.variation} — ${one.error}`).join("; ")}`,
1102
+ url,
1103
+ failed,
1104
+ });
1105
+ }
1106
+ return { url, entries, failed };
1107
+ }
1108
+ /** The keys in the cache right now, for telling a build from a hit. */
1109
+ cacheKeysNow() {
1110
+ return new Set([...this.collaborators.cache.getAll()].map(([key]) => key));
1111
+ }
1112
+ clearCache() {
1113
+ const cleared = [...this.collaborators.cache.getAll()].length;
1114
+ this.collaborators.cache.clear();
1115
+ return { cleared };
1116
+ }
1117
+ /**
1118
+ * Drop entries by key, and report what that actually took.
1119
+ *
1120
+ * `Cache.removeEntry` matches by **substring**, which is the surprise this
1121
+ * op has to surface rather than hide — a site's homepage url is a prefix of
1122
+ * every url on the site, so evicting "the homepage" can empty the cache. The
1123
+ * removal is measured by diffing the key set rather than predicted from the
1124
+ * argument, so the answer is what happened even if that matching changes.
1125
+ */
1126
+ evictCache(request) {
1127
+ const before = this.cacheKeysNow();
1128
+ this.collaborators.cache.removeEntry(request.key);
1129
+ const after = this.cacheKeysNow();
1130
+ const removed = [...before].filter((key) => !after.has(key));
1131
+ if (removed.length === 0) {
1132
+ throw new ControlHandlerError(CONTROL_ERRORS.noSuchEntry, {
1133
+ message: `nothing cached matched "${request.key}"`,
1134
+ cached: before.size,
1135
+ });
1136
+ }
1137
+ return { key: request.key, removed, remaining: after.size };
1138
+ }
1139
+ /**
1140
+ * Rebuild cached entries from the origin, and say whether the bytes moved.
1141
+ *
1142
+ * Built on the same `prewarm` capability rather than on `refreshUrl`: the
1143
+ * run's own refresh is fire-and-forget by design — it exists to keep a page
1144
+ * warm in the background and logs its failures instead of returning them.
1145
+ * The question here is the opposite kind, "did the origin actually change",
1146
+ * and it needs the before and after hashes of every entry it touched.
1147
+ */
1148
+ async refreshCache(request) {
1149
+ const prewarm = this.collaborators.prewarm;
1150
+ if (!prewarm) {
1151
+ throw new ControlHandlerError(CONTROL_ERRORS.noLocalCache, {
1152
+ message: "this run has no local documentHandler to rebuild with — start it with `--local`",
1153
+ });
1154
+ }
1155
+ const all = [...this.collaborators.cache.getAll()];
1156
+ const matched = request.key
1157
+ ? firstNonEmpty(all.filter(([key]) => key === request.key), all.filter(([key]) => decodeAssetKey(key).originUrl === request.key), all.filter(([key]) => key.includes(request.key)))
1158
+ : all;
1159
+ if (matched.length === 0) {
1160
+ throw new ControlHandlerError(CONTROL_ERRORS.noSuchEntry, {
1161
+ message: request.key
1162
+ ? `nothing cached for "${request.key}"`
1163
+ : "nothing is cached, so there is nothing to refresh",
1164
+ cached: all.length,
1165
+ });
1166
+ }
1167
+ const entries = [];
1168
+ const failed = [];
1169
+ for (const [key, before] of matched) {
1170
+ const { originUrl, variation } = decodeAssetKey(key);
1171
+ try {
1172
+ await prewarm(originUrl, variation ?? DEFAULT_VARIATION);
1173
+ }
1174
+ catch (error) {
1175
+ failed.push({
1176
+ variation: variation ?? DEFAULT_VARIATION,
1177
+ error: error instanceof Error ? error.message : String(error),
1178
+ });
1179
+ continue;
1180
+ }
1181
+ const after = this.collaborators.cache.getMeta(key);
1182
+ if (!after) {
1183
+ // The rebuild ran and left nothing behind. `refreshEntry` drops a stale
1184
+ // entry on failure for exactly this reason, so the entry being gone is
1185
+ // a result, not a crash — and reporting it as refreshed would hand back
1186
+ // a path to a file that no longer exists.
1187
+ failed.push({
1188
+ variation: variation ?? DEFAULT_VARIATION,
1189
+ error: `rebuilt without caching anything, and the stale entry was dropped (key ${key})`,
1190
+ });
1191
+ continue;
1192
+ }
1193
+ entries.push({
1194
+ key,
1195
+ originUrl,
1196
+ variation,
1197
+ bodySha: after.sha,
1198
+ bodyPath: after.path,
1199
+ changed: after.sha !== before.sha,
1200
+ previousSha: after.sha !== before.sha ? before.sha : undefined,
1201
+ bytes: after.bytes,
1202
+ status: after.status,
1203
+ });
1204
+ }
1205
+ return {
1206
+ entries,
1207
+ failed,
1208
+ changed: entries.filter((entry) => entry.changed).length,
1209
+ };
1210
+ }
1211
+ listCacheErrors() {
1212
+ const errors = this.collaborators.cacheErrors;
1213
+ if (!errors) {
1214
+ throw new ControlHandlerError(CONTROL_ERRORS.noLocalCache, {
1215
+ message: "this run has no local documentHandler, so it records no build failures — start it with `--local`",
1216
+ });
1217
+ }
1218
+ return { errors: errors() };
1219
+ }
1220
+ async rebuildFiles(request) {
1221
+ const rebuild = this.collaborators.rebuild;
1222
+ if (!rebuild) {
1223
+ throw new ControlHandlerError(CONTROL_ERRORS.noRebuild, {
1224
+ message: "this run has no file watchers wired, so there are no rebuild groups to trigger",
1225
+ });
1226
+ }
1227
+ const target = request.target ?? "all";
1228
+ let steps;
1229
+ try {
1230
+ steps = await rebuild(target);
1231
+ }
1232
+ catch (error) {
1233
+ if (error instanceof NoRebuildContextError) {
1234
+ // Not a failure of the rebuild — the run simply is not far enough along
1235
+ // to have one. "Wait and ask again" is the action, and a HANDLER_FAILED
1236
+ // would not say that.
1237
+ throw new ControlHandlerError(CONTROL_ERRORS.noRebuild, {
1238
+ message: error.message,
1239
+ });
1240
+ }
1241
+ throw error;
1242
+ }
1243
+ return {
1244
+ target,
1245
+ steps,
1246
+ // Lifted out of the prose because it is the fact most likely to
1247
+ // invalidate whatever the caller measured a moment ago.
1248
+ cacheCleared: steps.some((step) => step.target === "documentHandler"),
1249
+ reinstallsServiceWorker: steps.some((step) => step.target === "install"),
1250
+ };
1251
+ }
1252
+ /** Never logged: the config carries the origin's basic-auth passwords. */
1253
+ readRuntimeConfig() {
1254
+ const runtimeConfig = this.collaborators.runtimeConfig;
1255
+ if (!runtimeConfig) {
1256
+ throw new ControlHandlerError(CONTROL_ERRORS.handlerFailed, {
1257
+ message: "this run loads no runtime config",
1258
+ });
1259
+ }
1260
+ return { config: runtimeConfig() ?? null };
1261
+ }
1262
+ validateFiles() {
1263
+ const validate = this.collaborators.validate;
1264
+ if (!validate) {
1265
+ throw new ControlHandlerError(CONTROL_ERRORS.handlerFailed, {
1266
+ message: "this run has no validators wired",
1267
+ });
1268
+ }
1269
+ const problems = validate();
1270
+ return {
1271
+ valid: problems.length === 0,
1272
+ problems,
1273
+ firstProblemPerValidator: true,
1274
+ };
1275
+ }
1276
+ /**
1277
+ * Why a url came back the way it did.
1278
+ *
1279
+ * Three sources, none of which answers alone: the rule sets say what Speed
1280
+ * Kit is *allowed* to do with the url, the cache says whether the
1281
+ * documentHandler has ever handled it, and the page says what actually
1282
+ * happened — but only when the url is the page in front of the run.
1283
+ */
1284
+ async explainResponse(request) {
1285
+ const session = request.tab
1286
+ ? await this.browser(request)
1287
+ : this.collaborators.session;
1288
+ const pageUrl = session?.available ? session.url() : null;
1289
+ const url = this.resolveUrl(request.url ?? pageUrl);
1290
+ if (!this.collaborators.speedKitConfig) {
1291
+ throw new ControlHandlerError(CONTROL_ERRORS.configUnreadable, {
1292
+ message: "this run did not lend its SpeedKit config to the control socket — it is older than this op",
1293
+ });
1294
+ }
1295
+ let rules;
1296
+ try {
1297
+ rules = parseRuleSets(await this.collaborators.speedKitConfig());
1298
+ }
1299
+ catch (error) {
1300
+ // A config that does not evaluate is the answer, not a failure of this
1301
+ // tool: nothing downstream of it works either, and saying so beats a
1302
+ // verdict computed from a config the browser never saw.
1303
+ throw new ControlHandlerError(CONTROL_ERRORS.configUnreadable, {
1304
+ message: `config_SpeedKit did not evaluate: ${error instanceof Error ? error.message : String(error)}`,
1305
+ });
1306
+ }
1307
+ return explainResponse({
1308
+ url,
1309
+ rules,
1310
+ cache: this.cacheFactsFor(url),
1311
+ page: await this.pageFactsFor(url, pageUrl, session),
1312
+ });
1313
+ }
1314
+ /**
1315
+ * What `cache prewarm --all` builds: default, every variation the page has
1316
+ * produced in this run, and every one the runtime config names.
1317
+ *
1318
+ * Not the three device defaults: whether a config ever produces `tablet` is
1319
+ * decided in the browser, and building it for a site that never does is an
1320
+ * SSR build nobody reads. What the cache has seen is evidence; the names are
1321
+ * the config's own.
1322
+ */
1323
+ everyVariation() {
1324
+ const seen = [...this.collaborators.cache.getAll()].map(([key]) => decodeAssetKey(key).variation ?? DEFAULT_VARIATION);
1325
+ return [
1326
+ DEFAULT_VARIATION,
1327
+ ...seen,
1328
+ ...(this.collaborators.variations?.() ?? []),
1329
+ ];
1330
+ }
1331
+ /**
1332
+ * The beacons since a cursor, and with `key` only those that carried it —
1333
+ * with where in the payload and what it said.
1334
+ */
1335
+ readBeacons(request) {
1336
+ if (!this.collaborators.rumBeacons) {
1337
+ throw new ControlHandlerError(CONTROL_ERRORS.browserUnavailable, {
1338
+ message: "this run keeps no beacons — it is older than `rum beacons`, or was started without a local documentHandler",
1339
+ });
1340
+ }
1341
+ const all = this.collaborators.rumBeacons();
1342
+ const lastSeq = all.length ? all[all.length - 1].seq : 0;
1343
+ const since = all.filter((beacon) => beacon.seq > (request.sinceSeq ?? 0));
1344
+ const beacons = request.key
1345
+ ? since
1346
+ .map((beacon) => ({
1347
+ ...beacon,
1348
+ matches: findKey(beacon.data, request.key),
1349
+ }))
1350
+ .filter((beacon) => beacon.matches.length > 0)
1351
+ : since;
1352
+ return { beacons, lastSeq, kept: all.length };
1353
+ }
1354
+ /** The sweep, on the page `url` names when it names one. */
1355
+ async sweepViewport(request) {
1356
+ const browser = await this.browser(request);
1357
+ if (request.url) {
1358
+ await browser.navigate(request.url);
1359
+ }
1360
+ return runViewportSweep(browser, request);
1361
+ }
1362
+ /** Every page the documentHandler has cached: pages known to be accelerated. */
1363
+ cachedPages() {
1364
+ return [
1365
+ ...new Set([...this.collaborators.cache.getAll()].map(([key]) => decodeAssetKey(key).originUrl)),
1366
+ ];
1367
+ }
1368
+ /** The cached entry for this url, when the documentHandler has one. */
1369
+ cacheFactsFor(url) {
1370
+ const matched = [...this.collaborators.cache.getAll()].filter(([key]) => decodeAssetKey(key).originUrl === url.href);
1371
+ if (matched.length === 0) {
1372
+ return undefined;
1373
+ }
1374
+ const [key, entry] = matched[0];
1375
+ return {
1376
+ key,
1377
+ status: entry.status,
1378
+ variation: decodeAssetKey(key).variation,
1379
+ contentType: entry.contentType,
1380
+ bytes: entry.bytes,
1381
+ // Read here rather than reported as a path: whether the asset list is in
1382
+ // the body is the fact that decides how change detection reads, and
1383
+ // making the caller fetch the body to find out defeats the point.
1384
+ assetList: hasAssetList(safeRead(entry.path)),
1385
+ };
1386
+ }
1387
+ /**
1388
+ * What the page reported, but only when it *is* this url.
1389
+ *
1390
+ * Reporting the current page's RUM against a different url would be the
1391
+ * confident wrong answer this whole tool exists to prevent.
1392
+ */
1393
+ async pageFactsFor(url, pageUrl, session) {
1394
+ if (!pageUrl || new URL(pageUrl).href !== url.href) {
1395
+ return undefined;
1396
+ }
1397
+ const rum = await readRum(session, {
1398
+ keys: ["responseSource", "responseCause", "swBooted"],
1399
+ });
1400
+ if (!rum.available) {
1401
+ return { url: pageUrl };
1402
+ }
1403
+ const data = (rum.data ?? {});
1404
+ return {
1405
+ url: pageUrl,
1406
+ responseSource: data.responseSource,
1407
+ responseCause: data.responseCause,
1408
+ swBooted: data.swBooted,
1409
+ };
1410
+ }
1411
+ /**
1412
+ * The open tasks, decoded.
1413
+ *
1414
+ * The collector encodes `context` for the devtools panel's transport;
1415
+ * handing an agent percent-escapes of its own config would be a small lie
1416
+ * about what is in the file.
1417
+ */
1418
+ listTodos() {
1419
+ const tasks = this.collaborators.todos?.getOpenTasks() ?? [];
1420
+ return {
1421
+ tasks: tasks.map((task) => ({
1422
+ todo: task.todo.trim(),
1423
+ context: safeDecode(task.context),
1424
+ file: task.file,
1425
+ line: task.line,
1426
+ })),
1427
+ };
1428
+ }
1429
+ /**
1430
+ * The browser, or the typed reason there is none.
1431
+ *
1432
+ * Same guard as {@link readRum}: a run that has not opened its page yet is an
1433
+ * ordinary state, not a failure, and it deserves a code a caller can branch
1434
+ * on rather than whatever puppeteer throws from a closed target.
1435
+ */
1436
+ /**
1437
+ * The page a request acts on: the run's own, or the tab `tab` names.
1438
+ *
1439
+ * Resolved per request rather than switched for the run, so two callers on
1440
+ * two tabs never see each other's choice.
1441
+ */
1442
+ async browser(request) {
1443
+ const session = this.collaborators.session;
1444
+ if (!session?.available) {
1445
+ throw new ControlHandlerError(CONTROL_ERRORS.noPage, {
1446
+ message: "this run has no page open — it may still be starting, or the browser has gone",
1447
+ });
1448
+ }
1449
+ return request.tab ? session.tab(request.tab) : session;
1450
+ }
1451
+ /**
1452
+ * The preload registry, without requiring a page.
1453
+ *
1454
+ * Unlike every other browser op: a registration outlives the document it was
1455
+ * made against, so listing and removing one has to work between navigations
1456
+ * and after a tab has closed. Adding one still needs a page, and says so from
1457
+ * further in.
1458
+ */
1459
+ async preloads(request) {
1460
+ if (request.tab) {
1461
+ return (await this.browser(request)).preloads;
1462
+ }
1463
+ const session = this.collaborators.session;
1464
+ if (!session) {
1465
+ throw new ControlHandlerError(CONTROL_ERRORS.browserUnavailable, {
1466
+ message: "this run did not lend its browser to the control socket — it is older than the inject ops, or was started without one",
1467
+ });
1468
+ }
1469
+ return session.preloads;
1470
+ }
1471
+ /**
1472
+ * Put an injection on the run's own output.
1473
+ *
1474
+ * The guardrail that matters most on this tool. Everything else an agent does
1475
+ * through the socket is visible in what it changes; an injected script is
1476
+ * visible in nothing, outlives the turn that added it, and silently colours
1477
+ * every measurement taken afterwards. The human watching the terminal is the
1478
+ * only one who can catch that, and they cannot catch what was never printed.
1479
+ */
1480
+ announceInjection(data) {
1481
+ const { id: preload, origin, expiresAt } = data.preload;
1482
+ const what = data.recipe ? `recipe \`${data.recipe}\`` : "raw source";
1483
+ this.collaborators.cli.writeWarning(`an agent injected ${what} into every navigation of this run as ${preload} (${origin}), ${expiresAt ? `expiring ${expiresAt}` : "with no expiry"}. It will colour anything measured from here on.`);
1484
+ }
1485
+ async mutateBrowser(request) {
1486
+ const browser = await this.browser(request);
1487
+ switch (request.op) {
1488
+ case "browser.reset": {
1489
+ return browser.reset(request.scope ?? "cache");
1490
+ }
1491
+ case "browser.reinstall-sw": {
1492
+ return browser.reinstallServiceWorker();
1493
+ }
1494
+ case "browser.panel": {
1495
+ return browser.showPanel();
1496
+ }
1497
+ default: {
1498
+ return browser.navigate(request.url, request.wait, request.waitMs);
1499
+ }
1500
+ }
1501
+ }
1502
+ async readRum(request) {
1503
+ const session = request.tab
1504
+ ? await this.browser(request)
1505
+ : this.collaborators.session;
1506
+ if (!session?.available) {
1507
+ throw new ControlHandlerError(CONTROL_ERRORS.noPage, {
1508
+ message: "this run has no page open — it may still be starting, or the browser has gone",
1509
+ });
1510
+ }
1511
+ return readRum(session, {
1512
+ keys: request.op === "rum.get" ? request.keys : undefined,
1513
+ flush: request.op === "rum.get" ? request.flush : undefined,
1514
+ key: request.op === "rum.key" ? request.key : undefined,
1515
+ previous: request.op === "rum.previous",
1516
+ });
1517
+ }
1518
+ /**
1519
+ * Every file this run knows about, built ones included.
1520
+ *
1521
+ * The logical-name-to-path mapping is not guessable, and half the entries are
1522
+ * optional per customer — so a reader that has to stat paths and guess is
1523
+ * doing the thing this exists to stop.
1524
+ */
1525
+ listFiles() {
1526
+ return {
1527
+ files: this.collaborators.files.files.map((file) => this.describeFile(file)),
1528
+ };
1529
+ }
1530
+ readFile(request) {
1531
+ if (!this.collaborators.files.hasFile(request.name)) {
1532
+ throw new ControlHandlerError(CONTROL_ERRORS.noSuchFile, {
1533
+ message: `this run has no file called "${request.name}"`,
1534
+ available: this.collaborators.files.files.map((file) => file.name),
1535
+ });
1536
+ }
1537
+ const file = this.collaborators.files.getByName(request.name);
1538
+ const content = file.getContent() ?? "";
1539
+ const bodySha = createHash("sha256")
1540
+ .update(content)
1541
+ .digest("hex")
1542
+ .slice(0, 16);
1543
+ return {
1544
+ ...this.describeFile(file),
1545
+ bodySha,
1546
+ bodyPath: this.writeArtifact(bodySha, content, extensionFor(file.name)),
1547
+ grep: request.grep
1548
+ ? grepText(content, request.grep, request.maxMatches)
1549
+ : undefined,
1550
+ };
1551
+ }
1552
+ describeFile(file) {
1553
+ const config = file;
1554
+ let bytes = 0;
1555
+ try {
1556
+ bytes = (file.getContent() ?? "").length;
1557
+ }
1558
+ catch {
1559
+ // A virtual file that has not been built yet has nothing to measure.
1560
+ }
1561
+ return {
1562
+ name: file.name,
1563
+ type: file.type,
1564
+ path: config.path,
1565
+ virtual: file.type === FILE_TYPE.VIRTUAL_FILE,
1566
+ bytes,
1567
+ updated: typeof config.isUpdated === "function" ? config.isUpdated() : undefined,
1568
+ };
1569
+ }
1570
+ /**
1571
+ * A screenshot, written next to the run's other artifacts so the run's
1572
+ * retention prunes it. Named by time and device, not content: two captures of
1573
+ * the same page are two moments, and the name says which device each shows.
1574
+ */
1575
+ async takeScreenshot(request) {
1576
+ const shot = await (await this.browser(request)).screenshot(request);
1577
+ const bytes = Buffer.from(shot.data, "base64");
1578
+ const directory = join(this.runDirectory, ARTIFACTS_DIRECTORY, "screenshots");
1579
+ mkdirSync(directory, { recursive: true });
1580
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
1581
+ const path = join(directory, `${stamp}-${shot.emulation?.device ?? "window"}.png`);
1582
+ writeFileSync(path, bytes);
1583
+ return {
1584
+ path,
1585
+ url: (await this.browser(request)).url(),
1586
+ width: shot.width,
1587
+ height: shot.height,
1588
+ bytes: bytes.length,
1589
+ fullPage: Boolean(request.fullPage),
1590
+ selector: request.selector ?? null,
1591
+ emulation: shot.emulation,
1592
+ };
1593
+ }
1594
+ /** Content-addressed, so reading the same body twice does not write it twice. */
1595
+ writeArtifact(sha, body, extension = "html") {
1596
+ const directory = join(this.runDirectory, ARTIFACTS_DIRECTORY);
1597
+ mkdirSync(directory, { recursive: true });
1598
+ const path = join(directory, `${sha}.${extension}`);
1599
+ if (!existsSync(path)) {
1600
+ writeFileSync(path, body);
1601
+ }
1602
+ return path;
1603
+ }
1604
+ contentTypeOf(headers) {
1605
+ return (headers?.find((header) => header.name.toLowerCase() === "content-type")
1606
+ ?.value ?? null);
1607
+ }
1608
+ reply(socket, response) {
1609
+ if (socket.destroyed) {
1610
+ return;
1611
+ }
1612
+ socket.write(`${JSON.stringify(response)}\n`);
1613
+ }
1614
+ /**
1615
+ * A socket file outlives the process that made it, so binding fails with
1616
+ * EADDRINUSE against a run that is long gone. The run directory is per-pid,
1617
+ * so anything here belongs to this run's own id and is safe to clear.
1618
+ */
1619
+ removeStaleSocket() {
1620
+ try {
1621
+ if (existsSync(this.socketPath)) {
1622
+ unlinkSync(this.socketPath);
1623
+ }
1624
+ }
1625
+ catch {
1626
+ // if it cannot be removed, listen() will say so with a better message
1627
+ }
1628
+ }
1629
+ }