@nickpaustian/tela 0.2.0 → 0.4.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.
@@ -2,7 +2,9 @@ import { mkdir, writeFile, readFile, rm } from "fs/promises"
2
2
  import { existsSync } from "fs"
3
3
  import { dirname, join } from "path"
4
4
  import { sql } from "../db/client.ts"
5
+ import { config } from "../config/load.ts"
5
6
  import { findCollection } from "./collections.ts"
7
+ import { writeGathered } from "./gathered.ts"
6
8
  import { DIALECT } from "./richtext.ts"
7
9
  import { withDerived } from "./derive-values.ts"
8
10
  import type { Collection } from "../config/types.ts"
@@ -288,6 +290,14 @@ export async function exportRelease(
288
290
  cells.push(indexCell(collection))
289
291
  }
290
292
 
293
+ const gathered = await writeGathered(
294
+ config.gathered ?? [],
295
+ published.map((row: any) => ({ id: String(row.id), collection: String(row.collection), data: row.data ?? {} })),
296
+ options,
297
+ )
298
+ files.push(...gathered.files)
299
+ cells.push(...gathered.cells)
300
+
291
301
  return { files, cells }
292
302
  }
293
303
 
@@ -330,6 +340,12 @@ export async function exportRemoval(
330
340
  const files = [path]
331
341
  const cells = [entryCell(collection, slug)]
332
342
 
343
+ if (row) {
344
+ const gathered = await writeGathered(config.gathered ?? [], [{ id: String(row.id), collection, data: null }], options)
345
+ files.push(...gathered.files)
346
+ cells.push(...gathered.cells)
347
+ }
348
+
333
349
  if (isDataSource(collection)) return { files, cells }
334
350
 
335
351
  // The index always changes: the entry has left it.
@@ -663,5 +679,15 @@ export async function republishEntries(options: { root: string; collections?: st
663
679
  }),
664
680
  options.root,
665
681
  )
666
- return { files: [...rewritten.files, ...pictures.files], cells: [...rewritten.cells, ...pictures.cells] }
682
+ // Every published entry is here unless the caller narrowed it, and then the
683
+ // ledger only hears about the ones it was given.
684
+ const gathered = await writeGathered(
685
+ config.gathered ?? [],
686
+ rows.map((row: any) => ({ id: String(row.id), collection: String(row.collection), data: row.data ?? {} })),
687
+ { root: options.root, complete: !options.collections },
688
+ )
689
+ return {
690
+ files: [...rewritten.files, ...pictures.files, ...gathered.files],
691
+ cells: [...rewritten.cells, ...pictures.cells, ...gathered.cells],
692
+ }
667
693
  }
@@ -0,0 +1,103 @@
1
+ import { mkdir, readFile, writeFile } from "fs/promises"
2
+ import { dirname, join } from "path"
3
+ import type { GatheredList } from "../config/types.ts"
4
+
5
+ /**
6
+ * Lists gathered from what is published: every Vimeo video on the site, say,
7
+ * for a server that will only stream those.
8
+ *
9
+ * Kept as a ledger of what each published entry adds, so a publish touches one
10
+ * line of it rather than reading the whole site again. The ledger lives in the
11
+ * content repo with the list it explains: the list is then only ever a
12
+ * function of the ledger, and the repo's history shows which entry brought a
13
+ * value in.
14
+ */
15
+
16
+ /** Published like a data source, so whatever serves those serves this. */
17
+ export const gatheredPath = (name: string) => join("content", "data", `${name}.json`)
18
+ /** Outside `content/`: the ledger is Tela's bookkeeping, and a site rebuilds nothing when it moves. */
19
+ export const ledgerPath = (name: string) => join(".tela", "gathered", `${name}.json`)
20
+ export const gatheredCell = (name: string) => `cms:data:${name}`
21
+
22
+ /** An entry as it is now published, or `data: null` for one taken off the site. */
23
+ export interface GatherChange {
24
+ id: string
25
+ collection: string
26
+ data: Record<string, unknown> | null
27
+ }
28
+
29
+ type Ledger = Record<string, string[]>
30
+
31
+ async function read(root: string, path: string): Promise<unknown> {
32
+ try {
33
+ return JSON.parse(await readFile(join(root, path), "utf-8"))
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+
39
+ async function write(root: string, path: string, data: unknown) {
40
+ const file = join(root, path)
41
+ await mkdir(dirname(file), { recursive: true })
42
+ await writeFile(file, JSON.stringify(data, null, 2) + "\n")
43
+ }
44
+
45
+ function ledgerFrom(file: unknown): Ledger {
46
+ if (!file || typeof file !== "object" || Array.isArray(file)) return {}
47
+ return Object.fromEntries(
48
+ Object.entries(file).filter(([, values]) => Array.isArray(values) && values.every((one) => typeof one === "string")),
49
+ ) as Ledger
50
+ }
51
+
52
+ /** What one entry adds: text, once each, in a steady order. */
53
+ export function valuesFrom(list: GatheredList, change: GatherChange): string[] {
54
+ if (!change.data) return []
55
+ if (list.collections && !list.collections.includes(change.collection)) return []
56
+ const found = list.from(change.data, { collection: change.collection }) ?? []
57
+ const values = [...found].filter((one) => typeof one === "string" || typeof one === "number").map(String).filter(Boolean)
58
+ return [...new Set(values)].sort()
59
+ }
60
+
61
+ const sorted = (ledger: Ledger): Ledger => Object.fromEntries(Object.keys(ledger).sort().map((id) => [id, ledger[id]!]))
62
+
63
+ /**
64
+ * Bring each list up to date with entries that were just published or taken
65
+ * down. `complete` says the changes are everything published, so entries the
66
+ * ledger remembers and the changes don't name are gone.
67
+ *
68
+ * Returns the files written. A list's cell is reported only when the list
69
+ * itself changed; the ledger moving alone rebuilds nothing.
70
+ */
71
+ export async function writeGathered(
72
+ lists: GatheredList[],
73
+ changes: GatherChange[],
74
+ options: { root: string; complete?: boolean },
75
+ ): Promise<{ files: string[]; cells: string[] }> {
76
+ const files: string[] = []
77
+ const cells: string[] = []
78
+
79
+ for (const list of lists) {
80
+ const was = ledgerFrom(await read(options.root, ledgerPath(list.name)))
81
+ const next: Ledger = options.complete ? {} : { ...was }
82
+
83
+ for (const change of changes) {
84
+ const values = valuesFrom(list, change)
85
+ if (values.length) next[change.id] = values
86
+ else delete next[change.id]
87
+ }
88
+
89
+ const ledger = sorted(next)
90
+ if (JSON.stringify(ledger) !== JSON.stringify(sorted(was))) {
91
+ await write(options.root, ledgerPath(list.name), ledger)
92
+ files.push(ledgerPath(list.name))
93
+ }
94
+
95
+ const published = { values: [...new Set(Object.values(ledger).flat())].sort() }
96
+ if (JSON.stringify(await read(options.root, gatheredPath(list.name))) === JSON.stringify(published)) continue
97
+ await write(options.root, gatheredPath(list.name), published)
98
+ files.push(gatheredPath(list.name))
99
+ cells.push(gatheredCell(list.name))
100
+ }
101
+
102
+ return { files, cells }
103
+ }
@@ -0,0 +1,249 @@
1
+ import type { Field } from "../config/types.ts"
2
+ import { dataFields } from "../config/components.ts"
3
+
4
+ /**
5
+ * What a group of fields shows while it is not being edited.
6
+ *
7
+ * A group rests in one of two states: one line beside its title, or a
8
+ * read-only glance at what is inside. Both come from the group's own `peek`
9
+ * and `glance` when it declares them; these are the defaults for one that does
10
+ * not, read off its fields by type. Pure, because they run on every change.
11
+ */
12
+
13
+ export type GroupMode = "minimal" | "summary" | "full"
14
+ export type Rest = "minimal" | "summary"
15
+
16
+ export const REST: Rest = "summary"
17
+
18
+ /** One row of a glance: a labelled value in words, or a summary component drawing it. */
19
+ export interface GlanceRow {
20
+ key: string
21
+ label: string
22
+ text?: string
23
+ component?: string
24
+ value?: unknown
25
+ options?: Record<string, unknown>
26
+ }
27
+
28
+ const EXCERPT = 120
29
+ const LINE_PART = 60
30
+ const LINE_PARTS = 3
31
+ const ROWS_NAMED = 3
32
+
33
+ const shorten = (words: string, most: number) => (words.length > most ? words.slice(0, most - 1).trimEnd() + "…" : words)
34
+ const plain = (markdown: string) => markdown.replace(/[#*_>`]/g, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\s+/g, " ").trim()
35
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value)
36
+ const nameOf = (field: Field) => field.label || field.name
37
+
38
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
39
+
40
+ /** `2026-11-21` as `21 Nov 2026`. */
41
+ function dateSaid(value: string): string {
42
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
43
+ return match ? `${Number(match[3])} ${MONTHS[Number(match[2]) - 1]} ${match[1]}` : value
44
+ }
45
+
46
+ /** `13:30` as `1:30pm`. */
47
+ function timeSaid(value: string): string {
48
+ const match = /^(\d{2}):(\d{2})$/.exec(value)
49
+ if (!match) return value
50
+ const hour = Number(match[1])
51
+ return `${hour % 12 || 12}${match[2] === "00" ? "" : ":" + match[2]}${hour < 12 ? "am" : "pm"}`
52
+ }
53
+
54
+ /** An address as it is, and a link to another entry as what it points into: the id says nothing. */
55
+ function linkSaid(value: string): string {
56
+ const entry = /^tela:([^/]+)\//.exec(value)
57
+ return entry ? `An entry in ${entry[1]}` : value.replace(/^https?:\/\//, "")
58
+ }
59
+
60
+ function countOf(field: Field, rows: unknown[]): string {
61
+ const singular = typeof field.options?.singular === "string" ? field.options.singular.replace(/^an? /, "") : ""
62
+ const noun = singular ? (rows.length === 1 ? singular : singular + "s") : nameOf(field).toLowerCase()
63
+ return `${rows.length} ${noun}`
64
+ }
65
+
66
+ /** A list by what its rows say for themselves: each row's first words, or how many there are when none has any. */
67
+ function rowsSaid(field: Field, rows: unknown[]): string {
68
+ if (!rows.length) return ""
69
+ const inside = dataFields(field.of ?? [])
70
+ const named = rows.map((row) =>
71
+ isRecord(row)
72
+ ? inside
73
+ .filter((one) => ["text", "number", "date"].includes(one.type) && one.component !== "hidden")
74
+ .map((one) => said(one, row[one.name]))
75
+ .filter(Boolean)
76
+ .slice(0, 2)
77
+ .join(" ")
78
+ : "",
79
+ )
80
+ if (!inside.length || named.some((one) => !one)) return countOf(field, rows)
81
+ const more = rows.length - ROWS_NAMED
82
+ return named.slice(0, ROWS_NAMED).join(", ") + (more > 0 ? ` +${more} more` : "")
83
+ }
84
+
85
+ /** A value in words, for the types that have words. Empty when there is nothing to say. */
86
+ function said(field: Field, value: unknown): string {
87
+ if (value === undefined || value === null || value === "") return ""
88
+ if (field.type === "boolean") {
89
+ const on = typeof field.options?.on === "string" ? field.options.on : "Yes"
90
+ const off = typeof field.options?.off === "string" ? field.options.off : "No"
91
+ return value === true ? on : off
92
+ }
93
+ if (field.type === "number") return String(value)
94
+ if (field.type === "repeater") return Array.isArray(value) ? rowsSaid(field, value) : ""
95
+ if (typeof value !== "string") return ""
96
+ if (field.choices) return field.choices.find((choice) => choice.value === value)?.label ?? value
97
+ if (field.type === "date") return dateSaid(value)
98
+ if (field.type === "link") return linkSaid(value)
99
+ if (field.component === "time") return timeSaid(value)
100
+ return field.type === "markdown" ? plain(value) : value.trim()
101
+ }
102
+
103
+ const BUILT_IN = new Set(["text", "markdown", "date", "number", "boolean", "repeater", "link", "reference", "block"])
104
+ /** Components that only change how a built-in value is typed in, so the value still reads as its type. */
105
+ const PLAIN = new Set(["toggle", "choice", "slug", "time", "useWords", "daterange"])
106
+ /** Blocks drawn by their own component whose parts read well enough one by one. */
107
+ const OPEN = new Set(["person"])
108
+
109
+ /** The picture a block holds, when it holds one: a single pointer into the media library, however it is chosen. */
110
+ const pictureIn = (field: Field) =>
111
+ field.type === "block" ? (field.fields ?? []).find((one) => one.type === "reference" && one.to === "media" && !one.many) : undefined
112
+ /** The pictures a list's rows hold, one to a row that has one, with the name its block keeps the picture under. */
113
+ function picturesIn(field: Field, value: unknown): { value: Record<string, unknown>; picture: string }[] {
114
+ if (field.type !== "repeater" || !Array.isArray(value)) return []
115
+ const holder = dataFields(field.of ?? []).find((one) => pictureIn(one))
116
+ const picture = holder && pictureIn(holder)
117
+ if (!holder || !picture) return []
118
+ return value.flatMap((row) => {
119
+ const held = isRecord(row) ? row[holder.name] : undefined
120
+ return isRecord(held) && held[picture.name] ? [{ value: held, picture: picture.name }] : []
121
+ })
122
+ }
123
+
124
+ const ownSummary = (field: Field) => `${field.component}summary`.toLowerCase()
125
+
126
+ export interface GlanceOptions {
127
+ /** The components the admin has, by id. A field drawn by its own component is summarised by the summary component of the same name, where there is one. */
128
+ registered?: string[]
129
+ }
130
+
131
+ interface Found extends GlanceRow {
132
+ parents: string[]
133
+ }
134
+
135
+ function rowsOf(fields: Field[], values: Record<string, unknown>, trail: string[], parents: string[], options: GlanceOptions): Found[] {
136
+ const out: Found[] = []
137
+ for (const field of dataFields(fields)) {
138
+ if (field.writeOnly || field.component === "hidden") continue
139
+ const value = values?.[field.name]
140
+ const row = { key: [...trail, field.name].join("."), label: nameOf(field), parents }
141
+ const own = field.component !== undefined && !PLAIN.has(field.component)
142
+
143
+ const picture = pictureIn(field)
144
+ if (picture) {
145
+ if (isRecord(value) && value[picture.name]) out.push({ ...row, component: "picturesummary", value, options: { picture: picture.name } })
146
+ continue
147
+ }
148
+ if (own && field.type !== "reference") {
149
+ const held = isRecord(value) ? Object.keys(value).length > 0 : Array.isArray(value) ? value.length > 0 : Boolean(value)
150
+ if (held && options.registered?.includes(ownSummary(field))) out.push({ ...row, component: ownSummary(field), value, options: { glance: true } })
151
+ else if (field.type === "block" && OPEN.has(field.component!) && isRecord(value)) {
152
+ out.push(...rowsOf(field.fields ?? [], value, [...trail, field.name], [...parents, nameOf(field)], options))
153
+ }
154
+ continue
155
+ }
156
+ if (field.type === "reference") {
157
+ const held = Array.isArray(value) ? value.length > 0 : Boolean(value)
158
+ if (held) out.push({ ...row, component: "referencesummary", value, options: { to: field.to } })
159
+ continue
160
+ }
161
+ if (field.type === "block") {
162
+ if (field.fields && isRecord(value)) out.push(...rowsOf(field.fields, value, [...trail, field.name], [...parents, nameOf(field)], options))
163
+ continue
164
+ }
165
+ if (!BUILT_IN.has(field.type)) continue
166
+ const text = said(field, value)
167
+ const pictures = picturesIn(field, value)
168
+ if (pictures.length) {
169
+ out.push({ ...row, component: "picturessummary", value: pictures.map((one) => one.value), options: { picture: pictures[0].picture, caption: shorten(text, EXCERPT) } })
170
+ continue
171
+ }
172
+ if (text) out.push({ ...row, text: shorten(text, EXCERPT) })
173
+ }
174
+ return out
175
+ }
176
+
177
+ /**
178
+ * A glance for a group that declares none: each field that holds something,
179
+ * by type. A field inside a block is named on its own, and by its block as
180
+ * well only where two rows would otherwise read the same.
181
+ */
182
+ export function defaultGlance(fields: Field[], values: Record<string, unknown>, options: GlanceOptions = {}): GlanceRow[] {
183
+ const found = rowsOf(fields, values, [], [], options)
184
+ return found.map(({ parents, ...row }) => {
185
+ const shared = found.filter((other) => other.label === row.label).length > 1
186
+ return shared && parents.length ? { ...row, label: [...parents, row.label].join(": ") } : row
187
+ })
188
+ }
189
+
190
+ /** What may sit inside a group's title, which is a button: words, and names. */
191
+ const IN_A_LINE = new Set(["referencesummary"])
192
+
193
+ /** One line for a group that declares no `peek`: the first few things it holds. */
194
+ export function defaultPeek(fields: Field[], values: Record<string, unknown>, options: GlanceOptions = {}): GlanceRow[] {
195
+ return defaultGlance(fields, values, options)
196
+ .filter((row) => row.text !== undefined || IN_A_LINE.has(row.component ?? ""))
197
+ .slice(0, LINE_PARTS)
198
+ .map((row) => (row.text ? { ...row, text: shorten(row.text, LINE_PART) } : row))
199
+ }
200
+
201
+ /** What one person chose for one collection: how closed groups rest, and each group they set themselves. */
202
+ export interface GroupMemory {
203
+ rest?: Rest
204
+ modes: Record<string, GroupMode>
205
+ }
206
+
207
+ /** Who the memory is kept for, while it is kept in the browser: whoever uses this one. */
208
+ export const THIS_BROWSER = "me"
209
+
210
+ export const memoryKey = (person: string, collection: string) => `tela:groups:${person}:${collection}`
211
+
212
+ interface Storage {
213
+ getItem(key: string): string | null
214
+ setItem(key: string, value: string): void
215
+ }
216
+
217
+ const MODES = ["minimal", "summary", "full"]
218
+
219
+ export function readMemory(storage: Storage | undefined, key: string): GroupMemory {
220
+ try {
221
+ const held = JSON.parse(storage?.getItem(key) ?? "null")
222
+ if (!isRecord(held)) return { modes: {} }
223
+ const modes = isRecord(held.modes) ? held.modes : {}
224
+ return {
225
+ ...(held.rest === "minimal" || held.rest === "summary" ? { rest: held.rest } : {}),
226
+ modes: Object.fromEntries(Object.entries(modes).filter(([, mode]) => MODES.includes(mode as string))) as Record<string, GroupMode>,
227
+ }
228
+ } catch {
229
+ return { modes: {} }
230
+ }
231
+ }
232
+
233
+ export function writeMemory(storage: Storage | undefined, key: string, memory: GroupMemory): void {
234
+ try {
235
+ storage?.setItem(key, JSON.stringify(memory))
236
+ } catch {
237
+ // A full or forbidden store only means the choice is not remembered.
238
+ }
239
+ }
240
+
241
+ /**
242
+ * How a group starts. What the person last chose for it wins; otherwise an
243
+ * entry being written for the first time is open, so nothing has to be found,
244
+ * and one opened later rests, so the page reads as an overview.
245
+ */
246
+ export function startingMode(given: { remembered?: GroupMode; collapsed?: boolean; existing: boolean; rest: Rest }): GroupMode {
247
+ if (given.remembered) return given.remembered === "full" ? "full" : given.rest
248
+ return given.collapsed || given.existing ? given.rest : "full"
249
+ }
package/src/main.ts CHANGED
@@ -12,7 +12,10 @@ async function start() {
12
12
  // permissions, and applies whatever slice of the library the deployment was
13
13
  // granted.
14
14
  const library = telaLibrary()
15
- configureLibrary(library, { canWrite: true })
15
+ // What the library has to say in passing ("Copied #2f3040") is said by
16
+ // Tela's own toasts, so there is one voice on the page.
17
+ const notify = (message: string, notice?: { duration?: number; action?: { label: string; run: () => void } }) => ui.toast(message, notice)
18
+ configureLibrary(library, { canWrite: true, notify })
16
19
 
17
20
  // Then as this account and this deployment: whether it may change pictures,
18
21
  // and the one group it writes to and words them for. Asked now and waited
@@ -25,6 +28,7 @@ async function start() {
25
28
  if (!about?.managed) return
26
29
  configureLibrary(library, {
27
30
  canWrite: Boolean(about.canWrite),
31
+ notify,
28
32
  ...(about.writeGroup ? { writeGroup: about.writeGroup, view: about.writeGroup } : {}),
29
33
  ...(about.writeGroups ? { writeGroups: about.writeGroups } : {}),
30
34
  })
@@ -152,6 +152,7 @@ export const telaLibrary = (): LibraryPort => ({
152
152
  duplicateOf?: string[]
153
153
  similar?: Array<{ id: string; distance: number }>
154
154
  token?: string
155
+ ticket?: string
155
156
  error?: string
156
157
  } = {}
157
158
  try {
@@ -166,7 +167,7 @@ export const telaLibrary = (): LibraryPort => ({
166
167
  if (xhr.status === 409 && body.token) {
167
168
  return resolve({ duplicateOf: body.duplicateOf ?? [], similar: body.similar ?? [], token: body.token })
168
169
  }
169
- if (xhr.status === 202) return resolve({ pending: true })
170
+ if (xhr.status === 202) return resolve({ pending: true, ...(body.ticket ? { ticket: body.ticket } : {}) })
170
171
  if (xhr.status >= 200 && xhr.status < 300 && body.id) return resolve({ id: body.id })
171
172
  reject(new Error(body.error ?? `${xhr.status} ${xhr.statusText}`))
172
173
  }
@@ -174,4 +175,6 @@ export const telaLibrary = (): LibraryPort => ({
174
175
  }),
175
176
 
176
177
  confirmUpload: (token) => send(`/api/media/uploads/${encodeURIComponent(token)}`, "POST"),
178
+
179
+ pendingUpload: (ticket) => ask(`/api/media/uploads/${encodeURIComponent(ticket)}`),
177
180
  })
@@ -482,6 +482,10 @@ async function rewriteFor(pathname: string): Promise<string | null> {
482
482
 
483
483
  const server = Bun.serve({
484
484
  port,
485
+ // Bun's own ceiling is 128 MB, under what the media library says it takes.
486
+ // The routes that take files check their own limits; this only has to be
487
+ // above the largest of them.
488
+ maxRequestBodySize: 300 * 1024 * 1024,
485
489
 
486
490
  routes: {
487
491
  "/api/health": async () => {
@@ -1819,6 +1823,7 @@ const server = Bun.serve({
1819
1823
  can,
1820
1824
  json,
1821
1825
  changed: async (key, user) => picturesChanged(await mediaIdsFor(key), user),
1826
+ holdOpen: (req) => server.timeout(req, 0),
1822
1827
  fallback: {
1823
1828
  list: plainList as never,
1824
1829
  describe: (async (req: { params: { key: string } } & Request, user: SessionUser) => {
@@ -188,10 +188,39 @@ interface Waiting {
188
188
  until: number
189
189
  }
190
190
  const waiting = new Map<string, Waiting>()
191
+
192
+ /**
193
+ * Uploads the library was sent and did not answer for in time. It usually
194
+ * finishes on its own, so each is kept as a ticket the browser can ask about:
195
+ * "has this one landed yet?" The library gives an upload no name until it is
196
+ * done, so it is recognised by what was sent: its file name, in its group,
197
+ * made since the upload began.
198
+ */
199
+ interface Unconfirmed {
200
+ user: string
201
+ filename: string
202
+ group: string
203
+ since: number
204
+ until: number
205
+ }
206
+ const unconfirmed = new Map<string, Unconfirmed>()
207
+ /** Pictures a ticket has already been matched to, so two files of one name
208
+ * sent together are not both told they are the same picture. */
209
+ const confirmed = new Set<string>()
210
+
191
211
  const forgetStale = () => {
192
212
  for (const [token, one] of waiting) if (one.until < Date.now()) waiting.delete(token)
213
+ for (const [ticket, one] of unconfirmed) if (one.until < Date.now()) unconfirmed.delete(ticket)
193
214
  }
194
215
 
216
+ /** Clocks differ a little between here and the library. */
217
+ const CLOCK_SLACK_MS = 30 * 1000
218
+
219
+ /** Whether a failure means "no answer yet" rather than "no". A gateway cuts
220
+ * a long request off with one of these while the library carries on. */
221
+ const noAnswerYet = (error: unknown): boolean =>
222
+ error instanceof PseudoluxHttpError ? [408, 503, 504].includes(error.status) : true
223
+
195
224
  export function libraryRoutes(deps: {
196
225
  library: () => LibraryAccess | undefined
197
226
  authed: <T extends { params?: unknown }>(
@@ -201,6 +230,9 @@ export function libraryRoutes(deps: {
201
230
  json: Json
202
231
  /** After a picture's words, or whether it exists, changed: so what publishes it can be brought up to date. */
203
232
  changed?: (key: string, user: SessionUser) => Promise<void>
233
+ /** Keep this request's connection open however long its answer takes: an
234
+ * upload goes quiet while the library works on it. */
235
+ holdOpen?: (req: Request) => void
204
236
  /** Tela's own browse and describe, for a store that is not a library. */
205
237
  fallback: {
206
238
  list: (req: Req, user: SessionUser) => Promise<Response>
@@ -271,7 +303,8 @@ export function libraryRoutes(deps: {
271
303
  library: LibraryAccess,
272
304
  one: Pick<Waiting, "user" | "filename" | "contentType" | "downloadUrl" | "group">,
273
305
  rejectDuplicate: boolean,
274
- ): Promise<{ id: string } | { pending: true }> => {
306
+ ): Promise<{ id: string } | { pending: true; ticket: string }> => {
307
+ const since = Date.now() - CLOCK_SLACK_MS
275
308
  try {
276
309
  const made = await library.client.ingest({
277
310
  downloadUrl: one.downloadUrl,
@@ -300,11 +333,34 @@ export function libraryRoutes(deps: {
300
333
  if (error instanceof PseudoluxHttpError && error.status < 500 && error.status !== 408) {
301
334
  throw new Refusal(error.status, error.message)
302
335
  }
303
- // A gateway timeout is not a failure: the library finishes on its own.
304
- return { pending: true }
336
+ if (!noAnswerYet(error)) {
337
+ // The library tried and could not. Said as a failure: "still
338
+ // processing" would leave somebody waiting for a picture that is
339
+ // never coming.
340
+ throw new Refusal(
341
+ 502,
342
+ "The library could not make a picture of that file. If it opens in other programs, try saving it again as a JPEG or PNG.",
343
+ )
344
+ }
345
+ // No answer in time is not a failure: the library usually finishes on
346
+ // its own. The ticket lets the browser ask until it has, or give up.
347
+ forgetStale()
348
+ const ticket = crypto.randomUUID()
349
+ unconfirmed.set(ticket, { user: one.user, filename: one.filename, group: one.group, since, until: Date.now() + 30 * 60 * 1000 })
350
+ return { pending: true, ticket }
305
351
  }
306
352
  }
307
353
 
354
+ /** Whether an unconfirmed upload has landed: the newest picture in its
355
+ * group with its file name, made since it was sent. */
356
+ const landed = async (library: LibraryAccess, one: Unconfirmed): Promise<string | undefined> => {
357
+ const page = await upstream(library.client.listManaged({ anyTags: library.scope, tags: [one.group], limit: 100 }))
358
+ const found = page.assets.find(
359
+ (asset) => asset.filename === one.filename && Date.parse(asset.createdAt) >= one.since && !confirmed.has(asset.pid),
360
+ )
361
+ return found?.pid
362
+ }
363
+
308
364
  const body = async (req: Request): Promise<Record<string, unknown>> => {
309
365
  const read = await req.json().catch(() => null)
310
366
  if (!read || typeof read !== "object" || Array.isArray(read)) throw new Refusal(400, "Send a JSON body.")
@@ -465,6 +521,10 @@ export function libraryRoutes(deps: {
465
521
  const bytes = await req.arrayBuffer()
466
522
  if (bytes.byteLength === 0) throw new Refusal(400, "The file was empty.")
467
523
  if (bytes.byteLength > UPLOAD_LIMIT) throw new Refusal(413, "That file is larger than the library takes in one go.")
524
+ // From here the browser hears nothing until the library has stored
525
+ // and read the picture, which for a large one is longer than an idle
526
+ // connection is otherwise kept.
527
+ deps.holdOpen?.(req)
468
528
 
469
529
  const staging = await upstream(library.client.requestUpload({ filename, contentType }))
470
530
  const sent = await fetch(staging.uploadUrl, { method: "PUT", headers: { "content-type": contentType }, body: bytes })
@@ -476,6 +536,18 @@ export function libraryRoutes(deps: {
476
536
  },
477
537
 
478
538
  "/api/media/uploads/:token": {
539
+ /** Has an upload that got no answer landed yet? */
540
+ GET: route(async (req, user, library) => {
541
+ forgetStale()
542
+ const ticket = req.params.token ?? ""
543
+ const one = unconfirmed.get(ticket)
544
+ if (!one || one.user !== user.email) throw new Refusal(404, "That upload is no longer being followed.")
545
+ const id = await landed(library, one)
546
+ if (!id) return json({ pending: true }, 202)
547
+ unconfirmed.delete(ticket)
548
+ confirmed.add(id)
549
+ return json({ id })
550
+ }),
479
551
  POST: route(async (req, user, library) => {
480
552
  if (!library.tag || !can(user, "create", "media")) {
481
553
  throw new Refusal(403, "You can look at the library but not add to it.")
@@ -484,6 +556,7 @@ export function libraryRoutes(deps: {
484
556
  const one = waiting.get(req.params.token ?? "")
485
557
  if (!one || one.user !== user.email) throw new Refusal(404, "That upload is no longer waiting.")
486
558
  waiting.delete(req.params.token!)
559
+ deps.holdOpen?.(req)
487
560
  const outcome = await ingestStaged(library, one, false)
488
561
  return json(outcome, "pending" in outcome ? 202 : 200)
489
562
  }),
@@ -147,7 +147,6 @@
147
147
  library sets its own defaults, and more specific than that, so these win. */
148
148
  html .px {
149
149
  --px-font: var(--font-ui);
150
- --px-tile: 168px;
151
150
  --px-r-s: var(--r-s);
152
151
  --px-r-m: var(--r-m);
153
152
  --px-r-l: var(--r-l);