rvlib-shipkit 2.19.0 → 2.21.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 (196) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/package.json +1 -1
  3. package/src/annex/annex.ts +227 -0
  4. package/src/annex/offload.ts +279 -0
  5. package/src/checks/SK004-gitignore-policy.check.ts +6 -3
  6. package/src/checks/SK040-release-words.check.ts +43 -0
  7. package/src/checks/SK041-annex-links.check.ts +28 -0
  8. package/src/checks/SK042-post-kinds.check.ts +73 -0
  9. package/src/cli/cmd_Annex.ts +179 -0
  10. package/src/cli/cmd_Commands.ts +4 -1
  11. package/src/cli/cmd_GlobalProcesses.ts +2 -107
  12. package/src/cli/cmd_Home.ts +4 -3
  13. package/src/cli/cmd_Messages.ts +155 -0
  14. package/src/cli/cmd_Overview.ts +2 -1
  15. package/src/cli/cmd_Releases.ts +84 -0
  16. package/src/cli/cmd_Review.ts +176 -12
  17. package/src/cli/cmd_Shot.ts +4 -4
  18. package/src/cli/cmd_Social.ts +151 -8
  19. package/src/cli/cmd_Sound.ts +17 -4
  20. package/src/cli/cmd_Trailer.ts +67 -1
  21. package/src/cli/family-pages.ts +2 -0
  22. package/src/cli/kit/index.ts +1 -1
  23. package/src/cli/kit/verb.ts +11 -3
  24. package/src/cli/registry.ts +7 -1
  25. package/src/collections/collection-types.ts +8 -1
  26. package/src/collections/providers.ts +4 -1
  27. package/src/collections/review.ts +23 -4
  28. package/src/commands/model.ts +36 -0
  29. package/src/commands/registry.ts +49 -0
  30. package/src/commands/routes.ts +59 -0
  31. package/src/commands/runner.ts +35 -0
  32. package/src/commands/runs.ts +112 -0
  33. package/src/core/app-icon.ts +4 -3
  34. package/src/core/icon-type.ts +8 -0
  35. package/src/core/jobs.ts +4 -3
  36. package/src/core/layout.ts +11 -2
  37. package/src/core/squircle.ts +95 -0
  38. package/src/home/daemon-jobs.ts +26 -2
  39. package/src/home/global-units.ts +3 -0
  40. package/src/home/gui-app/ShipkitGui.swift +337 -5
  41. package/src/home/gui-app.ts +64 -33
  42. package/src/home/hmr-keep.ts +134 -0
  43. package/src/home/home-start.ts +2 -2
  44. package/src/home/lib-watch.ts +21 -11
  45. package/src/home/pm-switch.ts +112 -0
  46. package/src/home/pm.ts +1 -1
  47. package/src/home/process-apps.ts +181 -0
  48. package/src/home/resources.ts +3 -3
  49. package/src/home/run-web.ts +7 -4
  50. package/src/home/serve-web.ts +64 -14
  51. package/src/identities/collection.ts +49 -0
  52. package/src/identities/identities.ts +121 -14
  53. package/src/identities/machine.ts +4 -3
  54. package/src/identities/rating.ts +33 -0
  55. package/src/identities/shown.ts +170 -0
  56. package/src/identities/steps.ts +5 -0
  57. package/src/media-store/purge.ts +15 -1
  58. package/src/media-store/remote.ts +22 -6
  59. package/src/messages/brief.ts +117 -0
  60. package/src/messages/collection.ts +40 -0
  61. package/src/messages/model.ts +171 -0
  62. package/src/messages/routes.ts +15 -0
  63. package/src/messages/score.ts +182 -0
  64. package/src/messages/tabs.ts +13 -0
  65. package/src/release/notes.ts +130 -0
  66. package/src/release/run-bump.ts +41 -18
  67. package/src/release/run-release.ts +22 -4
  68. package/src/release/run-releases.ts +17 -15
  69. package/src/release/unit-resolve.ts +9 -0
  70. package/src/releases/add.ts +94 -0
  71. package/src/releases/before.ts +31 -0
  72. package/src/releases/collection.ts +36 -0
  73. package/src/releases/from-card.ts +151 -0
  74. package/src/releases/model.ts +327 -0
  75. package/src/releases/pictures.ts +110 -0
  76. package/src/releases/routes.ts +36 -0
  77. package/src/releases/store.ts +71 -0
  78. package/src/repo-config.ts +5 -0
  79. package/src/review/cells.ts +0 -11
  80. package/src/review/format.ts +10 -6
  81. package/src/review/http.ts +1 -1
  82. package/src/review/model.ts +102 -3
  83. package/src/review/notes.ts +2 -48
  84. package/src/review/routes.ts +28 -10
  85. package/src/review/stage-card.ts +197 -0
  86. package/src/review/stage-routes.ts +123 -0
  87. package/src/review/store.ts +47 -1
  88. package/src/review/trailer-card.ts +99 -0
  89. package/src/review/trailer-desk.ts +76 -4
  90. package/src/review/trailer-model.ts +106 -7
  91. package/src/review/trailer-notes.ts +45 -0
  92. package/src/review/trailer-routes.ts +119 -13
  93. package/src/review/trailer-voices.ts +144 -0
  94. package/src/review/watchers.ts +58 -1
  95. package/src/serve/hub-app/app-bridge.ts +71 -0
  96. package/src/serve/hub-app/benign-errors.ts +22 -0
  97. package/src/serve/hub-app/commands/commands-page.tsx +122 -0
  98. package/src/serve/hub-app/commands/commands-st.ts +177 -0
  99. package/src/serve/hub-app/commands.css +24 -0
  100. package/src/serve/hub-app/hash-route.ts +59 -8
  101. package/src/serve/hub-app/home-st.ts +19 -2
  102. package/src/serve/hub-app/home.html +3 -0
  103. package/src/serve/hub-app/hub-app.tsx +8 -0
  104. package/src/serve/hub-app/icons.tsx +5 -0
  105. package/src/serve/hub-app/identities-view.tsx +4 -1
  106. package/src/serve/hub-app/identities.css +1 -0
  107. package/src/serve/hub-app/index.html +3 -0
  108. package/src/serve/hub-app/keys.ts +2 -2
  109. package/src/serve/hub-app/machine-st.ts +41 -10
  110. package/src/serve/hub-app/messages/messages-page.tsx +354 -0
  111. package/src/serve/hub-app/messages/messages-st.ts +74 -0
  112. package/src/serve/hub-app/messages.css +35 -0
  113. package/src/serve/hub-app/project-list.css +7 -2
  114. package/src/serve/hub-app/project-list.tsx +9 -0
  115. package/src/serve/hub-app/projects-svc.ts +16 -6
  116. package/src/serve/hub-app/releases/releases-page.tsx +187 -0
  117. package/src/serve/hub-app/releases/releases-st.ts +111 -0
  118. package/src/serve/hub-app/releases.css +52 -0
  119. package/src/serve/hub-app/repo-sections.ts +16 -2
  120. package/src/serve/hub-app/repo-st.ts +66 -10
  121. package/src/serve/hub-app/review/clip-st.ts +34 -4
  122. package/src/serve/hub-app/review/kit.tsx +3 -3
  123. package/src/serve/hub-app/review/note-place.ts +31 -0
  124. package/src/serve/hub-app/review/review-cells.tsx +27 -3
  125. package/src/serve/hub-app/review/review-st.ts +77 -2
  126. package/src/serve/hub-app/review/review-thread.tsx +9 -31
  127. package/src/serve/hub-app/review/review-views.tsx +164 -58
  128. package/src/serve/hub-app/review/thread-st.ts +108 -41
  129. package/src/serve/hub-app/review/trailer-card.tsx +187 -0
  130. package/src/serve/hub-app/review/trailer-page.tsx +92 -36
  131. package/src/serve/hub-app/review/trailer-st.ts +306 -34
  132. package/src/serve/hub-app/review/trailer-timeline.tsx +68 -23
  133. package/src/serve/hub-app/review/trailer-voices-st.ts +370 -0
  134. package/src/serve/hub-app/review/trailer-voices.tsx +574 -0
  135. package/src/serve/hub-app/review.css +137 -6
  136. package/src/serve/hub-app/social/comms-page.tsx +65 -28
  137. package/src/serve/hub-app/social/identity-pictures.ts +46 -8
  138. package/src/serve/hub-app/social/kit.tsx +9 -6
  139. package/src/serve/hub-app/social/next-release.tsx +118 -0
  140. package/src/serve/hub-app/social/post-card.tsx +10 -2
  141. package/src/serve/hub-app/social/social-model.ts +39 -3
  142. package/src/serve/hub-app/social/social-page.tsx +179 -65
  143. package/src/serve/hub-app/social/social-st.ts +117 -27
  144. package/src/serve/hub-app/social/stage-popup.tsx +268 -0
  145. package/src/serve/hub-app/social/stage-st.ts +310 -0
  146. package/src/serve/hub-app/social/step-layout.ts +42 -0
  147. package/src/serve/hub-app/social.css +68 -1
  148. package/src/serve/hub-app/tree-build.ts +40 -1
  149. package/src/serve/hub-app/tree-svc.ts +10 -3
  150. package/src/serve/project-gutter-route.ts +12 -2
  151. package/src/serve/project-gutter.ts +4 -2
  152. package/src/serve/same-origin.ts +24 -1
  153. package/src/serve/serve-hub.ts +15 -1
  154. package/src/shipkit-files.ts +9 -7
  155. package/src/shot/box.ts +33 -12
  156. package/src/shot/client.ts +1 -1
  157. package/src/shot/shooter.ts +22 -12
  158. package/src/shot/shot-ask.ts +14 -3
  159. package/src/shot/shot.shipkit.ts +1 -1
  160. package/src/social/desk-index.ts +49 -8
  161. package/src/social/discord-layout.ts +54 -7
  162. package/src/social/drafts.ts +1 -1
  163. package/src/social/fit.ts +84 -0
  164. package/src/social/identity-words.ts +74 -0
  165. package/src/social/kind-pages.ts +41 -0
  166. package/src/social/kinds.ts +93 -0
  167. package/src/social/load.ts +125 -10
  168. package/src/social/media-limit.ts +63 -2
  169. package/src/social/presence.ts +1 -1
  170. package/src/social/publish/bluesky.ts +58 -19
  171. package/src/social/publish/index.ts +47 -6
  172. package/src/social/reach.ts +49 -0
  173. package/src/social/release-stage.ts +277 -0
  174. package/src/social/routes.ts +44 -8
  175. package/src/social/stage.ts +246 -0
  176. package/src/social/strip.ts +85 -0
  177. package/src/social/text.ts +6 -2
  178. package/src/social/unit.ts +57 -1
  179. package/src/social/writes.ts +11 -0
  180. package/src/trailer/bed.ts +111 -0
  181. package/src/trailer/build.ts +72 -40
  182. package/src/trailer/ffmpeg.ts +6 -0
  183. package/src/trailer/grammar.ts +37 -6
  184. package/src/trailer/graph.ts +12 -1
  185. package/src/trailer/public-words.ts +41 -0
  186. package/src/trailer/shot-plan.ts +75 -0
  187. package/src/trailer/shot-state.ts +191 -0
  188. package/src/trailer/sound/audio.ts +28 -0
  189. package/src/trailer/sound/brand.ts +53 -3
  190. package/src/trailer/sound/gen.ts +61 -2
  191. package/src/trailer/sound/index.ts +25 -11
  192. package/src/trailer/sound/presets.ts +86 -5
  193. package/src/trailer/sound/run.ts +1 -1
  194. package/src/trailer/sound/takes.ts +94 -0
  195. package/src/trailer/titles.ts +36 -0
  196. package/src/trailer/url.ts +1 -1
@@ -1,5 +1,28 @@
1
1
  // the one guard on a request that changes something, shared by the hub and
2
- // the standalone graph server.
2
+ // the standalone graph server, and where a request came from.
3
+
4
+ /** a Host header's name: its port, brackets and trailing dot gone, lowercase */
5
+ export function hostName(host: string): string {
6
+ const h = host.trim().toLowerCase()
7
+ const name = h.startsWith('[') ? h.slice(1, h.indexOf(']') < 0 ? undefined : h.indexOf(']')) : h.replace(/:\d+$/, '')
8
+ return name.replace(/\.$/, '')
9
+ }
10
+
11
+ /** a name only this machine resolves to itself */
12
+ export const loopbackName = (n: string): boolean => n === 'localhost' || n.endsWith('.localhost') || n === '::1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)
13
+
14
+ /** where a request came from: this machine, or another one over the tailnet (his phone) */
15
+ export type Reach = 'local' | 'tailnet'
16
+ /** the web's tag on what it forwards to the daemon, which never sees the browser's Host */
17
+ export const REACH_HEADER = 'x-shipkit-reach'
18
+
19
+ export const reachOfHost = (host: string | null): Reach => (host != null && host !== '' && loopbackName(hostName(host)) ? 'local' : 'tailnet')
20
+
21
+ /** the web's tag when it forwarded the request, else this server's own Host */
22
+ export function reachOf(req: Request): Reach {
23
+ const tag = req.headers.get(REACH_HEADER)
24
+ return tag === 'local' || tag === 'tailnet' ? tag : reachOfHost(req.headers.get('host') ?? new URL(req.url).host)
25
+ }
3
26
  /** 127.0.0.1 keeps other machines out, not other sites: any page open in the
4
27
  * browser can POST to localhost. A request that changes something passes
5
28
  * only from the hub's own page, or from a client that is not a browser at
@@ -39,6 +39,10 @@ import { readmeRoutes } from './readme-route.ts'
39
39
  import { reviewRoutes } from '../review/routes.ts'
40
40
  import { veilleRoutes } from '../veille/routes.ts'
41
41
  import { storesRoutes } from '../stores/routes.ts'
42
+ import { messagesRoutes } from '../messages/routes.ts'
43
+ import { releasesRoutes } from '../releases/routes.ts'
44
+ import { commandsRoutes } from '../commands/routes.ts'
45
+ import { noCli } from '../commands/registry.ts'
42
46
  import { socialRoutes } from '../social/routes.ts'
43
47
  import { embedRoute } from './embed.ts'
44
48
  import { pagesRoutes } from '../pages/routes.ts'
@@ -223,7 +227,8 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
223
227
  // editor: only the server knows where this repo sits on disk
224
228
  // `uses` tells the home which machine resources this repo needs,
225
229
  // `base` where this hub's page sits on the server that answers
226
- if (path === '/hub.json') return Response.json({ hub: 'shipkit', name: d.name, root: d.root, base, tools, uses: d.uses ?? [] })
230
+ // `cli`: the repo has a project CLI, so its commands section is no greyed row
231
+ if (path === '/hub.json') return Response.json({ hub: 'shipkit', name: d.name, root: d.root, base, tools, uses: d.uses ?? [], cli: noCli(d.root) == null })
227
232
  if (path.startsWith('/api/projects')) return (await projects.handle(req, path)) ?? new Response('not found', { status: 404 })
228
233
  // where the machine's home serves, and whether it does: a rail
229
234
  // click opens the home on that repo, or VS Code while none runs
@@ -367,6 +372,15 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
367
372
  // the store pages' desk (stores/routes.ts)
368
373
  const stores = await storesRoutes(d.root, req, path)
369
374
  if (stores != null) return stores
375
+ // the release files and their private pictures (releases/routes.ts)
376
+ const releases = await releasesRoutes(d.root, req, path)
377
+ if (releases != null) return releases
378
+ // the project CLI run from the page (commands/routes.ts)
379
+ const commands = await commandsRoutes(d.root, req, path)
380
+ if (commands != null) return commands
381
+ // the messages store, read whole (messages/routes.ts)
382
+ const messages = messagesRoutes(d.root, req, path)
383
+ if (messages != null) return messages
370
384
  // the Communications and Social desks (social/routes.ts)
371
385
  const social = await socialRoutes(d.root, req, path)
372
386
  if (social != null) return social
@@ -25,12 +25,13 @@
25
25
  import { check, type CheckDef } from './check.ts'
26
26
  import { review, type AutoRule, type KindDef, type ReviewDef, type ReviewSource, type ReviewUnit } from './review/unit.ts'
27
27
  import { site, type SiteDef, type SiteUnit } from './site/unit.ts'
28
- import { social, type SocialDef, type SocialUnit } from './social/unit.ts'
28
+ import { social, type GuardInput, type ReleaseHeading, type SocialDef, type SocialUnit, type SuggestedLine } from './social/unit.ts'
29
29
  import { stores, type StoresDef, type StoresUnit } from './stores/unit.ts'
30
30
  import { trailer, type TrailerDef, type TrailerUnit } from './trailer/adapter.ts'
31
+ import { ICON_IMAGE_TYPES, iconImageType } from './core/icon-type.ts'
31
32
 
32
33
  export { check, review, site, social, stores, trailer }
33
- export type { AutoRule, KindDef, ReviewDef, ReviewSource, ReviewUnit, SiteDef, SiteUnit, SocialDef, SocialUnit, StoresDef, StoresUnit, TrailerDef, TrailerUnit }
34
+ export type { AutoRule, GuardInput, KindDef, ReleaseHeading, ReviewDef, ReviewSource, ReviewUnit, SiteDef, SiteUnit, SocialDef, SocialUnit, StoresDef, StoresUnit, SuggestedLine, TrailerDef, TrailerUnit }
34
35
 
35
36
  /** one button beside a global process: a command, or a function of the file */
36
37
  export type ProcessAction = {
@@ -48,6 +49,10 @@ export type GlobalProcessDef = {
48
49
  id: string
49
50
  /** the name on the switch (default the id) */
50
51
  label?: string
52
+ /** the name of its macOS app in ~/Applications, where Spotlight and
53
+ * Launchpad find it (default the label). Only a process with a url has
54
+ * one; the daemon builds it, and removes it when the process goes */
55
+ app?: string
51
56
  /** one line: what it is for */
52
57
  description?: string
53
58
  /** the machine it runs on, as a hint beside the switch */
@@ -93,11 +98,7 @@ const KEBAB = /^[a-z0-9][a-z0-9-]*$/
93
98
  const words = (v: unknown): boolean => Array.isArray(v) && v.length > 0 && v.every((w) => typeof w === 'string')
94
99
  const httpUrl = (v: unknown): boolean => typeof v === 'string' && /^https?:\/\//.test(v)
95
100
 
96
- /** the image types an icon file can be, by extension */
97
- export const ICON_IMAGE_TYPES: Record<string, string> = { png: 'image/png', svg: 'image/svg+xml', ico: 'image/x-icon', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp' }
98
-
99
- /** the image an icon names (its extension), or null when it is text */
100
- export const iconImageType = (icon: string): string | null => ICON_IMAGE_TYPES[/\.([a-z]+)$/i.exec(icon)?.[1]?.toLowerCase() ?? ''] ?? null
101
+ export { ICON_IMAGE_TYPES, iconImageType }
101
102
 
102
103
  function iconProblem(icon: unknown): string | null {
103
104
  if (typeof icon !== 'string' || icon.trim() === '') return 'icon is an emoji or a repo relative image path'
@@ -113,6 +114,7 @@ export function globalProcessProblem(d: GlobalProcessDef): string | null {
113
114
  if (!words(d.cmd)) return `${at}: cmd is a list of words`
114
115
  if (d.down != null && !words(d.down)) return `${at}: down is a list of words`
115
116
  if (d.url != null && !httpUrl(d.url)) return `${at}: url must be an http url`
117
+ if (d.app !== undefined && (typeof d.app !== 'string' || d.app.trim() === '' || /^\.|[/:]/.test(d.app))) return `${at}: app is a file name: not empty, no leading dot, no / or :`
116
118
  if (d.probe != null && !httpUrl(d.probe)) return `${at}: probe must be an http url`
117
119
  if (d.down != null && d.probe == null && d.url == null) return `${at}: a bring-up (one with down) needs probe or url, the only truth of whether it is up`
118
120
  if (d.icon !== undefined) {
package/src/shot/box.ts CHANGED
@@ -34,6 +34,25 @@ export type Pw = { chromium: { launch(o: { headless: boolean; args: string[] }):
34
34
  * url (the box needs this Mac's localhost port forwarded); `close` ends it and frees its slot */
35
35
  export type Opened<B> = { browser: B; where: string; reach(url: string): Promise<void>; close(): Promise<void> }
36
36
 
37
+ /** a browser close that has not answered in this long (a stalled box route) is left behind, so its slot frees */
38
+ export const CLOSE_MS = 5000
39
+
40
+ /** the close of a browser, left after CLOSE_MS, then its slot freed whatever the close did */
41
+ const closeThenFree = async (close: () => Promise<void>, free: () => void): Promise<void> => {
42
+ try {
43
+ await Promise.race([close().catch(() => undefined), Bun.sleep(CLOSE_MS)])
44
+ } finally {
45
+ free()
46
+ }
47
+ }
48
+
49
+ /** wait for one of the repo's browser slots where its browser would run (on its box from a Mac), and hold it until
50
+ * the release: a caller that waits in the queue apart from its own timed work holds it first (openBrowser `held`) */
51
+ export async function slotFor(o: { root?: string; who: string; say?: (l: string) => void }): Promise<() => void> {
52
+ const box = filmBox(await browserCap(o.root))
53
+ return browserSlot(o.who, { ...(o.root ? { root: o.root } : {}), ...(o.say ? { say: o.say } : {}), onBox: box != null })
54
+ }
55
+
37
56
  const SSH = (box: string) => ['ssh', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', box]
38
57
  /** where the box's devtools answer on this Mac */
39
58
  const localCdp = (box: string): number => 40000 + (parseInt(createHash('sha1').update(box).digest('hex').slice(0, 4), 16) % 9000)
@@ -134,16 +153,15 @@ export function asLaunched(b: PwBrowser, all: PwPage[], store: BoxStore = 'job')
134
153
  }
135
154
 
136
155
  /** a browser for `who` of the repo at `root`: on its box from a Mac (filmBox), else launched here; one of the repo's
137
- * browser slots held until close */
138
- export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void; store?: BoxStore }): Promise<Opened<B>> {
156
+ * browser slots held until close (`held`: one its caller already holds from slotFor, freed here as one taken here) */
157
+ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void; store?: BoxStore; held?: () => void }): Promise<Opened<B>> {
139
158
  const say = o.say ?? ((l: string) => console.error(l))
140
- const cap = await browserCap(o.root)
141
- const box = filmBox(cap)
142
- const release = await browserSlot(o.who, { ...(o.root ? { root: o.root } : {}), say, onBox: box != null })
159
+ const box = filmBox(await browserCap(o.root))
160
+ const release = o.held ?? (await slotFor({ ...(o.root ? { root: o.root } : {}), who: o.who, say }))
143
161
  try {
144
162
  if (box == null) {
145
163
  const b = (await pw.chromium.launch({ headless: true, args: o.args })) as B & { close(): Promise<void> }
146
- return { browser: b, where: 'here', reach: async () => undefined, close: () => b.close().catch(() => undefined).finally(release) }
164
+ return { browser: b, where: 'here', reach: async () => undefined, close: () => closeThenFree(() => b.close(), release) }
147
165
  }
148
166
  const t = performance.now()
149
167
  const version = (JSON.parse(readFileSync(Bun.resolveSync('playwright-core/package.json', import.meta.dir), 'utf8')) as { version: string }).version
@@ -169,12 +187,15 @@ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; ar
169
187
  await forward(box, ['-R', `${port}:127.0.0.1:${port}`], own)
170
188
  reached.add(port)
171
189
  },
172
- async close() {
173
- // its pages close, the connection drops, the box's browser stays warm
174
- await browser.close().catch(() => undefined)
175
- own.p?.kill()
176
- release()
177
- },
190
+ // its pages close, the connection drops, the box's browser stays warm
191
+ close: () =>
192
+ closeThenFree(
193
+ () => browser.close(),
194
+ () => {
195
+ own.p?.kill()
196
+ release()
197
+ },
198
+ ),
178
199
  }
179
200
  } catch (e) {
180
201
  release()
@@ -99,7 +99,7 @@ async function ask(route: '/shot' | '/clip', a: ShotAsk | ClipAsk, log: (l: stri
99
99
  const { pmUp, pmUrl } = await import('../home/home-paths.ts')
100
100
  if (process.env['CI'] == null && process.env['SHIPKIT_NO_HOME'] == null && (await pmUp())) {
101
101
  log(`shot: starting the shot service (sk gp start ${SHOT_PROCESS})`)
102
- const { pmSwitchDeps, switchProcess } = await import('../cli/cmd_GlobalProcesses.ts')
102
+ const { pmSwitchDeps, switchProcess } = await import('../home/pm-switch.ts')
103
103
  const code = await switchProcess(SHOT_PROCESS, 'start', pmSwitchDeps(log, pmUrl()), 60_000)
104
104
  if (code !== 0) throw new Error(`the shot service did not start through pm: sk gp shows where it stands`)
105
105
  const started = await post(route, a)
@@ -26,8 +26,8 @@ import { dirname } from 'path'
26
26
  import { loadPlaywright } from '../smoke/run-smoke.ts'
27
27
  import { CLIP_INIT, CLIP_QUANTIZER, clipDone, installClip, KEY_EVERY, muxArgs, type PageClipAsk, type PageClipDone, TAKE, takeClip } from './clip-encoder.ts'
28
28
  import { type ClipPath, clipPathOf, domEncodeArgs, FrameTimeline, largestCanvas, screencastParams } from './dom-clip.ts'
29
- import { openBrowser, type PwBrowser } from './box.ts'
30
- import { capMsOf, type ClipAsk, pageMove, readMark, type ShotAsk, slotKey, Turns, waitReady } from './shot-ask.ts'
29
+ import { CLOSE_MS, openBrowser, type PwBrowser, slotFor } from './box.ts'
30
+ import { capMsOf, type ClipAsk, pageMove, readMark, type ShotAsk, slotKey, stillFormat, Turns, waitReady } from './shot-ask.ts'
31
31
 
32
32
  /** the slice of playwright the shots touch, so the lib types nothing it does not ship */
33
33
  type Cdp = {
@@ -82,8 +82,6 @@ export const LIVE_MS = 10_000
82
82
  export const BROWSER_IDLE_MS = 60_000
83
83
  /** the niceness of the process that launches the browser: chromium inherits it */
84
84
  export const SHOT_NICE = 10
85
- /** a browser close that has not answered in this long (a stalled box route) is left behind, so its slot frees */
86
- export const CLOSE_MS = 5000
87
85
  /** a page that paints nothing once the screencast starts is filmed from one still taken after this */
88
86
  const FIRST_FRAME_MS = 1000
89
87
 
@@ -119,6 +117,8 @@ export class Shooter {
119
117
  #browser: Browser | null = null
120
118
  #launching: Promise<Browser> | null = null
121
119
  #held: (() => void) | null = null
120
+ /** a slot taken in the queue and not yet handed to its browser's open */
121
+ #queued: (() => void) | null = null
122
122
  /** before a page goes to a url: the box route forwards this machine's localhost port to the box */
123
123
  #reach: (url: string) => Promise<void> = async () => undefined
124
124
  #slot: Slot | null = null
@@ -139,14 +139,22 @@ export class Shooter {
139
139
  return { browser: this.#browser?.isConnected() === true, url: this.#slot?.url ?? null, waiting: this.#turns.waiting }
140
140
  }
141
141
 
142
- /** a png of the url, written at `a.out` */
142
+ /** a still of the url, written at `a.out`, encoded by its extension (stillFormat) */
143
143
  shot(a: ShotAsk): Promise<ShotDone> {
144
- return this.#turns.run(() => withCap(`the shot of ${a.url}`, capMsOf(a), this.#shot(a)).finally(() => this.#touch()))
144
+ return this.#turns.run(() => this.#capped(`the shot of ${a.url}`, capMsOf(a), () => this.#shot(a)))
145
145
  }
146
146
 
147
147
  /** an mp4 of `a.seconds` of the url, written at `a.out`: its canvas when the canvas is the page, else the page */
148
148
  clip(a: ClipAsk): Promise<ShotDone> {
149
- return this.#turns.run(() => withCap(`the clip of ${a.url}`, capMsOf(a), this.#clip(a)).finally(() => this.#touch()))
149
+ return this.#turns.run(() => this.#capped(`the clip of ${a.url}`, capMsOf(a), () => this.#clip(a)))
150
+ }
151
+
152
+ /** the run capped once its browser slot is held: a wait behind the repo's other browsers is its queue, as its turn
153
+ * is, never part of its run (a tab of a sheet waits behind the others' browsers, it never fails at the cap) */
154
+ async #capped(what: string, capMs: number, run: () => Promise<ShotDone>): Promise<ShotDone> {
155
+ const f = this.#for
156
+ if (f != null && this.#held == null && this.#queued == null) this.#queued = await slotFor({ root: f.root, who: f.who, ...(f.say ? { say: f.say } : {}) })
157
+ return withCap(what, capMs, run()).finally(() => this.#touch())
150
158
  }
151
159
 
152
160
  async close(): Promise<void> {
@@ -169,9 +177,9 @@ export class Shooter {
169
177
  }
170
178
 
171
179
  #free(): void {
172
- const held = this.#held
173
- this.#held = null
174
- held?.()
180
+ const held = [this.#held, this.#queued]
181
+ this.#held = this.#queued = null
182
+ for (const h of held) h?.()
175
183
  }
176
184
 
177
185
  #touch(): void {
@@ -201,7 +209,9 @@ export class Shooter {
201
209
  let b: Browser
202
210
  if (f != null) {
203
211
  // the repo's browser: on its box from a Mac (box.ts), else launched here, its slot held until close
204
- const o = await openBrowser<Browser>(pw, { root: f.root, who: f.who, args: BROWSER_ARGS, ...(f.say ? { say: f.say } : {}) })
212
+ const held = this.#queued
213
+ this.#queued = null
214
+ const o = await openBrowser<Browser>(pw, { root: f.root, who: f.who, args: BROWSER_ARGS, ...(f.say ? { say: f.say } : {}), ...(held ? { held } : {}) })
205
215
  b = o.browser
206
216
  this.#reach = (url) => o.reach(url)
207
217
  this.#held = () => void o.close()
@@ -291,7 +301,7 @@ export class Shooter {
291
301
  phases['step'] = ms(t)
292
302
  }
293
303
  t = performance.now()
294
- const r = await slot.cdp.send('Page.captureScreenshot', { format: 'png', optimizeForSpeed: true })
304
+ const r = await slot.cdp.send('Page.captureScreenshot', { ...stillFormat(a.out), optimizeForSpeed: true })
295
305
  phases['capture'] = ms(t)
296
306
  mkdirSync(dirname(a.out), { recursive: true })
297
307
  await Bun.write(a.out, Buffer.from(String(r['data']), 'base64'))
@@ -65,8 +65,19 @@ export function normalizeUrl(s: string): string {
65
65
  throw new Error(`'${s}' is not a url: give http://host:port/path, localhost:5173/path or :5173/path`)
66
66
  }
67
67
 
68
- /** the file a shot lands in when no `--out` is given: under the repo's local scratch, named after the url */
69
- export function defaultOut(url: string, ext: 'png' | 'mp4'): string {
68
+ /** a still's quality as webp or jpeg: the page's text stays sharp at about an eighth of the png's bytes (a 1280x800
69
+ * page: png 1004 KB, webp 126 KB) */
70
+ export const STILL_QUALITY = 90
71
+ /** a still's encoding by its file's extension: webp and jpeg at STILL_QUALITY, png (lossless) for anything else */
72
+ export function stillFormat(out: string): { format: 'webp' | 'jpeg'; quality: number } | { format: 'png' } {
73
+ if (/\.webp$/i.test(out)) return { format: 'webp', quality: STILL_QUALITY }
74
+ if (/\.jpe?g$/i.test(out)) return { format: 'jpeg', quality: STILL_QUALITY }
75
+ return { format: 'png' }
76
+ }
77
+
78
+ /** the file a shot lands in when no `--out` is given: under the repo's local scratch, named after the url; a still
79
+ * is a webp */
80
+ export function defaultOut(url: string, ext: 'webp' | 'mp4'): string {
70
81
  const u = new URL(url)
71
82
  const slug = `${u.hostname}-${u.port || (u.protocol === 'https:' ? '443' : '80')}${u.pathname}${u.search}${u.hash}`
72
83
  .replace(/[^\w.-]+/g, '-')
@@ -113,7 +124,7 @@ export function askOf(f: ShotFlags, cwd: string): ShotAsk | ClipAsk {
113
124
  url,
114
125
  viewport: f.viewport == null ? DEFAULT_VIEWPORT : parseViewport(f.viewport),
115
126
  dpr: f.dpr == null ? 1 : positive('--dpr', f.dpr, 4),
116
- out: resolve(cwd, f.out ?? defaultOut(url, seconds == null ? 'png' : 'mp4')),
127
+ out: resolve(cwd, f.out ?? defaultOut(url, seconds == null ? 'webp' : 'mp4')),
117
128
  reload: f.reload === true,
118
129
  waitMs: f.wait == null ? DEFAULT_WAIT_MS : f.wait === '0' ? 0 : positive('--wait', f.wait, 60_000),
119
130
  }
@@ -7,7 +7,7 @@ import { shotUrlBase } from './shot-ask.ts'
7
7
  export default globalProcess({
8
8
  id: 'shot',
9
9
  label: 'shots',
10
- description: 'warm headless browser: sk shot <url> gives a png, --video a clip, for every repo',
10
+ description: 'warm headless browser: sk shot <url> gives a webp, --video a clip, for every repo',
11
11
  cmd: ['bun', join(import.meta.dir, 'serve-shot.ts')],
12
12
  probe: `${shotUrlBase()}/health`,
13
13
  icon: '📸',
@@ -2,15 +2,18 @@
2
2
  // stats says it: the social folder, the identities, the repo's config and social unit, the media a draft names outside
3
3
  // its folder, and the day; HEAD moves the calendar alone. The desk is built, put on the wire and zipped once a stamp,
4
4
  // and a page that holds the answer gets a 304. A stamp misses a media named outside the folder that appears where none
5
- // stood: its error line clears at the next change
5
+ // stood: its error line clears at the next change. next-release.json is kept the same way, on next.md beside the parts
6
6
  import { type Dirent, readdirSync, statSync } from 'node:fs'
7
7
  import { join, relative } from 'node:path'
8
8
  import { LAYOUT } from '../core/layout.ts'
9
9
  import { headCommit } from '../core/git-root.ts'
10
10
  import { unitFilesDeclaring } from '../core/unit-files.ts'
11
11
  import { identitiesDir, readIdentities, type Identities } from '../identities/identities.ts'
12
+ import { fileOf, NEXT } from '../releases/model.ts'
13
+ import { releasesDir } from '../releases/store.ts'
12
14
  import { loadRepoConfig } from '../repo-config.ts'
13
15
  import { tagged } from '../review/http.ts'
16
+ import { previewNextRelease, type NextRelease } from './release-stage.ts'
14
17
  import { wireOf } from './desk-wire.ts'
15
18
  import { loadDesk, type Desk } from './load.ts'
16
19
  import { commitMoments, dayOf, postedOf, timelineOf } from './presence.ts'
@@ -67,24 +70,29 @@ const stat = (abs: string): string => {
67
70
  const stampOf = (parts: string[]): string => Bun.hash(parts.join('\n')).toString(36)
68
71
 
69
72
  type Part<T> = { stamp: string; value: T }
73
+ type Answer = { stamp: string; tag: string; text: string; zip?: Uint8Array<ArrayBuffer> }
70
74
  type Held = {
71
75
  idsDir?: string | null
72
- config?: Part<string | undefined>
76
+ config?: Part<{ speaksAs: string | undefined; releases: boolean }>
73
77
  ids?: Part<Identities>
74
78
  unit?: Part<SocialUnit | null>
75
79
  desk?: Part<Desk> & { outside: string[] }
76
- answer?: { stamp: string; tag: string; text: string; zip?: Uint8Array<ArrayBuffer> }
80
+ answer?: Answer
81
+ next?: Answer
77
82
  }
78
83
  const held = new Map<string, Held>()
79
84
 
80
- /** the answer of `root` as it stands: rebuilt only for the parts whose stamp moved */
81
- export async function deskWire(root: string): Promise<{ stamp: string; tag: string; text: string; zip?: Uint8Array<ArrayBuffer> }> {
85
+ /** what both answers are built from, the config, the identities and the unit, each read again only when its stamp moved */
86
+ async function partsOf(root: string) {
82
87
  const h = held.get(root) ?? {}
83
88
  held.set(root, h)
84
89
  if (h.idsDir === undefined) h.idsDir = await identitiesDir(root)
85
90
 
86
91
  const configStamp = stat(join(root, 'repo.config.ts'))
87
- const config = h.config?.stamp === configStamp ? h.config : (h.config = { stamp: configStamp, value: (await loadRepoConfig(root, { fresh: true }).catch(() => null))?.speaksAs })
92
+ if (h.config?.stamp !== configStamp) {
93
+ const c = await loadRepoConfig(root, { fresh: true }).catch(() => null)
94
+ h.config = { stamp: configStamp, value: { speaksAs: c?.speaksAs, releases: c?.release?.releases === true } }
95
+ }
88
96
 
89
97
  const idsParts: string[] = []
90
98
  if (h.idsDir != null) tree(h.idsDir, idsParts)
@@ -93,17 +101,22 @@ export async function deskWire(root: string): Promise<{ stamp: string; tag: stri
93
101
 
94
102
  const unitStamp = stampOf(unitFilesDeclaring(root, 'social').map(stat))
95
103
  const unit = h.unit?.stamp === unitStamp ? h.unit : (h.unit = { stamp: unitStamp, value: await loadSocialUnit(root) })
104
+ return { h, config: h.config, ids, unit, stamps: [configStamp, idsStamp, unitStamp] }
105
+ }
96
106
 
107
+ /** the answer of `root` as it stands: rebuilt only for the parts whose stamp moved */
108
+ export async function deskWire(root: string): Promise<Answer> {
109
+ const { h, config, ids, unit, stamps } = await partsOf(root)
97
110
  const today = dayOf(Date.now())
98
111
  const social = join(root, LAYOUT.social)
99
- const folder: string[] = [today, configStamp, idsStamp, unitStamp]
112
+ const folder: string[] = [today, ...stamps]
100
113
  tree(social, folder)
101
114
  folder.push(stat(pushLog(root)))
102
115
  for (const p of h.desk?.outside ?? []) folder.push(stat(p))
103
116
  const deskStamp = stampOf(folder)
104
117
  let desk = h.desk
105
118
  if (desk?.stamp !== deskStamp) {
106
- const value = loadDesk(root, ids.value, { speaksAs: config.value, unit: unit.value })
119
+ const value = loadDesk(root, ids.value, { speaksAs: config.value.speaksAs, unit: unit.value })
107
120
  const outside = [...new Set(value.drafts.flatMap((d) => d.media.map((m) => m.path)).filter((p) => relative(social, p).startsWith('..')))]
108
121
  desk = h.desk = { stamp: deskStamp, value, outside }
109
122
  }
@@ -121,3 +134,31 @@ export async function deskAnswer(req: Request, root: string): Promise<Response>
121
134
  const a = await deskWire(root)
122
135
  return tagged(req, a.tag, () => a.text, a)
123
136
  }
137
+
138
+ /** what Communications shows of the release being filled: `preview` null in a repo with no release files or no
139
+ * next.md, `error` when next.md does not parse */
140
+ export type NextReleaseView = { preview: NextRelease | null; error?: string }
141
+
142
+ /** next.md as the release that cuts it would stage it, kept while next.md, the rhythm and the parts stand */
143
+ export async function nextReleaseWire(root: string): Promise<Answer> {
144
+ const { h, config, unit, stamps } = await partsOf(root)
145
+ const stamp = stampOf([...stamps, stat(join(releasesDir(root), fileOf(NEXT))), stat(join(root, LAYOUT.social, 'rhythm.md'))])
146
+ if (h.next?.stamp === stamp) return h.next
147
+ let view: NextReleaseView = { preview: null }
148
+ if (config.value.releases) {
149
+ try {
150
+ view = { preview: await previewNextRelease(root, unit.value, { ...(config.value.speaksAs ? { speaksAs: config.value.speaksAs } : {}), identitiesDir: h.idsDir ?? null }) }
151
+ } catch (e) {
152
+ view = { preview: null, error: (e as Error).message }
153
+ }
154
+ }
155
+ const text = JSON.stringify(view)
156
+ h.next = { stamp, tag: `"${Bun.hash(text).toString(36)}"`, text }
157
+ return h.next
158
+ }
159
+
160
+ /** `GET api/social/next-release.json`: 304 while the page holds the answer */
161
+ export async function nextReleaseAnswer(req: Request, root: string): Promise<Response> {
162
+ const a = await nextReleaseWire(root)
163
+ return tagged(req, a.tag, () => a.text, a)
164
+ }
@@ -1,9 +1,11 @@
1
1
  // an identity's Discord server as data (wiki tools/shipkit/social-identities.md, The server's layout): `layout.md`
2
2
  // beside its discord account.md, made true through the account's bot. Nothing is deleted unless asked, and never a
3
- // channel that holds a message; a server that already matches gets no call but the reads
3
+ // channel that holds a message; a server that already matches gets no call but the reads. Its stale picture rows
4
+ // (icon, banner, invite splash) are set with it (What each account shows)
4
5
  import { existsSync, readFileSync } from 'node:fs'
5
6
  import { join } from 'node:path'
6
7
  import type { Account } from '../identities/identities.ts'
8
+ import { DISCORD_ROWS, recordPushed, toPush, type PushReport } from '../identities/shown.ts'
7
9
  import { parseFrontmatter } from './md.ts'
8
10
  import { call, channelKey } from './publish/discord.ts'
9
11
 
@@ -123,9 +125,47 @@ export function channelChanges(ch: Channel, want: { name: string; parent_id: str
123
125
  return out
124
126
  }
125
127
 
126
- export type ApplyReport = { changes: string[]; left: string[] }
128
+ export type ApplyReport = PushReport
127
129
 
128
- /** makes the account's server match its layout; what it did (or would do, dry), and what it left alone */
130
+ /** what the bot's calls go through: the real api, or a test's */
131
+ export type Send = <T>(a: Account, method: string, path: string, body?: BodyInit) => Promise<T>
132
+
133
+ /** the guild features a server needs before its banner or invite splash takes a picture */
134
+ const NEEDS: Readonly<Record<string, string>> = { banner: 'BANNER', splash: 'INVITE_SPLASH' }
135
+
136
+ /** a picture as a data uri, the way Discord's api takes an image */
137
+ const dataUri = (abs: string): string => `data:${/\.png$/i.test(abs) ? 'image/png' : /\.webp$/i.test(abs) ? 'image/webp' : /\.gif$/i.test(abs) ? 'image/gif' : 'image/jpeg'};base64,${readFileSync(abs).toString('base64')}`
138
+
139
+ /** the server's stale picture rows (icon, banner, invite splash) set through the bot in one call, each recorded in
140
+ * shown.md; a banner or splash its boost level does not allow is left with the reason, still stale */
141
+ export async function pushServerPictures(a: Account, o: { dry: boolean }, send: Send = call, guild?: { features: string[] }): Promise<PushReport> {
142
+ const out: PushReport = { changes: [], left: [], recorded: [] }
143
+ const stale = toPush(a.uploads, 'discord')
144
+ if (stale.length === 0 || a.guild === '') return out
145
+ const g = guild ?? (await send<{ features: string[] }>(a, 'GET', `/guilds/${a.guild}`))
146
+ const body: Record<string, string> = {}
147
+ const sent: typeof stale = []
148
+ for (const u of stale) {
149
+ const key = DISCORD_ROWS[u.field]!
150
+ const need = NEEDS[key]
151
+ if (need != null && !g.features.includes(need)) {
152
+ out.left.push(`${u.field}: the server's boost level allows none yet (no ${need}), still stale`)
153
+ continue
154
+ }
155
+ body[key] = dataUri(u.abs[0]!)
156
+ sent.push(u)
157
+ }
158
+ if (sent.length === 0) return out
159
+ const words = sent.map((u) => `${u.field} (${u.files[0]})`).join(', ')
160
+ out.changes.push(o.dry ? `would set the server's ${words}` : `set the server's ${words}`)
161
+ if (o.dry) return out
162
+ await send(a, 'PATCH', `/guilds/${a.guild}`, JSON.stringify(body))
163
+ for (const u of sent) out.recorded.push(recordPushed(a, u))
164
+ return out
165
+ }
166
+
167
+ /** makes the account's server match its layout and its picture rows; what it did (or would do, dry), what it left
168
+ * alone, the shown.md it wrote */
129
169
  export async function applyLayout(a: Account, o: { dry: boolean; prune: boolean }): Promise<ApplyReport> {
130
170
  const layout = layoutOf(a)
131
171
  if (a.guild === '') {
@@ -140,8 +180,11 @@ export async function applyLayout(a: Account, o: { dry: boolean; prune: boolean
140
180
  changes.push(o.dry ? `would ${what}` : what)
141
181
  if (!o.dry) await run()
142
182
  }
143
- const guild = await call<{ name: string; owner_id: string }>(a, 'GET', `/guilds/${G}`)
183
+ const guild = await call<{ name: string; owner_id: string; features: string[] }>(a, 'GET', `/guilds/${G}`)
144
184
  if (guild.name !== layout.name) await act(`rename the server « ${layout.name} »`, () => call(a, 'PATCH', `/guilds/${G}`, json({ name: layout.name })))
185
+ const pictures = await pushServerPictures(a, o, call, guild)
186
+ changes.push(...pictures.changes)
187
+ left.push(...pictures.left)
145
188
 
146
189
  const roles = await call<Role[]>(a, 'GET', `/guilds/${G}/roles`)
147
190
  const roleIds = new Map<string, string>()
@@ -205,10 +248,14 @@ export async function applyLayout(a: Account, o: { dry: boolean; prune: boolean
205
248
  await act(`rename the category ${c.name} → ${cat.name}`, () => call(a, 'PATCH', `/channels/${id}`, json({ name: cat.name })))
206
249
  }
207
250
  place(c, CATEGORY, `the category ${cat.name}`)
251
+ // a dry run before its category exists: a channel the server already holds moves into it, never a new one
208
252
  if (c == null) {
209
253
  for (const def of cat.channels) {
210
- slot(def.voice ? VOICE : TEXT)
211
- changes.push(`would create #${def.name} in ${cat.name}`)
254
+ const type = def.voice ? VOICE : TEXT
255
+ const ch = channels.find((x) => x.type === type && same(channelKey(x.name), def.name))
256
+ if (ch) kept.add(ch.id)
257
+ slot(type)
258
+ changes.push(ch ? `would set #${def.name} (${cat.name}): category` : `would create #${def.name} in ${cat.name}`)
212
259
  }
213
260
  continue
214
261
  }
@@ -235,5 +282,5 @@ export async function applyLayout(a: Account, o: { dry: boolean; prune: boolean
235
282
  if (o.prune && empty && x.type === TEXT) await act(`delete #${x.name} (empty)`, () => call(a, 'DELETE', `/channels/${x.id}`))
236
283
  else left.push(`${x.type === CATEGORY ? 'category ' : '#'}${x.name}${x.type === TEXT ? (empty ? ' (empty, --prune deletes it)' : ' (holds messages)') : ''}`)
237
284
  }
238
- return { changes, left }
285
+ return { changes, left, recorded: pictures.recorded }
239
286
  }
@@ -8,7 +8,7 @@ import { parseFrontmatter } from './md.ts'
8
8
 
9
9
  /** the headings a draft holds besides its platforms */
10
10
  const OWN = ['Angle', 'Posted'] as const
11
- const OPTIONS = ['name', 'place', 'title', 'media', 'pin', 'outro', 'mark', 'tags'] as const
11
+ const OPTIONS = ['name', 'place', 'title', 'media', 'rating', 'pin', 'outro', 'mark', 'tags'] as const
12
12
  type Option = (typeof OPTIONS)[number]
13
13
  /** the options whose value is one of a few words: a vertical's end and its watermark's corner, words a project reads */
14
14
  const WORDS: Partial<Record<Option, readonly string[]>> = { outro: ['montage', 'short', 'none'], mark: ['left', 'right'] }
@@ -0,0 +1,84 @@
1
+ // a staged media cut or shrunk before it is copied into a draft (wiki tools/shipkit/social.md, A post staged): a clip's
2
+ // passage between his in and out, and « fit », one copy within the tightest limits of the venues it goes to (the
3
+ // seconds first, then the bytes: a lower bitrate, a smaller frame). Each writes a new file in a scratch folder; the
4
+ // stage then copies it clean like any media. ffmpeg on the CPU, never the GPU
5
+ import { mkdtempSync, statSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import { extname, join } from 'node:path'
8
+ import sharp from 'sharp'
9
+ import type { MediaLimits } from '../identities/identities.ts'
10
+ import { mp4Seconds } from './media-limit.ts'
11
+
12
+ const VIDEO = /\.(mp4|m4v|mov|webm)$/i
13
+ const IMAGE = /\.(png|jpe?g|webp)$/i
14
+
15
+ const scratch = (name: string): string => join(mkdtempSync(join(tmpdir(), 'stage-fit-')), name)
16
+
17
+ function ffmpeg(args: string[]): void {
18
+ const r = Bun.spawnSync(['ffmpeg', '-v', 'error', '-y', ...args], { stdout: 'ignore', stderr: 'pipe' })
19
+ if (r.exitCode !== 0) throw new Error(`ffmpeg: ${r.stderr.toString().trim().split('\n').at(-1) ?? `exit ${r.exitCode}`}`)
20
+ }
21
+
22
+ /** a clip's length in seconds: its mvhd box, else ffprobe */
23
+ export function secondsOf(file: string): number {
24
+ const s = /\.(mp4|m4v|mov)$/i.test(file) ? mp4Seconds(file) : null
25
+ if (s != null) return s
26
+ const r = Bun.spawnSync(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file], { stdout: 'pipe', stderr: 'ignore' })
27
+ const d = Number(r.stdout.toString().trim())
28
+ if (!Number.isFinite(d)) throw new Error(`${file}: no length ffprobe reads`)
29
+ return d
30
+ }
31
+
32
+ /** the passage of a clip from `from` to `to` seconds, encoded again so it starts on its first frame: an mp4 */
33
+ export function cutPassage(file: string, from: number, to: number): string {
34
+ if (!VIDEO.test(file)) throw new Error(`a passage is cut from a clip, not ${extname(file)}`)
35
+ const len = secondsOf(file)
36
+ if (!(from >= 0 && to > from && from < len)) throw new Error(`passage ${from} s to ${to} s: in a clip of ${len.toFixed(2)} s, in before out`)
37
+ const out = scratch('passage.mp4')
38
+ ffmpeg(['-ss', String(from), '-to', String(Math.min(to, len)), '-i', file, '-c:v', 'libx264', '-crf', '18', '-preset', 'veryfast', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', out])
39
+ return out
40
+ }
41
+
42
+ /** the tightest of several venues' limits: each bound the smallest one any venue names */
43
+ export function tightest(all: readonly MediaLimits[]): MediaLimits {
44
+ const min = (k: keyof MediaLimits): number | undefined => {
45
+ const v = all.flatMap((l) => (l[k] == null ? [] : [l[k]!]))
46
+ return v.length ? Math.min(...v) : undefined
47
+ }
48
+ const out: MediaLimits = {}
49
+ for (const k of ['imageBytes', 'videoBytes', 'videoSeconds'] as const) {
50
+ const v = min(k)
51
+ if (v != null) out[k] = v
52
+ }
53
+ return out
54
+ }
55
+
56
+ /** one copy within the limits, or the file itself when it already fits; a clip: its first seconds up to the bound, then
57
+ * a bitrate that lands under the bytes with a margin; an image: a jpeg whose quality steps down until it fits */
58
+ export async function fitTo(file: string, l: MediaLimits): Promise<string> {
59
+ const size = statSync(file).size
60
+ if (IMAGE.test(file)) {
61
+ if (l.imageBytes == null || size <= l.imageBytes) return file
62
+ for (const [q, w] of [[90, 4096], [82, 2560], [74, 2048], [66, 1600], [58, 1280]] as const) {
63
+ const out = scratch(`fit-${q}.jpg`)
64
+ await sharp(file).rotate().resize({ width: w, height: w, fit: 'inside', withoutEnlargement: true }).jpeg({ quality: q, mozjpeg: true }).toFile(out)
65
+ if (statSync(out).size <= l.imageBytes) return out
66
+ }
67
+ throw new Error(`${file}: no jpeg under ${(l.imageBytes / 1e6).toFixed(1)} MB down to 1280 px`)
68
+ }
69
+ if (!VIDEO.test(file)) return file
70
+ const len = secondsOf(file)
71
+ const secs = l.videoSeconds != null && len > l.videoSeconds ? l.videoSeconds : len
72
+ if (secs === len && (l.videoBytes == null || size <= l.videoBytes)) return file
73
+ const out = scratch('fit.mp4')
74
+ const kbps = l.videoBytes == null ? null : Math.floor(((l.videoBytes * 8 * 0.9) / secs - 128_000) / 1000)
75
+ if (kbps != null && kbps < 300) throw new Error(`${file}: ${secs.toFixed(1)} s under ${(l.videoBytes! / 1e6).toFixed(0)} MB leaves ${kbps} kb/s, too few for a clip worth posting: cut a passage`)
76
+ ffmpeg([
77
+ '-i', file, '-t', String(secs),
78
+ '-c:v', 'libx264', '-preset', 'veryfast', '-pix_fmt', 'yuv420p',
79
+ ...(kbps == null ? ['-crf', '20'] : ['-b:v', `${kbps}k`, '-maxrate', `${kbps}k`, '-bufsize', `${kbps * 2}k`]),
80
+ '-vf', 'scale=w=min(1920\\,iw):h=-2',
81
+ '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', out,
82
+ ])
83
+ return out
84
+ }