rvlib-shipkit 2.17.1 → 2.19.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 (64) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/package.json +1 -1
  3. package/src/asks/asks-queue.ts +63 -10
  4. package/src/checks/SK039-vscode-watch-generated.check.ts +119 -0
  5. package/src/cli/cmd_Asks.ts +3 -1
  6. package/src/cli/cmd_GlobalProcesses.ts +34 -11
  7. package/src/cli/cmd_Home.ts +38 -2
  8. package/src/cli/cmd_Secret.ts +4 -30
  9. package/src/cli/cmd_Social.ts +40 -1
  10. package/src/cli/cmd_Trailer.ts +15 -3
  11. package/src/cli/registry.ts +2 -1
  12. package/src/collections/actions.ts +29 -1
  13. package/src/collections/collection-types.ts +2 -0
  14. package/src/collections/providers.ts +1 -1
  15. package/src/home/home-paths.ts +5 -1
  16. package/src/home/home-start.ts +12 -12
  17. package/src/home/run-daemon.ts +11 -2
  18. package/src/home/run-pm.ts +9 -1
  19. package/src/home/supervise.ts +3 -1
  20. package/src/identities/identities.ts +22 -5
  21. package/src/review/http.ts +7 -2
  22. package/src/review/store.ts +81 -19
  23. package/src/scaffold/files/vscode-settings.json +9 -1
  24. package/src/secrets/manager.ts +59 -0
  25. package/src/secrets/name.ts +2 -0
  26. package/src/serve/hub-app/auto-text.tsx +6 -1
  27. package/src/serve/hub-app/col-card.tsx +10 -0
  28. package/src/serve/hub-app/cols-svc.ts +37 -6
  29. package/src/serve/hub-app/hub.css +1 -0
  30. package/src/serve/hub-app/review/review-st.ts +12 -2
  31. package/src/serve/hub-app/review/review-thread.tsx +1 -1
  32. package/src/serve/hub-app/review/thread-st.ts +17 -1
  33. package/src/serve/hub-app/social/identity-pictures.ts +74 -0
  34. package/src/serve/hub-app/social/kit.tsx +3 -3
  35. package/src/serve/hub-app/social/post-card.tsx +2 -1
  36. package/src/serve/hub-app/social/social-page.tsx +77 -37
  37. package/src/serve/hub-app/social.css +9 -4
  38. package/src/serve/hub-app/stores/stores-page.tsx +4 -3
  39. package/src/serve/hub-app/veille/veille-page.tsx +2 -1
  40. package/src/serve/serve-hub.ts +16 -6
  41. package/src/serve/warm-cell.ts +63 -1
  42. package/src/shot/box.ts +23 -8
  43. package/src/shot/browser-slot.ts +8 -1
  44. package/src/shot/client.ts +9 -4
  45. package/src/shot/clip-encoder.ts +5 -2
  46. package/src/shot/job-store.ts +167 -0
  47. package/src/shot/shooter.ts +8 -3
  48. package/src/social/discord-layout.ts +239 -0
  49. package/src/social/md.ts +14 -6
  50. package/src/social/publish/discord.ts +3 -2
  51. package/src/social/routes.ts +3 -3
  52. package/src/stores/routes.ts +2 -2
  53. package/src/suite/judge-suites.ts +1 -1
  54. package/src/suite/select.ts +32 -6
  55. package/src/suite/suite-cli.ts +5 -5
  56. package/src/trailer/build.ts +75 -50
  57. package/src/trailer/draft.ts +28 -0
  58. package/src/trailer/footage.ts +4 -2
  59. package/src/trailer/grammar.ts +11 -9
  60. package/src/trailer/graph.ts +41 -12
  61. package/src/trailer/profile.ts +35 -0
  62. package/src/trailer/prune.ts +15 -10
  63. package/src/trailer/stitch.ts +22 -10
  64. package/src/trailer/titles.ts +47 -2
@@ -0,0 +1,239 @@
1
+ // an identity's Discord server as data (wiki tools/shipkit/social-identities.md, The server's layout): `layout.md`
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
4
+ import { existsSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import type { Account } from '../identities/identities.ts'
7
+ import { parseFrontmatter } from './md.ts'
8
+ import { call, channelKey } from './publish/discord.ts'
9
+
10
+ export type ChannelDef = { name: string; emoji: string; topic: string; readOnly: boolean; voice: boolean; ageRestricted: boolean; only: string[] }
11
+ export type CategoryDef = { name: string; was: string[]; channels: ChannelDef[] }
12
+ export type RoleDef = { name: string; color: number; hoist: boolean; mentionable: boolean; owner: boolean }
13
+ /** a member by its Discord username, and the roles the apply gives it */
14
+ export type MemberDef = { name: string; roles: string[] }
15
+ export type DiscordLayout = { file: string; name: string; roles: RoleDef[]; members: MemberDef[]; categories: CategoryDef[] }
16
+
17
+ const ROLE_FLAGS = new Set(['hoist', 'mentionable', 'owner'])
18
+ const CHANNEL_FLAGS = new Set(['read only', 'voice', 'age restricted'])
19
+
20
+ const cells = (chunk: string): string[][] =>
21
+ chunk
22
+ .split('\n')
23
+ .filter((l) => /^\|.*\|$/.test(l.trim()))
24
+ .map((l) => l.trim().slice(1, -1).split('|').map((c) => c.trim()))
25
+ .slice(2)
26
+
27
+ const list = (cell: string | undefined): string[] => (cell ?? '').split(',').map((x) => x.trim()).filter((x) => x !== '')
28
+
29
+ /** a layout page read and checked: every bad row is one error line, thrown together */
30
+ export function parseLayout(raw: string, file: string): DiscordLayout {
31
+ const { meta, body } = parseFrontmatter(raw)
32
+ const errors: string[] = []
33
+ if (!meta.name) errors.push('front matter names no server name (name:)')
34
+ const roles: RoleDef[] = []
35
+ const members: MemberDef[] = []
36
+ const categories: CategoryDef[] = []
37
+ for (const chunk of body.split(/^## /m).slice(1)) {
38
+ const head = chunk.slice(0, chunk.indexOf('\n') === -1 ? chunk.length : chunk.indexOf('\n')).trim()
39
+ if (head === 'Roles') {
40
+ for (const [name = '', colour = '', flags] of cells(chunk)) {
41
+ const f = list(flags)
42
+ for (const x of f) if (!ROLE_FLAGS.has(x)) errors.push(`role ${name}: unknown flag "${x}" (${[...ROLE_FLAGS].join(', ')})`)
43
+ if (!/^#[0-9a-f]{6}$/i.test(colour)) errors.push(`role ${name}: colour "${colour}" is no #rrggbb`)
44
+ roles.push({ name, color: Number.parseInt(colour.slice(1), 16), hoist: f.includes('hoist'), mentionable: f.includes('mentionable'), owner: f.includes('owner') })
45
+ }
46
+ continue
47
+ }
48
+ if (head === 'Members') {
49
+ for (const [name = '', given] of cells(chunk)) {
50
+ if (!/^[a-z0-9_.]{2,32}$/.test(name)) errors.push(`member ${name}: a Discord username is 2 to 32 of a-z, 0-9, _ and .`)
51
+ members.push({ name, roles: list(given) })
52
+ }
53
+ continue
54
+ }
55
+ const m = /^(.+?)(?: \(was (.+)\))?$/.exec(head)!
56
+ const channels: ChannelDef[] = []
57
+ for (const [name = '', emoji = '', topic = '', flags, only] of cells(chunk)) {
58
+ const f = list(flags)
59
+ for (const x of f) if (!CHANNEL_FLAGS.has(x)) errors.push(`#${name}: unknown flag "${x}" (${[...CHANNEL_FLAGS].join(', ')})`)
60
+ if (!/^[\p{L}\p{N}][\p{L}\p{N}_-]*$/u.test(name)) errors.push(`#${name}: a channel name is letters, digits, - and _`)
61
+ channels.push({ name, emoji, topic, readOnly: f.includes('read only'), voice: f.includes('voice'), ageRestricted: f.includes('age restricted'), only: list(only) })
62
+ }
63
+ categories.push({ name: m[1]!, was: list(m[2]), channels })
64
+ }
65
+ // a text and a voice channel may share a name: each is found by its own type
66
+ const names = categories.flatMap((c) => c.channels.map((x) => `${x.voice ? 'voice ' : '#'}${x.name.toLowerCase()}`))
67
+ for (const n of new Set(names)) if (names.filter((x) => x === n).length > 1) errors.push(`${n}: named twice`)
68
+ for (const c of categories) for (const x of c.channels) for (const r of x.only) if (!roles.some((d) => d.name === r)) errors.push(`#${x.name}: only "${r}", no such role under ## Roles`)
69
+ for (const x of members) for (const r of x.roles) if (!roles.some((d) => d.name === r)) errors.push(`member ${x.name}: role "${r}", no such role under ## Roles`)
70
+ if (errors.length > 0) throw new Error(`${file}:\n ${errors.join('\n ')}`)
71
+ return { file, name: meta.name!, roles, members, categories }
72
+ }
73
+
74
+ /** the layout of a discord account, `layout.md` beside its account.md */
75
+ export function layoutOf(a: Account): DiscordLayout {
76
+ const file = join(a.dir, 'layout.md')
77
+ if (!existsSync(file)) throw new Error(`${a.identity}: no ${file}, the server's layout`)
78
+ return parseLayout(readFileSync(file, 'utf8'), file)
79
+ }
80
+
81
+ /** every channel name of a layout, its key in a draft's place and a `#name` of a text */
82
+ export const layoutChannels = (l: DiscordLayout): string[] => l.categories.flatMap((c) => c.channels.map((x) => x.name))
83
+
84
+ const TEXT = 0
85
+ const VOICE = 2
86
+ const CATEGORY = 4
87
+ /** send messages, create public and private threads, send in threads */
88
+ const WRITE = String((1n << 11n) | (1n << 35n) | (1n << 36n) | (1n << 38n))
89
+ const VIEW = String(1n << 10n)
90
+
91
+ type Overwrite = { id: string; type: number; allow: string; deny: string }
92
+ type Channel = { id: string; type: number; name: string; parent_id: string | null; topic?: string | null; nsfw?: boolean; position: number; permission_overwrites?: Overwrite[] }
93
+ type Role = { id: string; name: string; color: number; hoist: boolean; mentionable: boolean; managed: boolean }
94
+
95
+ const same = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase()
96
+
97
+ /** a channel shows as `<emoji>・<name>`; its name alone is its key */
98
+ const shown = (def: ChannelDef): string => (def.emoji === '' ? def.name : `${def.emoji}・${def.name}`)
99
+
100
+ /** the overwrites a channel wants: the everyone role is the guild's own id */
101
+ export function overwritesOf(def: ChannelDef, guild: string, roleIds: ReadonlyMap<string, string>): Overwrite[] {
102
+ return [
103
+ ...(def.readOnly ? [{ id: guild, type: 0, allow: '0', deny: WRITE }] : []),
104
+ ...(def.only.length === 0 ? [] : [{ id: guild, type: 0, allow: '0', deny: VIEW }]),
105
+ ...def.only.flatMap((name) => {
106
+ const id = roleIds.get(name)
107
+ return id == null ? [] : [{ id, type: 0, allow: VIEW, deny: '0' }]
108
+ }),
109
+ ]
110
+ }
111
+
112
+ const overwriteKey = (o: readonly Overwrite[]): string =>
113
+ o.map((x) => `${x.id}:${x.type}:${x.allow}:${x.deny}`).sort().join(',')
114
+
115
+ /** what differs between a channel and what it wants, by name; empty, it matches */
116
+ export function channelChanges(ch: Channel, want: { name: string; parent_id: string; topic?: string; nsfw: boolean; permission_overwrites: Overwrite[] }): string[] {
117
+ const out: string[] = []
118
+ if (ch.name !== want.name) out.push(`name ${want.name}`)
119
+ if (ch.parent_id !== want.parent_id) out.push('category')
120
+ if (want.topic != null && (ch.topic ?? '') !== want.topic) out.push('topic')
121
+ if ((ch.nsfw ?? false) !== want.nsfw) out.push(want.nsfw ? 'age restricted' : 'not age restricted')
122
+ if (overwriteKey(ch.permission_overwrites ?? []) !== overwriteKey(want.permission_overwrites)) out.push('permissions')
123
+ return out
124
+ }
125
+
126
+ export type ApplyReport = { changes: string[]; left: string[] }
127
+
128
+ /** makes the account's server match its layout; what it did (or would do, dry), and what it left alone */
129
+ export async function applyLayout(a: Account, o: { dry: boolean; prune: boolean }): Promise<ApplyReport> {
130
+ const layout = layoutOf(a)
131
+ if (a.guild === '') {
132
+ const guilds = await call<{ id: string; name: string }[]>(a, 'GET', '/users/@me/guilds')
133
+ throw new Error(`${a.file}: no guild, the server's id; the bot is in ${guilds.map((g) => `${g.id} (${g.name})`).join(', ') || 'no server yet'}`)
134
+ }
135
+ const G = a.guild
136
+ const changes: string[] = []
137
+ const left: string[] = []
138
+ const json = (b: unknown): string => JSON.stringify(b)
139
+ const act = async (what: string, run: () => Promise<unknown>): Promise<void> => {
140
+ changes.push(o.dry ? `would ${what}` : what)
141
+ if (!o.dry) await run()
142
+ }
143
+ const guild = await call<{ name: string; owner_id: string }>(a, 'GET', `/guilds/${G}`)
144
+ if (guild.name !== layout.name) await act(`rename the server « ${layout.name} »`, () => call(a, 'PATCH', `/guilds/${G}`, json({ name: layout.name })))
145
+
146
+ const roles = await call<Role[]>(a, 'GET', `/guilds/${G}/roles`)
147
+ const roleIds = new Map<string, string>()
148
+ for (const def of layout.roles) {
149
+ const want = { name: def.name, color: def.color, hoist: def.hoist, mentionable: def.mentionable }
150
+ let role = roles.find((r) => !r.managed && same(r.name, def.name))
151
+ if (role == null) {
152
+ await act(`create the role ${def.name}`, async () => {
153
+ role = await call<Role>(a, 'POST', `/guilds/${G}/roles`, json({ ...want, permissions: '0' }))
154
+ })
155
+ } else if (role.name !== def.name || role.color !== def.color || role.hoist !== def.hoist || role.mentionable !== def.mentionable) {
156
+ const id = role.id
157
+ await act(`update the role ${def.name}`, () => call(a, 'PATCH', `/guilds/${G}/roles/${id}`, json(want)))
158
+ }
159
+ if (role != null) roleIds.set(def.name, role.id)
160
+ if (def.owner && role != null) {
161
+ const member = await call<{ roles: string[] }>(a, 'GET', `/guilds/${G}/members/${guild.owner_id}`)
162
+ const id = role.id
163
+ if (!member.roles.includes(id)) await act(`give the owner the role ${def.name}`, () => call(a, 'PUT', `/guilds/${G}/members/${guild.owner_id}/roles/${id}`))
164
+ }
165
+ }
166
+
167
+ for (const def of layout.members) {
168
+ const found = await call<{ user: { username: string; id: string }; roles: string[] }[]>(a, 'GET', `/guilds/${G}/members/search?query=${encodeURIComponent(def.name)}&limit=10`)
169
+ const member = found.find((x) => x.user.username === def.name)
170
+ if (member == null) {
171
+ left.push(`member ${def.name} (not in the server yet)`)
172
+ continue
173
+ }
174
+ for (const r of def.roles) {
175
+ const id = roleIds.get(r)
176
+ if (id == null) changes.push(`would give ${def.name} the role ${r}`)
177
+ else if (!member.roles.includes(id)) await act(`give ${def.name} the role ${r}`, () => call(a, 'PUT', `/guilds/${G}/members/${member.user.id}/roles/${id}`))
178
+ }
179
+ }
180
+
181
+ const channels = await call<Channel[]>(a, 'GET', `/guilds/${G}/channels`)
182
+ const kept = new Set<string>()
183
+ const moves: { id: string; position: number; label: string }[] = []
184
+ // Discord numbers positions across the whole server, one count per type (categories, text, voice), in the order shown
185
+ const next = new Map<number, number>()
186
+ const slot = (type: number): number => {
187
+ const n = next.get(type) ?? 0
188
+ next.set(type, n + 1)
189
+ return n
190
+ }
191
+ const place = (ch: Channel | undefined, type: number, label: string): void => {
192
+ const position = slot(type)
193
+ if (ch == null) return
194
+ kept.add(ch.id)
195
+ if (ch.position !== position) moves.push({ id: ch.id, position, label })
196
+ }
197
+ for (const cat of layout.categories) {
198
+ let c = channels.find((x) => x.type === CATEGORY && [cat.name, ...cat.was].some((n) => same(n, x.name)))
199
+ if (c == null) {
200
+ await act(`create the category ${cat.name}`, async () => {
201
+ c = await call<Channel>(a, 'POST', `/guilds/${G}/channels`, json({ name: cat.name, type: CATEGORY }))
202
+ })
203
+ } else if (c.name !== cat.name) {
204
+ const id = c.id
205
+ await act(`rename the category ${c.name} → ${cat.name}`, () => call(a, 'PATCH', `/channels/${id}`, json({ name: cat.name })))
206
+ }
207
+ place(c, CATEGORY, `the category ${cat.name}`)
208
+ if (c == null) {
209
+ for (const def of cat.channels) {
210
+ slot(def.voice ? VOICE : TEXT)
211
+ changes.push(`would create #${def.name} in ${cat.name}`)
212
+ }
213
+ continue
214
+ }
215
+ for (const def of cat.channels) {
216
+ const type = def.voice ? VOICE : TEXT
217
+ const want = { name: shown(def), parent_id: c.id, ...(def.voice ? {} : { topic: def.topic }), nsfw: def.ageRestricted, permission_overwrites: overwritesOf(def, G, roleIds) }
218
+ let ch = channels.find((x) => x.type === type && same(channelKey(x.name), def.name))
219
+ if (ch == null) {
220
+ await act(`create #${def.name} in ${cat.name}`, async () => {
221
+ ch = await call<Channel>(a, 'POST', `/guilds/${G}/channels`, json({ ...want, type }))
222
+ })
223
+ } else {
224
+ const diff = channelChanges(ch, want)
225
+ const id = ch.id
226
+ if (diff.length > 0) await act(`set #${def.name} (${cat.name}): ${diff.join(', ')}`, () => call(a, 'PATCH', `/channels/${id}`, json(want)))
227
+ }
228
+ place(ch, type, `#${def.name}`)
229
+ }
230
+ }
231
+ if (moves.length > 0) await act(`move ${moves.map((m) => m.label).join(', ')}`, () => call(a, 'PATCH', `/guilds/${G}/channels`, json(moves.map(({ id, position }) => ({ id, position })))))
232
+
233
+ for (const x of channels.filter((x) => !kept.has(x.id))) {
234
+ const empty = x.type !== TEXT || (await call<unknown[]>(a, 'GET', `/channels/${x.id}/messages?limit=1`)).length === 0
235
+ if (o.prune && empty && x.type === TEXT) await act(`delete #${x.name} (empty)`, () => call(a, 'DELETE', `/channels/${x.id}`))
236
+ else left.push(`${x.type === CATEGORY ? 'category ' : '#'}${x.name}${x.type === TEXT ? (empty ? ' (empty, --prune deletes it)' : ' (holds messages)') : ''}`)
237
+ }
238
+ return { changes, left }
239
+ }
package/src/social/md.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // the markdown shapes every social file is written in: `key: value` front matter, `## <name>` sections, the
2
2
  // `| field | value |` tables of a profile
3
- import { existsSync } from 'node:fs'
3
+ import { statSync } from 'node:fs'
4
4
  import { isAbsolute, join } from 'node:path'
5
5
 
6
6
  /** `key: value` lines only, no nesting */
@@ -40,11 +40,21 @@ export function section(body: string, name: string): string | null {
40
40
  export type ProfileRow = {
41
41
  field: string
42
42
  value: string
43
- /** the value names files under the identity's `files` folder, a comma between two: their paths there, the
44
- * pictures to upload; empty, a text */
43
+ /** every path of the value that is a file under the identity's `files` folder, the pictures to upload; the rest of
44
+ * the value a note (a size, the other variant); empty, a text */
45
45
  files: string[]
46
46
  }
47
47
 
48
+ /** a relative path in a text: no scheme or folder before it, an extension after it */
49
+ const PATH = /(?<![\w/:.~-])[\w~-][\w~./-]*\.\w+/g
50
+
51
+ /** the paths a value names that are files under `root`, in their order, each once */
52
+ export function filesIn(value: string, root: string): string[] {
53
+ const out: string[] = []
54
+ for (const p of value.match(PATH) ?? []) if (!isAbsolute(p) && !p.startsWith('~') && !out.includes(p) && statSync(join(root, p), { throwIfNoEntry: false })?.isFile() === true) out.push(p)
55
+ return out
56
+ }
57
+
48
58
  /** the rows of the `| field | value |` table of a `## Profile` (or another) section; `filesRoot` the folder a picture
49
59
  * path is relative to, null when the rows name none */
50
60
  export function rows(body: string, name = 'Profile', filesRoot: string | null = null): ProfileRow[] {
@@ -53,9 +63,7 @@ export function rows(body: string, name = 'Profile', filesRoot: string | null =
53
63
  const m = /^\|\s*(.+?)\s*\|\s*(.*?)\s*\|$/.exec(line.trim())
54
64
  if (m == null || m[1] === 'field' || /^-+$/.test(m[1]!)) continue
55
65
  const value = m[2]!
56
- const parts = value.split(',').map((x) => x.trim())
57
- const files = filesRoot != null && parts.every((x) => /\.\w+$/.test(x) && !isAbsolute(x) && existsSync(join(filesRoot, x))) ? parts : []
58
- out.push({ field: m[1]!, value, files })
66
+ out.push({ field: m[1]!, value, files: filesRoot == null ? [] : filesIn(value, filesRoot) })
59
67
  }
60
68
  return out
61
69
  }
@@ -1,6 +1,6 @@
1
1
  // a draft's message posted to Discord as the identity's bot (wiki tools/shipkit/social.md, Publishing): to the channel
2
2
  // its place names, a `#name` of a channel made its link, its media attached, pinned when it asks; a message already
3
- // posted is edited at its link. The server's layout is the project's own tool
3
+ // posted is edited at its link. The server's layout: ../discord-layout.ts
4
4
  import type { Account } from '../../identities/identities.ts'
5
5
  import { withoutTags } from '../compose.ts'
6
6
  import type { SocialPost } from '../load.ts'
@@ -11,7 +11,8 @@ const TEXT = 0
11
11
 
12
12
  type Channel = { id: string; type: number; name: string }
13
13
 
14
- async function call<T>(a: Account, method: string, path: string, body?: BodyInit, json = true): Promise<T> {
14
+ /** one call of Discord's api as the account's bot, waiting out a rate limit */
15
+ export async function call<T>(a: Account, method: string, path: string, body?: BodyInit, json = true): Promise<T> {
15
16
  const auth = `Bot ${await secret(a.secret, `${a.file}: secret`)}`
16
17
  for (;;) {
17
18
  const r = await fetch(API + path, { method, headers: { Authorization: auth, ...(json && body != null ? { 'Content-Type': 'application/json' } : {}) }, body })
@@ -5,7 +5,7 @@
5
5
  import { existsSync } from 'node:fs'
6
6
  import { homedir } from 'node:os'
7
7
  import { isAbsolute, join, relative, resolve } from 'node:path'
8
- import { bad, NO_STORE, ranged } from '../review/http.ts'
8
+ import { bad, FRESH, NO_STORE, ranged } from '../review/http.ts'
9
9
  import { askedPosts, noteOn, notesBy } from '../review/notes.ts'
10
10
  import { readAllCached, storeDir } from '../review/store.ts'
11
11
  import { DRAFT_NAME, draftsDir, type Desk } from './load.ts'
@@ -44,7 +44,7 @@ function picture(desk: Desk, identity: string, rel: string): string {
44
44
  const i = desk.identities.find((x) => x.id === identity)
45
45
  if (i?.files == null) throw new Error(`${identity} has no files folder`)
46
46
  if (rel.startsWith('~/') || isAbsolute(rel)) {
47
- if (!i.pictures.some((p) => p.file === rel)) throw new Error(`not a picture of ${identity}: ${rel}`)
47
+ if (!i.pictures.some((p) => p.file === rel || p.also.includes(rel))) throw new Error(`not a picture of ${identity}: ${rel}`)
48
48
  return rel.startsWith('~/') ? join(homedir(), rel.slice(2)) : rel
49
49
  }
50
50
  const abs = resolve(i.files, rel)
@@ -91,7 +91,7 @@ export async function socialRoutes(root: string, req: Request, path: string): Pr
91
91
  const pic = /^picture\/([a-z0-9-]+)\/(.+)$/.exec(sub)
92
92
  if (pic) {
93
93
  const { desk } = await openDesk(root)
94
- return ranged(req, picture(desk, pic[1]!, decodeURIComponent(pic[2]!)))
94
+ return ranged(req, picture(desk, pic[1]!, decodeURIComponent(pic[2]!)), FRESH)
95
95
  }
96
96
  const prev = /^preview\/([^/]+)$/.exec(sub)
97
97
  if (prev) {
@@ -4,7 +4,7 @@
4
4
  import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
5
5
  import { join } from 'node:path'
6
6
  import { machineCommit } from '../core/machine-commit.ts'
7
- import { bad, NO_STORE, ranged } from '../review/http.ts'
7
+ import { bad, FRESH, NO_STORE, ranged } from '../review/http.ts'
8
8
  import { noteOn } from '../review/notes.ts'
9
9
  import { openReview } from '../review/project.ts'
10
10
  import { FILE_ROUTE, loadStoresUnit, shownFile, storesState, textFiles } from './desk.ts'
@@ -111,7 +111,7 @@ export async function storesRoutes(root: string, req: Request, path: string): Pr
111
111
  }
112
112
  if (path.startsWith(FILE_ROUTE) && req.method === 'GET') {
113
113
  const abs = shownFile(root, decodeURIComponent(path.slice(FILE_ROUTE.length)))
114
- return abs ? ranged(req, abs) : bad(`${path}?`, 404)
114
+ return abs ? ranged(req, abs, FRESH) : bad(`${path}?`, 404)
115
115
  }
116
116
  if (req.method !== 'POST') return bad(`stores: no route ${req.method} ${path}`, 404)
117
117
  const body = (await req.json().catch(() => ({}))) as Record<string, unknown>
@@ -47,7 +47,7 @@ export const FULL_TIMEOUT_MS = 120_000
47
47
  * trigger), so without this a hang lasts until something outside kills it. The quick
48
48
  * tier answers in seconds, so two minutes is far from any real run. */
49
49
  export const QUICK_CEILING_MS = 120_000
50
- /** the full tier runs every suite one after the other, about three minutes */
50
+ /** the full tier's ceiling: it runs every suite, slow ones included */
51
51
  export const FULL_CEILING_MS = 1_800_000
52
52
  const TESTS_KEYS = ['budgetMs', 'slow', 'serial', 'select']
53
53
  const SLOW_KEYS = ['file', 'catches', 'whyNotFast']
@@ -477,16 +477,39 @@ export function envFilesOf(rawArgs: string[], cwdRel: string): string[] {
477
477
  export function suiteFiles(top: string, cwdRel: string, testRoot: string | null, ignores: string[], isTest: (f: string) => boolean): string[] {
478
478
  const under = posix.normalize(posix.join(cwdRel, testRoot ?? '.'))
479
479
  const at = under === '.' ? '.' : under
480
- // bun discovers what git ignores too, an install excepted
481
- const listed = [
482
- ...git(top, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', at]).split('\0'),
483
- ...git(top, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--', at]).split('\0').filter((f) => !f.split('/').includes('node_modules')),
484
- ]
485
480
  const res = ignores.map((g) => globRe(g))
481
+ const relOf = (f: string): string => (cwdRel === '' || cwdRel === '.' ? f : f.slice(cwdRel.length + 1))
482
+ // bun discovers what git ignores too, an install excepted. Git lists an ignored folder as one entry
483
+ // (--directory), where listing its files walked every one of them first: 701,496 files and 12 s in a repo
484
+ // whose ignored data/ holds 655k. The folders bun would search are walked here, and a folder a bun ignore
485
+ // pattern covers whole (`data/**`) is never opened
486
+ const listed = git(top, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', at]).split('\0')
487
+ const covered = (dir: string): boolean => res.some((re) => re.test(`${relOf(dir)}/${PROBE}`))
488
+ const walk = (dir: string): void => {
489
+ let entries: import('fs').Dirent[]
490
+ try {
491
+ entries = readdirSync(join(top, dir), { withFileTypes: true })
492
+ } catch {
493
+ return
494
+ }
495
+ for (const e of entries) {
496
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue
497
+ const p = `${dir}/${e.name}`
498
+ const folder = e.isDirectory() || (e.isSymbolicLink() && statSync(join(top, p), { throwIfNoEntry: false })?.isDirectory() === true)
499
+ if (folder) {
500
+ if (!covered(p)) walk(p)
501
+ } else if (isTest(p)) listed.push(p)
502
+ }
503
+ }
504
+ for (const f of git(top, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory', '--', at]).split('\0')) {
505
+ if (f === '' || f.split('/').some((x) => x === 'node_modules' || x.startsWith('.'))) continue
506
+ if (!f.endsWith('/')) listed.push(f)
507
+ else if (!covered(f.slice(0, -1))) walk(f.slice(0, -1))
508
+ }
486
509
  const out: string[] = []
487
510
  for (const f of listed) {
488
511
  if (f === '' || !isTest(f) || !existsSync(join(top, f))) continue
489
- const rel = cwdRel === '' || cwdRel === '.' ? f : f.slice(cwdRel.length + 1)
512
+ const rel = relOf(f)
490
513
  if (inDotDir(rel)) continue
491
514
  if (res.some((re) => re.test(rel))) continue
492
515
  out.push(rel)
@@ -494,6 +517,9 @@ export function suiteFiles(top: string, cwdRel: string, testRoot: string | null,
494
517
  return [...new Set(out)].sort()
495
518
  }
496
519
 
520
+ /** a file name no test has: a folder whose every path an ignore pattern matches matches it too */
521
+ const PROBE = '\u0000probe'
522
+
497
523
  /** a bun ignore pattern as a regexp: `**` any depth, `*` one segment */
498
524
  export function globRe(glob: string): RegExp {
499
525
  const g = glob.replace(/^\.\//, '')
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
- // the floor `test` slot for a plain `bun test` script: quick tier suites in
3
- // parallel workers, the full tier one at a time, the declared serial ones after,
2
+ // the floor `test` slot for a plain `bun test` script: every suite in parallel
3
+ // workers (the full tier adds the slow ones), the declared serial ones after,
4
4
  // and each quick tier suite timed against the budget.
5
5
  // The LAST stdout line is the task headline the gate prints, and it keeps bun's
6
6
  // `Ran N tests` so the gate can still report what ran.
@@ -124,9 +124,9 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
124
124
 
125
125
  const help = Bun.spawnSync(['bun', 'test', '--help'], { stdout: 'pipe', stderr: 'pipe' })
126
126
  const helpText = `${help.stdout.toString()}${help.stderr.toString()}`
127
- // the full tier runs one suite at a time: its suites spawn git and whole
128
- // gates, and sharing a run measured slower than sequential and timed out
129
- const parallel = helpText.includes('--parallel') && tier === 'quick'
127
+ // both tiers share workers: the full tier adds the slow suites to the parallel phase, and a suite that cannot
128
+ // share a run is named in tests.serial
129
+ const parallel = helpText.includes('--parallel')
130
130
  const timed = helpText.includes('--update-timings')
131
131
  // bun drops these the moment any ignore reaches its command line
132
132
  const bunfig = bunfigTest(existsSync('bunfig.toml') ? readFileSync('bunfig.toml', 'utf8') : null)
@@ -14,6 +14,8 @@ import type { TitleMotion } from './motion.ts'
14
14
  import type { TitleRequest } from './titles.ts'
15
15
  import type { Stitched } from './stitch.ts'
16
16
  import { projectCli, readVocab } from './vocab.ts'
17
+ import { timed } from './profile.ts'
18
+ import type { Draft } from './draft.ts'
17
19
 
18
20
  export type Say = (line: string) => void
19
21
 
@@ -458,6 +460,10 @@ export interface BuildOptions {
458
460
  final: boolean
459
461
  say: Say
460
462
  cwd: string
463
+ /** a draft of the cut (draft.ts): smaller, quicker, its own mp4, no strip unless `strip` */
464
+ draft?: Draft
465
+ /** the strip of a draft too */
466
+ strip?: boolean
461
467
  }
462
468
 
463
469
  /** the shots `names` names and the cells their grids and splits read: what a preview films */
@@ -476,16 +482,16 @@ async function browserLanes(root: string): Promise<number> {
476
482
  }
477
483
 
478
484
  /** film the takes missing (and what --refilm names), as many at once as the repo's browser cap; every shot is tried,
479
- * the failures said together */
480
- async function filmAll(l: Loaded, world: World, refilm: Refilm, say: Say, only?: ReadonlySet<string>): Promise<Take[]> {
481
- const { filmTake } = await import('./footage.ts')
482
- const takes = takesOfLoaded(l)
485
+ * the failures said together. A draft's (`small`, the draft's trailer) reads the cut's own takes and films the rest small */
486
+ async function filmAll(l: Loaded, world: World, refilm: Refilm, say: Say, only?: ReadonlySet<string>, small?: Trailer): Promise<Take[]> {
487
+ const [{ filmTake, takesOf }, { draftTakes }] = await Promise.all([import('./footage.ts'), import('./draft.ts')])
488
+ const takes = small ? draftTakes(takesOfLoaded(l), takesOf(small, l.root, l), world, refilm) : takesOfLoaded(l)
483
489
  const ask = takesToFilm(takes, world, refilm, only)
484
490
  const failed: string[] = []
485
491
  const lane = async (): Promise<void> => {
486
492
  for (let group = ask.shift(); group; group = ask.shift()) {
487
493
  try {
488
- const got = await filmTake(group[0]!, { root: l.root, t: l.t, world: worldFor(world, group[0]!), cli: l.cli, holes: l.unit?.holes === true, say })
494
+ const got = await timed(`film ${group[0]!.shot.name}`, () => filmTake(group[0]!, { root: l.root, t: small ?? l.t, world: worldFor(world, group[0]!), cli: l.cli, holes: l.unit?.holes === true, draft: small !== undefined, say }))
489
495
  for (const tk of group) {
490
496
  const i = takes.indexOf(tk)
491
497
  takes[i] = { ...tk, stamp: got.stamp }
@@ -528,8 +534,32 @@ export async function scoreFile(l: Loaded, seconds: number, say: Say): Promise<s
528
534
  return w.file
529
535
  }
530
536
 
531
- /** everything the stitch reads but its output: sources, titles, sounds, the look */
532
- async function stitchInput(l: Loaded, takes: readonly Take[], shots: readonly Shot[], silent: boolean, say: Say = () => undefined) {
537
+ /** every sound the shots play, made where the house or the unit has to: the music cues, each shot's sfx and voices */
538
+ async function soundsOf(l: Loaded, shots: readonly Shot[], say: Say) {
539
+ const { durationOf } = await import('./ffmpeg.ts')
540
+ const resolve = (req: SoundRequest): Promise<string> => soundFile(l, req, say)
541
+ const ask = (kind: SoundRequest['kind'], text: string, x: { prompt?: true; gen?: SoundGen; run?: SoundRun; line: number }, seconds?: number, take?: string): SoundRequest => soundRequest(kind, text, x, l.dir, seconds, take)
542
+ const music = await timed('sounds', () => Promise.all(
543
+ musicCues(l.t).map(({ cue, at, end }) => {
544
+ if (cue.song === SCORE) return scoreFile(l, cue.from + end - at, say)
545
+ const seconds = cue.from + end - at
546
+ if (isFileSound(cue.song, cue)) return cue.song.endsWith('.mid') ? resolve(ask('music', fileOf(cue.song, l)!, cue, seconds)) : fileOf(cue.song, l)!
547
+ return resolve(ask('music', cue.song, cue, seconds, cue.take))
548
+ }),
549
+ ))
550
+ const sfx = await Promise.all(shots.map((s) => Promise.all(s.sfx.map(async (x) => {
551
+ const file = isFileSound(x.id, x) ? fileOf(x.id, l)! : await resolve(ask('sfx', x.id, x))
552
+ return { file, seconds: await durationOf(file) }
553
+ }))))
554
+ const voices = await Promise.all(shots.map((s) => Promise.all(s.voices.map(async (v) => {
555
+ const file = v.file ? fileOf(v.file, l)! : await resolve(ask('voice', v.text ?? 'run', v))
556
+ return { file, seconds: await durationOf(file) }
557
+ }))))
558
+ return { music, sfx, voices }
559
+ }
560
+
561
+ /** everything the stitch reads but its output: sources, titles, sounds (`sounds` when the caller started them), the look */
562
+ async function stitchInput(l: Loaded, takes: readonly Take[], shots: readonly Shot[], silent: boolean, say: Say = () => undefined, sounds?: ReturnType<typeof soundsOf>) {
533
563
  const { gridMask, splitMasks } = await import('./stitch.ts')
534
564
  const [{ cardPng, titlePng }, { lookOf }, { durationOf }, { trailerCache }, { loadBrand, identityLogo }] = await Promise.all([
535
565
  import('./titles.ts'),
@@ -569,27 +599,9 @@ async function stitchInput(l: Loaded, takes: readonly Take[], shots: readonly Sh
569
599
  const styleErrors = resolveStyles(l.t, brand?.trailer?.styles ?? {})
570
600
  if (styleErrors.length > 0) throw new Refused(styleErrors.map((e) => `${relative(l.root, l.file)}:${e.line}: ${e.message}`).join('\n'))
571
601
  const motions = titleMotions({ ...l.t, shots: [...shots] })
572
- const drawn = await Promise.all(shots.map((s, i) => Promise.all(s.titles.map(async (ti, j) => titlePng(titles, { ...titleRequest(l, ti, look, motions[i]![j]!), font: await titleFont(l, ti) })))))
602
+ const drawn = await timed('titles', () => Promise.all(shots.map((s, i) => Promise.all(s.titles.map(async (ti, j) => titlePng(titles, { ...titleRequest(l, ti, look, motions[i]![j]!), font: await titleFont(l, ti) }))))))
573
603
  if (silent) return { ...base, sources, titles: drawn, music: [], sfx: shots.map(() => []), voices: shots.map(() => []) }
574
- const resolve = (req: SoundRequest): Promise<string> => soundFile(l, req, say)
575
- const ask = (kind: SoundRequest['kind'], text: string, x: { prompt?: true; gen?: SoundGen; run?: SoundRun; line: number }, seconds?: number, take?: string): SoundRequest => soundRequest(kind, text, x, l.dir, seconds, take)
576
- const music = await Promise.all(
577
- musicCues(l.t).map(({ cue, at, end }) => {
578
- if (cue.song === SCORE) return scoreFile(l, cue.from + end - at, say)
579
- const seconds = cue.from + end - at
580
- if (isFileSound(cue.song, cue)) return cue.song.endsWith('.mid') ? resolve(ask('music', fileOf(cue.song, l)!, cue, seconds)) : fileOf(cue.song, l)!
581
- return resolve(ask('music', cue.song, cue, seconds, cue.take))
582
- }),
583
- )
584
- const sfx = await Promise.all(shots.map((s) => Promise.all(s.sfx.map(async (x) => {
585
- const file = isFileSound(x.id, x) ? fileOf(x.id, l)! : await resolve(ask('sfx', x.id, x))
586
- return { file, seconds: await durationOf(file) }
587
- }))))
588
- const voices = await Promise.all(shots.map((s) => Promise.all(s.voices.map(async (v) => {
589
- const file = v.file ? fileOf(v.file, l)! : await resolve(ask('voice', v.text ?? 'run', v))
590
- return { file, seconds: await durationOf(file) }
591
- }))))
592
- return { ...base, sources, titles: drawn, music, sfx, voices }
604
+ return { ...base, sources, titles: drawn, ...(await (sounds ?? soundsOf(l, shots, say))) }
593
605
  }
594
606
 
595
607
  /** a vertical cut finished: what the brand's vertical look draws over the stitched cut, the outro, the end card. The
@@ -671,38 +683,51 @@ async function pruneAfter(root: string, say: Say): Promise<void> {
671
683
  /** the whole cut: out/<cut>.mp4, its strip, montage page and shelf of takes; the timeline and what was rendered, said */
672
684
  export async function build(l: Loaded, o: BuildOptions): Promise<string> {
673
685
  const t0 = performance.now()
674
- const [{ trailerCache }, { stitch, strip, rendered }, { ffmpegMissing }] = await Promise.all([import('./footage.ts'), import('./stitch.ts'), import('./ffmpeg.ts')])
686
+ const [{ trailerCache }, { stitch, strip, rendered, renderMix }, { ffmpegMissing }] = await Promise.all([import('./footage.ts'), import('./stitch.ts'), import('./ffmpeg.ts')])
675
687
  const missing = ffmpegMissing()
676
688
  if (missing) throw new Refused(missing)
677
- const world = await worldOf(l)
678
- const takes = await filmAll(l, world, o.refilm, o.say)
679
- shelve(l, takes)
689
+ // the sound reads no take: it is made and mixed while the takes film, off the stitch's path
690
+ const sounds = soundsOf(l, l.t.shots, o.say)
691
+ const mixing = timed('the sound mixed', async () => renderMix({ t: l.t, ...(await sounds), cache: trailerCache(l.root, 'pieces') }))
692
+ // a take that fails throws first: the sound's own failure is said where the stitch awaits it
693
+ mixing.catch(() => undefined)
694
+ const world = await timed('world', () => worldOf(l))
695
+ // a draft draws the picture of its own smaller trailer (draft.ts); the sound stays the cut's
696
+ const small = o.draft ? (await import('./draft.ts')).draftOf(l.t, o.draft) : undefined
697
+ const lv: Loaded = small ? { ...l, t: small } : l
698
+ const takes = await timed('filming', () => filmAll(l, world, o.refilm, o.say, undefined, small))
699
+ // the shelf is what `keep` clones: a draft never writes it
700
+ if (!small) await timed('shelve', () => shelve(l, takes))
680
701
  const tFilm = performance.now()
681
- const input = await stitchInput(l, takes, l.t.shots, false, o.say)
682
- const out = join(outDir(l), `${l.t.name}.mp4`)
702
+ const input = await timed('stitch input (sources, titles, sounds)', () => stitchInput(lv, takes, lv.t.shots, false, o.say, sounds))
703
+ const out = join(outDir(l), `${lv.t.name}.mp4`)
683
704
  // a vertical cut stitches into the cache, and its finish writes the mp4
684
- const cut = l.t.vertical ? join(trailerCache(l.root, 'pieces'), `${l.t.name}-cut.mp4`) : out
685
- const done = await stitch({ ...input, t: l.t, out: cut, cache: trailerCache(l.root, 'pieces'), encoder: o.final ? 'final' : 'draft' })
686
- const finished = l.t.vertical ? await finishVertical(l, input, done, cut, out, o.final) : null
687
- const stripFile = join(outDir(l), `${l.t.name}.strip.png`)
688
- // the strip is drawn from the pieces' thumbs: the same pieces draw the same strip, so a build that rendered no
689
- // section keeps it
690
- const stripKey = join(trailerCache(l.root, 'pieces'), `${l.t.name}.strip.key`)
691
- const key = done.pieces.map((p) => p.thumbs).join('\n')
692
- const drawn = (): string => `${key}\n${statSync(stripFile).mtimeMs}`
693
- if (!existsSync(stripFile) || !existsSync(stripKey) || readFileSync(stripKey, 'utf8') !== drawn()) {
694
- await strip(done.pieces, stripFile)
695
- writeFileSync(stripKey, drawn())
705
+ const cut = lv.t.vertical ? join(trailerCache(l.root, 'pieces'), `${lv.t.name}-cut.mp4`) : out
706
+ const withStrip = !small || o.strip === true
707
+ const done = await timed('stitch', () => stitch({ ...input, t: lv.t, out: cut, cache: trailerCache(l.root, 'pieces'), encoder: o.final ? 'final' : 'draft', mixing, thumbs: withStrip }))
708
+ const finished = lv.t.vertical ? await finishVertical(lv, input, done, cut, out, o.final) : null
709
+ const stripFile = join(outDir(l), `${lv.t.name}.strip.png`)
710
+ if (withStrip) {
711
+ // the strip is drawn from the pieces' thumbs: the same pieces draw the same strip, so a build that rendered no
712
+ // section keeps it
713
+ const stripKey = join(trailerCache(l.root, 'pieces'), `${lv.t.name}.strip.key`)
714
+ const key = done.pieces.map((p) => p.thumbs).join('\n')
715
+ const drawn = (): string => `${key}\n${statSync(stripFile).mtimeMs}`
716
+ if (!existsSync(stripFile) || !existsSync(stripKey) || readFileSync(stripKey, 'utf8') !== drawn()) {
717
+ await timed('strip', () => strip(done.pieces, stripFile))
718
+ writeFileSync(stripKey, drawn())
719
+ }
696
720
  }
697
- writeFileSync(join(outDir(l), `${l.t.name}.montage.md`), montage(l.t, basename(l.file)))
721
+ if (!small) writeFileSync(join(outDir(l), `${l.t.name}.montage.md`), montage(l.t, basename(l.file)))
698
722
  for (const line of timeline(l, takes, world, o.cwd)) o.say(line)
699
- o.say(`ok: ${out} (${(finished?.seconds ?? total(l.t)).toFixed(2)} s) in ${((performance.now() - t0) / 1000).toFixed(1)} s: filming ${((tFilm - t0) / 1000).toFixed(1)} s, ${rendered(done)}${finished ? `, ${finished.note}` : ''}`)
700
- o.say(`ok: ${stripFile}`)
723
+ const what = small ? `a draft at ${small.size.join('x')}, ` : ''
724
+ o.say(`ok: ${out} (${what}${(finished?.seconds ?? total(lv.t)).toFixed(2)} s) in ${((performance.now() - t0) / 1000).toFixed(1)} s: filming ${((tFilm - t0) / 1000).toFixed(1)} s, ${rendered(done)}${finished ? `, ${finished.note}` : ''}`)
725
+ if (withStrip) o.say(`ok: ${stripFile}`)
701
726
  // the vertical's finish can lay an outro's own sound after the mix: its mp4 is what is measured then
702
727
  const heard = finished ? out : done.mix
703
728
  if (heard) {
704
729
  const [{ loudness, loudnessKept }, { MIX_TRUE_PEAK }] = await Promise.all([import('./ffmpeg.ts'), import('./graph.ts')])
705
- const { lufs, truePeak } = await (finished ? loudness(heard) : loudnessKept(heard))
730
+ const { lufs, truePeak } = await timed('the mix measured', () => (finished ? loudness(heard) : loudnessKept(heard)))
706
731
  const { master } = l.t
707
732
  const line = `the mix: ${lufs.toFixed(1)} LUFS integrated${master === null ? '' : ` (master ${master})`}, true peak ${truePeak.toFixed(1)} dBTP`
708
733
  if (truePeak > 0) refuse(`${line}, past 0 dBTP: it clips on a player. ${out} is written; lower the loudest sounds (a score's volume, a sfx or voice volume)`)
@@ -711,7 +736,7 @@ export async function build(l: Loaded, o: BuildOptions): Promise<string> {
711
736
  else if (Math.abs(off) > 0.5) o.say(`WARN ${line}, ${Math.abs(off).toFixed(1)} LU ${off < 0 ? 'under' : 'over'} its master, past what one gain into the ${MIX_TRUE_PEAK} dBTP limiter reaches (its loudest sound held down while the rest stays quiet)`)
712
737
  else o.say(`ok: ${line}`)
713
738
  }
714
- await pruneAfter(l.root, o.say)
739
+ await timed('prune', () => pruneAfter(l.root, o.say))
715
740
  return out
716
741
  }
717
742