@estiva-app/conversation 0.32.0 → 0.34.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.
- package/CHANGELOG.md +49 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/membership.d.ts +5 -0
- package/dist/membership.d.ts.map +1 -1
- package/dist/membership.js +7 -0
- package/dist/membership.js.map +1 -1
- package/dist/places.d.ts +100 -0
- package/dist/places.d.ts.map +1 -1
- package/dist/places.js +148 -1
- package/dist/places.js.map +1 -1
- package/dist/refusals.d.ts +59 -0
- package/dist/refusals.d.ts.map +1 -0
- package/dist/refusals.js +168 -0
- package/dist/refusals.js.map +1 -0
- package/package.json +1 -1
- package/src/index.ts +23 -1
- package/src/membership.ts +7 -1
- package/src/places.ts +192 -1
- package/src/refusals.ts +176 -0
package/src/places.ts
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
*/
|
|
27
27
|
import { fileIdOf, KIND, type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
|
|
28
28
|
import { FILE_ADDRESS, FOLDER_ID, KIND_APP_DATA, KIND_CHANGE } from './kinds.js'
|
|
29
|
-
import { APPDATA_TAG, FOLLOW_FIELD_PREFIX, memberOfField } from './membership.js'
|
|
29
|
+
import { APPDATA_TAG, FOLLOW_FIELD_PREFIX, buildMembershipChange, memberOfField } from './membership.js'
|
|
30
30
|
import { byOrder } from './order.js'
|
|
31
31
|
import { REPLY_FLOOR_CONTEXT, belowReplyFloor, effectiveReadAt, streamMarkerOf, threadContext } from './readState.js'
|
|
32
32
|
import { peopleNamedInBody } from './strength.js'
|
|
@@ -106,6 +106,8 @@ export interface Following {
|
|
|
106
106
|
allSince?: number
|
|
107
107
|
/** Every way in that holds now. */
|
|
108
108
|
ways: WayIn[]
|
|
109
|
+
/** Who put them in, when the way `added` holds and somebody else signed the Add; undefined for their own join. */
|
|
110
|
+
addedBy?: string
|
|
109
111
|
}
|
|
110
112
|
|
|
111
113
|
type Act = { event: Event; act: 'creation' | 'level' | 'clear' | 'join' | 'leave'; level?: Level }
|
|
@@ -294,6 +296,7 @@ export function followingOf(place: Place, person: string, facts: PlaceFacts): Fo
|
|
|
294
296
|
if (joined) {
|
|
295
297
|
out.ways.push('added')
|
|
296
298
|
starts.push(joined.event.created_at)
|
|
299
|
+
if (joined.event.pubkey !== person) out.addedBy = joined.event.pubkey
|
|
297
300
|
}
|
|
298
301
|
// 3. Made it: the first record orders before everything, so any leave ends it.
|
|
299
302
|
const made = after.find((a) => a.act === 'creation')
|
|
@@ -322,6 +325,194 @@ export function followingOf(place: Place, person: string, facts: PlaceFacts): Fo
|
|
|
322
325
|
return { ...out, in: true, level: chosen?.level ?? 'important', since: Math.min(...starts), ...(chosen?.allSince !== undefined ? { allSince: chosen.allSince } : {}) }
|
|
323
326
|
}
|
|
324
327
|
|
|
328
|
+
// ── Who a place lists ───────────────────────────────────────────────────────
|
|
329
|
+
|
|
330
|
+
/** One person a place lists, and how they are in it. */
|
|
331
|
+
export interface Listed {
|
|
332
|
+
pubkey: string
|
|
333
|
+
level: Level
|
|
334
|
+
/** Every way in that holds, of the ones anyone can see: `team` only for the team's members. */
|
|
335
|
+
ways: WayIn[]
|
|
336
|
+
since?: number
|
|
337
|
+
/** Who added them, when somebody else did. */
|
|
338
|
+
addedBy?: string
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Who a place lists (§11.8 *Who a place lists*), worked out from public
|
|
343
|
+
* events alone so every reader gets the same list: everyone who chose a level
|
|
344
|
+
* (at that level), everyone added or joined (at their level, or Important),
|
|
345
|
+
* its author, and, on a team's chat and spaces, the team's members at the
|
|
346
|
+
* default. Someone in it only through a team they follow is not named until
|
|
347
|
+
* they choose a level, and a member's private opt-out is not seen: the list
|
|
348
|
+
* undercounts. All first, then Important, each by since.
|
|
349
|
+
*
|
|
350
|
+
* `viewer`, with their own private teams list, is listed as they are in it:
|
|
351
|
+
* gone once they turned the default off, there when a team they follow
|
|
352
|
+
* reaches them. Everyone else sees them by public events alone.
|
|
353
|
+
*
|
|
354
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-place-lists-who-chose-a-level-and-its-teams-members.md
|
|
355
|
+
*/
|
|
356
|
+
export function placeListing(place: Place, facts: Omit<PlaceFacts, 'teams'>, viewer?: { pubkey: string; teams?: TeamsList }): Listed[] {
|
|
357
|
+
const people = new Set<string>()
|
|
358
|
+
const versions = place.address.startsWith(`${KIND_TEAM}:`) ? [] : facts.events.filter((e) => addressOf(e) === place.address)
|
|
359
|
+
for (const v of versions) people.add(v.pubkey)
|
|
360
|
+
for (const change of facts.events) {
|
|
361
|
+
if (change.kind !== KIND_CHANGE || tag(change, 'a') !== place.address) continue
|
|
362
|
+
const field = tag(change, 'field')
|
|
363
|
+
const member = memberOfField(field)
|
|
364
|
+
if (member !== undefined) people.add(member)
|
|
365
|
+
else if (field?.startsWith(FOLLOW_FIELD_PREFIX)) people.add(field.slice(FOLLOW_FIELD_PREFIX.length))
|
|
366
|
+
}
|
|
367
|
+
if (placeKindOf(place, facts.listing) !== 'topic') for (const m of teamMembersOf(place.team, facts.roster ?? [])) people.add(m.pubkey)
|
|
368
|
+
if (viewer) people.add(viewer.pubkey)
|
|
369
|
+
|
|
370
|
+
const listed: Listed[] = []
|
|
371
|
+
for (const pubkey of people) {
|
|
372
|
+
if (!PUBKEY.test(pubkey)) continue
|
|
373
|
+
// Nobody else's private teams list is readable: their following through a team they follow never shows.
|
|
374
|
+
const own = pubkey === viewer?.pubkey ? viewer.teams : undefined
|
|
375
|
+
const f = followingOf(place, pubkey, { ...facts, teams: own })
|
|
376
|
+
if (!f.in || !f.level) continue
|
|
377
|
+
listed.push({ pubkey, level: f.level, ways: f.ways, ...(f.since !== undefined ? { since: f.since } : {}), ...(f.addedBy ? { addedBy: f.addedBy } : {}) })
|
|
378
|
+
}
|
|
379
|
+
const rank = (l: Listed) => (l.level === 'all' ? 0 : 1)
|
|
380
|
+
return listed.sort((a, b) => rank(a) - rank(b) || (a.since ?? 0) - (b.since ?? 0) || a.pubkey.localeCompare(b.pubkey))
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ── Add, and the switch: Not following, Important, All, back to the default ──
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* The `prev` an Add of `person` to the place names (§11.8): the person's own
|
|
387
|
+
* leave, when it is the field's current change. Undefined when they never
|
|
388
|
+
* left, or were put back in since — an Add needs none then.
|
|
389
|
+
*/
|
|
390
|
+
function currentLeaveOf(place: Place, person: string, events: readonly Event[]): Event | undefined {
|
|
391
|
+
const last = actsOf(place, person, events)
|
|
392
|
+
.filter((a) => a.act === 'join' || a.act === 'leave')
|
|
393
|
+
.at(-1)
|
|
394
|
+
return last?.act === 'leave' ? last.event : undefined
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** The ms a change sorts at (§6.3): its `ts` where it agrees with `created_at`, else `created_at`. */
|
|
398
|
+
function sortMsOf(event: Event): number {
|
|
399
|
+
const ts = Number(tag(event, 'ts'))
|
|
400
|
+
return Number.isSafeInteger(ts) && Math.floor(ts / 1000) === event.created_at ? ts : event.created_at * 1000
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Add a person to a topic, a space or a team's chat (§11.8): a `member:<P>` =
|
|
405
|
+
* `true` by anyone, naming the person's leave with `prev` when they left. The
|
|
406
|
+
* relay refuses a change that does not sort after its `prev` (§6.2), so an
|
|
407
|
+
* adder whose clock is behind the leave stamps the Add 1 ms after it. `folder` is the
|
|
408
|
+
* place's own team: its root's `h`, or the team itself for its chat. `events`
|
|
409
|
+
* are the place's events, as {@link placeFilters} read them.
|
|
410
|
+
*
|
|
411
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/anyone-may-add-a-person-to-a-file.md
|
|
412
|
+
*/
|
|
413
|
+
export function buildPlaceAdd(
|
|
414
|
+
pubkey: string,
|
|
415
|
+
createdAtMs: number,
|
|
416
|
+
args: { place: Place; folder: string; person: string; events: readonly Event[]; note?: string },
|
|
417
|
+
): UnsignedEvent {
|
|
418
|
+
const leave = currentLeaveOf(args.place, args.person, args.events)
|
|
419
|
+
const prev = leave?.id
|
|
420
|
+
const at = leave ? Math.max(createdAtMs, sortMsOf(leave) + 1) : createdAtMs
|
|
421
|
+
return buildMembershipChange(pubkey, at, {
|
|
422
|
+
file: args.place.address,
|
|
423
|
+
folder: args.folder,
|
|
424
|
+
person: args.person,
|
|
425
|
+
member: true,
|
|
426
|
+
...(args.note !== undefined ? { note: args.note } : {}),
|
|
427
|
+
...(prev !== undefined ? { prev } : {}),
|
|
428
|
+
})
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** What the switch on a place can be set to: a level, Not following, or back to the team's default. */
|
|
432
|
+
export type SwitchChoice = Level | 'not-following' | 'default'
|
|
433
|
+
|
|
434
|
+
/** What the switch shows for a person on a place. */
|
|
435
|
+
export interface SwitchState {
|
|
436
|
+
/** The level that lights for them, or Not following. A mute already kept shows as Not following (§11.8 *Muting*). */
|
|
437
|
+
shown: Level | 'not-following'
|
|
438
|
+
/** Whether a team's default would reach them here, were it not turned off. */
|
|
439
|
+
defaultReaches: boolean
|
|
440
|
+
/** A default reaches them and they chose a level, or turned it off. "Back to the default" is offered then. */
|
|
441
|
+
againstDefault: boolean
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** The id the private `off` list names a place by: a topic's or space's `d`, a team's chat by the team's uuid. */
|
|
445
|
+
export function placeOffId(place: Place): string {
|
|
446
|
+
return dOf(place.address)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** What the switch shows for `person` on the place, from what {@link placeFilters} read. */
|
|
450
|
+
export function switchStateOf(place: Place, person: string, facts: PlaceFacts, opts: { muted?: boolean } = {}): SwitchState {
|
|
451
|
+
const following = followingOf(place, person, facts)
|
|
452
|
+
const id = placeOffId(place)
|
|
453
|
+
const off = facts.teams?.off.includes(id) ?? false
|
|
454
|
+
const withDefault = off ? followingOf(place, person, { ...facts, teams: { ...facts.teams!, off: facts.teams!.off.filter((o) => o !== id) } }) : following
|
|
455
|
+
const defaultReaches = withDefault.ways.includes('team')
|
|
456
|
+
const shown = opts.muted || !following.in || !following.level ? 'not-following' : following.level
|
|
457
|
+
return { shown, defaultReaches, againstDefault: defaultReaches && (off || following.ways.includes('level')) }
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** The writes one choice on the switch takes. */
|
|
461
|
+
export interface SwitchWrites {
|
|
462
|
+
/** The public changes to sign as the person, in order: a level, or a leave. */
|
|
463
|
+
changes: UnsignedEvent[]
|
|
464
|
+
/** The private `off` list's change, when the choice turns a team's default off or back on ({@link withPlaceOff}). */
|
|
465
|
+
off?: { id: string; off: boolean }
|
|
466
|
+
/** Whether a mute already kept for the place is taken out (§11.8 *Muting*): choosing a level or the default does. */
|
|
467
|
+
clearsMute: boolean
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The writes for one choice on a place's switch (§11.8). A level is a
|
|
472
|
+
* `follow:<P>`. Not following is never public: a leave only when `P` chose
|
|
473
|
+
* a level, joined, was added or made the place, and an `off` entry when a
|
|
474
|
+
* team's default reaches `P` — a place `P` is in only by a default gets the
|
|
475
|
+
* entry alone. Back to the default is an empty `follow:<P>` when a level was
|
|
476
|
+
* chosen, and takes the place out of `off`. `folder` is the place's own team:
|
|
477
|
+
* its root's `h`, or the team itself for its chat.
|
|
478
|
+
*
|
|
479
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-persons-level-on-a-place-is-theirs-alone.md
|
|
480
|
+
*/
|
|
481
|
+
export function switchWrites(
|
|
482
|
+
pubkey: string,
|
|
483
|
+
createdAtMs: number,
|
|
484
|
+
args: { place: Place; folder: string; choice: SwitchChoice; following: Following; teams?: TeamsList },
|
|
485
|
+
): SwitchWrites {
|
|
486
|
+
const { place, folder, choice, following } = args
|
|
487
|
+
const id = placeOffId(place)
|
|
488
|
+
const isOff = args.teams?.off.includes(id) ?? false
|
|
489
|
+
if (choice === 'all' || choice === 'important') {
|
|
490
|
+
return { changes: [buildLevelChange(pubkey, createdAtMs, { place: place.address, folder, level: choice })], clearsMute: true }
|
|
491
|
+
}
|
|
492
|
+
if (choice === 'default') {
|
|
493
|
+
const changes = following.ways.includes('level') ? [buildLevelChange(pubkey, createdAtMs, { place: place.address, folder, level: '' })] : []
|
|
494
|
+
return { changes, ...(isOff ? { off: { id, off: false } } : {}), clearsMute: true }
|
|
495
|
+
}
|
|
496
|
+
const byDefault = following.ways.includes('team')
|
|
497
|
+
const joined = following.ways.some((w) => w === 'added' || w === 'author')
|
|
498
|
+
// Where a default reaches P and only a chosen level holds besides, clearing the level reads as
|
|
499
|
+
// "back to the default" to everyone else: nobody sees that P switched the place off.
|
|
500
|
+
const changes = joined || (following.ways.includes('level') && !byDefault)
|
|
501
|
+
? [buildMembershipChange(pubkey, createdAtMs, { file: place.address, folder, person: pubkey, member: false })]
|
|
502
|
+
: following.ways.includes('level')
|
|
503
|
+
? [buildLevelChange(pubkey, createdAtMs, { place: place.address, folder, level: '' })]
|
|
504
|
+
: []
|
|
505
|
+
return { changes, ...(byDefault ? { off: { id, off: true } } : {}), clearsMute: false }
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** The teams list with a place's default turned off, or back on: what to serialize, encrypt and write whole. */
|
|
509
|
+
export function withPlaceOff(list: Pick<TeamsList, 'teams' | 'off'> | undefined, change: { id: string; off: boolean }): Pick<TeamsList, 'teams' | 'off'> {
|
|
510
|
+
const off = new Set(list?.off ?? [])
|
|
511
|
+
if (change.off) off.add(change.id)
|
|
512
|
+
else off.delete(change.id)
|
|
513
|
+
return { teams: { ...(list?.teams ?? {}) }, off: [...off].sort() }
|
|
514
|
+
}
|
|
515
|
+
|
|
325
516
|
/**
|
|
326
517
|
* The filters that read what {@link followingOf} needs for one place: its
|
|
327
518
|
* root and changes, the team's roster, the team's list and the commands
|
package/src/refusals.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* refusals, the one set of words every app says when a send, an edit, a
|
|
3
|
+
* reaction or a file is refused (ONE-4).
|
|
4
|
+
*
|
|
5
|
+
* A refusal comes from the relay (`invalid: …`, `restricted: …`, an HTTP body),
|
|
6
|
+
* from Estiva ID, from the builders' own checks (`content is N bytes, max M`),
|
|
7
|
+
* from the network, or from the app itself. Whatever it was, a person reads
|
|
8
|
+
* one plain reason for its cause, the same in Peek, Ship and Leaf, and never
|
|
9
|
+
* the relay's words: those go to the console. The comment box and the cards
|
|
10
|
+
* put the reason in their sentence ("Not sent: <reason>. Your text is back in
|
|
11
|
+
* the box."), so a reason is lower case and ends with no full stop.
|
|
12
|
+
*
|
|
13
|
+
* An app with a cause of its own hands `{ cause }` rather than a sentence, so
|
|
14
|
+
* its words are these too. A file's own words (`uploadRefusal`) are a whole
|
|
15
|
+
* line on its card, and `tooLarge` stops a file over the relay's limit before
|
|
16
|
+
* it uploads (Miky, 4 Nov: the server's limits, checked in every app first).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Why something was refused, as far as a person needs to know. */
|
|
20
|
+
export type RefusalCause =
|
|
21
|
+
| 'too-long'
|
|
22
|
+
| 'gone'
|
|
23
|
+
| 'no-access'
|
|
24
|
+
| 'archived'
|
|
25
|
+
| 'busy'
|
|
26
|
+
| 'clock'
|
|
27
|
+
| 'signed-out'
|
|
28
|
+
| 'unknown'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Each cause's reason, put in a sentence by the box or the card. `gone` is
|
|
32
|
+
* what the relay says for an edit or a reaction on a message that was deleted
|
|
33
|
+
* or that you can no longer write beside: it does not say which.
|
|
34
|
+
*/
|
|
35
|
+
export const REFUSAL_REASONS: Readonly<Record<RefusalCause, string>> = {
|
|
36
|
+
'too-long': 'it is too long',
|
|
37
|
+
gone: 'this message was deleted, or you can no longer write here',
|
|
38
|
+
'no-access': 'you can no longer write here',
|
|
39
|
+
archived: 'this team is archived',
|
|
40
|
+
busy: 'too many at once, try again in a moment',
|
|
41
|
+
clock: 'your computer’s clock is wrong; set it and try again',
|
|
42
|
+
'signed-out': 'you are signed out; sign in again',
|
|
43
|
+
unknown: 'something went wrong, try again',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The text a refusal carries: a string, an `Error`'s message, or `{ error }` / `{ message }` / `{ reason }`, one JSON body deep. */
|
|
47
|
+
function textOf(reason: unknown): string {
|
|
48
|
+
if (reason == null) return ''
|
|
49
|
+
if (typeof reason === 'string') {
|
|
50
|
+
const json = reason.trim()
|
|
51
|
+
if (json.startsWith('{')) {
|
|
52
|
+
try {
|
|
53
|
+
return textOf(JSON.parse(json)) || reason
|
|
54
|
+
} catch {
|
|
55
|
+
return reason
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return reason
|
|
59
|
+
}
|
|
60
|
+
if (reason instanceof Error) return textOf(reason.message)
|
|
61
|
+
if (typeof reason === 'object') {
|
|
62
|
+
const r = reason as Record<string, unknown>
|
|
63
|
+
for (const key of ['error', 'message', 'reason']) {
|
|
64
|
+
const value = r[key]
|
|
65
|
+
if (typeof value === 'string') return textOf(value)
|
|
66
|
+
if (value && typeof value === 'object') return textOf(value)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return String(reason)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const CAUSES = new Set<string>(Object.keys(REFUSAL_REASONS))
|
|
73
|
+
|
|
74
|
+
/*
|
|
75
|
+
In order: the first that matches is the cause. Scope and identity before
|
|
76
|
+
`restricted:`, which also prefixes "insufficient scope". Each reason above
|
|
77
|
+
maps back to its own cause, so a reason passed on twice stays the same.
|
|
78
|
+
|
|
79
|
+
Words, because the relay sends no reason code yet (SPEC: "until then a
|
|
80
|
+
refusal is its sentence alone"). When the TEA issue "When the server says
|
|
81
|
+
no, every app knows why" adds them, `refusalCause` reads the code first and
|
|
82
|
+
these rules stay only for a refusal that carries none.
|
|
83
|
+
why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-refusal-starts-with-a-reason-code-every-app-reads.md
|
|
84
|
+
*/
|
|
85
|
+
const RULES: readonly [RegExp, RefusalCause][] = [
|
|
86
|
+
[/content (is \d+ bytes, max|exceeds maximum size)|too long/i, 'too-long'],
|
|
87
|
+
[/rate-limited|quota|too many|too busy|relay is busy|admission|\b429\b|concurrency/i, 'busy'],
|
|
88
|
+
[/timestamp too far|clock/i, 'clock'],
|
|
89
|
+
[/auth-required|insufficient scope|does not match authenticated|signed out|sign in|\b401\b|token_rejected|session_expired/i, 'signed-out'],
|
|
90
|
+
[/archived/i, 'archived'],
|
|
91
|
+
[/target (event )?not found|not (editable|deletable) by you|was deleted|no longer on this page/i, 'gone'],
|
|
92
|
+
[/^(restricted|blocked):|not a (channel |relay )?member|only members|no longer (post|write)|banned|timed out until|writes are fenced|\b403\b/i, 'no-access'],
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
/** What a refusal comes to; `{ cause }` is taken as it is. */
|
|
96
|
+
export function refusalCause(reason: unknown): RefusalCause {
|
|
97
|
+
if (reason && typeof reason === 'object' && 'cause' in reason) {
|
|
98
|
+
const cause = (reason as { cause: unknown }).cause
|
|
99
|
+
if (typeof cause === 'string' && CAUSES.has(cause)) return cause as RefusalCause
|
|
100
|
+
}
|
|
101
|
+
const text = textOf(reason)
|
|
102
|
+
for (const [rule, cause] of RULES) if (rule.test(text)) return cause
|
|
103
|
+
return 'unknown'
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The plain reason for any refusal, to say after "Not sent:", "Not saved:" or "Not reacted:". */
|
|
107
|
+
export function refusalReason(reason: unknown): string {
|
|
108
|
+
return REFUSAL_REASONS[refusalCause(reason)]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Why a file did not upload, as far as a person needs to know. */
|
|
112
|
+
export type UploadCause = 'too-large' | 'type' | 'unreadable' | 'busy' | 'signed-out' | 'no-access' | 'unknown'
|
|
113
|
+
|
|
114
|
+
const MB = 1024 * 1024
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The relay's size limits (buzz `BUZZ_MAX_*_BYTES`, read back on production on
|
|
118
|
+
* 4 Nov): a GIF 10 MB, another picture 50 MB, anything else 100 MB, since
|
|
119
|
+
* Cloudflare refuses a larger body before the relay sees it (a video's 500 MB
|
|
120
|
+
* is never reached). Cloudflare's 100 MB is taken as decimal, the lower
|
|
121
|
+
* reading, so nothing that passes here is turned away there.
|
|
122
|
+
*/
|
|
123
|
+
export const UPLOAD_LIMITS = { gif: 10 * MB, image: 50 * MB, other: 100_000_000 } as const
|
|
124
|
+
|
|
125
|
+
/** The most a file of this type may be, in bytes. */
|
|
126
|
+
export function uploadLimit(type: string | undefined): number {
|
|
127
|
+
const t = (type ?? '').toLowerCase()
|
|
128
|
+
if (t === 'image/gif') return UPLOAD_LIMITS.gif
|
|
129
|
+
if (t.startsWith('image/')) return UPLOAD_LIMITS.image
|
|
130
|
+
return UPLOAD_LIMITS.other
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Whole MB either way: 10,485,760 bytes and 100,000,000 bytes both say what the limit is called.
|
|
134
|
+
const tooLargeLine = (bytes: number) => `Too large: the most is ${bytes % MB === 0 ? bytes / MB : Math.round(bytes / 1e6)} MB`
|
|
135
|
+
|
|
136
|
+
/** The line for a file over its limit, said before it uploads; undefined when it fits. */
|
|
137
|
+
export function tooLarge(file: { size: number; type?: string }): string | undefined {
|
|
138
|
+
const limit = uploadLimit(file.type)
|
|
139
|
+
return file.size > limit ? tooLargeLine(limit) : undefined
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const UPLOAD_LINES: Readonly<Record<Exclude<UploadCause, 'too-large'>, string>> = {
|
|
143
|
+
type: 'This type of file can’t be added',
|
|
144
|
+
unreadable: 'This file could not be read',
|
|
145
|
+
busy: 'Too many at once, try again in a moment',
|
|
146
|
+
'signed-out': 'Sign in again',
|
|
147
|
+
'no-access': 'You can no longer add files here',
|
|
148
|
+
unknown: 'Could not upload, try again',
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The line on a file's card when its upload was refused: from protocol's
|
|
153
|
+
* `upload failed: <status> <body>`, any other error, or `{ cause }`. A 413
|
|
154
|
+
* names the limit the relay gave, or the type's own when Cloudflare answered.
|
|
155
|
+
*/
|
|
156
|
+
export function uploadRefusal(reason: unknown, file?: { type?: string }): string {
|
|
157
|
+
if (reason && typeof reason === 'object' && 'cause' in reason) {
|
|
158
|
+
const cause = (reason as { cause: unknown }).cause
|
|
159
|
+
if (cause === 'too-large') return tooLargeLine(uploadLimit(file?.type))
|
|
160
|
+
if (typeof cause === 'string' && Object.hasOwn(UPLOAD_LINES, cause)) return UPLOAD_LINES[cause as keyof typeof UPLOAD_LINES]
|
|
161
|
+
}
|
|
162
|
+
const raw = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : textOf(reason)
|
|
163
|
+
const status = Number(/upload failed:\s*(\d{3})/i.exec(raw)?.[1] ?? 0)
|
|
164
|
+
const said = textOf(raw.replace(/^.*?upload failed:\s*\d{3}\s*/is, ''))
|
|
165
|
+
if (status === 413 || /file too large/i.test(said)) {
|
|
166
|
+
const max = Number(/max (\d+)\)?/i.exec(said)?.[1] ?? 0)
|
|
167
|
+
if (/dimensions/i.test(said)) return UPLOAD_LINES.unreadable
|
|
168
|
+
return tooLargeLine(max || uploadLimit(file?.type))
|
|
169
|
+
}
|
|
170
|
+
if (status === 415 || /content type|unsupported container/i.test(said)) return UPLOAD_LINES.type
|
|
171
|
+
if (status === 422 || /metadata|invalid image|duration|resolution/i.test(said)) return UPLOAD_LINES.unreadable
|
|
172
|
+
if (status === 429 || /rate limit|concurrency/i.test(said)) return UPLOAD_LINES.busy
|
|
173
|
+
if (status === 401 || /authentication failed|signed out/i.test(said)) return UPLOAD_LINES['signed-out']
|
|
174
|
+
if (status === 403) return UPLOAD_LINES['no-access']
|
|
175
|
+
return UPLOAD_LINES.unknown
|
|
176
|
+
}
|