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
@@ -0,0 +1,246 @@
1
+ // a post staged from a source (wiki tools/shipkit/social.md, A post staged): a review card's media, or a release's
2
+ // notes, written as one v3 draft at once, the media copied in with its metadata left out, committed by its own paths.
3
+ // The repo's guard runs before anything is written, so a draft it refuses never sits on the disk. A dry run writes the
4
+ // same draft into a scratch folder and loads it, so the popup's counts, places and problems are the desk's own. Staging
5
+ // never posts: publishing stays his act in Communications
6
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { dirname, extname, join, relative } from 'node:path'
9
+ import { LAYOUT } from '../core/layout.ts'
10
+ import { identitiesDir, loadIdentities } from '../identities/identities.ts'
11
+ import type { PostRating } from '../identities/rating.ts'
12
+ import { loadRepoConfig } from '../repo-config.ts'
13
+ import { idOf } from '../review/model.ts'
14
+ import { DRAFT_NAME, draftsDir, loadDesk, VERTICAL, type Draft } from './load.ts'
15
+ import { fitTo, tightest } from './fit.ts'
16
+ import { kindProblem, sourceKind } from './kinds.ts'
17
+ import { stripCopy } from './strip.ts'
18
+ import { guardWith, loadSocialUnit, type ReleaseHeading, type SocialUnit } from './unit.ts'
19
+ import { commitPaths } from './writes.ts'
20
+
21
+ /** where a staged draft comes from: a review card (any id of its thread), or a release `<unit>@<version>` */
22
+ export type StageSource = { review: string } | { release: string }
23
+
24
+ export type StageMedia = {
25
+ /** the local file, absolute */
26
+ file: string
27
+ /** what its copy is called, without the extension: `<topic>-<view>` */
28
+ name: string
29
+ /** a 9:16 clip: the draft gets its `## vertical` too */
30
+ vertical?: boolean
31
+ }
32
+
33
+ export type StageInput = {
34
+ source: StageSource
35
+ title: string
36
+ /** his text, under each heading */
37
+ text: string
38
+ media?: StageMedia | null
39
+ alt?: string
40
+ rating: PostRating
41
+ /** unset, its source's: `feature` from a card, `release` from a release (wiki guides/post-kinds/index.md) */
42
+ kind?: string
43
+ /** a `custom` kind's one line on why no kind fits */
44
+ kindWhy?: string
45
+ /** `picked` unset: his own act chose it */
46
+ status?: 'draft' | 'picked'
47
+ /** `<YYYY-MM-DD> <tag>`, a slot of the rhythm */
48
+ slot?: string
49
+ /** `#a #b` */
50
+ tags?: string
51
+ angle: string
52
+ /** the headings the text goes under; unset, `short` */
53
+ headings?: readonly StageHeading[]
54
+ now?: Date
55
+ }
56
+
57
+ /** a heading a stage writes: a venue of the unit, and what only this message carries, its own media and rating (a
58
+ * release's nsfw picture on the venue that takes it), its `name` beside another message on the same account */
59
+ export type StageHeading = ReleaseHeading & { name?: string; rating?: PostRating; media?: StageMedia }
60
+
61
+ /** every media a stage copies: the draft's, then each heading's own, once a name */
62
+ export function stageMedia(input: Pick<StageInput, 'media' | 'headings'>): { name: string; file: string }[] {
63
+ const all = [input.media, ...(input.headings ?? []).map((h) => h.media)].filter((m): m is StageMedia => m != null)
64
+ const out = new Map<string, string>()
65
+ for (const m of all) out.set(mediaFile(m), m.file)
66
+ return [...out].map(([name, file]) => ({ name, file }))
67
+ }
68
+
69
+ export type Staged = { slug: string; files: string[]; draft: Draft | null; errors: string[]; /** a dry run's draft.md, as it would be written */ text?: string }
70
+
71
+ const sourceLine = (s: StageSource): string => ('review' in s ? `review: ${s.review}` : `release: ${s.release}`)
72
+
73
+ /** the kind a stage writes: the one asked, else its source's */
74
+ export const stagedKind = (input: Pick<StageInput, 'kind' | 'source'>): string => input.kind?.trim() || sourceKind(input.source)
75
+
76
+ /** the name a staged media's copy takes in its draft, `media/<name>[-vertical].<ext>` */
77
+ export const mediaFile = (m: StageMedia): string => {
78
+ const ext = extname(m.file).toLowerCase()
79
+ return `media/${m.name}${m.vertical && ext === '.mp4' ? '-vertical' : ''}${ext === '.jpeg' ? '.jpg' : ext}`
80
+ }
81
+
82
+ /** the draft.md a stage writes, `media` its media name as the draft gives it */
83
+ export function draftText(input: StageInput, media: string | null): string {
84
+ const one = (v: string | undefined): string => (v ?? '').replace(/\s*\n\s*/g, ' ').trim()
85
+ const head = [
86
+ `title: ${one(input.title)}`,
87
+ `kind: ${stagedKind(input)}`,
88
+ ...(one(input.kindWhy) ? [`kindWhy: ${one(input.kindWhy)}`] : []),
89
+ `status: ${input.status ?? 'picked'}`,
90
+ `rating: ${input.rating}`,
91
+ ...(media ? [`media: ${media}`] : []),
92
+ ...(one(input.alt) ? [`alt: ${one(input.alt)}`] : []),
93
+ ...(input.slot ? [`slot: ${input.slot}`] : []),
94
+ sourceLine(input.source),
95
+ ]
96
+ const text = input.text.trim()
97
+ if (/^## /m.test(text)) throw new Error('the text holds a "## " line: it would start a heading')
98
+ const tags = one(input.tags)
99
+ const opts = (h: StageHeading, tagged: boolean): string => {
100
+ const o = [
101
+ ...(h.name ? [`name: ${h.name}`] : []),
102
+ ...(h.place ? [`place: ${h.place}`] : []),
103
+ ...(h.rating ? [`rating: ${h.rating}`] : []),
104
+ ...(h.media ? [`media: ${mediaFile(h.media)}`] : []),
105
+ ...(tagged && tags ? [`tags: ${tags}`] : []),
106
+ ]
107
+ return o.length ? ` (${o.join(', ')})` : ''
108
+ }
109
+ const headings = input.headings ?? [{ id: 'short' }]
110
+ const body = headings.map((h) => `## ${h.id}${opts(h, h.id === 'short')}\n\n${text}`)
111
+ if (media?.endsWith('-vertical.mp4') && !headings.some((h) => h.id === VERTICAL)) body.push(`## ${VERTICAL}${tags ? ` (tags: ${tags})` : ''}\n\n${text}`)
112
+ return `---\n${head.join('\n')}\n---\n\n## Angle\n\n${input.angle.trim()}\n\n${body.join('\n\n')}\n`
113
+ }
114
+
115
+ /** the slug a stage at `now` gives a title */
116
+ export const stageSlug = (title: string, now: Date): string => idOf(now, title)
117
+
118
+ /** the guard's problems with what the stage would write, and its kind's: run before any file is. A stage never writes
119
+ * an old word or a custom with no reason, so every kind problem refuses it */
120
+ export function guardStage(unit: SocialUnit | null, input: StageInput): string[] {
121
+ const kind = kindProblem(stagedKind(input), input.kindWhy ?? '', unit?.kinds ?? [])
122
+ return [
123
+ ...guardWith(unit, { title: input.title, alt: input.alt ?? '', texts: [input.text, ...(input.tags?.trim() ? [input.tags] : [])], files: stageMedia(input).map((m) => m.file) }),
124
+ ...(kind ? [kind.text] : []),
125
+ ]
126
+ }
127
+
128
+ type Ctx = { unit: SocialUnit | null; speaksAs: string | undefined; identitiesDir?: string | null }
129
+
130
+ export async function contextOf(root: string, o: Partial<Ctx>): Promise<Ctx> {
131
+ const speaksAs = 'speaksAs' in o ? o.speaksAs : (await loadRepoConfig(root, { fresh: true }).catch(() => null))?.speaksAs
132
+ const unit = 'unit' in o ? (o.unit ?? null) : await loadSocialUnit(root)
133
+ // the folder is the real repo's house, resolved here: a dry run loads from a scratch folder that has none
134
+ return { unit, speaksAs, identitiesDir: o.identitiesDir !== undefined ? o.identitiesDir : await identitiesDir(root) }
135
+ }
136
+
137
+ /** one draft as the desk loads it, and the load's lines about it */
138
+ async function loadOne(root: string, slug: string, c: Ctx): Promise<{ draft: Draft | null; errors: string[] }> {
139
+ const ids = await loadIdentities({ ...(c.identitiesDir !== undefined ? { dir: c.identitiesDir } : {}), cwd: root })
140
+ const desk = loadDesk(root, ids, { speaksAs: c.speaksAs, unit: c.unit })
141
+ return { draft: desk.drafts.find((d) => d.slug === slug) ?? null, errors: desk.errors.filter((e) => e.includes(slug)) }
142
+ }
143
+
144
+ /** the draft a stage would write, loaded from a scratch folder: its messages, the accounts it skips, every problem.
145
+ * Its media is named where it is, never copied */
146
+ export async function stageDry(root: string, input: StageInput, o: Partial<Ctx> = {}): Promise<Staged> {
147
+ const c = await contextOf(root, o)
148
+ const slug = stageSlug(input.title, input.now ?? new Date())
149
+ // a vertical's name, so the load reads it as one, on a link to the very file
150
+ const media = input.media ? mediaFile(input.media) : null
151
+ const text = draftText(input, media)
152
+ const r = await dryLoad(root, slug, text, stageMedia(input), c)
153
+ return { ...r, text, errors: [...new Set([...guardStage(c.unit, input), ...r.errors])] }
154
+ }
155
+
156
+ /** one draft's text loaded from a scratch copy of the social folder (its rhythm, a link to its media): the desk's own
157
+ * lines about it, its path left out of each */
158
+ export async function dryLoad(root: string, slug: string, raw: string, media: readonly { name: string; file: string }[], o: Partial<Ctx> = {}): Promise<Staged> {
159
+ const c = await contextOf(root, o)
160
+ const scratch = mkdtempSync(join(tmpdir(), 'stage-dry-'))
161
+ try {
162
+ const dir = join(draftsDir(scratch), slug)
163
+ mkdirSync(dir, { recursive: true })
164
+ const rhythm = join(root, LAYOUT.social, 'rhythm.md')
165
+ if (existsSync(rhythm)) copyFileSync(rhythm, join(scratch, LAYOUT.social, 'rhythm.md'))
166
+ for (const m of media) {
167
+ mkdirSync(dirname(join(dir, m.name)), { recursive: true })
168
+ symlinkSync(m.file, join(dir, m.name))
169
+ }
170
+ writeFileSync(join(dir, 'draft.md'), raw)
171
+ const { draft, errors } = await loadOne(scratch, slug, c)
172
+ return { slug, files: [], draft, errors: [...new Set(errors.map((e) => e.replace(`${relative(scratch, join(dir, 'draft.md'))}: `, '')))] }
173
+ } finally {
174
+ rmSync(scratch, { recursive: true, force: true })
175
+ }
176
+ }
177
+
178
+ /** « fit »: the media made one copy within the tightest limits of the venues the draft reaches (a dry stage says which);
179
+ * the input as it was when the media fits already */
180
+ export async function fitStage(root: string, input: StageInput, o: Partial<Ctx> = {}): Promise<StageInput> {
181
+ if (!input.media) return input
182
+ const c = await contextOf(root, o)
183
+ const dry = await stageDry(root, input, c)
184
+ const ids = await loadIdentities({ ...(c.identitiesDir !== undefined ? { dir: c.identitiesDir } : {}), cwd: root })
185
+ const reached = new Set((dry.draft?.posts ?? []).map((p) => p.platform))
186
+ const who = ids.identities.find((i) => i.id === dry.draft?.identity)
187
+ const limits = (who?.accounts ?? []).filter((a) => reached.has(a.id)).map((a) => a.limits)
188
+ const file = await fitTo(input.media.file, tightest(limits))
189
+ return file === input.media.file ? input : { ...input, media: { ...input.media, file } }
190
+ }
191
+
192
+ /** « ✍️ polish »: the draft note (wiki tools/shipkit/social-desks.md) asking an agent to rewrite each heading in the
193
+ * identity's voice and fill its alt, raised to the social unit's notes topic where the store has it */
194
+ export async function askPolish(root: string, slug: string, title: string, unit: SocialUnit | null, why = 'staged'): Promise<{ id: string }> {
195
+ const { noteOn } = await import('../review/notes.ts')
196
+ const { specOf, storeDir } = await import('../review/store.ts')
197
+ const dir = storeDir(root)
198
+ const spec = specOf(dir)
199
+ const want = unit?.notes ?? 'social'
200
+ const topic = Object.keys(spec.topics).length === 0 || spec.topics[want] ? want : undefined
201
+ return noteOn(dir, {
202
+ subject: { kind: 'draft', slug },
203
+ origin: { by: 'owner', from: why === 'staged' ? 'stage' : why },
204
+ name: title || slug,
205
+ text: `polish: rewrite each heading of ${slug} in the identity's voice, each venue its own words within its max, fill its alt, keep its media and rating`,
206
+ ...(topic ? { topic } : {}),
207
+ what: [
208
+ `Polish the ${why} draft « ${title} » (\`.shipkit/social/drafts/${slug}/draft.md\`).`,
209
+ "- each heading's text in the identity's voice (wiki preferences/writing-voice/index.md and the project's voice page), never the same botcopy twice",
210
+ '- the alt describes the media; the rating and the media stay',
211
+ '- the repo guard must pass: `sk social` shows no line for it',
212
+ '- then close this note: `sk review fixed <this id> --note "polished"`',
213
+ ].join('\n'),
214
+ })
215
+ }
216
+
217
+ /** the draft written in the repo, its media copied in clean, then committed by its own paths; refused before any
218
+ * write while the repo's guard names a problem. The load's lines about the written draft come back with it */
219
+ export async function stageDraft(root: string, input: StageInput, o: Partial<Ctx> = {}): Promise<Staged> {
220
+ const c = await contextOf(root, o)
221
+ const problems = guardStage(c.unit, input)
222
+ if (problems.length > 0) throw new Error(`the repo's guard refuses it: ${problems.join('; ')}`)
223
+ for (const m of stageMedia(input)) if (!existsSync(m.file)) throw new Error(`no media ${m.file}`)
224
+ const slug = stageSlug(input.title, input.now ?? new Date())
225
+ if (!DRAFT_NAME.test(slug)) throw new Error(`draft ${slug}?`)
226
+ const dir = join(draftsDir(root), slug)
227
+ if (existsSync(dir)) throw new Error(`drafts/${slug} already exists`)
228
+ const media = input.media ? mediaFile(input.media) : null
229
+ const files: string[] = []
230
+ mkdirSync(dir, { recursive: true })
231
+ try {
232
+ for (const m of stageMedia(input)) {
233
+ mkdirSync(dirname(join(dir, m.name)), { recursive: true })
234
+ stripCopy(m.file, join(dir, m.name))
235
+ files.push(join(dir, m.name))
236
+ }
237
+ writeFileSync(join(dir, 'draft.md'), draftText(input, media))
238
+ files.unshift(join(dir, 'draft.md'))
239
+ } catch (e) {
240
+ rmSync(dir, { recursive: true, force: true })
241
+ throw e
242
+ }
243
+ const { draft, errors } = await loadOne(root, slug, c)
244
+ commitPaths(files, `social: ${slug} staged from ${'review' in input.source ? `the card ${input.source.review}` : `the release ${input.source.release}`}`)
245
+ return { slug, files, draft, errors }
246
+ }
@@ -0,0 +1,85 @@
1
+ // a media copied into a draft with what it says about where it was made left out (wiki tools/shipkit/social.md, A post
2
+ // staged): a png's text, time and exif chunks, a jpeg's exif, xmp, iptc and comments, a webp's exif and xmp, a clip's
3
+ // tags, chapters and encoder name. The pixels and the colour profile stay. Images are rewritten here, byte for byte
4
+ // the rest; a clip goes through ffmpeg, its streams copied, never encoded again
5
+ import { readFileSync, writeFileSync } from 'node:fs'
6
+ import { extname } from 'node:path'
7
+
8
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
9
+ /** the png chunks that carry words, a time or exif */
10
+ const PNG_DROP = new Set(['tEXt', 'zTXt', 'iTXt', 'eXIf', 'tIME'])
11
+
12
+ export function stripPng(b: Buffer): Buffer {
13
+ if (!b.subarray(0, 8).equals(PNG_SIG)) throw new Error('not a png')
14
+ const keep: Buffer[] = [PNG_SIG]
15
+ for (let at = 8; at + 12 <= b.length; ) {
16
+ const len = b.readUInt32BE(at)
17
+ const type = b.toString('latin1', at + 4, at + 8)
18
+ const end = at + 12 + len
19
+ if (!PNG_DROP.has(type)) keep.push(b.subarray(at, end))
20
+ at = end
21
+ if (type === 'IEND') break
22
+ }
23
+ return Buffer.concat(keep)
24
+ }
25
+
26
+ /** the jpeg segments that carry exif or xmp (APP1), iptc (APP13) and comments (COM) */
27
+ const JPEG_DROP = new Set([0xe1, 0xed, 0xfe])
28
+
29
+ export function stripJpeg(b: Buffer): Buffer {
30
+ if (b[0] !== 0xff || b[1] !== 0xd8) throw new Error('not a jpeg')
31
+ const keep: Buffer[] = [b.subarray(0, 2)]
32
+ let at = 2
33
+ while (at + 4 <= b.length && b[at] === 0xff) {
34
+ const marker = b[at + 1]!
35
+ // the scan: the rest is the image
36
+ if (marker === 0xda) break
37
+ const end = at + 2 + b.readUInt16BE(at + 2)
38
+ if (!JPEG_DROP.has(marker)) keep.push(b.subarray(at, end))
39
+ at = end
40
+ }
41
+ keep.push(b.subarray(at))
42
+ return Buffer.concat(keep)
43
+ }
44
+
45
+ export function stripWebp(b: Buffer): Buffer {
46
+ if (b.toString('latin1', 0, 4) !== 'RIFF' || b.toString('latin1', 8, 12) !== 'WEBP') throw new Error('not a webp')
47
+ const keep: Buffer[] = []
48
+ for (let at = 12; at + 8 <= b.length; ) {
49
+ const type = b.toString('latin1', at, at + 4)
50
+ const len = b.readUInt32LE(at + 4)
51
+ const end = at + 8 + len + (len % 2)
52
+ if (type === 'VP8X') {
53
+ const c = Buffer.from(b.subarray(at, end))
54
+ // the flags say no exif (bit 3) and no xmp (bit 2) any more
55
+ c[8] = c[8]! & ~0x0c
56
+ keep.push(c)
57
+ } else if (type !== 'EXIF' && type !== 'XMP ') keep.push(b.subarray(at, end))
58
+ at = end
59
+ }
60
+ const body = Buffer.concat(keep)
61
+ const head = Buffer.alloc(12)
62
+ head.write('RIFF', 0, 'latin1')
63
+ head.writeUInt32LE(body.length + 4, 4)
64
+ head.write('WEBP', 8, 'latin1')
65
+ return Buffer.concat([head, body])
66
+ }
67
+
68
+ const CLIP = new Set(['.mp4', '.m4v', '.mov', '.webm'])
69
+
70
+ /** `from` copied to `to` with its metadata left out; a kind it cannot clean is refused, never copied as it is */
71
+ export function stripCopy(from: string, to: string): void {
72
+ const ext = extname(from).toLowerCase()
73
+ if (ext === '.png') return writeFileSync(to, stripPng(readFileSync(from)))
74
+ if (ext === '.jpg' || ext === '.jpeg') return writeFileSync(to, stripJpeg(readFileSync(from)))
75
+ if (ext === '.webp') return writeFileSync(to, stripWebp(readFileSync(from)))
76
+ if (!CLIP.has(ext)) throw new Error(`${from}: a ${ext || 'file'} is no media a draft takes (png, jpg, webp, mp4, mov, webm)`)
77
+ const r = Bun.spawnSync(
78
+ ['ffmpeg', '-v', 'error', '-y', '-i', from, '-map', '0', '-c', 'copy', '-map_metadata', '-1', '-map_metadata:s', '-1', '-map_chapters', '-1', '-fflags', '+bitexact', '-flags:v', '+bitexact', '-flags:a', '+bitexact', to],
79
+ { stdout: 'ignore', stderr: 'pipe' },
80
+ )
81
+ if (r.exitCode !== 0) {
82
+ // a stream ffmpeg cannot copy into the same container: the file is refused, the reason named
83
+ throw new Error(`ffmpeg could not clean ${from}: ${r.stderr.toString().trim().split('\n').at(-1) ?? `exit ${r.exitCode}`}`)
84
+ }
85
+ }
@@ -106,6 +106,7 @@ export function overviewText(m: Model, today: string, stats: Readonly<Record<str
106
106
  if (waiting.length > 8) out.push(` … and ${waiting.length - 8} more: sk social plan`)
107
107
  out.push('', sourcesLine(sent))
108
108
  if (social.errors.length) out.push('', `${plural(social.errors.length, 'error')} in .shipkit/social/:`, ...social.errors.map((e) => ` ${e}`))
109
+ if (social.warnings.length) out.push('', `${plural(social.warnings.length, 'warning')}, never an error (an old kind word stays until the repo moves its drafts):`, ...social.warnings.map((e) => ` ${e}`))
109
110
  return out
110
111
  }
111
112
 
@@ -163,11 +164,14 @@ export function postText(m: Model, slug: string): string[] {
163
164
  const w = Math.max(0, ...posts.map((p) => p.key.length))
164
165
  for (const p of posts) {
165
166
  const s = m.sent.find((x) => x.slug === d.slug && x.key === p.key)
166
- out.push(`${pad(p.key, w)} ${pad(fam(p), 7)} ${s ? `posted ${when(s)} ${s.url}` : `waiting, ${p.length} characters${p.tags.length ? `, ${p.tags.join(' ')}` : ''}`}`)
167
+ const at = p.place ? ` in ${p.place}` : ''
168
+ out.push(`${pad(p.key, w)} ${pad(fam(p), 7)} ${s ? `posted ${when(s)} ${s.url}` : p.refused ? `refused: ${p.refused}` : `waiting${at}, ${p.length} characters${p.tags.length ? `, ${p.tags.join(' ')}` : ''}`}`)
167
169
  }
170
+ for (const k of d.skipped) out.push(`${pad(k.account, w)} skipped: ${k.why}`)
171
+ if (d.rating !== 'safe') out.splice(2, 0, `rated ${d.rating}`)
168
172
  const left = d.posts.filter((p) => p.posted === '').length
169
173
  out.push('', left ? `${left} of ${d.posts.length} messages waiting` : `every message posted`)
170
- const errors = m.social.errors.filter((e) => e.includes(d.slug))
174
+ const errors = [...m.social.errors, ...m.social.warnings].filter((e) => e.includes(d.slug))
171
175
  if (errors.length) out.push('', ...errors)
172
176
  return out
173
177
  }
@@ -4,6 +4,7 @@
4
4
  import { existsSync } from 'node:fs'
5
5
  import { importFresh } from '../core/discover-checks.ts'
6
6
  import { unitFilesDeclaring } from '../core/unit-files.ts'
7
+ import { ownKindsProblem, type OwnKind } from './kinds.ts'
7
8
 
8
9
  /** what the desk shows of a draft's `post.md` beyond its front matter */
9
10
  export interface ArticleInfo {
@@ -11,9 +12,43 @@ export interface ArticleInfo {
11
12
  url: string
12
13
  }
13
14
 
15
+ /** what the repo's guard reads of a draft: every word it says in public and every media file it carries */
16
+ export interface GuardInput {
17
+ title: string
18
+ alt: string
19
+ /** each heading's text, as he writes it */
20
+ texts: readonly string[]
21
+ /** each media, absolute */
22
+ files: readonly string[]
23
+ /** what a picture shows, in words (a trailer shot a line sits over): held to what a picture may show, never to the
24
+ * rules of a public word */
25
+ shows?: readonly string[]
26
+ }
27
+
28
+ /** a line the stage popup offers, and where it comes from (`tested`, a message's id) */
29
+ export interface SuggestedLine {
30
+ text: string
31
+ source: string
32
+ }
33
+
34
+ /** the headings a release stages, each a group or an account of the identity with the options a draft writes */
35
+ export interface ReleaseHeading {
36
+ id: string
37
+ place?: string
38
+ }
39
+
14
40
  export interface SocialDef {
15
41
  /** the words a draft's `topics` take; another word fails the load. Unset, any word */
16
42
  topics?: readonly string[]
43
+ /** the project's own post kinds beside the shared set (kinds.ts), each with its rules page in the repo */
44
+ kinds?: readonly OwnKind[]
45
+ /** why a draft may not go out, one line a problem: run at stage and at every load, so a draft with one never
46
+ * publishes, opens or copies */
47
+ guard?(d: GuardInput): readonly string[]
48
+ /** the lines the stage popup offers for a card; unset, the tested phrasings of the repo's messages store */
49
+ lines?(card: { id: string; title: string }): readonly SuggestedLine[]
50
+ /** a release of the repo stages one draft with these headings; unset, a release stages nothing */
51
+ release?: { headings: readonly ReleaseHeading[] }
17
52
  /** a draft folder holding a `post.md`: its address on the site */
18
53
  article?(dir: string): ArticleInfo
19
54
  /** the article as the site renders it, html; its media paths under `mediaBase` */
@@ -29,7 +64,14 @@ const WORD = /^[a-z][a-z0-9-]*$/
29
64
  /** why a social unit cannot be read, or null */
30
65
  export function socialProblem(d: SocialDef): string | null {
31
66
  for (const t of d.topics ?? []) if (!WORD.test(t)) return `social: topic '${t}' is a lowercase word`
32
- for (const f of ['article', 'preview'] as const) if (d[f] !== undefined && typeof d[f] !== 'function') return `social: ${f} is a function`
67
+ if (d.kinds !== undefined) {
68
+ if (!Array.isArray(d.kinds)) return 'social: kinds is a list of { id, for, page }'
69
+ const why = ownKindsProblem(d.kinds)
70
+ if (why !== null) return why
71
+ }
72
+ for (const f of ['article', 'preview', 'guard', 'lines'] as const) if (d[f] !== undefined && typeof d[f] !== 'function') return `social: ${f} is a function`
73
+ for (const h of d.release?.headings ?? []) if (!WORD.test(h.id)) return `social: release heading '${h.id}' is a group or an account id`
74
+ if (d.release !== undefined && d.release.headings.length === 0) return 'social: release names no heading'
33
75
  if (d.notes !== undefined && !WORD.test(d.notes)) return `social: notes '${d.notes}' is a review topic, a lowercase word`
34
76
  return null
35
77
  }
@@ -40,6 +82,20 @@ export function social(d: SocialDef): SocialUnit {
40
82
  return { ...d, kind: 'social' }
41
83
  }
42
84
 
85
+ /** THE repo's public text guard on one input (wiki tools/shipkit/social.md, The guard): the unit's `guard`, one line
86
+ * a problem; a guard that throws is one problem naming why; no unit or no guard, none */
87
+ export function guardWith(unit: SocialUnit | null | undefined, input: Partial<GuardInput>): string[] {
88
+ if (unit?.guard == null) return []
89
+ try {
90
+ return [...unit.guard({ title: input.title ?? '', alt: input.alt ?? '', texts: input.texts ?? [], files: input.files ?? [], ...(input.shows ? { shows: input.shows } : {}) })]
91
+ } catch (e) {
92
+ return [`the repo's guard failed: ${(e as Error).message}`]
93
+ }
94
+ }
95
+
96
+ /** the guard of the repo at `root`, its unit read fresh: a release note, a phrasing of the messages store */
97
+ export const publicProblems = async (root: string, input: Partial<GuardInput>): Promise<string[]> => guardWith(await loadSocialUnit(root), input)
98
+
43
99
  /** the repo's social unit, or null; two of them is an error naming both files */
44
100
  export async function loadSocialUnit(root: string): Promise<SocialUnit | null> {
45
101
  if (!existsSync(root)) return null
@@ -6,6 +6,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
6
6
  import { join } from 'node:path'
7
7
  import { gitBin } from '../core/git-bin.ts'
8
8
  import { STEP, type Account } from '../identities/identities.ts'
9
+ import { recordShown, TEXT_FILE } from '../identities/shown.ts'
9
10
  import { setHeadingText, setPostedLine } from './drafts.ts'
10
11
  import { accountOf, draftPost, draftsDir, type Desk } from './load.ts'
11
12
  import { setMeta } from './md.ts'
@@ -108,6 +109,16 @@ export function setLive(desk: Desk, identity: string, account: string, url: stri
108
109
  return [a.file]
109
110
  }
110
111
 
112
+ /** « Done, uploaded »: the account now shows one of a picture row's files (its first when none is named), recorded in
113
+ * its shown.md; a file the row does not name is refused, so the client never names a path of its own. « Done,
114
+ * pasted »: a text row as its value is now, refused when `sha` (what the page showed) is no longer it */
115
+ export function setShown(desk: Desk, identity: string, account: string, row: string, file?: string, sha?: string): string[] {
116
+ const a = accountOf(desk, identity, account)
117
+ const { abs, row: r } = recordShown(a, row, file, sha)
118
+ commitPaths([abs], `identities: ${identity} ${account} shows its ${row}, ${r.file === TEXT_FILE ? 'pasted' : r.file} (${r.sha})`)
119
+ return [abs]
120
+ }
121
+
111
122
  /** one step of `## Setup` ticked or not, by its index among the bullets; its message and errors name it from 1, as the
112
123
  * page numbers it */
113
124
  export function setStep(desk: Desk, identity: string, account: string, index: number, done: boolean): string[] {
@@ -0,0 +1,111 @@
1
+ // a cut's sound without its voice lines (wiki tools/trailer/trailer-sound.md, Your own voice): the music, ducked under
2
+ // each line as the cut ducks it, and the sfx, so a take is heard over what it will sit in. The mix of the build with
3
+ // every voice at volume 0, at the cut's own level; `.shipkit/cache/trailer/bed/<key>.m4a`, the key its ffmpeg words.
4
+ // Beside it, the whole cut in his voice or its standin's, and one line's passage
5
+ import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { houseRequests, load, soundsOf } from './build.ts'
8
+ import { ffmpeg } from './ffmpeg.ts'
9
+ import { trailerCache } from './footage.ts'
10
+ import { mixArgs } from './graph.ts'
11
+ import { soundStates } from './sound/index.ts'
12
+ import { PASSAGE_PAD, type Timeline } from '../review/trailer-model.ts'
13
+
14
+ /** the bed of the cut in `file`, made when the cache misses; refused while a paid line of the cut is not made yet, so
15
+ * a click on the hub never bills */
16
+ export async function voiceBed(root: string, file: string): Promise<string> {
17
+ const l = await load(file, root)
18
+ const unpaid = (await soundStates(root, houseRequests(l))).filter((s) => 'cost' in s && s.cost !== null)
19
+ if (unpaid.length > 0) throw new Error(`${unpaid.length} paid line${unpaid.length > 1 ? 's' : ''} of this cut ${unpaid.length > 1 ? 'are' : 'is'} not made yet: sk trailer makes ${unpaid.length > 1 ? 'them' : 'it'}, then the bed plays`)
20
+ const sounds = await soundsOf(l, l.t.shots, () => undefined)
21
+ const silent = { ...l.t, shots: l.t.shots.map((s) => ({ ...s, voices: s.voices.map((v) => ({ ...v, volume: 0 })) })) }
22
+ const dir = join(trailerCache(root, 'pieces'), '..', 'bed')
23
+ const probe = mixArgs({ t: silent, ...sounds }, '{out}')
24
+ const key = new Bun.CryptoHasher('sha1').update(probe.join('\0')).digest('hex').slice(0, 16)
25
+ const out = join(dir, `${key}.m4a`)
26
+ if (existsSync(out)) return out
27
+ mkdirSync(dir, { recursive: true })
28
+ const tmp = join(dir, `${key}.part-${process.pid}.m4a`)
29
+ await ffmpeg(mixArgs({ t: silent, ...sounds }, tmp))
30
+ renameSync(tmp, out)
31
+ return out
32
+ }
33
+
34
+
35
+ const voicing = new Map<string, Promise<VoicedCut>>()
36
+
37
+ export interface VoicedCut {
38
+ file: string
39
+ /** the file's name in the cache: what the hub's url names */
40
+ key: string
41
+ }
42
+
43
+ /** the render `video` of the cut in `file` with the cut's whole sound mixed again, his takes on (`takes`, the standin
44
+ * where he made none) or off (the standin on every line): the build's own sounds and mix, its picture copied beside
45
+ * it. `.shipkit/cache/trailer/voiced/<key>.mp4`, the key the render's time and the mix's own; one make at a time per
46
+ * side, so the player's range requests never start a second. Refused while a paid line of that side is not made, so a
47
+ * click on the hub never bills, and when the cut's length is no longer its render's */
48
+ export function voicedCut(root: string, file: string, video: string, takes: boolean, rendered: Timeline | null = null): Promise<VoicedCut> {
49
+ const id = `${file}\0${video}\0${statSync(video).mtimeMs}\0${takes}`
50
+ const going = voicing.get(id)
51
+ if (going) return going
52
+ const p = makeVoiced(root, file, video, takes, rendered).finally(() => voicing.delete(id))
53
+ voicing.set(id, p)
54
+ return p
55
+ }
56
+
57
+ /** `rendered`: the timeline the render was made from, so a cut edited since is refused rather than mixed off its
58
+ * picture */
59
+ async function makeVoiced(root: string, file: string, video: string, takes: boolean, rendered: Timeline | null): Promise<VoicedCut> {
60
+ const [{ durationOf }, { renderMix }, { total }, { timelineOf }] = await Promise.all([import('./ffmpeg.ts'), import('./stitch.ts'), import('./grammar.ts'), import('../review/trailer-desk.ts')])
61
+ const l = await load(file, root, { check: false })
62
+ if (l.errors.length > 0) throw new Error(`${l.errors.length} error${l.errors.length > 1 ? 's' : ''} in the cut: ${l.errors[0]!.message} (line ${l.errors[0]!.line})`)
63
+ if (l.t.vertical) throw new Error("a vertical cut lays its outro's sound after the mix: its voice toggle is not made")
64
+ const unpaid = (await soundStates(root, houseRequests(l), takes)).filter((s) => 'cost' in s && s.cost !== null)
65
+ if (unpaid.length > 0) throw new Error(`${unpaid.length} paid line${unpaid.length > 1 ? 's' : ''} of this side ${unpaid.length > 1 ? 'are' : 'is'} not made yet: sk trailer makes ${unpaid.length > 1 ? 'them' : 'it'}, then it plays`)
66
+ const [seconds, T] = [await durationOf(video), total(l.t)]
67
+ const now = timelineOf(l.t).shots
68
+ const moved = rendered?.shots.find((s, i) => s.name !== now[i]?.name || Math.abs(s.start - (now[i]?.start ?? -1)) > 1e-3)
69
+ if (Math.abs(seconds - T) > 0.1 || (rendered && rendered.shots.length !== now.length) || moved)
70
+ throw new Error(`the cut changed since its render${moved ? ` (shot ${moved.name})` : `: ${T.toFixed(2)} s now, ${seconds.toFixed(2)} s rendered`}: sk trailer renders it again, then both voices play`)
71
+ const mix = await renderMix({ t: l.t, ...(await soundsOf(l, l.t.shots, () => undefined, takes)), cache: trailerCache(root, 'pieces') })
72
+ const dir = join(trailerCache(root, 'pieces'), '..', 'voiced')
73
+ const key = new Bun.CryptoHasher('sha1').update(`${video}\0${statSync(video).mtimeMs}\0${mix.key}`).digest('hex').slice(0, 16)
74
+ const out = join(dir, `${key}.mp4`)
75
+ if (existsSync(out)) return { file: out, key }
76
+ mkdirSync(dir, { recursive: true })
77
+ const tmp = join(dir, `${key}.part-${process.pid}.mp4`)
78
+ await ffmpeg(['-i', video, '-i', mix.file, '-map', '0:v', '-map', '1:a', '-c', 'copy', '-movflags', '+faststart', tmp])
79
+ renameSync(tmp, out)
80
+ return { file: out, key }
81
+ }
82
+
83
+ /** a made voiced cut by its key; null when absent */
84
+ export function voicedFile(root: string, key: string): string | null {
85
+ if (!/^[0-9a-f]{16}$/.test(key)) return null
86
+ const f = join(trailerCache(root, 'pieces'), '..', 'voiced', `${key}.mp4`)
87
+ return existsSync(f) ? f : null
88
+ }
89
+
90
+ /** a voice line's passage as one file: the cut's picture from PASSAGE_PAD before the line to PASSAGE_PAD after its
91
+ * longer version, its bed under it, and one version of the line (`voice`, else none) at its place and volume. One
92
+ * element plays it all on one clock. `.shipkit/cache/trailer/passage/<key>.mp4`, the key its ffmpeg words and the
93
+ * render's time */
94
+ export async function voicePassage(root: string, o: { video: string; videoMtime: number; bed: string; at: number; seconds: number; total: number; voice: string | null; volume: number }): Promise<{ file: string; lead: number }> {
95
+ const lead = Math.min(PASSAGE_PAD, o.at)
96
+ const from = o.at - lead
97
+ const len = Math.min(o.total - from, lead + o.seconds + PASSAGE_PAD)
98
+ const n = (x: number): string => x.toFixed(3)
99
+ const voice = o.voice ? ['-i', o.voice] : []
100
+ const mix = o.voice ? `[2:a]aresample=48000,aformat=channel_layouts=stereo,volume=${n(o.volume)},adelay=${Math.round(lead * 1000)}:all=1[v];[1:a][v]amix=inputs=2:normalize=0:duration=first[a]` : '[1:a]anull[a]'
101
+ const args = (out: string): string[] => ['-ss', n(from), '-t', n(len), '-i', o.video, '-ss', n(from), '-t', n(len), '-i', o.bed, ...voice, '-filter_complex', mix, '-map', '0:v', '-map', '[a]', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-t', n(len), out]
102
+ const dir = join(trailerCache(root, 'pieces'), '..', 'passage')
103
+ const key = new Bun.CryptoHasher('sha1').update(`${o.videoMtime}\0${args('{out}').join('\0')}`).digest('hex').slice(0, 16)
104
+ const file = join(dir, `${key}.mp4`)
105
+ if (existsSync(file)) return { file, lead }
106
+ mkdirSync(dir, { recursive: true })
107
+ const tmp = join(dir, `${key}.part-${process.pid}.mp4`)
108
+ await ffmpeg(args(tmp))
109
+ renameSync(tmp, file)
110
+ return { file, lead }
111
+ }