@estiva-app/interop 0.75.0 → 0.77.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 { MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING } from '@estiva-app/protocol'
17
+ import { FILE_KINDS, MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING, fileIdFormOf } from '@estiva-app/protocol'
18
18
  import {
19
19
  attachmentsInDocument,
20
20
  BLOCK_DOCUMENT_FORMAT,
@@ -22,7 +22,7 @@ import {
22
22
  imetaTag,
23
23
  parseBlockDocument,
24
24
  } from '@estiva-app/protocol'
25
- import { identifierOf, planPlaceFile, planUnlistFile, type FolderRef } from './folders.js'
25
+ import { identifierOf, listedEntriesOf, listsFile, planPlaceFile, planUnlistFile, type FolderRef } from './folders.js'
26
26
  /*
27
27
  SPEC §6.4's comment strength and §6.3's ordering are the conversation
28
28
  package's (CON-5): one copy of each rule, read here for a file's `comments`,
@@ -228,7 +228,7 @@ export const KIND_MESSAGE = 9
228
228
  const KIND_DELETION = 5
229
229
 
230
230
  /** The tags a comment's body earns for what it names: `ActionEventArgs.linkTags`. */
231
- const LINK_TAG_NAMES = new Set(['a', 'q', 'part'])
231
+ const LINK_TAG_NAMES = new Set(['a', 'o', 'q', 'part'])
232
232
 
233
233
  /**
234
234
  * Every kind an app's comments might be under — what it publishes **now**, plus
@@ -2392,27 +2392,43 @@ function inTargetFolder(change: SignedEvent, folders: ReadonlySet<string> | unde
2392
2392
  function foldChanges(changes: SignedEvent[], rule: RecordsRule, root: SignedEvent | undefined) {
2393
2393
  const fields: Record<string, { value: string; by: string; at: number; format: ContentFormat }> = {}
2394
2394
  const folders = targetFolders(root)
2395
+ const id = root && tagValue(root, 'd')
2395
2396
  for (const change of [...changes].filter((c) => inTargetFolder(c, folders)).sort(byOrder)) {
2396
- const field = tagValue(change, rule.fieldTag)
2397
- const value = tagValue(change, rule.valueTag)
2398
- if (!field || value === undefined) continue // a partial change sets nothing
2399
- // A summary is new, so it takes neither of §6.2's exceptions: a change the
2400
- // reader cannot check against the root's Folder is not read (SPEC §6.12).
2401
- if (field === SUMMARY_FIELD && !folders) continue
2402
- // The format travels with the *winning* change, not with the object. SPEC
2403
- // §13.4: "an app MUST read the tag from the event it took the value from,
2404
- // never from the object's root" — a description created as marker text and
2405
- // later edited into blocks is a root with no tag and a change with one.
2406
- fields[field] = {
2407
- value,
2408
- by: change.pubkey,
2409
- at: change.created_at,
2410
- format: contentFormatOf(change),
2397
+ // A change whose `O` is not its `a`'s file is about neither (SPEC §6.2).
2398
+ const O = tagValue(change, 'O')
2399
+ if (O !== undefined && id !== undefined && O !== id) continue
2400
+ for (const { field, value } of settingsOf(change, rule)) {
2401
+ // A summary is new, so it takes neither of §6.2's exceptions: a change the
2402
+ // reader cannot check against the root's Folder is not read (SPEC §6.12).
2403
+ if (field === SUMMARY_FIELD && !folders) continue
2404
+ // The format travels with the *winning* change, not with the object. SPEC
2405
+ // §13.4: "an app MUST read the tag from the event it took the value from,
2406
+ // never from the object's root" — a description created as marker text and
2407
+ // later edited into blocks is a root with no tag and a change with one.
2408
+ fields[field] = {
2409
+ value,
2410
+ by: change.pubkey,
2411
+ at: change.created_at,
2412
+ format: contentFormatOf(change),
2413
+ }
2411
2414
  }
2412
2415
  }
2413
2416
  return fields
2414
2417
  }
2415
2418
 
2419
+ /**
2420
+ * The fields one change sets under `rule`: one per `set` when it carries any
2421
+ * (SPEC §6.2, applied at the change's time as that many one-field changes),
2422
+ * else its field and value tags. A partial change sets nothing.
2423
+ */
2424
+ function settingsOf(change: SignedEvent, rule: RecordsRule): { field: string; value: string }[] {
2425
+ const sets = change.tags.filter((t) => t[0] === 'set' && t[1] && typeof t[2] === 'string')
2426
+ if (sets.length) return sets.map((t) => ({ field: t[1], value: t[2] }))
2427
+ const field = tagValue(change, rule.fieldTag)
2428
+ const value = tagValue(change, rule.valueTag)
2429
+ return field && value !== undefined ? [{ field, value }] : []
2430
+ }
2431
+
2416
2432
  /**
2417
2433
  * One object's fold out of a pooled answer: its app's change kind, naming it as
2418
2434
  * the **first** target tag, as `archiveOf` reads it. Empty when the app declares
@@ -2522,15 +2538,19 @@ function archiveOf(
2522
2538
  }
2523
2539
  const folders = targetFolders(root)
2524
2540
  let last: SignedEvent | undefined
2541
+ let archived: string | undefined
2525
2542
  for (const change of changes) {
2526
2543
  // The target is the first target tag, as every other fold reads it: a
2527
2544
  // change archiving one file must not archive another it also mentions.
2528
2545
  if (change.kind !== rule.changeKind || tagValue(change, rule.targetTag) !== address) continue
2529
2546
  if (!inTargetFolder(change, folders)) continue
2530
- if (tagValue(change, rule.fieldTag) !== ARCHIVED_FIELD || tagValue(change, rule.valueTag) === undefined) continue
2531
- if (!last || byOrder(last, change) < 0) last = change
2547
+ const O = tagValue(change, 'O')
2548
+ if (O !== undefined && O !== identifier) continue
2549
+ const set = settingsOf(change, rule).find((s) => s.field === ARCHIVED_FIELD)
2550
+ if (!set) continue
2551
+ if (!last || byOrder(last, change) < 0) [last, archived] = [change, set.value]
2532
2552
  }
2533
- if (!last || tagValue(last, rule.valueTag) !== 'true') return undefined
2553
+ if (!last || archived !== 'true') return undefined
2534
2554
  const note = last.content.trim()
2535
2555
  return {
2536
2556
  by: last.pubkey,
@@ -5913,6 +5933,13 @@ export interface ActionEventArgs {
5913
5933
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-file-is-its-fields-each-kept-in-order-by-the-relay.md
5914
5934
  */
5915
5935
  prev?: string
5936
+ /**
5937
+ * The types the relay keeps in order (`RelayFileReads.inOrder`): a comment
5938
+ * on a file of one names it by its id too, and a Folder command lists it by
5939
+ * its id (SPEC §6.4, "Apps move to the pair type by type"). Absent, by its
5940
+ * address alone, as every reader reads it.
5941
+ */
5942
+ inOrder?: readonly string[]
5916
5943
  pubkey: string
5917
5944
  createdAtMs: number
5918
5945
  }
@@ -5973,7 +6000,7 @@ export function buildActionEvents(
5973
6000
  return [
5974
6001
  first,
5975
6002
  ...folders.flatMap((listing) =>
5976
- planUnlistFile(args.pubkey, args.createdAtMs, { folder: listing.id, address: args.address, hasState: listing.hasState }),
6003
+ planUnlistFile(args.pubkey, args.createdAtMs, { folder: listing.id, address: args.address, hasState: listing.hasState, inOrder: args.inOrder }),
5977
6004
  ),
5978
6005
  ]
5979
6006
  }
@@ -5987,7 +6014,7 @@ export function buildActionEvents(
5987
6014
  return `"${declared.label}" lists what it creates, and a kind ${first.kind} has no address to list.`
5988
6015
  }
5989
6016
  const created = pointerToAddress({ kind: first.kind, pubkey: first.pubkey, identifier, relays: [] })
5990
- return [first, ...planPlaceFile(args.pubkey, args.createdAtMs, { folder: args.folder, address: created, hasState: args.folderHasState })]
6017
+ return [first, ...planPlaceFile(args.pubkey, args.createdAtMs, { folder: args.folder, address: created, hasState: args.folderHasState, inOrder: args.inOrder })]
5991
6018
  }
5992
6019
  // A change or a comment adds nothing to a Folder and removes nothing from it.
5993
6020
  return [first]
@@ -6116,6 +6143,8 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
6116
6143
  // The file the change is about, by its id, beside its address (§6.2): the
6117
6144
  // relay keeps each field in order by it.
6118
6145
  const fileId = records.targetTag === 'a' ? identifierOf(address) : undefined
6146
+ // A comment names its file by its id too once its type is kept in order (§6.4, "A comment in both forms").
6147
+ const byId = fileIdFormOf(args.inOrder ?? [], address)
6119
6148
  const tags: string[][] = declared.emits.field
6120
6149
  ? [
6121
6150
  [records.targetTag, address],
@@ -6134,6 +6163,7 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
6134
6163
  ['A', address],
6135
6164
  ['K', String(kind)],
6136
6165
  ['P', args.objectAuthor],
6166
+ ...(byId ? [['O', byId.id], ['K', byId.type]] : []),
6137
6167
  ...(replyTo
6138
6168
  ? [
6139
6169
  ['e', replyTo.id],
@@ -6149,6 +6179,7 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
6149
6179
  : [
6150
6180
  ['a', address],
6151
6181
  ['k', String(kind)],
6182
+ ...(byId ? [['o', byId.id], ['k', byId.type]] : []),
6152
6183
  ['p', args.objectAuthor],
6153
6184
  ]),
6154
6185
  ['h', folder],
@@ -6182,6 +6213,8 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
6182
6213
  for (const tag of args.linkTags ?? []) {
6183
6214
  if (!LINK_TAG_NAMES.has(tag[0]) || typeof tag[1] !== 'string') continue
6184
6215
  if ((tag[0] === 'a' || tag[0] === 'part') && tag[1] === address) continue
6216
+ // The comment's own file by its id is its `o`/`O` already, never a link.
6217
+ if ((tag[0] === 'o' || tag[0] === 'part') && fileId !== undefined && tag[1] === fileId) continue
6185
6218
  if (tag[0] === 'q' && tag[1] === replyTo?.id) continue
6186
6219
  if (!tags.some((t) => t[0] === tag[0] && t[1] === tag[1])) tags.push([...tag])
6187
6220
  }
@@ -6358,6 +6391,12 @@ export interface FolderSummary {
6358
6391
  * another app's files resolves them with {@link resolveFolderContents}.
6359
6392
  */
6360
6393
  addresses?: string[]
6394
+ /**
6395
+ * The files this folder's state lists by their id (an `o` entry, SPEC §3.3),
6396
+ * other than one it already lists by address — present only when there are
6397
+ * any. Ask whether a folder lists a file with `listsFile`, which reads both.
6398
+ */
6399
+ ids?: string[]
6361
6400
  /**
6362
6401
  * The Folder's own address as a file — its `kind:39000`, `39000:<relay>:<id>`.
6363
6402
  * What a state lists when it holds this Folder, and what an `archived`
@@ -6545,11 +6584,14 @@ async function readFolderRecords(query: QueryFn): Promise<{ events: SignedEvent[
6545
6584
  if (event.kind !== KIND_FOLDER_STATE && event.kind !== KIND_CHANNEL) continue
6546
6585
  const state = event.kind === KIND_FOLDER_STATE
6547
6586
  const existing = byId.get(id)
6548
- const addresses = state ? event.tags.filter((tag) => tag[0] === 'a' && tag[1]).map((tag) => tag[1]) : (existing?.addresses ?? [])
6587
+ const { addresses, ids } = state
6588
+ ? listedEntriesOf(event, new Map())
6589
+ : { addresses: existing?.addresses ?? [], ids: existing?.ids ?? [] }
6549
6590
  byId.set(id, {
6550
6591
  id,
6551
6592
  hasState: state || (existing?.hasState ?? false),
6552
6593
  ...(addresses.length ? { addresses } : {}),
6594
+ ...(ids.length ? { ids } : {}),
6553
6595
  })
6554
6596
  }
6555
6597
  // The title, privacy and admins are the channel's (§3.2), whichever order the events arrived.
@@ -6668,7 +6710,7 @@ export async function archiveImpact(
6668
6710
  for (const file of contents.files) {
6669
6711
  if (!file.address) continue
6670
6712
  const others = folders.filter(
6671
- (other) => !inTree.has(other.id) && !other.archived && other.addresses?.includes(file.address!),
6713
+ (other) => !inTree.has(other.id) && !other.archived && listsFile(other, file.address!),
6672
6714
  )
6673
6715
  if (others.length) {
6674
6716
  staysVisible.push({ address: file.address, kind: file.kind, in: others.map(({ id, name }) => ({ id, name })) })
@@ -6809,15 +6851,18 @@ async function placeRecordChannels(
6809
6851
  query: QueryFn,
6810
6852
  ): Promise<{ recordsOf: Map<string, string[]>; archives: SignedEvent[]; rootOf: Map<string, SignedEvent> }> {
6811
6853
  const containersOf = new Map<string, { pointer: AddressPointer; containers: string[] }>()
6812
- for (const event of events) {
6813
- if (event.kind !== KIND_FOLDER_STATE) continue
6854
+ const states = events.filter((event) => event.kind === KIND_FOLDER_STATE)
6855
+ // A file listed by its id alone (§3.3) costs one read for every such entry, before the roots.
6856
+ const ids = [...new Set(states.flatMap((state) => listedEntriesOf(state, new Map()).ids))]
6857
+ const addressOfId = ids.length ? await addressesOfIds(ids, query) : new Map<string, string>()
6858
+ for (const event of states) {
6814
6859
  const container = tagValue(event, 'd')
6815
6860
  if (!container) continue
6816
- for (const tag of event.tags) {
6817
- if (tag[0] !== 'a' || !tag[1]) continue
6861
+ const listed = listedEntriesOf(event, addressOfId)
6862
+ for (const address of [...listed.addresses, ...listed.ids.flatMap((id) => addressOfId.get(id) ?? [])]) {
6818
6863
  let pointer: AddressPointer
6819
6864
  try {
6820
- pointer = referenceToPointer(tag[1])
6865
+ pointer = referenceToPointer(address)
6821
6866
  } catch {
6822
6867
  continue
6823
6868
  }
@@ -7001,7 +7046,7 @@ export async function resolveFolderContents(
7001
7046
  ? // §5.2: one tag type lists every file, topics included, with no special
7002
7047
  // case. The order is the folder's, so it is preserved rather than sorted.
7003
7048
  {
7004
- addresses: [...new Set(state.tags.filter((t) => t[0] === 'a' && t[1]).map((t) => t[1]))],
7049
+ addresses: await listedAddressesOf(state, query),
7005
7050
  placed: new Map<string, SignedEvent[]>(),
7006
7051
  }
7007
7052
  : options.listedOnly
@@ -7251,6 +7296,56 @@ export async function resolveFolderContents(
7251
7296
  }
7252
7297
  }
7253
7298
 
7299
+ /**
7300
+ * A Folder state's files as addresses, in its order, each once (SPEC §3.3).
7301
+ *
7302
+ * An `o` entry names a file by its id alone, so it costs a read: one request
7303
+ * for every such entry, asking each id's addressable roots, and an id is
7304
+ * the file whose one kind and author answer it, as a link by id is resolved
7305
+ * (§7.7). An id answered by none, or by two files, is dropped like an `a`
7306
+ * nothing parses. A state with no `o` entry reads nothing.
7307
+ */
7308
+ async function listedAddressesOf(state: SignedEvent, query: QueryFn): Promise<string[]> {
7309
+ const all = listedEntriesOf(state, new Map())
7310
+ if (all.ids.length === 0) return all.order
7311
+ const addressOf = await addressesOfIds(all.ids, query)
7312
+ // Folded against the addresses found: an `a` with an `o`'s id and another kind or author is drawn beside it.
7313
+ const { order, ids } = listedEntriesOf(state, addressOf)
7314
+ const byId = new Set(ids)
7315
+ const listed = order.flatMap((entry) => (byId.has(entry) ? (addressOf.get(entry) ?? []) : [entry]))
7316
+ return [...new Set(listed)]
7317
+ }
7318
+
7319
+ /**
7320
+ * The address of each file named by its id alone: the one file kind and
7321
+ * author whose root holds that `d`, as a link by id is resolved (§7.7). Only
7322
+ * the file kinds are asked: the relay keeps a `d` unique across those alone,
7323
+ * so under any other kind anyone could claim a listed file's id. One request
7324
+ * for all of them; an id answered by none, or by two files, is absent.
7325
+ */
7326
+ async function addressesOfIds(ids: readonly string[], query: QueryFn): Promise<Map<string, string>> {
7327
+ const found = await queryChunked(
7328
+ Array.from({ length: Math.ceil(ids.length / ID_GROUP) }, (_, i) => {
7329
+ const group = ids.slice(i * ID_GROUP, (i + 1) * ID_GROUP)
7330
+ return { kinds: [...FILE_KINDS], '#d': group, limit: group.length * 2 }
7331
+ }),
7332
+ query,
7333
+ )
7334
+ const asked = new Set(ids)
7335
+ const owners = new Map<string, Set<string>>()
7336
+ for (const event of found) {
7337
+ const id = tagValue(event, 'd')
7338
+ if (id === undefined || !asked.has(id) || !FILE_KINDS.includes(event.kind)) continue
7339
+ owners.set(id, (owners.get(id) ?? new Set()).add(`${event.kind}:${event.pubkey.toLowerCase()}`))
7340
+ }
7341
+ const out = new Map<string, string>()
7342
+ for (const [id, one] of owners) if (one.size === 1) out.set(id, `${[...one][0]}:${id}`)
7343
+ return out
7344
+ }
7345
+
7346
+ /** Ids per filter when a Folder state's `o` entries are resolved. */
7347
+ const ID_GROUP = 50
7348
+
7254
7349
  /**
7255
7350
  * The contents of a folder that has no state event — containment by `h`.
7256
7351
  *
package/src/references.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  type ProjectionCache,
31
31
  type QueryFn,
32
32
  } from './projection.js'
33
+ import { fileIdFormOf } from '@estiva-app/protocol'
33
34
 
34
35
  const KIND_PROJECT = 30850
35
36
  const KIND_ISSUE = 30851
@@ -76,6 +77,28 @@ export interface FileCandidatesOptions {
76
77
  cache?: ProjectionCache
77
78
  /** When each address was last written or read, in seconds — newer first within a tier. */
78
79
  at?: ReadonlyMap<string, number>
80
+ /** The types the relay keeps in order (`RelayFileReads.inOrder`): a project of one is picked as its link. */
81
+ inOrder?: readonly string[]
82
+ /** The host Ship serves projects from: a picked project's link is `<it>/project/<d>`. Ship's own unless said, so every app picks the same link. */
83
+ projectOrigin?: string
84
+ }
85
+
86
+ /** Where Ship serves projects (§13.1, decided 2026-11-03): one link for a project, whichever app picked it. */
87
+ export const SHIP_ORIGIN = 'https://ship.estiva.app'
88
+
89
+ /**
90
+ * How a picked file goes in the text (§13.1): a project whose type the relay
91
+ * keeps in order as Ship's path link with its id and no title, which every
92
+ * app's host answers; anything else as `nostr:naddr…`.
93
+ *
94
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-file-is-named-by-its-id-in-a-capital-and-small-tag.md
95
+ */
96
+ export function pickedFileUri(
97
+ address: string,
98
+ { inOrder = [], projectOrigin = SHIP_ORIGIN }: Pick<FileCandidatesOptions, 'inOrder' | 'projectOrigin'> = {},
99
+ ): string {
100
+ const byId = fileIdFormOf(inOrder, address)
101
+ return byId?.type === 'osnova.project' ? `${projectOrigin.replace(/\/+$/, '')}/project/${byId.id}` : fileReference(address)
79
102
  }
80
103
 
81
104
  /**
@@ -93,7 +116,7 @@ export async function fileCandidates(
93
116
  objects: readonly (ForeignObject | null | undefined)[],
94
117
  tier: number,
95
118
  query: QueryFn,
96
- { cache, at }: FileCandidatesOptions = {},
119
+ { cache, at, inOrder, projectOrigin }: FileCandidatesOptions = {},
97
120
  ): Promise<ReferenceCandidate[]> {
98
121
  const files = objects.filter(offerable)
99
122
  const parents = new Map<string, ForeignObject>()
@@ -111,7 +134,7 @@ export async function fileCandidates(
111
134
  const summary = summaryOf(o)
112
135
  return {
113
136
  id: o.address,
114
- uri: fileReference(o.address),
137
+ uri: pickedFileUri(o.address, { inOrder, projectOrigin }),
115
138
  type: typeOf(o.kind)!,
116
139
  kind: o.kind,
117
140
  title: o.slots.title!.value,