rvlib-shipkit 2.9.0 → 2.11.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 (75) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +1 -1
  3. package/src/cli/cmd_Media.ts +164 -0
  4. package/src/cli/cmd_Review.ts +2 -1
  5. package/src/cli/family-pages.ts +1 -0
  6. package/src/cli/registry.ts +2 -0
  7. package/src/collections/pings.ts +6 -4
  8. package/src/core/app-icon.ts +17 -4
  9. package/src/core/scratch-objects.ts +56 -0
  10. package/src/core/trace-audit.ts +13 -1
  11. package/src/home/home-paths.ts +4 -0
  12. package/src/home/home-routes.ts +36 -2
  13. package/src/home/hubs.ts +5 -0
  14. package/src/home/inbox-shape.ts +182 -0
  15. package/src/home/inbox.ts +48 -0
  16. package/src/home/run-daemon.ts +12 -2
  17. package/src/home/serve-web.ts +155 -16
  18. package/src/ledger/git-scan.ts +73 -25
  19. package/src/ledger/repo-view.ts +2 -22
  20. package/src/media-kinds.ts +7 -0
  21. package/src/media-store/content.ts +51 -0
  22. package/src/media-store/daemon.ts +91 -0
  23. package/src/media-store/db.ts +74 -0
  24. package/src/media-store/fact.ts +9 -0
  25. package/src/media-store/kind.ts +44 -0
  26. package/src/media-store/purge.ts +139 -0
  27. package/src/media-store/remote.ts +93 -0
  28. package/src/media-store/space.ts +124 -0
  29. package/src/media-store/sync.ts +101 -0
  30. package/src/media-store/upload.ts +98 -0
  31. package/src/repo-config.ts +4 -0
  32. package/src/review/anim.ts +6 -5
  33. package/src/review/cells.ts +552 -0
  34. package/src/review/format.ts +1 -1
  35. package/src/review/media-kind.ts +84 -0
  36. package/src/review/media-read.ts +48 -0
  37. package/src/review/model.ts +43 -5
  38. package/src/review/previews.ts +153 -0
  39. package/src/review/routes.ts +105 -47
  40. package/src/review/store.ts +106 -45
  41. package/src/review/trailer-desk.ts +79 -46
  42. package/src/review/trailer-media.ts +163 -0
  43. package/src/review/trailer-routes.ts +5 -2
  44. package/src/serve/hub-app/home-st.ts +39 -9
  45. package/src/serve/hub-app/home.html +2 -1
  46. package/src/serve/hub-app/hub-app.tsx +7 -23
  47. package/src/serve/hub-app/icons.tsx +2 -0
  48. package/src/serve/hub-app/inbox-st.ts +144 -0
  49. package/src/serve/hub-app/inbox-view.tsx +205 -0
  50. package/src/serve/hub-app/inbox.css +73 -0
  51. package/src/serve/hub-app/item-view.tsx +19 -0
  52. package/src/serve/hub-app/keys.ts +4 -3
  53. package/src/serve/hub-app/palette-st.ts +2 -1
  54. package/src/serve/hub-app/project-list.tsx +1 -0
  55. package/src/serve/hub-app/projects-svc.ts +1 -1
  56. package/src/serve/hub-app/repo-st.ts +1 -1
  57. package/src/serve/hub-app/review/kind-view.tsx +21 -22
  58. package/src/serve/hub-app/review/kit.tsx +11 -12
  59. package/src/serve/hub-app/review/review-board.tsx +15 -13
  60. package/src/serve/hub-app/review/review-cells.tsx +241 -0
  61. package/src/serve/hub-app/review/review-kit.ts +79 -0
  62. package/src/serve/hub-app/review/review-list.tsx +87 -122
  63. package/src/serve/hub-app/review/review-page.tsx +22 -79
  64. package/src/serve/hub-app/review/review-st.ts +269 -698
  65. package/src/serve/hub-app/review/review-thread.tsx +302 -0
  66. package/src/serve/hub-app/review/review-views.tsx +322 -253
  67. package/src/serve/hub-app/review/thread-st.ts +770 -0
  68. package/src/serve/hub-app/review.css +235 -91
  69. package/src/serve/hub-runtime.ts +9 -4
  70. package/src/serve/serve-hub.ts +4 -1
  71. package/src/serve/warm-cell.ts +6 -1
  72. package/src/trailer/footage.ts +6 -2
  73. package/src/trailer/passage.ts +4 -2
  74. package/src/trailer/prune.ts +6 -10
  75. package/src/serve/hub-app/review/review-answer.tsx +0 -249
@@ -0,0 +1,48 @@
1
+ // the reads a route or a tool makes of a card's file (wiki build/shipkit/review.md, Media in the Space): its key in the
2
+ // Space by the facts its item.json keeps, a URL signed for a file the disk let go, the file fetched back for its bytes
3
+ import { existsSync, readFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { mediaKey } from '../media-store/content.ts'
6
+ import type { MediaFact } from '../media-store/fact.ts'
7
+ import { fetchBack, signedIfUp, signedUrl } from '../media-store/remote.ts'
8
+ import { FILE_RE, ID_RE } from './model.ts'
9
+
10
+ export const REVIEW_KIND = 'review'
11
+
12
+ /** where the Space keeps a file of a card */
13
+ export const reviewKey = (f: Pick<MediaFact, 'sha'>, name: string): string => mediaKey(REVIEW_KIND, f, name)
14
+ /** where the Space keeps an image's preview at a size: by the image's own sha, so it is found from the item alone */
15
+ export const previewKey = (f: Pick<MediaFact, 'sha'>, size: string): string => `${REVIEW_KIND}/${f.sha}.${size}.webp`
16
+
17
+ /** the fact a head keeps for one of its files, read from its item.json alone */
18
+ export function factOfFile(dir: string, id: string, name: string): MediaFact | null {
19
+ if (!ID_RE.test(id) || !FILE_RE.test(name)) return null
20
+ try {
21
+ const head = JSON.parse(readFileSync(join(dir, id, 'item.json'), 'utf8')) as { media?: Record<string, MediaFact> }
22
+ return head.media?.[name] ?? null
23
+ } catch {
24
+ return null
25
+ }
26
+ }
27
+
28
+ /** a signed URL for a file of an item that the disk no longer holds and the Space does; null otherwise */
29
+ export async function remoteUrl(dir: string, id: string, name: string): Promise<string | null> {
30
+ const f = factOfFile(dir, id, name)
31
+ return f ? signedUrl(reviewKey(f, name), f.size) : null
32
+ }
33
+
34
+ /** a signed URL for an image's preview at a size, when the Space holds it */
35
+ export async function remotePreviewUrl(dir: string, id: string, name: string, size: string): Promise<string | null> {
36
+ const f = factOfFile(dir, id, name)
37
+ return f ? signedIfUp(previewKey(f, size)) : null
38
+ }
39
+
40
+ /** the path of an item's file on the disk, fetched back from the Space first when the disk let it go; null when neither
41
+ * holds it */
42
+ export async function ensureLocal(dir: string, id: string, name: string): Promise<string | null> {
43
+ if (!ID_RE.test(id) || !FILE_RE.test(name)) return null
44
+ const path = join(dir, id, name)
45
+ if (existsSync(path)) return path
46
+ const f = factOfFile(dir, id, name)
47
+ return f ? fetchBack(path, reviewKey(f, name), f, { store: dir, item: id, name }) : null
48
+ }
@@ -3,6 +3,7 @@
3
3
  // (verdicts, replies, ratings, state changes, read marks). The state is derived from the thread, never stored, so the
4
4
  // hub and every CLI write at once with no lost update. Pure and browser safe: the store, the routes and the hub page
5
5
  // share it. The on disk shape is pkm-multi's (scripts/review/store.ts) verbatim, so either store opens in the other.
6
+ import type { MediaFact } from '../media-store/fact.ts'
6
7
 
7
8
  /** WHAT is judged: `shot` (a plain image or clip), `screen`, `frame` (a frame of a trailer cut), or a kind a repo names
8
9
  * for itself (pkm-multi's place, creature, song...), read as is */
@@ -145,7 +146,10 @@ export type ReviewView = MediaView | GalleryView
145
146
 
146
147
  export const isGallery = (v: ReviewView): v is GalleryView => 'gallery' in v
147
148
 
148
- /** `item.json`: the head, written at creation, changed only by `add-view` */
149
+
150
+ export const SHA_RE = /^[0-9a-f]{64}$/
151
+
152
+ /** `item.json`: the head, written at creation, changed by `add-view`, a draft's refresh and the media facts it lacks */
149
153
  export interface Item {
150
154
  id: string
151
155
  /** ISO time */
@@ -172,6 +176,8 @@ export interface Item {
172
176
  wip?: { live: string; frame: number }
173
177
  /** a choice: every view is an option, he scores them and picks one */
174
178
  choice?: true
179
+ /** each media file the views name, by its name: what the Space keeps it under once the disk lets it go */
180
+ media?: Record<string, MediaFact>
175
181
  }
176
182
 
177
183
  /** a choice card: he picks one of its views */
@@ -205,8 +211,32 @@ export function pasteBlock(i: Item, state: string, w: CardWhere): string {
205
211
  ].join('\n')
206
212
  }
207
213
 
208
- /** a view's name as the page and the CLI show it: its label, or « view n » */
209
- export const viewName = (v: ReviewView | undefined, i: number): string => v?.label || `view ${i + 1}`
214
+ /** a view's letter in its version: A for the first, Z for the 26th, then AA, AB… A digit after a version's digit reads
215
+ * like a version, so a view is never numbered */
216
+ export function viewLetter(i: number): string {
217
+ let n = i + 1
218
+ let s = ''
219
+ while (n > 0) {
220
+ const r = (n - 1) % 26
221
+ s = String.fromCharCode(65 + r) + s
222
+ n = Math.floor((n - 1) / 26)
223
+ }
224
+ return s
225
+ }
226
+
227
+ /** a view as the page and the CLI tag it: its version's number and its letter, `3.B` */
228
+ export const viewTag = (n: number, i: number): string => `${n}.${viewLetter(i)}`
229
+
230
+ /** a view's name as the page and the CLI show it: its label, or « view B » */
231
+ export const viewName = (v: ReviewView | undefined, i: number): string => v?.label || `view ${viewLetter(i)}`
232
+
233
+ /** every media file a card's views name: images, pairs, clips and their posters, sounds and their waveforms, tiles */
234
+ export function viewFilesOf(i: Item): string[] {
235
+ return i.views.flatMap((v) => {
236
+ if (isGallery(v)) return v.gallery.map((g) => g.file)
237
+ return [...Object.values(v.files), ...(v.clip ? [v.clip.poster] : []), ...(v.audio ? [v.audio.wave, ...(v.audio.waveBefore ? [v.audio.waveBefore] : [])] : [])]
238
+ })
239
+ }
210
240
 
211
241
  /** the first view, media when there is one; a note with no image has none */
212
242
  export const firstView = (i: Item): MediaView | undefined => i.views[0] as MediaView | undefined
@@ -723,6 +753,13 @@ export function itemProblems(v: unknown): string[] {
723
753
  if (v.light !== undefined && v.light !== 'review') out.push('light: review, or absent')
724
754
  if (v.wip !== undefined && !(obj(v.wip) && typeof v.wip.live === 'string' && v.wip.live !== '' && Number.isInteger(v.wip.frame))) out.push('wip: { live, frame }, or absent')
725
755
  if (v.choice !== undefined && !(v.choice === true && Array.isArray(v.views) && v.views.length >= 2)) out.push('choice: true on a card of two views or more, or absent')
756
+ if (v.media !== undefined) {
757
+ if (!obj(v.media)) out.push('media: { <file name>: { sha, size, type } }, or absent')
758
+ else
759
+ for (const [n, f] of Object.entries(v.media))
760
+ if (!FILE_RE.test(n) || !obj(f) || typeof f.sha !== 'string' || !SHA_RE.test(f.sha) || !Number.isInteger(f.size) || (f.size as number) < 0 || typeof f.type !== 'string')
761
+ out.push(`media.${n}: a file of the item, { sha: sha256 hex, size: bytes, type }`)
762
+ }
726
763
  return out
727
764
  }
728
765
 
@@ -909,10 +946,11 @@ function reactionsOf(v: unknown, views: readonly ReviewView[], errors: string[],
909
946
  return out
910
947
  }
911
948
 
912
- /** what a reaction or a rectangle is on, as the CLI prints it: `[from above]`, `[trees / oak-v2]` */
949
+ /** what a reaction or a rectangle is on, as the CLI prints it: its view's letter and label, `[B from above]`,
950
+ * `[C trees / oak-v2]`, `[A]` */
913
951
  export function placeText(r: { view?: number | undefined; tile?: number | undefined }, views: readonly ReviewView[]): string {
914
952
  const i = r.view ?? 0
915
953
  const v = views[i]
916
954
  const tile = r.tile !== undefined && v && isGallery(v) ? ` / ${v.gallery[r.tile]?.label || `image ${r.tile + 1}`}` : ''
917
- return `[${viewName(v, i)}${tile}]`
955
+ return `[${viewLetter(i)}${v?.label ? ` ${v.label}` : ''}${tile}]`
918
956
  }
@@ -0,0 +1,153 @@
1
+ // a view's image at the size the page draws it (wiki build/shipkit/review.md, Previews): a webp made once per media
2
+ // file, kept in the repo's cache (`.shipkit/cache/review-previews/<id>/<name>.<size>.webp`, local, never in the store),
3
+ // made again only when its source is newer. The full file is fetched only on zoom
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
5
+ import { dirname, join } from 'node:path'
6
+ import { LAYOUT } from '../core/layout.ts'
7
+ import { FILE_RE, firstView, ID_RE, isGallery, isPair, thumbFileOf, type Item, type ReviewItem } from './model.ts'
8
+ import { probe, stillAt } from './media.ts'
9
+ import { ensureLocal, remotePreviewUrl } from './media-read.ts'
10
+
11
+ /** `thumb` a list row's picture, `fit` a view in the card column: the widest each is drawn, at 2x */
12
+ export const PREVIEW_W = { thumb: 480, fit: 1600 } as const
13
+ export type PreviewSize = keyof typeof PREVIEW_W
14
+ export const isPreviewSize = (s: string): s is PreviewSize => s in PREVIEW_W
15
+
16
+ const IMAGE = /\.(png|jpe?g|webp)$/i
17
+
18
+ const JOBS = 3
19
+ let running = 0
20
+ const waiting: (() => void)[] = []
21
+ const making = new Map<string, Promise<string | null>>()
22
+
23
+ async function slot<T>(work: () => Promise<T>): Promise<T> {
24
+ if (running >= JOBS) await new Promise<void>((go) => waiting.push(go))
25
+ running++
26
+ try {
27
+ return await work()
28
+ } finally {
29
+ running--
30
+ waiting.shift()?.()
31
+ }
32
+ }
33
+
34
+ /** the preview folder of a store: `<repo>/.shipkit/cache/review-previews`, the store being `<repo>/.shipkit/review` */
35
+ export const previewDir = (dir: string): string => join(dirname(dirname(dir)), LAYOUT.cache, 'review-previews')
36
+
37
+ // a poster's preview may come from a lit frame of its clip: its own name, so the black ones made before are not reused
38
+ const outOf = (dir: string, id: string, name: string, size: PreviewSize): string => join(previewDir(dir), id, `${name}.${size}${POSTER.test(name) ? '.lit' : ''}.webp`)
39
+
40
+ /** the preview of an item's image at a size, made on the first ask; null when the name is no image of the item or
41
+ * the image does not read. A made preview of an image the disk let go stays good; else the image is fetched back */
42
+ export async function previewFile(dir: string, id: string, name: string, size: PreviewSize): Promise<string | null> {
43
+ if (!ID_RE.test(id) || !FILE_RE.test(name) || !IMAGE.test(name)) return null
44
+ const out = outOf(dir, id, name, size)
45
+ const here = join(dir, id, name)
46
+ if (!existsSync(here) && existsSync(out)) return out
47
+ const src = await ensureLocal(dir, id, name)
48
+ if (!src) return null
49
+ if (existsSync(out) && statSync(out).mtimeMs >= statSync(src).mtimeMs) return out
50
+ const pending = making.get(out)
51
+ if (pending) return pending
52
+ const job = slot(async () => {
53
+ mkdirSync(dirname(out), { recursive: true })
54
+ const tmp = `${out}.${process.pid}.tmp`
55
+ try {
56
+ const { default: sharp } = await import('sharp')
57
+ const still = POSTER.test(name) ? await litStill(dir, id, name, src, out) : src
58
+ await sharp(still === src ? src : readFileSync(still))
59
+ .resize({ width: PREVIEW_W[size], withoutEnlargement: true })
60
+ .webp({ quality: size === 'thumb' ? 75 : 82 })
61
+ .toFile(tmp)
62
+ } catch (e) {
63
+ console.error(`FAIL: review preview ${size} of ${id}/${name}: ${(e as Error).message}`)
64
+ return null
65
+ }
66
+ renameSync(tmp, out)
67
+ rmSync(`${out}.still.png`, { force: true })
68
+ return out
69
+ }).finally(() => making.delete(out))
70
+ making.set(out, job)
71
+ return job
72
+ }
73
+
74
+ /** every preview being made has landed: a test removes its folder only after */
75
+ export const previewsSettled = async (): Promise<void> => void (await Promise.all([...making.values()]))
76
+
77
+ /** a preview to answer: its file, or when neither it nor its image is on the disk, a signed URL of the Space's copy */
78
+ export async function previewOrRemote(dir: string, id: string, name: string, size: PreviewSize): Promise<{ file: string } | { url: string } | null> {
79
+ if (!ID_RE.test(id) || !FILE_RE.test(name) || !IMAGE.test(name)) return null
80
+ if (!existsSync(join(dir, id, name)) && !existsSync(outOf(dir, id, name, size))) {
81
+ const url = await remotePreviewUrl(dir, id, name, size)
82
+ if (url) return { url }
83
+ }
84
+ const file = await previewFile(dir, id, name, size)
85
+ return file ? { file } : null
86
+ }
87
+
88
+
89
+ const POSTER = /^(v\d+-)?poster\.png$/
90
+ /** a picture whose brightest channel averages under this is black: a trailer's first frame fades in from black */
91
+ const BLACK = 12
92
+ /** where in a clip a poster is looked for when its first frame is black, a share of its length */
93
+ const TRIES = [0.1, 0.25, 0.5]
94
+
95
+ const isBlack = async (png: string): Promise<boolean> => {
96
+ const { default: sharp } = await import('sharp')
97
+ // read as bytes: libvips caches by file name, and the still is written again at the same path
98
+ const st = await sharp(readFileSync(png)).stats()
99
+ return Math.max(...st.channels.slice(0, 3).map((c) => c.mean)) < BLACK
100
+ }
101
+
102
+ /** a clip's poster for its preview: the poster itself, or when it is black (a trailer opens on black) the first frame
103
+ * further in that is not; the clip's file is the poster's view's video, or its after on a pair */
104
+ async function litStill(dir: string, id: string, name: string, poster: string, out: string): Promise<string> {
105
+ if (!(await isBlack(poster))) return poster
106
+ const prefix = name.slice(0, name.length - 'poster.png'.length)
107
+ const clipRe = new RegExp(`^${prefix}(video|after)\\.(mp4|webm)$`)
108
+ const clip = readdirSync(join(dir, id)).find((f) => clipRe.test(f)) ?? Object.keys(mediaOf(dir, id)).find((f) => clipRe.test(f))
109
+ const video = clip ? await ensureLocal(dir, id, clip) : null
110
+ if (!video) return poster
111
+ const still = `${out}.still.png`
112
+ try {
113
+ const { duration } = probe(video)
114
+ for (const at of TRIES) {
115
+ await stillAt(video, duration * at, still)
116
+ if (!(await isBlack(still))) return still
117
+ }
118
+ } catch (e) {
119
+ console.error(`FAIL: review preview of ${id}/${name}: no lit frame: ${(e as Error).message}`)
120
+ }
121
+ return poster
122
+ }
123
+
124
+ /** the media facts a head keeps, by name: what names a file the disk let go */
125
+ const mediaOf = (dir: string, id: string): Record<string, unknown> => {
126
+ try {
127
+ return (JSON.parse(readFileSync(join(dir, id, 'item.json'), 'utf8')) as { media?: Record<string, unknown> }).media ?? {}
128
+ } catch {
129
+ return {}
130
+ }
131
+ }
132
+
133
+ /** every image a card draws: each view's image or pair, a clip's poster, a sound's waveforms, a gallery's tiles */
134
+ export function imagesOf(i: Item): string[] {
135
+ const names = i.views.flatMap((v) => {
136
+ if (isGallery(v)) return v.gallery.map((g) => g.file)
137
+ const f = v.files
138
+ return [...('image' in f ? [f.image] : isPair(f) ? [f.before, f.after] : []), ...(v.clip ? [v.clip.poster] : []), ...(v.audio ? [v.audio.wave, ...(v.audio.waveBefore ? [v.audio.waveBefore] : [])] : [])]
139
+ })
140
+ return [...new Set(names)].filter((n) => IMAGE.test(n))
141
+ }
142
+
143
+ /** the previews of these cards made ahead, so each opens on them: its list thumb, every image at the fit size. Already
144
+ * made ones cost a stat */
145
+ export async function warmPreviews(dir: string, cards: readonly ReviewItem[]): Promise<void> {
146
+ await Promise.all(
147
+ cards.flatMap((x) => {
148
+ const first = firstView(x.item)
149
+ const thumb = first ? thumbFileOf(first) : ''
150
+ return [...(IMAGE.test(thumb) ? [previewFile(dir, x.item.id, thumb, 'thumb')] : []), ...imagesOf(x.item).map((n) => previewFile(dir, x.item.id, n, 'fit'))]
151
+ }),
152
+ )
153
+ }
@@ -1,17 +1,22 @@
1
1
  // the hub's review routes (wiki build/shipkit/review.md, The hub): the store's list, an item's images and clips, the
2
2
  // owner's verdicts, replies and read marks appended to its thread. The trailer view's routes: trailer-routes.ts. Paths are
3
3
  // relative to the repo hub's base. null: not a path of these
4
- import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
4
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
5
5
  import { tmpdir } from 'node:os'
6
6
  import { dirname, extname, join } from 'node:path'
7
7
  import { isAnimFormat, isAnimLabels, isAnimMode, pairAnimation } from './anim.ts'
8
8
  import { startAuto } from './auto.ts'
9
9
  import { bad, KEEP, NO_STORE, ranged, TYPES } from './http.ts'
10
- import type { Rect, Subject } from './model.ts'
10
+ import { viewFilesOf, type Rect, type ReviewItem, type Subject } from './model.ts'
11
11
  import { pasteHosts } from './paste.ts'
12
12
  import { openReview, partFile, viewOfItem } from './project.ts'
13
+ import { isPreviewSize, previewOrRemote, warmPreviews } from './previews.ts'
13
14
  import { roleOf } from './role.ts'
14
- import { addMessage, imageFile, markRead, raiseItem, rateSubject, readAllCached, readItem, specOf, storeDir, storeStamp, threadImage, writeVerdict } from './store.ts'
15
+ import { addMessage, imageFile, itemOfRef, markRead, raiseItem, rateSubject, readAllCached, readItem, specOf, storeDir, storeStamp, threadImage, writeVerdict } from './store.ts'
16
+ import { boardOf, pageOf, queryOf, threadIndex, threadOfId, threadView, type ThreadIndex } from './cells.ts'
17
+ import { membersOf, threadsOf, type Thread } from './threads.ts'
18
+ import { upKeys } from '../media-store/remote.ts'
19
+ import { remoteUrl, reviewKey } from './media-read.ts'
15
20
  import { trailerRoutes } from './trailer-routes.ts'
16
21
  import { specData, type ReviewUnit } from './unit.ts'
17
22
  import { liveWatchers } from './watchers.ts'
@@ -53,50 +58,69 @@ function dataUrlFile(url: unknown): { file: string; done(): void } | null {
53
58
 
54
59
  const obj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
55
60
 
56
- // ── the list's thumbnails: a 480 px webp of an item's image, cached beside the items (readAll skips dot names) ──
61
+ let listing: { dir: string; tag: string; body: string; zipped: Uint8Array<ArrayBuffer> | null } | null = null
57
62
 
58
- const THUMB_W = 480
59
- const THUMB_JOBS = 3
60
- let running = 0
61
- const waiting: (() => void)[] = []
62
- const making = new Map<string, Promise<string | null>>()
63
+ // ── the paged list and one thread: an index over the store's threads, built again when a file moved or a minute
64
+ // passed (a claim goes stale on the clock); its build number is every answer's ETag ──
63
65
 
64
- async function slot<T>(work: () => Promise<T>): Promise<T> {
65
- if (running >= THUMB_JOBS) await new Promise<void>((go) => waiting.push(go))
66
- running++
67
- try {
68
- return await work()
69
- } finally {
70
- running--
71
- waiting.shift()?.()
72
- }
66
+ const INDEX_MS = 60_000
67
+ const BOOT = Date.now().toString(36)
68
+ let builds = 0
69
+ interface Indexed {
70
+ stamp: string
71
+ at: number
72
+ tag: string
73
+ ix: ThreadIndex
74
+ threads: Thread[]
75
+ broken: { id: string; error: string }[]
73
76
  }
77
+ /** one index per store: the daemon serves every house repo, and two open pages must not rebuild each other's */
78
+ const threadIx = new Map<string, Indexed>()
74
79
 
75
- export function thumbFile(dir: string, id: string, name: string): Promise<string | null> {
76
- const src = imageFile(dir, id, name)
77
- if (!src || !/\.(png|jpe?g|webp)$/.test(name)) return Promise.resolve(null)
78
- const out = join(dir, '.thumbs', id, `${name}.webp`)
79
- if (existsSync(out) && statSync(out).mtimeMs >= statSync(src).mtimeMs) return Promise.resolve(out)
80
- const pending = making.get(out)
81
- if (pending) return pending
82
- const job = slot(async () => {
83
- mkdirSync(join(dir, '.thumbs', id), { recursive: true })
84
- const tmp = `${out}.${process.pid}.tmp`
85
- try {
86
- const { default: sharp } = await import('sharp')
87
- await sharp(src).resize({ width: THUMB_W, withoutEnlargement: true }).webp({ quality: 75 }).toFile(tmp)
88
- } catch (e) {
89
- console.error(`FAIL: review thumbnail of ${id}/${name}: ${(e as Error).message}`)
90
- return null
91
- }
92
- renameSync(tmp, out)
93
- return out
94
- }).finally(() => making.delete(out))
95
- making.set(out, job)
96
- return job
80
+ function indexOf(dir: string): Indexed {
81
+ const stamp = storeStamp(dir)
82
+ const held = threadIx.get(dir)
83
+ if (held && held.stamp === stamp && Date.now() - held.at < INDEX_MS) return held
84
+ const all = readAllCached(dir)
85
+ const ix = threadIndex(all.items)
86
+ const made: Indexed = { stamp, at: Date.now(), tag: `"${BOOT}.${++builds}"`, ix, threads: threadsOf(all.items), broken: all.broken }
87
+ threadIx.set(dir, made)
88
+ // the cards that need someone open on their previews: made in the background, one stat each once made
89
+ void warmPreviews(
90
+ dir,
91
+ ix.entries.filter((e) => e.row.active).map((e) => e.t.head),
92
+ )
93
+ return made
97
94
  }
98
95
 
99
- let listing: { dir: string; tag: string; body: string; zipped: Uint8Array<ArrayBuffer> | null } | null = null
96
+ /** the store's thread index as the list reads it, its build's tag beside it: the home's inbox reads every repo's.
97
+ * null for a repo with no store */
98
+ export function storeIndex(root: string): { tag: string; ix: ThreadIndex } | null {
99
+ const dir = storeDir(root)
100
+ if (storeStamp(dir) === 'none') return null
101
+ const x = indexOf(dir)
102
+ return { tag: x.tag, ix: x.ix }
103
+ }
104
+
105
+ /** the media files the thread's views name that neither the disk nor the Space holds (a clip deleted before it went up) */
106
+ function missingOf(dir: string, members: readonly ReviewItem[]): string[] {
107
+ const away = members.flatMap((x) => viewFilesOf(x.item).flatMap((n) => (existsSync(join(dir, x.item.id, n)) ? [] : [{ x, n }])))
108
+ const keyOf = ({ x, n }: (typeof away)[number]): string | null => (x.item.media?.[n] ? reviewKey(x.item.media[n], n) : null)
109
+ const up = upKeys(away.flatMap((a) => keyOf(a) ?? []))
110
+ return away.flatMap((a) => (up.has(keyOf(a) ?? '') ? [] : [`${a.x.item.id}/${a.n}`]))
111
+ }
112
+
113
+ /** a file the disk let go, answered by the Space: the signed URL lives an hour, the browser keeps the redirect half of it */
114
+ const toSpace = (url: string): Response => new Response(null, { status: 302, headers: { Location: url, 'Cache-Control': 'private, max-age=1800' } })
115
+
116
+ /** a json answer with its ETag, 304 when the page holds it; gzipped when the page takes it */
117
+ function tagged(req: Request, tag: string, body: () => unknown): Response {
118
+ const headers = { 'Content-Type': 'application/json', ETag: tag, 'Cache-Control': 'no-cache', Vary: 'Accept-Encoding' }
119
+ if (req.headers.get('If-None-Match') === tag) return new Response(null, { status: 304, headers: { ETag: tag } })
120
+ const text = JSON.stringify(body())
121
+ if (text.length < 4096 || !/\bgzip\b/.test(req.headers.get('Accept-Encoding') ?? '')) return new Response(text, { headers })
122
+ return new Response(Bun.gzipSync(new TextEncoder().encode(text)), { headers: { ...headers, 'Content-Encoding': 'gzip' } })
123
+ }
100
124
 
101
125
  async function reviewRoute(req: Request, path: string, dir: string, unit: ReviewUnit | null): Promise<Response | null> {
102
126
  if (path === '/api/review' && req.method === 'GET') {
@@ -109,6 +133,29 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
109
133
  listing.zipped ??= Bun.gzipSync(new TextEncoder().encode(listing.body))
110
134
  return new Response(listing.zipped, { headers: { ...headers, 'Content-Encoding': 'gzip' } })
111
135
  }
136
+ if (path === '/api/review/threads' && req.method === 'GET') {
137
+ const x = indexOf(dir)
138
+ const q = new URL(req.url).searchParams
139
+ return tagged(req, x.tag, () => pageOf(x.ix, queryOf(q), x.broken))
140
+ }
141
+ const one = /^\/api\/review\/threads\/([^/]+)$/.exec(path)
142
+ if (one && req.method === 'GET') {
143
+ const x = indexOf(dir)
144
+ const ref = decodeURIComponent(one[1] ?? '')
145
+ let id = ref
146
+ try {
147
+ id = itemOfRef(dir, ref)?.item.id ?? ref
148
+ } catch (e) {
149
+ return bad(e)
150
+ }
151
+ const t = threadOfId(id, x.threads)
152
+ if (!t) return bad(`no item ${ref}`, 404)
153
+ return tagged(req, x.tag, () => ({ ...threadView(t, readAllCached(dir).items, x.threads, id), missing: missingOf(dir, membersOf(t)) }))
154
+ }
155
+ if (path === '/api/review/board' && req.method === 'GET') {
156
+ const x = indexOf(dir)
157
+ return tagged(req, x.tag, () => ({ role: roleOf(dir), rows: boardOf(readAllCached(dir).items) }))
158
+ }
112
159
  if (path === '/api/review/watchers' && req.method === 'GET') return Response.json(liveWatchers(dir), { headers: NO_STORE })
113
160
  // the unit's words, the dispatcher's holder: what the page draws the list's filters, labels and board with
114
161
  if (path === '/api/review/spec' && req.method === 'GET') {
@@ -164,10 +211,14 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
164
211
  const f = threadImage(dir, t[1] ?? '', t[2] ?? '')
165
212
  return f ? new Response(Bun.file(f), { headers: { 'Content-Type': TYPES[extname(f)] ?? 'application/octet-stream', ...KEEP } }) : bad('no such image', 404)
166
213
  }
167
- const th = /^\/api\/review\/([^/]+)\/thumb\/([^/]+)$/.exec(path)
168
- if (th && req.method === 'GET') {
169
- const f = await thumbFile(dir, th[1] ?? '', th[2] ?? '')
170
- return f ? new Response(Bun.file(f), { headers: { 'Content-Type': 'image/webp', ...KEEP } }) : bad('no such image', 404)
214
+ // a view's image at the size the page draws it; `thumb/<name>` is the preview's thumb size
215
+ const pv = /^\/api\/review\/([^/]+)\/(?:preview\/([^/]+)|thumb)\/([^/]+)$/.exec(path)
216
+ if (pv && req.method === 'GET') {
217
+ const size = pv[2] ?? 'thumb'
218
+ if (!isPreviewSize(size)) return bad(`preview size ${size}: thumb or fit`, 404)
219
+ const p = await previewOrRemote(dir, pv[1] ?? '', pv[3] ?? '', size)
220
+ if (p && 'url' in p) return toSpace(p.url)
221
+ return p ? new Response(Bun.file(p.file), { headers: { 'Content-Type': 'image/webp', ...KEEP } }) : bad('no such image', 404)
171
222
  }
172
223
  const m = /^\/api\/review\/([^/]+)\/([^/]+)$/.exec(path)
173
224
  if (!m) return null
@@ -179,7 +230,12 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
179
230
  return r.ok ? Response.json(r.message, { headers: NO_STORE }) : Response.json({ error: r.errors.join('\n'), errors: r.errors }, { status: 400, headers: NO_STORE })
180
231
  }
181
232
  if (name === 'reply') return Response.json(addMessage(dir, id, 'owner', ((await req.json()) as { text?: unknown }).text), { headers: NO_STORE })
182
- if (name === 'read') return Response.json({ read: markRead(dir, id, 'owner') }, { headers: NO_STORE })
233
+ if (name === 'read') {
234
+ // the page names the words it drew: a word that came after them stays unread
235
+ const b = (await req.json().catch(() => ({}))) as { of?: unknown }
236
+ const of = Array.isArray(b.of) ? b.of.filter((m): m is string => typeof m === 'string') : undefined
237
+ return Response.json({ read: markRead(dir, id, 'owner', 'owner', new Date(), of) }, { headers: NO_STORE })
238
+ }
183
239
  // the card's folder, or one of its files, shown in the Finder: only names the store's own checks accept
184
240
  if (name === 'reveal') {
185
241
  const b = (await req.json().catch(() => ({}))) as { file?: unknown }
@@ -230,7 +286,9 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
230
286
  }
231
287
  }
232
288
  const f = imageFile(dir, id, name)
233
- return f ? ranged(req, f) : bad(`no file ${id}/${name}`, 404)
289
+ if (f) return ranged(req, f)
290
+ const url = await remoteUrl(dir, id, name)
291
+ return url ? toSpace(url) : bad(`no file ${id}/${name}`, 404)
234
292
  }
235
293
 
236
294
  /** the review and trailer routes of the repo at `root`; null for any other path */