rvlib-shipkit 2.12.0 → 2.13.0

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 (290) hide show
  1. package/CHANGELOG.md +48 -13
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +7 -5
  20. package/src/cli/cmd_Review.ts +4 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +5 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +53 -4
  68. package/src/home/inbox.ts +16 -1
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +104 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +2 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/daemon.ts +56 -70
  100. package/src/media-store/put.ts +4 -2
  101. package/src/media-store/space.ts +23 -4
  102. package/src/pages/forward.ts +35 -0
  103. package/src/pages/frame-client.ts +118 -0
  104. package/src/pages/routes.ts +29 -0
  105. package/src/pages/unit.ts +92 -0
  106. package/src/plan/planner.ts +12 -0
  107. package/src/plan/repo-source.ts +19 -5
  108. package/src/reflect/transcript.ts +35 -10
  109. package/src/release/public-clean.ts +301 -0
  110. package/src/release/published-here.ts +22 -0
  111. package/src/release/run-bump.ts +2 -1
  112. package/src/release/run-release.ts +4 -1
  113. package/src/repo-config.ts +53 -2
  114. package/src/review/http.ts +16 -2
  115. package/src/review/model.ts +15 -4
  116. package/src/review/notes.ts +77 -0
  117. package/src/review/project.ts +6 -38
  118. package/src/review/routes.ts +4 -12
  119. package/src/review/store.ts +41 -1
  120. package/src/review/trailer-media.ts +7 -4
  121. package/src/review/trailer-shots.ts +21 -4
  122. package/src/review/unit.ts +1 -1
  123. package/src/scaffold/files/agent-handoff.md +3 -0
  124. package/src/scaffold/files/agent-index.md +4 -12
  125. package/src/scaffold/project-scaffold.ts +5 -4
  126. package/src/serve/embed.ts +1 -1
  127. package/src/serve/hub-app/col-card.tsx +3 -17
  128. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  129. package/src/serve/hub-app/cols-svc.ts +0 -13
  130. package/src/serve/hub-app/dock-st.ts +4 -2
  131. package/src/serve/hub-app/dock-view.tsx +2 -0
  132. package/src/serve/hub-app/frames-st.ts +35 -0
  133. package/src/serve/hub-app/hash-route.ts +64 -1
  134. package/src/serve/hub-app/home-st.ts +31 -7
  135. package/src/serve/hub-app/home-strip.css +9 -1
  136. package/src/serve/hub-app/home-strip.tsx +7 -6
  137. package/src/serve/hub-app/home.html +5 -0
  138. package/src/serve/hub-app/hub-app.tsx +49 -5
  139. package/src/serve/hub-app/hub.css +29 -11
  140. package/src/serve/hub-app/icons.tsx +16 -1
  141. package/src/serve/hub-app/identities-st.ts +210 -0
  142. package/src/serve/hub-app/identities-view.tsx +352 -0
  143. package/src/serve/hub-app/identities.css +48 -0
  144. package/src/serve/hub-app/identity-address.ts +52 -0
  145. package/src/serve/hub-app/inbox-st.ts +59 -6
  146. package/src/serve/hub-app/inbox-view.tsx +48 -6
  147. package/src/serve/hub-app/inbox.css +12 -1
  148. package/src/serve/hub-app/index.html +3 -0
  149. package/src/serve/hub-app/keys.ts +10 -2
  150. package/src/serve/hub-app/list-walk.ts +89 -0
  151. package/src/serve/hub-app/machine-st.ts +12 -0
  152. package/src/serve/hub-app/media-view.tsx +2 -1
  153. package/src/serve/hub-app/pages-frames.tsx +134 -0
  154. package/src/serve/hub-app/pages-svc.ts +111 -0
  155. package/src/serve/hub-app/palette-st.ts +18 -3
  156. package/src/serve/hub-app/palette-view.tsx +9 -2
  157. package/src/serve/hub-app/planned-view.tsx +2 -1
  158. package/src/serve/hub-app/project-list.css +18 -14
  159. package/src/serve/hub-app/project-list.tsx +88 -49
  160. package/src/serve/hub-app/projects-svc.ts +33 -3
  161. package/src/serve/hub-app/repo-sections.ts +19 -2
  162. package/src/serve/hub-app/repo-st.ts +75 -19
  163. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  164. package/src/serve/hub-app/review/review-kit.ts +30 -7
  165. package/src/serve/hub-app/review/review-page.tsx +1 -1
  166. package/src/serve/hub-app/review/review-st.ts +19 -8
  167. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  168. package/src/serve/hub-app/review/review-views.tsx +84 -19
  169. package/src/serve/hub-app/review/thread-st.ts +1 -10
  170. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  171. package/src/serve/hub-app/review.css +17 -8
  172. package/src/serve/hub-app/site/site-part.tsx +173 -0
  173. package/src/serve/hub-app/site/site-st.ts +157 -0
  174. package/src/serve/hub-app/site.css +35 -0
  175. package/src/serve/hub-app/social/calendar.tsx +182 -0
  176. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  177. package/src/serve/hub-app/social/kit.tsx +244 -0
  178. package/src/serve/hub-app/social/post-card.tsx +456 -0
  179. package/src/serve/hub-app/social/problems.tsx +60 -0
  180. package/src/serve/hub-app/social/social-model.ts +154 -0
  181. package/src/serve/hub-app/social/social-page.tsx +674 -0
  182. package/src/serve/hub-app/social/social-st.ts +986 -0
  183. package/src/serve/hub-app/social.css +289 -0
  184. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  185. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  186. package/src/serve/hub-app/stores.css +54 -0
  187. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  188. package/src/serve/hub-app/timeline-view.tsx +3 -2
  189. package/src/serve/hub-app/tree-build.ts +6 -0
  190. package/src/serve/hub-app/tree-row.tsx +27 -4
  191. package/src/serve/hub-app/tree-svc.ts +18 -49
  192. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  193. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  194. package/src/serve/hub-app/veille.css +84 -0
  195. package/src/serve/hub-runtime.ts +14 -9
  196. package/src/serve/project-gutter-route.ts +44 -12
  197. package/src/serve/run-lanes.ts +7 -4
  198. package/src/serve/same-origin.ts +1 -1
  199. package/src/serve/serve-hub.ts +20 -12
  200. package/src/serve/tracked-watch.ts +24 -3
  201. package/src/serve/warm-cell.ts +5 -1
  202. package/src/shipkit-files.ts +15 -4
  203. package/src/shipkit.ts +0 -1
  204. package/src/shot/box.ts +162 -0
  205. package/src/shot/browser-slot.ts +62 -0
  206. package/src/shot/client.ts +43 -7
  207. package/src/shot/clip-encoder.ts +93 -12
  208. package/src/shot/film-box.ts +188 -0
  209. package/src/shot/shooter.ts +50 -15
  210. package/src/shot/shot-ask.ts +10 -2
  211. package/src/shot/stepped-clip.ts +5 -4
  212. package/src/site/desk.ts +242 -0
  213. package/src/site/routes.ts +66 -0
  214. package/src/site/unit.ts +62 -0
  215. package/src/social/brands.ts +22 -0
  216. package/src/social/compose.ts +97 -0
  217. package/src/social/desk-index.ts +123 -0
  218. package/src/social/desk-wire.ts +64 -0
  219. package/src/social/drafts.ts +183 -0
  220. package/src/social/house.ts +24 -0
  221. package/src/social/load.ts +319 -0
  222. package/src/social/md.ts +70 -0
  223. package/src/social/media-facts.ts +53 -0
  224. package/src/social/media-kind.ts +189 -0
  225. package/src/social/media-limit.ts +42 -0
  226. package/src/social/media-of.ts +30 -0
  227. package/src/social/migrate.ts +123 -0
  228. package/src/social/open.ts +17 -0
  229. package/src/social/post-url.ts +158 -0
  230. package/src/social/presence.ts +332 -0
  231. package/src/social/public-read.ts +53 -0
  232. package/src/social/publish/bluesky.ts +168 -0
  233. package/src/social/publish/discord.ts +76 -0
  234. package/src/social/publish/index.ts +24 -0
  235. package/src/social/publish/secret.ts +13 -0
  236. package/src/social/push.ts +31 -0
  237. package/src/social/richtext.ts +37 -0
  238. package/src/social/routes.ts +180 -0
  239. package/src/social/stats.ts +134 -0
  240. package/src/social/text.ts +267 -0
  241. package/src/social/tracker-route.ts +39 -0
  242. package/src/social/tracker.ts +255 -0
  243. package/src/social/unit.ts +53 -0
  244. package/src/social/writes.ts +130 -0
  245. package/src/start-repo.ts +14 -9
  246. package/src/stores/collection.ts +27 -0
  247. package/src/stores/desk.ts +336 -0
  248. package/src/stores/model.ts +187 -0
  249. package/src/stores/routes.ts +126 -0
  250. package/src/stores/unit.ts +57 -0
  251. package/src/suite/calibrate.ts +127 -0
  252. package/src/suite/core-counters.ts +91 -0
  253. package/src/suite/judge-suites.ts +94 -34
  254. package/src/suite/suite-cli.ts +44 -10
  255. package/src/suite/suite-cpu-preload.ts +34 -9
  256. package/src/trailer/adapter.ts +4 -0
  257. package/src/trailer/build.ts +42 -11
  258. package/src/trailer/ffmpeg.ts +11 -0
  259. package/src/trailer/footage.ts +30 -13
  260. package/src/trailer/grammar.ts +18 -2
  261. package/src/trailer/graph.ts +28 -6
  262. package/src/trailer/passage.ts +17 -5
  263. package/src/trailer/plan.ts +74 -3
  264. package/src/trailer/stitch.ts +67 -26
  265. package/src/trailer/url.ts +1 -1
  266. package/src/trailer/versions.ts +24 -0
  267. package/src/ts/gate-typecheck.ts +32 -0
  268. package/src/ts/typecheck-cli.ts +9 -11
  269. package/src/tui/tui-app.tsx +0 -1
  270. package/src/veille/asks.ts +155 -0
  271. package/src/veille/auto.ts +31 -0
  272. package/src/veille/batch.ts +27 -0
  273. package/src/veille/chrome.ts +127 -0
  274. package/src/veille/collection.ts +28 -0
  275. package/src/veille/desk.ts +242 -0
  276. package/src/veille/identity.ts +80 -0
  277. package/src/veille/import.ts +68 -0
  278. package/src/veille/log.ts +183 -0
  279. package/src/veille/platforms.ts +118 -0
  280. package/src/veille/reads.ts +66 -0
  281. package/src/veille/replied.ts +110 -0
  282. package/src/veille/routes.ts +185 -0
  283. package/src/veille/service.ts +81 -0
  284. package/src/veille/watch.ts +116 -0
  285. package/src/veille/worth.ts +46 -0
  286. package/src/wiki/scan-md.ts +18 -0
  287. package/src/collections/posts.ts +0 -142
  288. package/src/contracts/manifests/social.contract.ts +0 -20
  289. package/src/scaffold/files/agent-coding.md +0 -35
  290. package/src/ts/typecheck-cache.ts +0 -11
@@ -1,6 +1,7 @@
1
1
  // the one way code asks for a shot or a clip: `shotUrl` and `clipUrl` post to
2
2
  // the warm shot service (serve-shot.ts), start it through pm when it is down,
3
- // and shoot in process only when the machine has no pm (CI, SHIPKIT_NO_HOME).
3
+ // and shoot in process only when the machine has no pm (CI, SHIPKIT_NO_HOME). A repo filmed by its box films there
4
+ // from a Mac (box.ts), on a Shooter of this process.
4
5
  // `sk shot` and the trailer's `url` film both call these.
5
6
  import { DEFAULT_FPS, DEFAULT_VIEWPORT, DEFAULT_WAIT_MS, type ClipAsk, type ShotAsk, shotUrlBase, type Viewport } from './shot-ask.ts'
6
7
  import type { ShotDone } from './shooter.ts'
@@ -8,9 +9,11 @@ import type { ShotDone } from './shooter.ts'
8
9
  /** the global process id pm knows the service by (shot.shipkit.ts) */
9
10
  export const SHOT_PROCESS = 'shot'
10
11
 
11
- export type ShotInput = { url: string; out: string; viewport?: Viewport; dpr?: number; reload?: boolean; waitMs?: number; step?: string; at?: number }
12
+ /** `root`: the repo the shot is for, whose browser cap it holds a slot of while it runs (browser-slot.ts); default the
13
+ * repo the cwd is in */
14
+ export type ShotInput = { url: string; out: string; viewport?: Viewport; dpr?: number; reload?: boolean; waitMs?: number; step?: string; at?: number; root?: string }
12
15
  export type ClipInput = ShotInput & { seconds: number; fps?: number; dom?: boolean }
13
- export type ShotResult = ShotDone & { via: 'warm' | 'started' | 'local' }
16
+ export type ShotResult = ShotDone & { via: 'warm' | 'started' | 'local' | 'box' }
14
17
 
15
18
  const shotAsk = (i: ShotInput): ShotAsk => ({
16
19
  url: i.url,
@@ -27,20 +30,53 @@ function stepped(i: { step?: string }, r: ShotResult): void {
27
30
  }
28
31
 
29
32
  /** a png of `url` at `out` (absolute), through the warm browser; with `step`, the page drawn at `at` first */
30
- export async function shotUrl(i: ShotInput, log: (l: string) => void = () => {}): Promise<ShotResult> {
31
- const r = await ask('/shot', { ...shotAsk(i), ...(i.step ? { step: i.step, at: i.at ?? 0 } : {}) }, log)
33
+ export async function shotUrl(i: ShotInput, log: (l: string) => void = quiet): Promise<ShotResult> {
34
+ const a: ShotAsk = { ...shotAsk(i), ...(i.step ? { step: i.step, at: i.at ?? 0 } : {}) }
35
+ const r = (await onBox(`shot ${i.url}`, i, log, (s) => s.shot(a))) ?? (await held(`shot ${i.url}`, i, log, () => ask('/shot', a, log)))
32
36
  stepped(i, r)
33
37
  return r
34
38
  }
35
39
 
36
40
  /** an mp4 of `seconds` of `url` at `out` (absolute): a page that is a canvas through its WebCodecs, any other page (or
37
41
  * `dom`) as chromium paints it */
38
- export async function clipUrl(i: ClipInput, log: (l: string) => void = () => {}): Promise<ShotResult> {
39
- const r = await ask('/clip', { ...shotAsk(i), seconds: i.seconds, fps: i.fps ?? DEFAULT_FPS, dom: i.dom ?? false, ...(i.step ? { step: i.step } : {}) } satisfies ClipAsk, log)
42
+ export async function clipUrl(i: ClipInput, log: (l: string) => void = quiet): Promise<ShotResult> {
43
+ const a: ClipAsk = { ...shotAsk(i), seconds: i.seconds, fps: i.fps ?? DEFAULT_FPS, dom: i.dom ?? false, ...(i.step ? { step: i.step } : {}) }
44
+ const r = (await onBox(`clip ${i.url}`, i, log, (s) => s.clip(a))) ?? (await held(`clip ${i.url}`, i, log, () => ask('/clip', a, log)))
40
45
  stepped(i, r)
41
46
  return r
42
47
  }
43
48
 
49
+ const quiet = (): void => {}
50
+
51
+ /** a repo whose browsers live on its box films there from a Mac (box.ts): on a Shooter of this process, connected to
52
+ * the box's warm browser, never on this machine's shot service; null when the repo films here */
53
+ async function onBox(who: string, i: ShotInput, log: (l: string) => void, run: (s: import('./shooter.ts').Shooter) => Promise<ShotDone>): Promise<ShotResult | null> {
54
+ const { browserCap } = await import('./browser-slot.ts')
55
+ const { filmBox } = await import('./box.ts')
56
+ const cap = await browserCap(i.root)
57
+ if (cap == null || filmBox(cap) == null) return null
58
+ const { Shooter } = await import('./shooter.ts')
59
+ const { dirname } = await import('path')
60
+ const s = new Shooter([cap.root, dirname(import.meta.dir)], { slot: { root: cap.root, who, say: log === quiet ? (l) => console.error(l) : log } })
61
+ try {
62
+ return { ...(await run(s)), via: 'box' }
63
+ } finally {
64
+ await s.close()
65
+ }
66
+ }
67
+
68
+ /** the ask run while it holds one of its repo's browser slots: the warm browser shooting for a repo counts against
69
+ * that repo's cap; a wait is said through `log`, or on stderr when the caller logs nothing */
70
+ async function held<T>(who: string, i: ShotInput, log: (l: string) => void, run: () => Promise<T>): Promise<T> {
71
+ const { browserSlot } = await import('./browser-slot.ts')
72
+ const release = await browserSlot(who, { ...(i.root ? { root: i.root } : {}), ...(log === quiet ? {} : { say: log }) })
73
+ try {
74
+ return await run()
75
+ } finally {
76
+ release()
77
+ }
78
+ }
79
+
44
80
  /** null when nothing listens (start it), else the service's answer; a refusal throws its reason */
45
81
  async function post(route: string, a: ShotAsk): Promise<ShotDone | null> {
46
82
  let r: Response
@@ -1,37 +1,55 @@
1
1
  // a clip filmed by the page itself: each frame of its largest canvas goes to
2
- // the page's WebCodecs encoder (H.264, the media engine) on the page's own
3
- // animation frames, in real time, and the stream comes back in takes of at
4
- // most TAKE bytes, never whole (one answer of a long clip's base64 can close
5
- // the browser). ffmpeg then muxes it into an mp4 with no second encode.
2
+ // the page's WebCodecs encoder (H.264, the media engine), and the stream comes
3
+ // back in takes of at most TAKE bytes, never whole (one answer of a long
4
+ // clip's base64 can close the browser). ffmpeg then muxes it into an mp4 with
5
+ // no second encode. Real time films the page's own animation frames; a step
6
+ // hook films frame n once `window[step](n / fps)` drew it, stamped n / fps
7
+ // whatever the page's speed.
6
8
  //
7
9
  // the constraint a reader breaks first: `installClip`, `takeClip` and
8
10
  // `CLIP_INIT` run IN the page, so they import nothing and read only their
9
11
  // argument and the document. A WebGL canvas keeps no drawing buffer after it
10
12
  // presents, so the clip's page is opened with CLIP_INIT, which asks every
11
- // WebGL context for `preserveDrawingBuffer`; a WebGPU canvas read on a frame
12
- // it did not draw gives an older drawing, so it is read only after a draw.
13
+ // WebGL context for `preserveDrawingBuffer`; a WebGPU canvas read after the
14
+ // task of its draw gives an older drawing, so a stepped clip takes it at the
15
+ // queue's submit (CLIP_INIT calls `__skOnDraw`), and the real time clip reads
16
+ // it only on a frame it drew.
13
17
 
14
- /** what the page films: seconds of its largest canvas at fps, H.264 at a fixed quantizer */
15
- export type PageClipAsk = { seconds: number; fps: number; quantizer: number; keyEvery: number }
18
+ /** what the page films: seconds of its largest canvas at fps, H.264 at a fixed quantizer; with `step`, frame by frame
19
+ * through `window[step](t)` */
20
+ export type PageClipAsk = { seconds: number; fps: number; quantizer: number; keyEvery: number; step?: string }
16
21
 
17
- /** what the page says once the film ran */
18
- export type PageClipDone = { frames: number; repeated: number; width: number; height: number; canvasOfViewport: string }
22
+ /** what the page says once the film ran; `msPerFrame` the stepped clip's wall time a frame */
23
+ export type PageClipDone = { frames: number; repeated: number; width: number; height: number; canvasOfViewport: string; msPerFrame?: number }
19
24
 
20
25
  /** IN THE PAGE, as an init script: every WebGL context keeps its drawing buffer, so a frame reads back after it presents;
21
- * a WebGPU canvas counts its drawings (window.__skDraws): read on a frame it did not draw, it gives an older drawing */
26
+ * a WebGPU canvas is marked (`__skWebgpu`) and counts its drawings (window.__skDraws): read on a frame it did not
27
+ * draw, it gives an older drawing. Each queue submit after a canvas's getCurrentTexture, in that same task, calls
28
+ * window.__skOnDraw(canvas): the one moment its drawing reads back */
22
29
  export const CLIP_INIT = `(() => {
23
30
  const get = HTMLCanvasElement.prototype.getContext
24
31
  HTMLCanvasElement.prototype.getContext = function (type, attrs) {
25
32
  if (type === 'webgl' || type === 'webgl2' || type === 'experimental-webgl') attrs = Object.assign({}, attrs, { preserveDrawingBuffer: true })
26
- if (type === 'webgpu') window.__skDraws ??= 0
33
+ if (type === 'webgpu') { window.__skDraws ??= 0; this.__skWebgpu = true }
27
34
  return get.call(this, type, attrs)
28
35
  }
29
36
  if (typeof GPUCanvasContext !== 'undefined') {
37
+ let drawing = new Set()
38
+ const later = new MessageChannel()
39
+ later.port1.onmessage = () => (drawing = new Set())
30
40
  const current = GPUCanvasContext.prototype.getCurrentTexture
31
41
  GPUCanvasContext.prototype.getCurrentTexture = function () {
32
42
  window.__skDraws = (window.__skDraws ?? 0) + 1
43
+ if (drawing.size === 0) later.port2.postMessage(0)
44
+ drawing.add(this.canvas)
33
45
  return current.call(this)
34
46
  }
47
+ const submit = GPUQueue.prototype.submit
48
+ GPUQueue.prototype.submit = function (buffers) {
49
+ const r = submit.call(this, buffers)
50
+ if (window.__skOnDraw) for (const c of drawing) window.__skOnDraw(c)
51
+ return r
52
+ }
35
53
  }
36
54
  })()`
37
55
 
@@ -80,6 +98,69 @@ export async function installClip(a: PageClipAsk): Promise<string | null> {
80
98
  const total = Math.round(a.seconds * a.fps)
81
99
  const step = 1000 / a.fps
82
100
  const rect = { x: 0, y: 0, width, height }
101
+ if (a.step != null) {
102
+ const hook = (window as unknown as Record<string, unknown>)[a.step]
103
+ if (typeof hook !== 'function') {
104
+ enc.close()
105
+ return `the page has no window.${a.step}(t): a stepped page draws the time it is given there`
106
+ }
107
+ const webgpu = (canvas as unknown as { __skWebgpu?: boolean }).__skWebgpu === true
108
+ const frame = (): Promise<void> => new Promise((ok) => requestAnimationFrame(() => ok()))
109
+ const mark = (): string | null => {
110
+ const m = document.querySelector('meta[name="shot-ready"]')
111
+ return m == null ? null : (m.getAttribute('content') ?? '').trim().toLowerCase()
112
+ }
113
+ const on = w as unknown as { __skOnDraw?: (c: HTMLCanvasElement) => void }
114
+ const drawn: { frame: VideoFrame | null } = { frame: null }
115
+ on.__skOnDraw = (c) => {
116
+ if (c !== canvas) return
117
+ drawn.frame?.close()
118
+ drawn.frame = new VideoFrame(canvas, { timestamp: 0 })
119
+ }
120
+ const us = 1e6 / a.fps
121
+ st.done = (async (): Promise<PageClipDone> => {
122
+ let last: VideoFrame | null = null
123
+ let repeated = 0
124
+ const t0 = performance.now()
125
+ try {
126
+ for (let n = 0; n < total; n++) {
127
+ if (st.failed) throw new Error(st.failed)
128
+ drawn.frame?.close()
129
+ drawn.frame = null
130
+ await (hook as (t: number) => unknown)(+(n / a.fps).toFixed(6))
131
+ await frame()
132
+ await frame()
133
+ for (const since = performance.now(); mark() != null && mark() !== 'ready'; await frame())
134
+ if (performance.now() - since > 30_000) throw new Error(`frame ${n}: the page has <meta name="shot-ready"> and never set content="ready" in 30 s`)
135
+ // a WebGPU drawing is the one taken at its submit; none since the hook: the canvas shows the last one
136
+ if (webgpu && drawn.frame == null) {
137
+ if (last == null) throw new Error(`frame 0: the page's WebGPU canvas drew nothing after window.${a.step}(0), and it reads back only in the task of its draw: the hook draws the time it is given`)
138
+ repeated++
139
+ } else {
140
+ last?.close()
141
+ last = (webgpu ? drawn.frame : null) ?? new VideoFrame(canvas, { timestamp: 0 })
142
+ if (last === drawn.frame) drawn.frame = null
143
+ }
144
+ const f = new VideoFrame(last, { timestamp: Math.round(n * us), duration: Math.round(us), visibleRect: rect })
145
+ enc.encode(f, { keyFrame: n % a.keyEvery === 0, avc: { quantizer: a.quantizer } } as VideoEncoderEncodeOptions)
146
+ f.close()
147
+ while (enc.encodeQueueSize > 4) await frame()
148
+ }
149
+ const msPerFrame = (performance.now() - t0) / total
150
+ await enc.flush()
151
+ if (st.failed) throw new Error(st.failed)
152
+ return { frames: total, repeated, width, height, canvasOfViewport, msPerFrame }
153
+ } finally {
154
+ delete on.__skOnDraw
155
+ last?.close()
156
+ drawn.frame?.close()
157
+ if (enc.state !== 'closed') enc.close()
158
+ }
159
+ })()
160
+ st.done.catch(() => undefined)
161
+ w.__skClip = st
162
+ return null
163
+ }
83
164
  // a WebGPU canvas is read only on a frame it drew (CLIP_INIT counts them), else its last drawing is filmed again
84
165
  const gpu = w as unknown as { __skDraws?: number }
85
166
  st.done = new Promise<PageClipDone>((ok, fail) => {
@@ -0,0 +1,188 @@
1
+ // the box half of the box route (box.ts): run by bun on the box that films for a repo (repo.config.ts browsers.box),
2
+ // uploaded there by its content hash, node builtins only. One warm chromium on the box's discrete GPU, its devtools on
3
+ // 127.0.0.1:CDP_PORT (the Mac reaches it through ssh), its profile kept, so its HTTP cache outlives each film. It is
4
+ // chromium's headless shell: the full chromium's headless mode composites a WebGPU canvas black in the box's session 0
5
+ // (no display). The shell ships without the DirectX shader compiler Dawn's D3D12 loads, so it gets the full
6
+ // chromium's copy; the full chromium also reads the discrete GPU's LUID off chrome://gpu, which the shell lacks.
7
+ // up <playwright version> the browser answering (started when down: installed when missing, its GPU's LUID found)
8
+ // watch <pid> ends the browser once nothing used it for IDLE_MS (started by up, outside the ssh session)
9
+ // the constraint a reader breaks first: Windows OpenSSH ends every process of its session when it closes, so the
10
+ // browser and the watcher are created through WMI, outside it
11
+ import { createHash } from 'node:crypto'
12
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
13
+ import { homedir, uptime } from 'node:os'
14
+ import { dirname, join } from 'node:path'
15
+
16
+ export const CDP_PORT = 9333
17
+ const PROBE_PORT = 9334
18
+ /** the browser ends once no film touched it for this long and no page holds a url */
19
+ const IDLE_MS = 10 * 60_000
20
+ /** and past this long with no film, whatever its pages */
21
+ const STALE_MS = 60 * 60_000
22
+
23
+ const DIR = join(homedir(), 'dev', 'shipkit-film')
24
+ const USED = join(DIR, 'used')
25
+ const PID = join(DIR, 'browser.pid')
26
+ const say = (s: string) => console.error(`box: ${s}`)
27
+
28
+ /** this script's version: a browser another version started is replaced */
29
+ const VERSION = createHash('sha1').update(readFileSync(import.meta.path)).digest('hex').slice(0, 12)
30
+
31
+ const BROWSER_ARGS = [
32
+ '--use-angle=d3d11',
33
+ '--enable-gpu',
34
+ '--ignore-gpu-blocklist',
35
+ '--enable-unsafe-webgpu',
36
+ '--autoplay-policy=no-user-gesture-required',
37
+ '--mute-audio',
38
+ '--no-first-run',
39
+ '--no-default-browser-check',
40
+ '--lang=en-US',
41
+ // a headless page is never backgrounded: its frames and timers run at full rate
42
+ '--disable-background-timer-throttling',
43
+ '--disable-backgrounding-occluded-windows',
44
+ '--disable-renderer-backgrounding',
45
+ '--disable-features=CalculateNativeWinOcclusion',
46
+ ]
47
+
48
+ async function answers(port: number): Promise<boolean> {
49
+ try {
50
+ return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })).ok
51
+ } catch {
52
+ return false
53
+ }
54
+ }
55
+
56
+ /** playwright `version`'s full chromium and headless shell, installed into the user's ms-playwright when missing, the
57
+ * shell given the full one's DirectX shader compiler */
58
+ function chromium(version: string): { full: string; shell: string } {
59
+ const root = join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'ms-playwright')
60
+ const find = (prefix: string, exe: string) =>
61
+ (existsSync(root) ? readdirSync(root) : [])
62
+ .filter((d) => d.startsWith(prefix) && /^\d+$/.test(d.slice(prefix.length)))
63
+ .sort((a, b) => Number(b.slice(prefix.length)) - Number(a.slice(prefix.length)))
64
+ .map((d) => join(root, d, exe))
65
+ .find((p) => existsSync(p))
66
+ const both = () => ({ full: find('chromium-', 'chrome-win64/chrome.exe'), shell: find('chromium_headless_shell-', 'chrome-headless-shell-win64/chrome-headless-shell.exe') })
67
+ let got = both()
68
+ if (!got.full || !got.shell) {
69
+ say(`installing playwright ${version}'s chromium and headless shell into ${root}`)
70
+ const p = Bun.spawnSync(['bunx', `playwright@${version}`, 'install', 'chromium', 'chromium-headless-shell'], { cwd: DIR, stdout: 'inherit', stderr: 'inherit' })
71
+ got = both()
72
+ if (p.exitCode !== 0 || !got.full || !got.shell) throw new Error(`installing chromium (playwright ${version}) failed, exit ${p.exitCode}`)
73
+ }
74
+ for (const dll of ['dxil.dll', 'dxcompiler.dll']) {
75
+ const to = join(dirname(got.shell), dll)
76
+ if (!existsSync(to)) copyFileSync(join(dirname(got.full), dll), to)
77
+ }
78
+ return { full: got.full, shell: got.shell }
79
+ }
80
+
81
+ /** a process outside the ssh session (WMI), its pid */
82
+ function detached(line: string): number {
83
+ const ps = `$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = '${line.replaceAll("'", "''")}'; CurrentDirectory = '${DIR}' }; if ($r.ReturnValue -ne 0) { exit $r.ReturnValue }; $r.ProcessId`
84
+ const p = Bun.spawnSync(['powershell', '-NoProfile', '-NonInteractive', '-Command', ps], { stdout: 'pipe', stderr: 'pipe' })
85
+ const pid = Number(p.stdout.toString().trim())
86
+ if (p.exitCode !== 0 || !(pid > 0)) throw new Error(`starting ${line.slice(0, 80)} failed (${p.exitCode}): ${p.stderr.toString().trim()}`)
87
+ return pid
88
+ }
89
+
90
+ const kill = (pid: number) => Bun.spawnSync(['taskkill', '/T', '/F', '/PID', String(pid)], { stdout: 'ignore', stderr: 'ignore' })
91
+
92
+ const alive = (pid: number) => {
93
+ try {
94
+ process.kill(pid, 0)
95
+ return true
96
+ } catch {
97
+ return false
98
+ }
99
+ }
100
+
101
+ const quote = (s: string) => `"${s}"`
102
+
103
+ /** the LUID of the box's discrete GPU as chromium names it (`high,low`): chromium on Windows draws on the adapter the
104
+ * display uses (an integrated one on wm), whatever the page's powerPreference. Read once per boot from chrome://gpu */
105
+ async function discreteLuid(exe: string): Promise<string | null> {
106
+ const cache = join(DIR, 'luid.txt')
107
+ const boot = String(Math.round((Date.now() / 1000 - uptime()) / 60))
108
+ const [at, luid] = existsSync(cache) ? readFileSync(cache, 'utf8').trim().split(' ') : []
109
+ if (at === boot && luid) return luid === 'none' ? null : luid
110
+ const profile = join(DIR, 'probe-profile')
111
+ const pid = detached([exe, '--headless=new', `--remote-debugging-port=${PROBE_PORT}`, `--user-data-dir=${profile}`, '--no-first-run', 'about:blank'].map(quote).join(' '))
112
+ try {
113
+ for (let i = 0; i < 100 && !(await answers(PROBE_PORT)); i++) await Bun.sleep(100)
114
+ const target = (await (await fetch(`http://127.0.0.1:${PROBE_PORT}/json/new?chrome://gpu`, { method: 'PUT' })).json()) as { webSocketDebuggerUrl: string }
115
+ const text = await new Promise<string>((done, fail) => {
116
+ const ws = new WebSocket(target.webSocketDebuggerUrl)
117
+ let n = 0
118
+ const ask = () => ws.send(JSON.stringify({ id: ++n, method: 'Runtime.evaluate', params: { expression: "document.querySelector('info-view')?.shadowRoot?.textContent ?? ''", returnByValue: true } }))
119
+ ws.onopen = ask
120
+ ws.onmessage = (e) => {
121
+ const v = (JSON.parse(String(e.data)) as { result?: { result?: { value?: string } } }).result?.result?.value ?? ''
122
+ if (/GPU0/.test(v)) {
123
+ ws.close()
124
+ done(v)
125
+ } else if (n > 50) fail(new Error('chrome://gpu named no GPU in 5 s'))
126
+ else setTimeout(ask, 100)
127
+ }
128
+ ws.onerror = () => fail(new Error('chrome://gpu: its devtools socket failed'))
129
+ })
130
+ const found = /GPU\d+\s*:\s*VENDOR= 0x(?:10de|1002)[^\n]*?LUID=\{(\d+),(\d+)\}/i.exec(text)
131
+ const got = found ? `${found[1]},${found[2]}` : null
132
+ writeFileSync(cache, `${boot} ${got ?? 'none'}`)
133
+ return got
134
+ } finally {
135
+ // its profile stays for the next boot's probe: chromium holds its files a while after the kill
136
+ kill(pid)
137
+ }
138
+ }
139
+
140
+ async function up(version: string): Promise<void> {
141
+ const t = performance.now()
142
+ mkdirSync(DIR, { recursive: true })
143
+ writeFileSync(USED, String(Date.now()))
144
+ const [was, by] = existsSync(PID) ? readFileSync(PID, 'utf8').trim().split(' ') : []
145
+ if (by === VERSION && (await answers(CDP_PORT))) {
146
+ console.log(`up warm ${Math.round(performance.now() - t)}`)
147
+ return
148
+ }
149
+ if (Number(was) > 0) kill(Number(was))
150
+ const exe = chromium(version)
151
+ const luid = await discreteLuid(exe.full)
152
+ if (luid == null) say('no discrete GPU named in chrome://gpu: the browser draws on the default adapter')
153
+ const args = [`--remote-debugging-port=${CDP_PORT}`, `--user-data-dir=${join(DIR, 'profile')}`, ...BROWSER_ARGS, ...(luid ? [`--use-adapter-luid=${luid}`] : []), 'about:blank']
154
+ const pid = detached([exe.shell, ...args].map(quote).join(' '))
155
+ writeFileSync(PID, `${pid} ${VERSION}`)
156
+ for (let i = 0; i < 150 && !(await answers(CDP_PORT)); i++) await Bun.sleep(100)
157
+ if (!(await answers(CDP_PORT))) throw new Error(`the browser (pid ${pid}) did not answer on 127.0.0.1:${CDP_PORT} in 15 s`)
158
+ detached([process.execPath, import.meta.path, 'watch', String(pid)].map(quote).join(' '))
159
+ console.log(`up started ${Math.round(performance.now() - t)} pid ${pid}${luid ? ` luid ${luid}` : ''}`)
160
+ }
161
+
162
+ async function watch(pid: number): Promise<void> {
163
+ for (;;) {
164
+ await Bun.sleep(30_000)
165
+ if (!alive(pid)) return
166
+ const idle = Date.now() - (statSync(USED, { throwIfNoEntry: false })?.mtimeMs ?? 0)
167
+ let busy = false
168
+ try {
169
+ const pages = (await (await fetch(`http://127.0.0.1:${CDP_PORT}/json/list`)).json()) as { type: string; url: string }[]
170
+ busy = pages.some((p) => p.type === 'page' && p.url !== 'about:blank')
171
+ } catch {}
172
+ if (idle > STALE_MS || (idle > IDLE_MS && !busy)) {
173
+ kill(pid)
174
+ rmSync(PID, { force: true })
175
+ return
176
+ }
177
+ }
178
+ }
179
+
180
+ if (import.meta.main) {
181
+ const [cmd, arg] = process.argv.slice(2)
182
+ if (cmd === 'up' && arg) await up(arg)
183
+ else if (cmd === 'watch' && Number(arg) > 0) await watch(Number(arg))
184
+ else {
185
+ console.error('usage: film-box.ts up <playwright version> | watch <browser pid>')
186
+ process.exit(2)
187
+ }
188
+ }
@@ -6,6 +6,10 @@
6
6
  // a canvas through the page's WebCodecs (clip-encoder.ts), any other page
7
7
  // through chromium's screencast and ffmpeg (dom-clip.ts).
8
8
  //
9
+ // A stepped clip (`step`) films a canvas page the same way, frame by frame
10
+ // through the page's hook, and any other page a screenshot a frame
11
+ // (stepped-clip.ts).
12
+ //
9
13
  // it never slows the machine's other work: the browser runs niced, the page
10
14
  // stays live only LIVE_MS after a request and is then frozen (no frame, no
11
15
  // timer, no cpu), a frozen page is loaded again before its next still (an
@@ -21,6 +25,7 @@ import { dirname } from 'path'
21
25
  import { loadPlaywright } from '../smoke/run-smoke.ts'
22
26
  import { CLIP_INIT, CLIP_QUANTIZER, clipDone, installClip, KEY_EVERY, muxArgs, type PageClipAsk, type PageClipDone, TAKE, takeClip } from './clip-encoder.ts'
23
27
  import { type ClipPath, clipPathOf, domEncodeArgs, FrameTimeline, largestCanvas, screencastParams } from './dom-clip.ts'
28
+ import { openBrowser, type PwBrowser } from './box.ts'
24
29
  import { capMsOf, type ClipAsk, pageMove, readMark, type ShotAsk, slotKey, Turns, waitReady } from './shot-ask.ts'
25
30
 
26
31
  /** the slice of playwright the shots touch, so the lib types nothing it does not ship */
@@ -39,13 +44,13 @@ type Page = {
39
44
  isClosed(): boolean
40
45
  }
41
46
  type Context = { newPage(): Promise<Page>; newCDPSession(p: Page): Promise<Cdp>; addInitScript(s: { content: string }): Promise<void>; close(): Promise<void> }
42
- type Browser = {
47
+ export type Browser = {
43
48
  newContext(o: { viewport: { width: number; height: number }; deviceScaleFactor: number; locale?: string }): Promise<Context>
44
49
  close(): Promise<void>
45
50
  isConnected(): boolean
46
51
  on(event: 'disconnected', cb: () => void): void
47
52
  }
48
- type Playwright = { chromium: { launch(o: { headless: boolean; args: string[] }): Promise<Browser> } }
53
+ type Playwright = { chromium: { launch(o: { headless: boolean; args: string[] }): Promise<Browser>; connectOverCDP(url: string): Promise<PwBrowser> } }
49
54
 
50
55
  /** WebGL on the GPU over metal on a mac: in software a 3D page crawls. Audio plays with no gesture */
51
56
  export const BROWSER_ARGS = [...(process.platform === 'darwin' ? ['--use-angle=metal', '--enable-gpu', '--ignore-gpu-blocklist'] : []), '--autoplay-policy=no-user-gesture-required']
@@ -81,17 +86,27 @@ const ms = (t0: number): number => Math.round(performance.now() - t0)
81
86
  const withCap = <T>(what: string, capMs: number, p: Promise<T>): Promise<T> =>
82
87
  Promise.race([p, new Promise<T>((_, fail) => setTimeout(() => fail(new Error(`${what} took past ${capMs / 1000} s`)), capMs).unref?.())])
83
88
 
89
+ /** the repo a Shooter's browser works for, and the name its browser slot is held under */
90
+ export type BrowserFor = { root: string; who: string; say?: (l: string) => void }
91
+
84
92
  export class Shooter {
85
93
  readonly #roots: string[]
86
94
  readonly #turns = new Turns()
95
+ readonly #for: BrowserFor | null
87
96
  #browser: Browser | null = null
88
97
  #launching: Promise<Browser> | null = null
98
+ #held: (() => void) | null = null
99
+ /** before a page goes to a url: the box route forwards this machine's localhost port to the box */
100
+ #reach: (url: string) => Promise<void> = async () => undefined
89
101
  #slot: Slot | null = null
90
102
  #idle: ReturnType<typeof setTimeout> | null = null
91
103
  #live: ReturnType<typeof setTimeout> | null = null
92
104
 
93
- constructor(roots: string[]) {
105
+ /** `slot`: the repo whose browser cap (browser-slot.ts) this browser counts against, one slot held from its launch
106
+ * to its close; the warm service passes none, each of its askers holds one instead */
107
+ constructor(roots: string[], o: { slot?: BrowserFor } = {}) {
94
108
  this.#roots = roots
109
+ this.#for = o.slot ?? null
95
110
  }
96
111
 
97
112
  get warm(): { browser: boolean; url: string | null; waiting: number } {
@@ -115,6 +130,13 @@ export class Shooter {
115
130
  const b = this.#browser
116
131
  this.#browser = null
117
132
  await b?.close().catch(() => undefined)
133
+ this.#free()
134
+ }
135
+
136
+ #free(): void {
137
+ const held = this.#held
138
+ this.#held = null
139
+ held?.()
118
140
  }
119
141
 
120
142
  #touch(): void {
@@ -140,11 +162,20 @@ export class Shooter {
140
162
  try {
141
163
  setPriority(SHOT_NICE)
142
164
  } catch {}
143
- const b = await pw.chromium.launch({ headless: true, args: BROWSER_ARGS })
165
+ const f = this.#for
166
+ let b: Browser
167
+ if (f != null) {
168
+ // the repo's browser: on its box from a Mac (box.ts), else launched here, its slot held until close
169
+ const o = await openBrowser<Browser>(pw, { root: f.root, who: f.who, args: BROWSER_ARGS, ...(f.say ? { say: f.say } : {}) })
170
+ b = o.browser
171
+ this.#reach = (url) => o.reach(url)
172
+ this.#held = () => void o.close()
173
+ } else b = await pw.chromium.launch({ headless: true, args: BROWSER_ARGS })
144
174
  b.on('disconnected', () => {
145
175
  if (this.#browser === b) {
146
176
  this.#browser = null
147
177
  this.#slot = null
178
+ this.#free()
148
179
  }
149
180
  })
150
181
  this.#browser = b
@@ -196,7 +227,10 @@ export class Shooter {
196
227
  const t = performance.now()
197
228
  slot.url = a.url
198
229
  if (move === 'reload') await slot.page.reload({ waitUntil: 'load', timeout: 60_000 })
199
- else await slot.page.goto(a.url, { waitUntil: 'load', timeout: 60_000 })
230
+ else {
231
+ await this.#reach(a.url)
232
+ await slot.page.goto(a.url, { waitUntil: 'load', timeout: 60_000 })
233
+ }
200
234
  phases['load'] = ms(t)
201
235
  }
202
236
  let t = performance.now()
@@ -230,21 +264,19 @@ export class Shooter {
230
264
  const page = await ctx.newPage()
231
265
  Shooter.#listen(page, errors)
232
266
  let t = performance.now()
267
+ await this.#reach(a.url)
233
268
  await page.goto(a.url, { waitUntil: 'load', timeout: 60_000 })
234
269
  await waitReady(() => page.evaluate(readMark), a.waitMs, { now: () => performance.now(), sleep: (n) => page.waitForTimeout(n) })
235
270
  phases['load'] = ms(t)
236
271
  t = performance.now()
237
- if (a.step) {
238
- const note = await (await import('./stepped-clip.ts')).stepPage(await ctx.newCDPSession(page), page, a as ClipAsk & { step: string })
239
- phases['film'] = ms(t)
240
- return { out: a.out, ms: ms(t0), phases, errors, note, stepped: true }
241
- }
272
+ const stepped = a.step ? { stepped: true as const } : {}
242
273
  const path: ClipPath = clipPathOf({ dom: a.dom === true, canvas: await page.evaluate(largestCanvas), viewport: a.viewport })
243
- const why = path === 'canvas' ? await page.evaluate(installClip, { seconds: a.seconds, fps: a.fps, quantizer: CLIP_QUANTIZER, keyEvery: KEY_EVERY } satisfies PageClipAsk) : null
274
+ const why = path === 'canvas' ? await page.evaluate(installClip, { seconds: a.seconds, fps: a.fps, quantizer: CLIP_QUANTIZER, keyEvery: KEY_EVERY, ...(a.step ? { step: a.step } : {}) } satisfies PageClipAsk) : null
244
275
  if (path === 'dom' || why != null) {
245
- const note = await filmPage(await ctx.newCDPSession(page), page, a)
276
+ const cdp = await ctx.newCDPSession(page)
277
+ const note = a.step ? await (await import('./stepped-clip.ts')).stepPage(cdp, page, a as ClipAsk & { step: string }) : await filmPage(cdp, page, a)
246
278
  phases['film'] = ms(t)
247
- return { out: a.out, ms: ms(t0), phases, errors, note: why == null ? note : `${note}; the canvas path refused: ${why}` }
279
+ return { out: a.out, ms: ms(t0), phases, errors, note: why == null ? note : `${note}; the canvas path refused: ${why}`, ...stepped }
248
280
  }
249
281
  const parts: Buffer[] = []
250
282
  let done: PageClipDone | null = null
@@ -273,8 +305,11 @@ export class Shooter {
273
305
  phases['mux'] = ms(t)
274
306
  const d = done as unknown as PageClipDone
275
307
  const mb = (stream.length / 2 ** 20).toFixed(1)
276
- const note = `${d.frames} frames ${d.width}x${d.height} at ${a.fps} fps (${d.repeated} repeated for a slow page), canvas ${d.canvasOfViewport}, ${mb} MB H.264 from the page's WebCodecs, muxed`
277
- return { out: a.out, ms: ms(t0), phases, errors, note }
308
+ const how = a.step
309
+ ? `each stepped through window.${a.step}(t) and its ready mark (${d.msPerFrame?.toFixed(0)} ms a frame, ${d.repeated} the page did not draw again)`
310
+ : `(${d.repeated} repeated for a slow page)`
311
+ const note = `${d.frames} frames ${d.width}x${d.height} at ${a.fps} fps ${how}, canvas ${d.canvasOfViewport}, ${mb} MB H.264 from the page's WebCodecs, muxed`
312
+ return { out: a.out, ms: ms(t0), phases, errors, note, ...stepped }
278
313
  } finally {
279
314
  await ctx.close().catch(() => undefined)
280
315
  }
@@ -87,6 +87,8 @@ export type ShotFlags = {
87
87
  fps?: string
88
88
  long?: boolean
89
89
  dom?: boolean
90
+ step?: string
91
+ at?: string
90
92
  }
91
93
 
92
94
  const positive = (flag: string, s: string, max: number): number => {
@@ -102,6 +104,11 @@ export function askOf(f: ShotFlags, cwd: string): ShotAsk | ClipAsk {
102
104
  if (seconds != null && seconds > MAX_CLIP_SECONDS && f.long !== true) throw new Error(`--video ${seconds}: a clip past ${MAX_CLIP_SECONDS} s needs --long (a long clip is a long wait and a big file)`)
103
105
  if (seconds == null && f.fps != null) throw new Error('--fps only applies to a clip: add --video <seconds>')
104
106
  if (seconds == null && f.dom === true) throw new Error('--dom only applies to a clip: add --video <seconds>')
107
+ if (f.step != null && !/^[A-Za-z_$][\w$]*$/.test(f.step)) throw new Error(`--step '${f.step}' is not a window function name, like __trailerStep`)
108
+ if (f.at != null && f.step == null) throw new Error('--at only applies to a stepped still: add --step <hook>')
109
+ if (f.at != null && seconds != null) throw new Error('--at only applies to a still: a stepped clip draws every time from 0')
110
+ const at = f.at == null ? undefined : Number(f.at)
111
+ if (at !== undefined && !(Number.isFinite(at) && at >= 0)) throw new Error(`--at '${f.at}' must be seconds, 0 or more`)
105
112
  const base: ShotAsk = {
106
113
  url,
107
114
  viewport: f.viewport == null ? DEFAULT_VIEWPORT : parseViewport(f.viewport),
@@ -110,9 +117,10 @@ export function askOf(f: ShotFlags, cwd: string): ShotAsk | ClipAsk {
110
117
  reload: f.reload === true,
111
118
  waitMs: f.wait == null ? DEFAULT_WAIT_MS : f.wait === '0' ? 0 : positive('--wait', f.wait, 60_000),
112
119
  }
113
- if (seconds == null) return base
120
+ const step = f.step == null ? {} : { step: f.step }
121
+ if (seconds == null) return { ...base, ...step, ...(f.step == null ? {} : { at: at ?? 0 }) }
114
122
  if (!base.out.endsWith('.mp4')) throw new Error(`--out '${f.out}': a clip is an mp4 (H.264)`)
115
- return { ...base, seconds, fps: f.fps == null ? DEFAULT_FPS : positive('--fps', f.fps, 60), dom: f.dom === true }
123
+ return { ...base, seconds, fps: f.fps == null ? DEFAULT_FPS : positive('--fps', f.fps, 60), dom: f.dom === true, ...step }
116
124
  }
117
125
 
118
126
  export const isClip = (a: ShotAsk | ClipAsk): a is ClipAsk => 'seconds' in a
@@ -1,7 +1,8 @@
1
- // a clip filmed frame by frame (wiki build/trailer.md, film page): before each frame the page is asked to draw the
2
- // frame's time, `window[step](t)`, then the shot service waits for its ready mark and two painted frames, takes one
3
- // screenshot, and ffmpeg encodes the frames in order. The page's own speed never shows: a frame that takes a second to
4
- // draw sits beside one that took a millisecond. The page owns its clock while it is stepped
1
+ // a stepped clip of a page whose canvas is not the page (wiki build/trailer.md, film page): before each frame the page
2
+ // is asked to draw the frame's time, `window[step](t)`, then the shot service waits for its ready mark and two painted
3
+ // frames, takes one screenshot, and ffmpeg encodes the frames in order. A canvas page is stepped inside the page and
4
+ // encoded by its own WebCodecs instead (clip-encoder.ts installClip). The page's own speed never shows: a frame that
5
+ // takes a second to draw sits beside one that took a millisecond. The page owns its clock while it is stepped
5
6
  import { mkdirSync } from 'fs'
6
7
  import { dirname } from 'path'
7
8
  import { domEncodeArgs } from './dom-clip.ts'