rvlib-shipkit 2.11.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.
- package/CHANGELOG.md +56 -12
- package/README.md +1 -1
- package/package.json +4 -2
- package/src/agent-time/store.ts +2 -2
- package/src/check.ts +1 -1
- package/src/checks/SK001-package-json-shape.check.ts +4 -0
- package/src/checks/SK003-claude-md-shape.check.ts +1 -1
- package/src/checks/SK004-gitignore-policy.check.ts +27 -2
- package/src/checks/SK005-rvlib-versions.check.ts +1 -1
- package/src/checks/SK008-reviewer-agent.check.ts +2 -2
- package/src/checks/SK012-config-barrel-import.check.ts +1 -1
- package/src/checks/SK015-nested-repo.check.ts +1 -1
- package/src/checks/SK035-public-clean.check.ts +46 -0
- package/src/checks/SK036-draft-media-size.check.ts +28 -0
- package/src/cli/cmd_Backup.ts +152 -0
- package/src/cli/cmd_Ci.ts +8 -11
- package/src/cli/cmd_Drill.ts +145 -0
- package/src/cli/cmd_Home.ts +50 -3
- package/src/cli/cmd_Media.ts +96 -5
- package/src/cli/cmd_Review.ts +8 -2
- package/src/cli/cmd_Shot.ts +5 -2
- package/src/cli/cmd_Smoke.ts +4 -1
- package/src/cli/cmd_Social.ts +226 -0
- package/src/cli/cmd_Start.ts +1 -1
- package/src/cli/cmd_Time.ts +1 -1
- package/src/cli/cmd_Trailer.ts +9 -2
- package/src/cli/cmd_Veille.ts +173 -0
- package/src/cli/family-pages.ts +3 -0
- package/src/cli/registry.ts +13 -2
- package/src/cli.ts +5 -2
- package/src/collections/actions.ts +1 -49
- package/src/collections/checks.ts +2 -1
- package/src/collections/collection-types.ts +11 -2
- package/src/collections/providers.ts +4 -4
- package/src/collections/review.ts +2 -1
- package/src/collections/tests.ts +19 -8
- package/src/contracts/apply-contracts.ts +1 -3
- package/src/contracts/contract-manifests.ts +2 -3
- package/src/contracts/contract-types.ts +0 -1
- package/src/contracts/contracts-engine.ts +0 -3
- package/src/core/app-icon.ts +9 -3
- package/src/core/bun-builtins.ts +2 -2
- package/src/core/discover-checks.ts +37 -5
- package/src/core/fix-scope.ts +4 -2
- package/src/core/floor-resolve.ts +68 -48
- package/src/core/floor.ts +9 -0
- package/src/core/git-root.ts +24 -0
- package/src/core/last-good.ts +3 -1
- package/src/core/layout.ts +8 -0
- package/src/core/log-stamp.ts +36 -0
- package/src/core/loop-watch.ts +93 -0
- package/src/core/machine-link.ts +134 -0
- package/src/core/memory-watch.ts +41 -0
- package/src/core/one-way-in-policy.ts +27 -19
- package/src/core/run-ci.ts +6 -8
- package/src/core/run-fixers.ts +9 -9
- package/src/core/slots.ts +21 -0
- package/src/core/tree-rev.ts +60 -0
- package/src/core/unit-files.ts +42 -0
- package/src/drill/render.ts +140 -0
- package/src/drill/run.ts +269 -0
- package/src/fleet/scan-fleet.ts +6 -5
- package/src/home/daemon-jobs.ts +201 -0
- package/src/home/global-context.ts +34 -1
- package/src/home/home-routes.ts +22 -15
- package/src/home/hubs.ts +10 -3
- package/src/home/inbox-shape.ts +61 -6
- package/src/home/inbox.ts +75 -4
- package/src/home/lib-watch.ts +10 -3
- package/src/home/machine-stores.ts +15 -29
- package/src/home/run-daemon.ts +15 -18
- package/src/home/run-pm.ts +2 -0
- package/src/home/serve-daemon.ts +4 -3
- package/src/home/serve-web.ts +110 -1
- package/src/hooks/commit-message.ts +28 -19
- package/src/hooks/leak-guard.ts +10 -3
- package/src/hooks/run-hooks.ts +2 -6
- package/src/identities/identities.ts +334 -0
- package/src/identities/machine-route.ts +126 -0
- package/src/identities/machine.ts +62 -0
- package/src/init-repo.ts +1 -1
- package/src/ledger/check-stats.ts +10 -9
- package/src/ledger/gate-checks.ts +32 -1
- package/src/ledger/record-kept.ts +112 -0
- package/src/ledger/repo-view.ts +10 -0
- package/src/ledger/run-log.ts +17 -12
- package/src/ledger/run-timeline.ts +8 -4
- package/src/ledger/store.ts +7 -0
- package/src/ledger/suite-log.ts +17 -13
- package/src/media-kinds.ts +9 -1
- package/src/media-store/backup/daemon.ts +73 -0
- package/src/media-store/backup/keys.ts +25 -0
- package/src/media-store/backup/manifest.ts +193 -0
- package/src/media-store/backup/restore.ts +192 -0
- package/src/media-store/backup/run.ts +278 -0
- package/src/media-store/backup/secret.ts +86 -0
- package/src/media-store/backup/snapshot.ts +64 -0
- package/src/media-store/backup/sources.ts +199 -0
- package/src/media-store/content.ts +11 -1
- package/src/media-store/daemon.ts +56 -70
- package/src/media-store/hand.ts +58 -0
- package/src/media-store/put.ts +122 -0
- package/src/media-store/space.ts +73 -11
- package/src/pages/forward.ts +35 -0
- package/src/pages/frame-client.ts +118 -0
- package/src/pages/routes.ts +29 -0
- package/src/pages/unit.ts +92 -0
- package/src/plan/planner.ts +12 -0
- package/src/plan/repo-source.ts +19 -5
- package/src/reflect/transcript.ts +35 -10
- package/src/release/public-clean.ts +301 -0
- package/src/release/published-here.ts +22 -0
- package/src/release/run-bump.ts +2 -1
- package/src/release/run-release.ts +4 -1
- package/src/repo-config.ts +53 -2
- package/src/review/http.ts +16 -2
- package/src/review/media-kind.ts +3 -3
- package/src/review/media-read.ts +3 -3
- package/src/review/model.ts +24 -5
- package/src/review/notes.ts +77 -0
- package/src/review/project.ts +6 -38
- package/src/review/routes.ts +8 -13
- package/src/review/store.ts +46 -4
- package/src/review/trailer-media.ts +24 -3
- package/src/review/trailer-shots.ts +106 -0
- package/src/review/unit.ts +1 -1
- package/src/scaffold/files/agent-handoff.md +3 -0
- package/src/scaffold/files/agent-index.md +4 -12
- package/src/scaffold/project-scaffold.ts +5 -4
- package/src/serve/embed.ts +1 -1
- package/src/serve/hub-app/col-card.tsx +3 -17
- package/src/serve/hub-app/col-tables-view.tsx +2 -1
- package/src/serve/hub-app/cols-svc.ts +12 -14
- package/src/serve/hub-app/dock-st.ts +4 -2
- package/src/serve/hub-app/dock-view.tsx +2 -0
- package/src/serve/hub-app/frames-st.ts +35 -0
- package/src/serve/hub-app/hash-route.ts +64 -1
- package/src/serve/hub-app/home-st.ts +31 -7
- package/src/serve/hub-app/home-strip.css +9 -1
- package/src/serve/hub-app/home-strip.tsx +7 -6
- package/src/serve/hub-app/home.html +5 -0
- package/src/serve/hub-app/hub-app.tsx +49 -5
- package/src/serve/hub-app/hub.css +29 -11
- package/src/serve/hub-app/icons.tsx +16 -1
- package/src/serve/hub-app/identities-st.ts +210 -0
- package/src/serve/hub-app/identities-view.tsx +352 -0
- package/src/serve/hub-app/identities.css +48 -0
- package/src/serve/hub-app/identity-address.ts +52 -0
- package/src/serve/hub-app/inbox-st.ts +59 -6
- package/src/serve/hub-app/inbox-view.tsx +48 -6
- package/src/serve/hub-app/inbox.css +12 -1
- package/src/serve/hub-app/index.html +3 -0
- package/src/serve/hub-app/keys.ts +10 -2
- package/src/serve/hub-app/list-walk.ts +89 -0
- package/src/serve/hub-app/machine-st.ts +12 -0
- package/src/serve/hub-app/media-view.tsx +2 -1
- package/src/serve/hub-app/pages-frames.tsx +134 -0
- package/src/serve/hub-app/pages-svc.ts +111 -0
- package/src/serve/hub-app/palette-st.ts +18 -3
- package/src/serve/hub-app/palette-view.tsx +9 -2
- package/src/serve/hub-app/planned-view.tsx +2 -1
- package/src/serve/hub-app/project-list.css +18 -14
- package/src/serve/hub-app/project-list.tsx +88 -49
- package/src/serve/hub-app/projects-svc.ts +33 -3
- package/src/serve/hub-app/repo-sections.ts +19 -2
- package/src/serve/hub-app/repo-st.ts +75 -19
- package/src/serve/hub-app/review/review-cells.tsx +3 -3
- package/src/serve/hub-app/review/review-kit.ts +30 -7
- package/src/serve/hub-app/review/review-page.tsx +1 -1
- package/src/serve/hub-app/review/review-st.ts +33 -11
- package/src/serve/hub-app/review/review-thread.tsx +11 -9
- package/src/serve/hub-app/review/review-views.tsx +84 -19
- package/src/serve/hub-app/review/thread-st.ts +1 -10
- package/src/serve/hub-app/review/trailer-page.tsx +2 -1
- package/src/serve/hub-app/review.css +17 -8
- package/src/serve/hub-app/site/site-part.tsx +173 -0
- package/src/serve/hub-app/site/site-st.ts +157 -0
- package/src/serve/hub-app/site.css +35 -0
- package/src/serve/hub-app/social/calendar.tsx +182 -0
- package/src/serve/hub-app/social/comms-page.tsx +306 -0
- package/src/serve/hub-app/social/kit.tsx +244 -0
- package/src/serve/hub-app/social/post-card.tsx +456 -0
- package/src/serve/hub-app/social/problems.tsx +60 -0
- package/src/serve/hub-app/social/social-model.ts +154 -0
- package/src/serve/hub-app/social/social-page.tsx +674 -0
- package/src/serve/hub-app/social/social-st.ts +986 -0
- package/src/serve/hub-app/social.css +289 -0
- package/src/serve/hub-app/stores/stores-page.tsx +311 -0
- package/src/serve/hub-app/stores/stores-st.ts +286 -0
- package/src/serve/hub-app/stores.css +54 -0
- package/src/serve/hub-app/test-view.tsx +9 -2
- package/src/serve/hub-app/tests-svc.ts +16 -1
- package/src/serve/hub-app/timeline-geometry.ts +1 -1
- package/src/serve/hub-app/timeline-view.tsx +3 -2
- package/src/serve/hub-app/tree-build.ts +6 -0
- package/src/serve/hub-app/tree-row.tsx +27 -4
- package/src/serve/hub-app/tree-svc.ts +18 -49
- package/src/serve/hub-app/veille/veille-page.tsx +514 -0
- package/src/serve/hub-app/veille/veille-st.ts +443 -0
- package/src/serve/hub-app/veille.css +84 -0
- package/src/serve/hub-runtime.ts +14 -9
- package/src/serve/project-gutter-route.ts +44 -12
- package/src/serve/resources-wire.ts +48 -0
- package/src/serve/run-lanes.ts +7 -4
- package/src/serve/same-origin.ts +1 -1
- package/src/serve/serve-hub.ts +27 -18
- package/src/serve/tracked-watch.ts +24 -3
- package/src/serve/warm-cell.ts +5 -1
- package/src/shipkit-files.ts +15 -4
- package/src/shipkit.ts +0 -1
- package/src/shot/box.ts +162 -0
- package/src/shot/browser-slot.ts +62 -0
- package/src/shot/client.ts +43 -7
- package/src/shot/clip-encoder.ts +93 -12
- package/src/shot/film-box.ts +188 -0
- package/src/shot/shooter.ts +50 -15
- package/src/shot/shot-ask.ts +10 -2
- package/src/shot/stepped-clip.ts +5 -4
- package/src/site/desk.ts +242 -0
- package/src/site/routes.ts +66 -0
- package/src/site/unit.ts +62 -0
- package/src/social/brands.ts +22 -0
- package/src/social/compose.ts +97 -0
- package/src/social/desk-index.ts +123 -0
- package/src/social/desk-wire.ts +64 -0
- package/src/social/drafts.ts +183 -0
- package/src/social/house.ts +24 -0
- package/src/social/load.ts +319 -0
- package/src/social/md.ts +70 -0
- package/src/social/media-facts.ts +53 -0
- package/src/social/media-kind.ts +189 -0
- package/src/social/media-limit.ts +42 -0
- package/src/social/media-of.ts +30 -0
- package/src/social/migrate.ts +123 -0
- package/src/social/open.ts +17 -0
- package/src/social/post-url.ts +158 -0
- package/src/social/presence.ts +332 -0
- package/src/social/public-read.ts +53 -0
- package/src/social/publish/bluesky.ts +168 -0
- package/src/social/publish/discord.ts +76 -0
- package/src/social/publish/index.ts +24 -0
- package/src/social/publish/secret.ts +13 -0
- package/src/social/push.ts +31 -0
- package/src/social/richtext.ts +37 -0
- package/src/social/routes.ts +180 -0
- package/src/social/stats.ts +134 -0
- package/src/social/text.ts +267 -0
- package/src/social/tracker-route.ts +39 -0
- package/src/social/tracker.ts +255 -0
- package/src/social/unit.ts +53 -0
- package/src/social/writes.ts +130 -0
- package/src/start-repo.ts +14 -9
- package/src/stores/collection.ts +27 -0
- package/src/stores/desk.ts +336 -0
- package/src/stores/model.ts +187 -0
- package/src/stores/routes.ts +126 -0
- package/src/stores/unit.ts +57 -0
- package/src/suite/calibrate.ts +127 -0
- package/src/suite/core-counters.ts +91 -0
- package/src/suite/judge-suites.ts +94 -34
- package/src/suite/suite-cli.ts +44 -10
- package/src/suite/suite-cpu-preload.ts +34 -9
- package/src/trailer/adapter.ts +4 -0
- package/src/trailer/build.ts +42 -11
- package/src/trailer/ffmpeg.ts +11 -0
- package/src/trailer/footage.ts +30 -13
- package/src/trailer/grammar.ts +18 -2
- package/src/trailer/graph.ts +28 -6
- package/src/trailer/passage.ts +21 -6
- package/src/trailer/plan.ts +74 -3
- package/src/trailer/shelf.ts +16 -0
- package/src/trailer/stitch.ts +67 -26
- package/src/trailer/url.ts +1 -1
- package/src/trailer/versions.ts +24 -0
- package/src/ts/gate-typecheck.ts +32 -0
- package/src/ts/typecheck-cli.ts +9 -11
- package/src/tui/tui-app.tsx +0 -1
- package/src/veille/asks.ts +155 -0
- package/src/veille/auto.ts +31 -0
- package/src/veille/batch.ts +27 -0
- package/src/veille/chrome.ts +127 -0
- package/src/veille/collection.ts +28 -0
- package/src/veille/desk.ts +242 -0
- package/src/veille/identity.ts +80 -0
- package/src/veille/import.ts +68 -0
- package/src/veille/log.ts +183 -0
- package/src/veille/platforms.ts +118 -0
- package/src/veille/reads.ts +66 -0
- package/src/veille/replied.ts +110 -0
- package/src/veille/routes.ts +185 -0
- package/src/veille/service.ts +81 -0
- package/src/veille/watch.ts +116 -0
- package/src/veille/worth.ts +46 -0
- package/src/wiki/scan-md.ts +18 -0
- package/src/collections/posts.ts +0 -142
- package/src/contracts/manifests/social.contract.ts +0 -20
- package/src/scaffold/files/agent-coding.md +0 -35
- package/src/ts/typecheck-cache.ts +0 -11
package/src/shot/box.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// THE BOX ROUTE: a repo whose repo.config.ts `browsers.box` names an ssh host films there when it runs on a Mac. Every
|
|
2
|
+
// browser start of the repo (a take, a Shooter: sk shot, look sheets, thumbs, the trailer's films) asks `openBrowser`,
|
|
3
|
+
// which on such a Mac connects to the box's warm chromium (film-box.ts) instead of launching one: its devtools reached
|
|
4
|
+
// through an ssh forward, each localhost page it opens reached back on this Mac through a reverse forward (the urls
|
|
5
|
+
// unchanged), its frames drawn and encoded on the box's GPU, only the result crossing back. Anywhere else, or with
|
|
6
|
+
// SK_FILM_HERE=1 for one run, it launches here as before, under the browser cap either way.
|
|
7
|
+
//
|
|
8
|
+
// The one constraint a reader breaks first: a box that does not answer is one loud line and nothing filmed, never a
|
|
9
|
+
// browser launched on the Mac instead (the Mac is the machine the route protects).
|
|
10
|
+
import { createHash } from 'crypto'
|
|
11
|
+
import { readFileSync } from 'fs'
|
|
12
|
+
import { browserCap, type BrowserCap, browserSlot, HERE_ENV } from './browser-slot.ts'
|
|
13
|
+
import { CDP_PORT } from './film-box.ts'
|
|
14
|
+
|
|
15
|
+
/** the box this machine films on for the repo, or null: a Mac whose repo names one, unless SK_FILM_HERE=1 */
|
|
16
|
+
export function filmBox(c: Pick<BrowserCap, 'box'> | null, env: Record<string, string | undefined> = process.env, platform = process.platform): string | null {
|
|
17
|
+
return c?.box != null && platform === 'darwin' && env[HERE_ENV] !== '1' ? c.box : null
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** the slice of playwright the route drives: a browser to connect to, its default context, a page's viewport */
|
|
21
|
+
type PwPage = { setViewportSize(v: { width: number; height: number }): Promise<void>; addInitScript(s: { content: string }): Promise<void>; close(): Promise<void> }
|
|
22
|
+
type PwContext = { newPage(): Promise<PwPage>; newCDPSession(p: PwPage): Promise<{ send(m: string, p?: Record<string, unknown>): Promise<unknown> }> }
|
|
23
|
+
export type PwBrowser = { contexts(): PwContext[]; close(): Promise<void>; isConnected(): boolean; on(e: 'disconnected', cb: () => void): void }
|
|
24
|
+
export type Pw = { chromium: { launch(o: { headless: boolean; args: string[] }): Promise<unknown>; connectOverCDP(url: string): Promise<PwBrowser> } }
|
|
25
|
+
|
|
26
|
+
/** a browser opened for a repo: `browser` takes newContext as a launched one does; `reach` before a page goes to a
|
|
27
|
+
* url (the box needs this Mac's localhost port forwarded); `close` ends it and frees its slot */
|
|
28
|
+
export type Opened<B> = { browser: B; where: string; reach(url: string): Promise<void>; close(): Promise<void> }
|
|
29
|
+
|
|
30
|
+
const SSH = (box: string) => ['ssh', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', box]
|
|
31
|
+
/** where the box's devtools answer on this Mac */
|
|
32
|
+
const localCdp = (box: string): number => 40000 + (parseInt(createHash('sha1').update(box).digest('hex').slice(0, 4), 16) % 9000)
|
|
33
|
+
const FILM_DIR = 'dev/shipkit-film'
|
|
34
|
+
const BOX_FILE = new URL('./film-box.ts', import.meta.url).pathname
|
|
35
|
+
const BOX_SCRIPT = readFileSync(BOX_FILE)
|
|
36
|
+
const BOX_HASH = createHash('sha1').update(BOX_SCRIPT).digest('hex').slice(0, 12)
|
|
37
|
+
const MISSING = 86
|
|
38
|
+
|
|
39
|
+
const down = (box: string, why: string): Error =>
|
|
40
|
+
new Error(`${box} is down, nothing filmed (${why.trim().split('\n').at(-1) ?? why}). To film on this Mac for one run: ${HERE_ENV}=1 <the same command>`)
|
|
41
|
+
|
|
42
|
+
async function run(cmd: string[], stdin?: Uint8Array): Promise<{ code: number; out: string; err: string }> {
|
|
43
|
+
const p = Bun.spawn(cmd, { stdin: stdin ?? 'ignore', stdout: 'pipe', stderr: 'pipe' })
|
|
44
|
+
const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()])
|
|
45
|
+
return { code: await p.exited, out, err }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** the box's warm browser answering, its script uploaded first when the box lacks this version of it */
|
|
49
|
+
async function boxUp(box: string, version: string, say: (l: string) => void): Promise<string> {
|
|
50
|
+
const script = `${FILM_DIR}/film-box-${BOX_HASH}.ts`
|
|
51
|
+
const go = () => run([...SSH(box), `if exist ${script.replaceAll('/', '\\')} (bun ${script} up ${version}) else (exit ${MISSING})`])
|
|
52
|
+
let r = await go()
|
|
53
|
+
if (r.code === MISSING) {
|
|
54
|
+
await run([...SSH(box), `mkdir ${FILM_DIR.replaceAll('/', '\\')} 2>nul`])
|
|
55
|
+
const up = await run(['scp', '-q', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', BOX_FILE, `${box}:${script}`])
|
|
56
|
+
if (up.code === 255 && /connect|resolve|timed out|refused/i.test(up.err)) throw down(box, up.err)
|
|
57
|
+
if (up.code !== 0) throw new Error(`${box}: uploading ${script} failed (exit ${up.code}): ${up.err.trim()}`)
|
|
58
|
+
r = await go()
|
|
59
|
+
}
|
|
60
|
+
if (r.code === 255) throw down(box, r.err)
|
|
61
|
+
if (r.code !== 0) throw new Error(`${box}: its film browser did not come up (exit ${r.code}): ${r.err.trim()}`)
|
|
62
|
+
for (const l of r.err.split('\n').filter(Boolean)) say(l)
|
|
63
|
+
return r.out.trim()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** an ssh forward added to the box's master connection (instant, kept with it), else a tunnel process of our own */
|
|
67
|
+
async function forward(box: string, spec: string[], own: { p: ReturnType<typeof Bun.spawn> | null }): Promise<void> {
|
|
68
|
+
const r = await run(['ssh', '-O', 'forward', ...spec, box])
|
|
69
|
+
if (r.code === 0) return
|
|
70
|
+
own.p?.kill()
|
|
71
|
+
own.p = Bun.spawn([...SSH(box), '-N', '-o', 'ExitOnForwardFailure=yes', ...spec], { stdin: 'ignore', stdout: 'ignore', stderr: 'pipe' })
|
|
72
|
+
await Bun.sleep(1500)
|
|
73
|
+
if (own.p.exitCode != null) throw down(box, await new Response(own.p.stderr as ReadableStream).text())
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
77
|
+
|
|
78
|
+
/** the box's default context as a launched browser's newContext: each context a set of pages there, the viewport set
|
|
79
|
+
* per page; one context because only it keeps the profile's HTTP cache */
|
|
80
|
+
function asLaunched(b: PwBrowser, all: PwPage[]) {
|
|
81
|
+
return {
|
|
82
|
+
isConnected: () => b.isConnected(),
|
|
83
|
+
on: (e: 'disconnected', cb: () => void) => b.on(e, cb),
|
|
84
|
+
close: async () => {
|
|
85
|
+
await Promise.all(all.splice(0).map((p) => p.close().catch(() => undefined)))
|
|
86
|
+
await b.close()
|
|
87
|
+
},
|
|
88
|
+
async newContext(o: { viewport: { width: number; height: number }; deviceScaleFactor: number }) {
|
|
89
|
+
const ctx = b.contexts()[0]
|
|
90
|
+
if (ctx == null) throw new Error('the box browser has no default context')
|
|
91
|
+
const pages: PwPage[] = []
|
|
92
|
+
const scripts: string[] = []
|
|
93
|
+
return {
|
|
94
|
+
async newPage() {
|
|
95
|
+
const p = await ctx.newPage()
|
|
96
|
+
pages.push(p)
|
|
97
|
+
all.push(p)
|
|
98
|
+
await p.setViewportSize(o.viewport)
|
|
99
|
+
if (o.deviceScaleFactor !== 1)
|
|
100
|
+
await (await ctx.newCDPSession(p)).send('Emulation.setDeviceMetricsOverride', { ...o.viewport, deviceScaleFactor: o.deviceScaleFactor, mobile: false })
|
|
101
|
+
for (const content of scripts) await p.addInitScript({ content })
|
|
102
|
+
return p
|
|
103
|
+
},
|
|
104
|
+
newCDPSession: (p: PwPage) => ctx.newCDPSession(p),
|
|
105
|
+
async addInitScript(s: { content: string }) {
|
|
106
|
+
scripts.push(s.content)
|
|
107
|
+
for (const p of pages) await p.addInitScript(s)
|
|
108
|
+
},
|
|
109
|
+
async close() {
|
|
110
|
+
await Promise.all(pages.splice(0).map((p) => p.close().catch(() => undefined)))
|
|
111
|
+
},
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** a browser for `who` of the repo at `root`: on its box from a Mac (filmBox), else launched here; one of the repo's
|
|
118
|
+
* browser slots held until close */
|
|
119
|
+
export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void }): Promise<Opened<B>> {
|
|
120
|
+
const say = o.say ?? ((l: string) => console.error(l))
|
|
121
|
+
const cap = await browserCap(o.root)
|
|
122
|
+
const box = filmBox(cap)
|
|
123
|
+
const release = await browserSlot(o.who, { ...(o.root ? { root: o.root } : {}), say, onBox: box != null })
|
|
124
|
+
try {
|
|
125
|
+
if (box == null) {
|
|
126
|
+
const b = (await pw.chromium.launch({ headless: true, args: o.args })) as B & { close(): Promise<void> }
|
|
127
|
+
return { browser: b, where: 'here', reach: async () => undefined, close: () => b.close().catch(() => undefined).finally(release) }
|
|
128
|
+
}
|
|
129
|
+
const t = performance.now()
|
|
130
|
+
const version = (JSON.parse(readFileSync(Bun.resolveSync('playwright-core/package.json', import.meta.dir), 'utf8')) as { version: string }).version
|
|
131
|
+
const state = await boxUp(box, version, say)
|
|
132
|
+
const own: { p: ReturnType<typeof Bun.spawn> | null } = { p: null }
|
|
133
|
+
const cdp = localCdp(box)
|
|
134
|
+
await forward(box, ['-L', `${cdp}:127.0.0.1:${CDP_PORT}`], own)
|
|
135
|
+
const b = await pw.chromium.connectOverCDP(`http://127.0.0.1:${cdp}`)
|
|
136
|
+
say(`${o.who}: filming on ${box} (${state.split(' ').slice(0, 2).join(' ')}, ${Math.round(performance.now() - t)} ms to its browser)`)
|
|
137
|
+
const reached = new Set<number>()
|
|
138
|
+
const pages: PwPage[] = []
|
|
139
|
+
const browser = asLaunched(b, pages)
|
|
140
|
+
return {
|
|
141
|
+
browser: browser as B,
|
|
142
|
+
where: box,
|
|
143
|
+
async reach(url: string) {
|
|
144
|
+
const u = new URL(url)
|
|
145
|
+
if (!LOCAL.has(u.hostname)) return
|
|
146
|
+
const port = Number(u.port || (u.protocol === 'https:' ? 443 : 80))
|
|
147
|
+
if (reached.has(port)) return
|
|
148
|
+
await forward(box, ['-R', `${port}:127.0.0.1:${port}`], own)
|
|
149
|
+
reached.add(port)
|
|
150
|
+
},
|
|
151
|
+
async close() {
|
|
152
|
+
// its pages close, the connection drops, the box's browser stays warm
|
|
153
|
+
await browser.close().catch(() => undefined)
|
|
154
|
+
own.p?.kill()
|
|
155
|
+
release()
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
} catch (e) {
|
|
159
|
+
release()
|
|
160
|
+
throw e
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// THE BROWSER CAP: every headless browser that shoots or records on a repo's behalf (an sk shot ask, a Shooter given
|
|
2
|
+
// a slot, sk smoke, the trailer's films, a repo script's own browser) holds one slot of that repo's pool
|
|
3
|
+
// (core/slots.ts browserPool) for its whole life; repo.config.ts `browsers.max` sizes the pool. A slot left by a dead
|
|
4
|
+
// process is free at once (the lease's liveness rule). A repo whose `browsers.box` names a host never starts one on a
|
|
5
|
+
// Mac: browserSlot refuses there, but for the box route's own slot (`onBox`, box.ts) and SK_FILM_HERE=1.
|
|
6
|
+
//
|
|
7
|
+
// The one constraint a reader breaks first: the slot belongs to the process that starts the browser. A parent that
|
|
8
|
+
// holds one and waits on a child that takes one deadlocks at cap 1, so a parent only counts its children (the
|
|
9
|
+
// trailer's lanes are the cap) and never holds a slot for them.
|
|
10
|
+
import { existsSync } from 'fs'
|
|
11
|
+
import { dirname, join, resolve } from 'path'
|
|
12
|
+
import { browserPool, browsersProblem, DEFAULT_BROWSERS, takeSlot } from '../core/slots.ts'
|
|
13
|
+
|
|
14
|
+
/** one run films on this machine even though its repo names a box: the owner's switch when the box is off */
|
|
15
|
+
export const HERE_ENV = 'SK_FILM_HERE'
|
|
16
|
+
|
|
17
|
+
export type BrowserCap = { repo: string; cap: number; root: string; box: string | null }
|
|
18
|
+
|
|
19
|
+
/** the nearest dir at or above `from` holding a repo.config.ts, or null */
|
|
20
|
+
function configRoot(from: string): string | null {
|
|
21
|
+
for (let d = resolve(from); ; d = dirname(d)) {
|
|
22
|
+
if (existsSync(join(d, 'repo.config.ts'))) return d
|
|
23
|
+
if (dirname(d) === d) return null
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** the browser cap of the repo at `root` (default: the repo the cwd is in), or null outside any repo; a value that is
|
|
28
|
+
* not a whole number of browsers throws */
|
|
29
|
+
export async function browserCap(root?: string): Promise<BrowserCap | null> {
|
|
30
|
+
const at = root ?? configRoot(process.cwd())
|
|
31
|
+
if (at == null || !existsSync(join(at, 'repo.config.ts'))) return null
|
|
32
|
+
const { loadRepoConfig } = await import('../repo-config.ts')
|
|
33
|
+
const c = await loadRepoConfig(at)
|
|
34
|
+
const bad = browsersProblem(c.browsers)
|
|
35
|
+
if (bad != null) throw new Error(`${join(at, 'repo.config.ts')}: ${bad}`)
|
|
36
|
+
return { repo: c.name, cap: c.browsers?.max ?? DEFAULT_BROWSERS, root: at, box: c.browsers?.box ?? null }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** why `who` may not start a browser of this repo on this machine, or null: a repo filmed by its box never starts one
|
|
40
|
+
* on a Mac, unless the slot is the box route's own (its browser on the box) */
|
|
41
|
+
export function browserRefusal(c: Pick<BrowserCap, 'repo' | 'box'>, who: string, onBox: boolean, platform = process.platform, env: Record<string, string | undefined> = process.env): string | null {
|
|
42
|
+
if (c.box == null || onBox || platform !== 'darwin' || env[HERE_ENV] === '1') return null
|
|
43
|
+
return `${who}: ${c.repo} films on ${c.box} (repo.config.ts browsers.box), so no browser of it starts on this Mac: a browser goes through shot/box.ts openBrowser (${HERE_ENV}=1 films here for one run, the owner's call)`
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** wait for one of the repo's browser slots and hold it until the returned release (or this process ends), saying
|
|
47
|
+
* once whom it waits on; outside any repo there is no cap and nothing is held. `onBox`: the browser runs on the
|
|
48
|
+
* repo's box, this Mac only drives it */
|
|
49
|
+
export async function browserSlot(who: string, o: { root?: string; say?: (l: string) => void; pollMs?: number; onBox?: boolean } = {}): Promise<() => void> {
|
|
50
|
+
const c = await browserCap(o.root)
|
|
51
|
+
if (c == null) return () => undefined
|
|
52
|
+
const no = browserRefusal(c, who, o.onBox === true)
|
|
53
|
+
if (no != null) throw new Error(no)
|
|
54
|
+
const say = o.say ?? ((l: string) => console.error(l))
|
|
55
|
+
const got = await takeSlot(browserPool(c.repo, c.cap), { repo: c.repo, check: who }, {
|
|
56
|
+
pollMs: o.pollMs ?? 250,
|
|
57
|
+
onWait: (held) =>
|
|
58
|
+
say(`${who}: waiting for a browser of ${c.repo}, all ${c.cap} held (repo.config.ts browsers.max): ${held.map((h) => `pid ${h.pid} (${h.check})`).join(', ') || 'a holder starting'}`),
|
|
59
|
+
})
|
|
60
|
+
if (got == null) throw new Error(`${who}: the browser slot wait of ${c.repo} stopped with no slot`)
|
|
61
|
+
return got.release
|
|
62
|
+
}
|
package/src/shot/client.ts
CHANGED
|
@@ -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
|
-
|
|
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 =
|
|
31
|
-
const
|
|
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 =
|
|
39
|
-
const
|
|
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
|
package/src/shot/clip-encoder.ts
CHANGED
|
@@ -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)
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
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
|
|
12
|
-
//
|
|
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
|
-
|
|
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
|
|
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
|
+
}
|