@estiva-app/interop 0.108.1 → 0.110.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/src/projection.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import { decodeNevent, encodeNaddr, encodeNevent, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
16
  import { parseProfile, type Profile, type SignedEvent } from '@estiva-app/protocol'
17
- import { FILE_KINDS, MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING, fileIdFormOf } from '@estiva-app/protocol'
17
+ import { BASE_TYPE_OF_KIND, FILE_KINDS, MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING, changeTypeTags, fileIdFormOf } from '@estiva-app/protocol'
18
18
  import {
19
19
  attachmentsInDocument,
20
20
  BLOCK_DOCUMENT_FORMAT,
@@ -1612,8 +1612,9 @@ const BARE_FILE_MANIFEST: Manifest = {
1612
1612
  id: 'delete',
1613
1613
  label: 'Delete',
1614
1614
  description:
1615
- 'Ask the relay to delete this file. The relay decides — only its author, or the owner of ' +
1616
- 'an agent that wrote it, may — and its comments stay as separate events.',
1615
+ 'Delete this file. Where the relay keeps topics in order it is marked deleted, by anyone in its team, ' +
1616
+ 'stays on its lists and can be restored; elsewhere the relay is asked to delete it and decides — only ' +
1617
+ 'its author, or the owner of an agent that wrote it, may. Its comments stay as separate events.',
1617
1618
  effect: 'destructive',
1618
1619
  appliesTo: [String(KIND_BARE_FILE)],
1619
1620
  /*
@@ -3551,6 +3552,8 @@ function buildObject(args: {
3551
3552
 
3552
3553
  /** The field a file is deleted by (SPEC §6.5): `true` deletes it, the empty value restores it. */
3553
3554
  const DELETED_FIELD = 'deleted'
3555
+ /** A file's change (§6.2): what a Delete on a file kept in order is written as, whatever a listing names. */
3556
+ const KIND_FILE_CHANGE = 1851
3554
3557
 
3555
3558
  /**
3556
3559
  * An addressable file's actions, each with what its field holds now, however
@@ -6458,6 +6461,12 @@ export interface ActionEventArgs {
6458
6461
  kind: number
6459
6462
  /** Address of the object being acted on. */
6460
6463
  address: string
6464
+ /**
6465
+ * The type of a named-type file (`kind:30852`), the `k` of its first
6466
+ * record: a change to one says it in `K` (§6.2), and its address does not
6467
+ * carry it. Not needed for the four base kinds.
6468
+ */
6469
+ type?: string
6461
6470
  /** Author of the object — needed for NIP-22's `P`/`p` tags. */
6462
6471
  objectAuthor: string
6463
6472
  folder: string
@@ -6549,12 +6558,29 @@ export interface ActionEventArgs {
6549
6558
  */
6550
6559
  export function buildActionEvent(args: ActionEventArgs): UnsignedActionEvent | string {
6551
6560
  const declared = args.manifest.actions?.find((a) => a.id === args.actionId)
6561
+ if (declared && marksDeleted(declared, args)) return buildOneActionEvent(args)
6552
6562
  if (declared?.emits.listed === true && (declared.emits.kind === KIND_DELETION || isCreationAction(declared))) {
6553
6563
  return `"${declared.label}" is followed by a team command, so it is built with buildActionEvents.`
6554
6564
  }
6555
6565
  return buildOneActionEvent(args)
6556
6566
  }
6557
6567
 
6568
+ /**
6569
+ * Whether an older listing's Delete, declared as a `kind:5`, is written as
6570
+ * the file's `deleted` change instead (SPEC §7.3, §6.5): on a file whose type
6571
+ * the relay keeps in order (`args.inOrder`), which refuses a `kind:5` on it.
6572
+ * That change marks the file only — nothing is taken off a team's list — and
6573
+ * a restore is the same field set back to empty (`setDeleted`). A Delete
6574
+ * declared as the `deleted` field is already a change, built as one.
6575
+ *
6576
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-file-type-is-kept-in-order-and-a-delete-only-marks-the-file.md
6577
+ */
6578
+ function marksDeleted(declared: ManifestAction, args: Pick<ActionEventArgs, 'inOrder' | 'kind'>): boolean {
6579
+ // By the file's type, not the shape of its id: the relay refuses a `kind:5` on any file of a type it keeps in order.
6580
+ const type = BASE_TYPE_OF_KIND[args.kind]
6581
+ return declared.emits.kind === KIND_DELETION && type !== undefined && (args.inOrder ?? []).includes(type)
6582
+ }
6583
+
6558
6584
  /** An action that makes a new object rather than changing one — a form. */
6559
6585
  function isCreationAction(declared: ManifestAction): boolean {
6560
6586
  return declared.input?.type === 'object' && !!declared.input.properties
@@ -6587,7 +6613,8 @@ export function buildActionEvents(
6587
6613
  const first = buildOneActionEvent(args)
6588
6614
  if (typeof first === 'string') return first
6589
6615
  const declared = args.manifest.actions!.find((a) => a.id === args.actionId)!
6590
- if (declared.emits.listed !== true) return [first]
6616
+ // A delete that marks the file takes it off no team's list, so a restore brings back exactly what was there.
6617
+ if (declared.emits.listed !== true || marksDeleted(declared, args)) return [first]
6591
6618
 
6592
6619
  if (declared.emits.kind === KIND_DELETION) {
6593
6620
  if (!args.listedIn) return `"${declared.label}" unlists what it deletes, and needs the teams that list it.`
@@ -6627,6 +6654,21 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
6627
6654
  return `"${declared.label}" does not apply to a kind ${kind}.`
6628
6655
  }
6629
6656
 
6657
+ // A `kind:5` Delete on a file kept in order: built as its `deleted` change, `true`, whatever the confirm passed (§7.3).
6658
+ if (marksDeleted(declared, args)) {
6659
+ if (replyTo) return `"${declared.label}" is not a comment, so it cannot reply to one.`
6660
+ if (args.prev === undefined) return `"${declared.label}" follows the file's last delete or restore, or its first record: pass its prev.`
6661
+ if (!records) return 'That app does not say how its records are written.'
6662
+ // A file's change is a `kind:1851` (§6.2): never the kind a listing names, which could be a `kind:5` again or a profile.
6663
+ if (records.changeKind !== KIND_FILE_CHANGE) return `"${declared.label}" is written as a kind ${KIND_FILE_CHANGE} change, which that app does not say it writes.`
6664
+ const asChange: ManifestAction = { ...declared, emits: { kind: KIND_FILE_CHANGE, field: DELETED_FIELD }, input: { type: 'string' } }
6665
+ return buildOneActionEvent({
6666
+ ...args,
6667
+ value: 'true',
6668
+ manifest: { ...manifest, actions: (manifest.actions ?? []).map((a) => (a === declared ? asChange : a)) },
6669
+ })
6670
+ }
6671
+
6630
6672
  const isCreation = isCreationAction(declared)
6631
6673
 
6632
6674
  // A reply is a comment with a parent — what the scalar path below builds for
@@ -6741,10 +6783,21 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
6741
6783
  const fileId = records.targetTag === 'a' ? identifierOf(address) : undefined
6742
6784
  // A comment names its file by its id too once its type is kept in order (§6.4, "A comment in both forms").
6743
6785
  const byId = fileIdFormOf(args.inOrder ?? [], address)
6786
+ // The type of the file a change is about (§6.2): none for a team's own address.
6787
+ let typeTags: string[][] = []
6788
+ if (declared.emits.field && records.targetTag === 'a') {
6789
+ try {
6790
+ typeTags = changeTypeTags(address, args.type)
6791
+ } catch {
6792
+ // A named-type file (`30852`) whose type the caller did not pass: its first record's `k` (`ActionEventArgs.type`).
6793
+ return `"${declared.label}" was not saved: this file's type is not known.`
6794
+ }
6795
+ }
6744
6796
  const tags: string[][] = declared.emits.field
6745
6797
  ? [
6746
6798
  [records.targetTag, address],
6747
6799
  ...(fileId !== undefined ? [['O', fileId]] : []),
6800
+ ...typeTags,
6748
6801
  [records.fieldTag, declared.emits.field],
6749
6802
  [records.valueTag, value],
6750
6803
  ['h', folder],
@@ -19,7 +19,7 @@
19
19
  *
20
20
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/each-file-on-a-topic-keeps-its-own-place-and-look.md
21
21
  */
22
- import type { SignedEvent, UnsignedEvent } from '@estiva-app/protocol'
22
+ import { changeTypeTags, type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
23
23
  import { byOrder } from '@estiva-app/conversation'
24
24
  import { changedAt, combineChanges, conflictOf, fieldsSetBy } from './fields.js'
25
25
 
@@ -30,6 +30,7 @@ export type FileLook = 'row' | 'card'
30
30
 
31
31
  const ORDER = 'order:'
32
32
  const LOOK = 'look:'
33
+ const LISTS = 'lists:'
33
34
  /** The field a file's place on a topic is kept in: `order:<d>`. */
34
35
  export const orderField = (file: string): string => `${ORDER}${file}`
35
36
  /** The field a file's look on a topic is kept in: `look:<d>`. */
@@ -107,7 +108,16 @@ export interface FileArrangement {
107
108
  * on the relay, one a reader skips included (the relay chains them all),
108
109
  * or the topic's first record when the field never changed.
109
110
  */
110
- prev: { order: string; look: string }
111
+ prev: {
112
+ order: string
113
+ look: string
114
+ /**
115
+ * Its entry on the list, `lists:<d>`: what taking it off follows where
116
+ * the relay keeps topics in order (`planRemoveFromTopic`'s `prev`).
117
+ * Optional only so an arrangement built by hand still type-checks.
118
+ */
119
+ lists?: string
120
+ }
111
121
  /** The latest time (ms) among those, so a change is stamped after it. */
112
122
  prevAt: number
113
123
  }
@@ -166,12 +176,14 @@ export function arrangementHeads(
166
176
  const list = tagOf(event, 'a')
167
177
  if (!list) continue
168
178
  for (const { field } of fieldsSetBy(event)) {
169
- if (!isArrangeField(field)) continue
179
+ const isEntry = field.startsWith(LISTS)
180
+ if (!isArrangeField(field) && !isEntry) continue
170
181
  const heads = out.get(list) ?? { good: new Map(), any: new Map() }
171
182
  out.set(list, heads)
172
183
  const held = heads.any.get(field)
173
184
  if (!held || byOrder(held, event) < 0) heads.any.set(field, event)
174
- if (!readsAs(event, field, list, teamOfList(list))) continue
185
+ // An entry is folded by `listEntries`; here only its head is kept, as the next `prev`.
186
+ if (isEntry || !readsAs(event, field, list, teamOfList(list))) continue
175
187
  const good = heads.good.get(field)
176
188
  if (!good || byOrder(good, event) < 0) heads.good.set(field, event)
177
189
  }
@@ -193,10 +205,12 @@ export function arrangementOf(heads: Heads | undefined, file: string, listed: Si
193
205
  const look = looked ? valueIn(looked, lookField(file)) : undefined
194
206
  const orderHead = heads?.any.get(orderField(file))
195
207
  const lookHead = heads?.any.get(lookField(file))
208
+ // The relay chains every entry, one a reader skips included; `listed` is the newest one that counts.
209
+ const listsHead = heads?.any.get(`${LISTS}${file}`) ?? listed
196
210
  return {
197
211
  ...(isPlaceKey(key) ? { order: key } : {}),
198
212
  ...(look === 'row' || look === 'card' ? { look } : {}),
199
- prev: { order: orderHead?.id ?? root.id, look: lookHead?.id ?? root.id },
213
+ prev: { order: orderHead?.id ?? root.id, look: lookHead?.id ?? root.id, lists: listsHead.id },
200
214
  prevAt: Math.max(changedAt(root), orderHead ? changedAt(orderHead) : 0, lookHead ? changedAt(lookHead) : 0),
201
215
  }
202
216
  }
@@ -232,6 +246,7 @@ function fieldChange(pubkey: string, createdAtMs: number, topic: ArrangeHolder,
232
246
  tags: [
233
247
  ['a', topic.address],
234
248
  ['O', holder[3]],
249
+ ...changeTypeTags(topic.address),
235
250
  ['field', field],
236
251
  ['value', value],
237
252
  ['h', topic.folder],
@@ -322,15 +337,20 @@ export function planLookInTopic(
322
337
  * over the list read again, so a refusal plans the move again rather than
323
338
  * leaving the file back but last. The move is stamped after the listing, so
324
339
  * its place is not older than it.
340
+ *
341
+ * `listsPrev`, where the relay keeps topics in order, is the change the
342
+ * listing follows: the Remove it undoes (the id the relay accepted), not the
343
+ * file's `prev.lists`, which was read before it.
325
344
  */
326
345
  export function planPutBackInTopic(
327
346
  pubkey: string,
328
347
  createdAtMs: number,
329
- args: { topic: ArrangeHolder; file: ArrangedFile; after: string | null },
348
+ args: { topic: ArrangeHolder; file: ArrangedFile; after: string | null; listsPrev?: string },
330
349
  ): { relist: UnsignedEvent; move: (files: readonly ArrangedFile[], createdAtMs: number) => UnsignedEvent | null } {
331
350
  const listedAt = stamp(createdAtMs, [args.file])
332
351
  const holder = ADDRESS.exec(args.topic.address)
333
352
  if (!holder) throw new Error(`not a file address: ${JSON.stringify(args.topic.address)}`)
353
+ if (args.listsPrev !== undefined && !/^[0-9a-f]{64}$/.test(args.listsPrev)) throw new Error(`not an event id: ${JSON.stringify(args.listsPrev)}`)
334
354
  const relist: UnsignedEvent = {
335
355
  pubkey,
336
356
  created_at: Math.floor(listedAt / 1000),
@@ -338,15 +358,17 @@ export function planPutBackInTopic(
338
358
  tags: [
339
359
  ['a', args.topic.address],
340
360
  ['O', holder[3]],
361
+ ...changeTypeTags(args.topic.address),
341
362
  ['field', `lists:${args.file.file}`],
342
363
  ['value', 'true'],
343
364
  ['h', args.topic.folder],
344
365
  ['ts', String(listedAt)],
366
+ ...(args.listsPrev ? [['prev', args.listsPrev]] : []),
345
367
  ['o', args.file.file],
346
368
  ],
347
369
  content: '',
348
370
  }
349
- const move = (files: readonly ArrangedFile[], ms: number) => {
371
+ const move =(files: readonly ArrangedFile[], ms: number) => {
350
372
  // Back on the list it has no place yet; a list read before the listing landed does not hold it.
351
373
  const held = files.find((f) => f.file === args.file.file)
352
374
  const back: ArrangedFile = { ...(held ?? args.file), order: undefined, prevAt: Math.max((held ?? args.file).prevAt, listedAt) }
package/src/topics.ts CHANGED
@@ -5,8 +5,9 @@
5
5
  * A topic lists files from any Folder, one entry per file, by the file's id.
6
6
  * An entry is a `kind:1851` change on the topic: `a` and `O` name the topic,
7
7
  * `field` is `lists:<d>`, `value` is `true` or `false`, `h` is the topic's
8
- * Folder, then `ts`, then `["o", <d>]` naming the listed file. The newest
9
- * entry per topic and file counts (§6.3).
8
+ * Folder, then `ts`, then — where the relay keeps topics in order — `prev`,
9
+ * the change it follows (§6.13), then `["o", <d>]` naming the listed file.
10
+ * The newest entry per topic and file counts (§6.3).
10
11
  *
11
12
  * `O` is the file the change is about and `o` another file it points at
12
13
  * (why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-change-is-about-its-file-as-a-comment-is.md),
@@ -25,7 +26,7 @@
25
26
  * nobody to the file (§11.8).
26
27
  */
27
28
  import { encodeNpub, type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
28
- import { RELAY_PAGE_CEILING } from '@estiva-app/protocol'
29
+ import { RELAY_PAGE_CEILING, changeTypeTags } from '@estiva-app/protocol'
29
30
  import {
30
31
  byOrder,
31
32
  candidateFilesOf,
@@ -84,10 +85,27 @@ export interface ListHolder {
84
85
  folder: string
85
86
  }
86
87
 
88
+ /**
89
+ * What a list entry is handed. `prev` is the change it follows (§6.13): the
90
+ * newest `lists:<d>` change on the topic for that file, or the topic's first
91
+ * record when the file was never on it — a listed file's `prev.lists` from
92
+ * {@link topicList}, or `prevsAfterSwitch(query, topic, [listsField(file)])`.
93
+ * Pass it where the relay keeps topics in order (`fileFieldsOf(reads,
94
+ * TOPIC_TYPE, …)`), and send through `writeChange` so a stale one is followed
95
+ * again; leave it out elsewhere, and the entry is written as before. Two
96
+ * people adding different files never clash: each file is its own field.
97
+ */
98
+ export interface ListEntryArgs {
99
+ topic: ListHolder
100
+ file: string
101
+ note?: string
102
+ prev?: string
103
+ }
104
+
87
105
  function entry(
88
106
  pubkey: string,
89
107
  createdAtMs: number,
90
- args: { list: ListHolder; file: string; listed: boolean; note?: string },
108
+ args: { list: ListHolder; file: string; listed: boolean; note?: string; prev?: string },
91
109
  ): UnsignedEvent {
92
110
  const holder = ADDRESS.exec(args.list.address)
93
111
  if (!holder) throw new Error(`not a file address: ${JSON.stringify(args.list.address)}`)
@@ -96,6 +114,7 @@ function entry(
96
114
  // A reader ignores a file on its own list (§6.14): refuse it here rather than publish an entry that shows nothing.
97
115
  if (args.file === holder[3]) throw new Error('a file is not on its own list')
98
116
  if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw new Error(`not epoch milliseconds: ${createdAtMs}`)
117
+ if (args.prev !== undefined && !/^[0-9a-f]{64}$/.test(args.prev)) throw new Error(`not an event id: ${JSON.stringify(args.prev)}`)
99
118
  return {
100
119
  pubkey,
101
120
  created_at: Math.floor(createdAtMs / 1000),
@@ -103,10 +122,13 @@ function entry(
103
122
  tags: [
104
123
  ['a', args.list.address],
105
124
  ['O', holder[3]],
125
+ ...changeTypeTags(args.list.address),
106
126
  ['field', listsField(args.file)],
107
127
  ['value', args.listed ? 'true' : 'false'],
108
128
  ['h', args.list.folder],
109
129
  ['ts', String(createdAtMs)],
130
+ // Where `order:` and `look:` carry theirs (§6.14).
131
+ ...(args.prev ? [['prev', args.prev]] : []),
110
132
  ['o', args.file],
111
133
  ],
112
134
  // Empty unless the person wrote a note: each app says "added" and "removed" in its own words (§6.14).
@@ -118,21 +140,13 @@ function entry(
118
140
  * Put a file on a topic's list: `[kind:1851 lists:<d> = true]`, signed by
119
141
  * whoever adds it. `file` is the listed file's id (its `d`), from any Folder.
120
142
  */
121
- export function planListInTopic(
122
- pubkey: string,
123
- createdAtMs: number,
124
- args: { topic: ListHolder; file: string; note?: string },
125
- ): UnsignedEvent[] {
126
- return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: true, note: args.note })]
143
+ export function planListInTopic(pubkey: string, createdAtMs: number, args: ListEntryArgs): UnsignedEvent[] {
144
+ return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: true, note: args.note, prev: args.prev })]
127
145
  }
128
146
 
129
147
  /** Take a file off a topic's list: `[kind:1851 lists:<d> = false]`. {@link planListInTopic} in reverse. */
130
- export function planRemoveFromTopic(
131
- pubkey: string,
132
- createdAtMs: number,
133
- args: { topic: ListHolder; file: string; note?: string },
134
- ): UnsignedEvent[] {
135
- return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: false, note: args.note })]
148
+ export function planRemoveFromTopic(pubkey: string, createdAtMs: number, args: ListEntryArgs): UnsignedEvent[] {
149
+ return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: false, note: args.note, prev: args.prev })]
136
150
  }
137
151
 
138
152
  /** Which topics list a file: every entry naming its id in `o`. Fold with {@link listEntries}. */