@estiva-app/interop 0.36.0 → 0.37.1

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.
@@ -941,6 +941,18 @@ function webTemplate(event, entity) {
941
941
  * served by the plain noun.
942
942
  */
943
943
  export const KIND_BARE_FILE = 30840;
944
+ /**
945
+ * The field that archives a file, whatever its kind — FOL-46.
946
+ *
947
+ * **One concept for every file.** A Ship project, a Ship issue, a Peek topic, a
948
+ * bare file and a Folder are all archived the same way: a change setting
949
+ * `archived` to `'true'` on the file's address, and an empty value to restore
950
+ * it. That is the shape Ship has written for projects since SPEC §6.5, so
951
+ * nothing on the relay needs migrating. It is a change, never a deletion, so it
952
+ * is reversible, attributed, and open to anyone who may write in the Folder —
953
+ * not only the author.
954
+ */
955
+ export const ARCHIVED_FIELD = 'archived';
944
956
  /**
945
957
  * Where a `ResolvedManifest.address` would name the manifest event, this names
946
958
  * the section of the specification the manifest is built from. Not an address,
@@ -1048,6 +1060,22 @@ const BARE_FILE_MANIFEST = {
1048
1060
  emits: { kind: 1851, field: 'parent' },
1049
1061
  input: { type: 'string' },
1050
1062
  },
1063
+ /*
1064
+ `archive` is the one field every file may carry (FOL-46): `true` hides the
1065
+ file and everything under it from every list, an empty value brings it
1066
+ back. A change, so anyone in the team may, and the archiving change's
1067
+ `content` is the resolution summary a person gave (`ActionEventArgs.note`).
1068
+ */
1069
+ {
1070
+ id: 'archive',
1071
+ label: 'Archive',
1072
+ description: 'Take this file and everything under it out of every list once nobody needs to see it, or bring it ' +
1073
+ 'back: `true` archives, an empty value restores. Nothing is deleted, and a link still opens it.',
1074
+ effect: 'writes',
1075
+ appliesTo: [String(KIND_BARE_FILE)],
1076
+ emits: { kind: 1851, field: ARCHIVED_FIELD },
1077
+ input: { type: 'string', enum: ARCHIVED_FIELD },
1078
+ },
1051
1079
  {
1052
1080
  id: 'delete',
1053
1081
  label: 'Delete',
@@ -1058,6 +1086,13 @@ const BARE_FILE_MANIFEST = {
1058
1086
  emits: { kind: KIND_DELETION },
1059
1087
  },
1060
1088
  ],
1089
+ vocabularies: {
1090
+ // Ship's `ARCHIVED_STATES`, value for value: one field, one vocabulary.
1091
+ [ARCHIVED_FIELD]: [
1092
+ { value: '', label: 'Active', colour: 'neutral' },
1093
+ { value: 'true', label: 'Archived', colour: 'muted' },
1094
+ ],
1095
+ },
1061
1096
  };
1062
1097
  function bareFileManifest() {
1063
1098
  return { manifest: BARE_FILE_MANIFEST, address: BARE_FILE_MANIFEST_ADDRESS, viaRecommendation: false };
@@ -1414,6 +1449,83 @@ function foldChanges(changes, rule) {
1414
1449
  }
1415
1450
  return fields;
1416
1451
  }
1452
+ /**
1453
+ * How an `archived` change is read when the file's kind declares no rule of its
1454
+ * own — a Folder, whose `kind:39000` no app owns, and a bare file. SPEC §7.1's
1455
+ * `kind:1851` shape, the one every Estiva app writes.
1456
+ */
1457
+ const ARCHIVE_RULE = {
1458
+ changeKind: 1851,
1459
+ targetTag: 'a',
1460
+ fieldTag: 'field',
1461
+ valueTag: 'value',
1462
+ order: ['ts', 'created_at', 'id'],
1463
+ rule: 'last-write-wins-per-field',
1464
+ };
1465
+ /** The rule an `archived` change on this file is folded by: its app's, or SPEC's. */
1466
+ function archiveRuleOf(manifest) {
1467
+ return manifest?.records ?? ARCHIVE_RULE;
1468
+ }
1469
+ /**
1470
+ * The note Ship wrote on every archive before FOL-46, when the note was the
1471
+ * activity feed's wording rather than anything a person typed. Twelve are on
1472
+ * production (measured 2026-09-29), and none of them is a resolution.
1473
+ */
1474
+ const PLACEHOLDER_ARCHIVE_NOTE = 'archived';
1475
+ /**
1476
+ * Whether a file — or a Folder — is archived, itself or with an ancestor.
1477
+ *
1478
+ * Reads the {@link Archive} a resolver put on it. A resolver leaves archived
1479
+ * files out of a Folder's contents, so this matters where a file is reached
1480
+ * directly: a link, a mention, a page opened by address.
1481
+ */
1482
+ export function isArchived(file) {
1483
+ return !!file?.archived;
1484
+ }
1485
+ /**
1486
+ * The file's archive, if the last `archived` change archived it.
1487
+ *
1488
+ * `changes` may hold any events; only this rule's change kind, naming this
1489
+ * address, setting this field, is read. Last write wins, by the same order as
1490
+ * every other field.
1491
+ */
1492
+ function archiveOf(changes, address, rule) {
1493
+ let last;
1494
+ for (const change of changes) {
1495
+ // The target is the first target tag, as every other fold reads it: a
1496
+ // change archiving one file must not archive another it also mentions.
1497
+ if (change.kind !== rule.changeKind || tagValue(change, rule.targetTag) !== address)
1498
+ continue;
1499
+ if (tagValue(change, rule.fieldTag) !== ARCHIVED_FIELD || tagValue(change, rule.valueTag) === undefined)
1500
+ continue;
1501
+ if (!last || byOrder(last, change) < 0)
1502
+ last = change;
1503
+ }
1504
+ if (!last || tagValue(last, rule.valueTag) !== 'true')
1505
+ return undefined;
1506
+ const note = last.content.trim();
1507
+ return {
1508
+ by: last.pubkey,
1509
+ at: last.created_at,
1510
+ ...(note && note !== PLACEHOLDER_ARCHIVE_NOTE ? { resolution: last.content } : {}),
1511
+ };
1512
+ }
1513
+ /**
1514
+ * The first archived ancestor of `address`, walking `parentOf`, with its archive.
1515
+ *
1516
+ * Stops at a cycle rather than looping: `parentRef` is written by people, and
1517
+ * two files each moved under the other is a state the relay accepts.
1518
+ */
1519
+ function archivedAncestorOf(address, parentOf, archiveAt) {
1520
+ const seen = new Set([address]);
1521
+ for (let parent = parentOf(address); parent && !seen.has(parent); parent = parentOf(parent)) {
1522
+ seen.add(parent);
1523
+ const archive = archiveAt(parent);
1524
+ if (archive)
1525
+ return { ...archive, with: archive.with ?? parent };
1526
+ }
1527
+ return undefined;
1528
+ }
1417
1529
  function truncate(text, limit) {
1418
1530
  if (!limit || text.length <= limit)
1419
1531
  return text;
@@ -1839,6 +1951,7 @@ function buildObject(args) {
1839
1951
  ? { ...action, current: held[action.field] }
1840
1952
  : action),
1841
1953
  viaRecommendation: args.viaRecommendation,
1954
+ ...(args.archived ? { archived: args.archived } : {}),
1842
1955
  };
1843
1956
  }
1844
1957
  /**
@@ -1932,7 +2045,7 @@ depth = 0,
1932
2045
  * Optional memo for the NIP-89 discovery half. See {@link ProjectionCache} —
1933
2046
  * omitting it is exactly the old behaviour.
1934
2047
  */
1935
- cache) {
2048
+ cache, options = {}) {
1936
2049
  const pointer = addressPointerOf(naddr);
1937
2050
  if (!pointer)
1938
2051
  return null;
@@ -1945,6 +2058,8 @@ cache) {
1945
2058
  const assembled = assembleObject(plan, await query(plan.filters));
1946
2059
  if (assembled.object.unreachable)
1947
2060
  return assembled.object;
2061
+ if (options.archivedWith)
2062
+ await markArchivedParents([{ object: assembled.object, manifest: resolved.manifest }], query);
1948
2063
  return withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled)));
1949
2064
  }
1950
2065
  /**
@@ -1987,7 +2102,7 @@ export async function resolveForeignObjects(references, query,
1987
2102
  /** Defaults to asking the relay. The browser passes a cached lookup. */
1988
2103
  lookupPeople,
1989
2104
  /** See {@link ProjectionCache}. Omitting it still reads each app's manifest once per call. */
1990
- cache) {
2105
+ cache, options = {}) {
1991
2106
  const results = {};
1992
2107
  const asked = [];
1993
2108
  for (const reference of new Set(references)) {
@@ -2032,7 +2147,10 @@ cache) {
2032
2147
  chunks.push(filters.slice(start, start + MAX_FILTERS_PER_QUERY));
2033
2148
  }
2034
2149
  const events = (await Promise.all(chunks.map((chunk) => query(chunk)))).flat();
2035
- const assembled = plans.map(({ reference, plan }) => ({ reference, built: assembleObject(plan, events) }));
2150
+ const assembled = plans.map(({ reference, plan }) => ({ reference, plan, built: assembleObject(plan, events) }));
2151
+ if (options.archivedWith) {
2152
+ await markArchivedParents(assembled.map(({ plan, built }) => ({ object: built.object, manifest: plan.resolved.manifest })), query);
2153
+ }
2036
2154
  const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))];
2037
2155
  const reachable = assembled.some(({ built }) => !built.object.unreachable);
2038
2156
  const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {};
@@ -2052,6 +2170,76 @@ cache) {
2052
2170
  }
2053
2171
  return results;
2054
2172
  }
2173
+ /**
2174
+ * Mark each object that is hidden with an archived parent — FOL-46.
2175
+ *
2176
+ * An issue whose project is archived is archived with it, and its page says so
2177
+ * rather than drawing live work. The cascade is computed here and never written
2178
+ * to the issue, so unarchiving the project restores it exactly.
2179
+ *
2180
+ * **One read for the whole set, and only when some object has a parent**, so a
2181
+ * topic page or a project page pays nothing. One level: the parent's own
2182
+ * parent is not followed, because the page is about this file and its
2183
+ * container, and a deeper walk is a round trip per level. A Folder listing
2184
+ * walks the whole chain it holds ({@link resolveFolderContents}).
2185
+ *
2186
+ * The parent is folded by the child's app's rule when that app also draws the
2187
+ * parent's kind — a project is Ship's as its issue is — and by SPEC's rule
2188
+ * otherwise, since the parent's own manifest is not in hand ({@link relatedRuleOf}).
2189
+ */
2190
+ async function markArchivedParents(entries, query) {
2191
+ const waiting = entries.filter(({ object: o }) => !o.unreachable && !o.archived && o.parentRef && addressPointerOf(o.parentRef));
2192
+ if (waiting.length === 0)
2193
+ return;
2194
+ const rules = waiting.map(({ object, manifest }) => relatedRuleOf(manifest, object.parentRef));
2195
+ const parents = [...new Set(waiting.map(({ object }) => object.parentRef))];
2196
+ const changes = await readArchiveChanges(parents, query, rules);
2197
+ for (const [index, { object }] of waiting.entries()) {
2198
+ const archive = archiveOf(changes, object.parentRef, rules[index]);
2199
+ if (archive)
2200
+ object.archived = { ...archive, with: object.parentRef };
2201
+ }
2202
+ }
2203
+ /**
2204
+ * The rule another file's archive is read by, from an app known to hold it:
2205
+ * that app's own, when it draws the file's kind — an issue's project is Ship's,
2206
+ * a hive's inspection the hive log's — and SPEC's otherwise.
2207
+ */
2208
+ function relatedRuleOf(manifest, address) {
2209
+ const kind = addressPointerOf(address)?.kind;
2210
+ return manifest && kind !== undefined && manifest.projections?.[String(kind)] ? archiveRuleOf(manifest) : ARCHIVE_RULE;
2211
+ }
2212
+ /**
2213
+ * Addresses per filter when reading archive changes. A filter's `limit` caps
2214
+ * every change naming its addresses — titles, statuses, moves — not only the
2215
+ * archives, and a relay answers newest first, so a small group keeps the
2216
+ * archive change inside the page.
2217
+ */
2218
+ const ARCHIVE_READ_GROUP = 25;
2219
+ /**
2220
+ * The filters asking for every change naming these addresses, once per distinct
2221
+ * change shape among `rules` — SPEC's alone unless an app writes its own.
2222
+ */
2223
+ function archiveFilters(addresses, rules = [ARCHIVE_RULE]) {
2224
+ const shapes = new Map(rules.map((rule) => [`${rule.changeKind}:${rule.targetTag}`, rule]));
2225
+ const filters = [];
2226
+ for (const rule of shapes.values()) {
2227
+ for (let start = 0; start < addresses.length; start += ARCHIVE_READ_GROUP) {
2228
+ const group = addresses.slice(start, start + ARCHIVE_READ_GROUP);
2229
+ filters.push({ kinds: [rule.changeKind], [`#${rule.targetTag}`]: group, limit: RELAY_PAGE_CEILING });
2230
+ }
2231
+ }
2232
+ return filters;
2233
+ }
2234
+ /** Every change naming these addresses, in each of `rules`' shapes, in as few requests as the relay allows. */
2235
+ async function readArchiveChanges(addresses, query, rules) {
2236
+ const filters = archiveFilters(addresses, rules);
2237
+ const events = [];
2238
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
2239
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
2240
+ }
2241
+ return events;
2242
+ }
2055
2243
  /** An `naddr` or a `<kind>:<pubkey>:<d>`, or null for anything else. */
2056
2244
  function addressPointerOf(reference) {
2057
2245
  try {
@@ -2096,6 +2284,9 @@ function planObject(naddr, pointer, resolved, depth) {
2096
2284
  { kinds: [pointer.kind], authors: [pointer.pubkey], '#d': [pointer.identifier], limit: 1 },
2097
2285
  // Only when the app actually declares a change kind — see `foldRuleOf`.
2098
2286
  ...(manifest.records ? [{ kinds: [manifest.records.changeKind], '#a': [address], limit: 500 }] : []),
2287
+ // Every file may be archived, including one whose app folds nothing
2288
+ // (FOL-46). SPEC's change kind, when the app has not named its own.
2289
+ ...(manifest.records ? [] : [{ kinds: [ARCHIVE_RULE.changeKind], '#a': [address], limit: 500 }]),
2099
2290
  { kinds: commentKinds, '#a': [address], limit: CONVERSATION_LIMIT },
2100
2291
  ...(childFilter ? [childFilter.filter] : []),
2101
2292
  ];
@@ -2181,6 +2372,7 @@ function assembleObject(plan, answered) {
2181
2372
  viaRecommendation,
2182
2373
  webTemplate: resolved.webTemplate,
2183
2374
  comments,
2375
+ archived: archiveOf(events, address, archiveRuleOf(manifest)),
2184
2376
  });
2185
2377
  /*
2186
2378
  The `list` slot — PRO-7.
@@ -3234,6 +3426,11 @@ function buildOneActionEvent(args) {
3234
3426
  if (args.contentFormat !== undefined && !isCreation && (!declared.emits.field || declared.emits.kind === KIND_DELETION)) {
3235
3427
  return `"${declared.label}" takes no prose value, so it takes no content format.`;
3236
3428
  }
3429
+ // A note is a change's `content`. Anywhere else it would be dropped, and the
3430
+ // resolution a person typed lost without a word.
3431
+ if (args.note !== undefined && (isCreation || !declared.emits.field || declared.emits.kind === KIND_DELETION)) {
3432
+ return `"${declared.label}" is not a change, so it takes no note.`;
3433
+ }
3237
3434
  // An object-creating action is a different event entirely — a new object
3238
3435
  // rather than a change to one — so it branches before the scalar path.
3239
3436
  if (isCreation) {
@@ -3346,7 +3543,7 @@ function buildOneActionEvent(args) {
3346
3543
  created_at: Math.floor(args.createdAtMs / 1000),
3347
3544
  kind: declared.emits.kind,
3348
3545
  tags,
3349
- content: declared.emits.field ? '' : value,
3546
+ content: declared.emits.field ? (args.note ?? '') : value,
3350
3547
  };
3351
3548
  }
3352
3549
  /**
@@ -3405,9 +3602,12 @@ const nameOf = (event) => (event ? tagValue(event, 'name') : undefined);
3405
3602
  *
3406
3603
  * Not a list of ids: a new team is a folder somebody creates, not a code
3407
3604
  * change. Moved here from Peek and Ship, which each held the same line.
3605
+ *
3606
+ * An archived Folder is not navigated by (FOL-46), and a listing that has not
3607
+ * read archives — a summary with no `archived` field — keeps every Folder.
3408
3608
  */
3409
3609
  export function topLevelFolders(folders) {
3410
- return folders.filter((folder) => folder.hasState && !folder.listedIn?.length);
3610
+ return folders.filter((folder) => folder.hasState && !folder.listedIn?.length && !folder.archived);
3411
3611
  }
3412
3612
  /**
3413
3613
  * Every folder this identity can see, for a sidebar.
@@ -3444,6 +3644,12 @@ export async function listFolders(query) {
3444
3644
  ...(addresses.length ? { addresses } : {}),
3445
3645
  });
3446
3646
  }
3647
+ for (const event of events) {
3648
+ const id = tagValue(event, 'd');
3649
+ const folder = id && event.kind === KIND_CHANNEL ? byId.get(id) : undefined;
3650
+ if (folder)
3651
+ folder.channel = pointerToAddress({ kind: KIND_CHANNEL, pubkey: event.pubkey, identifier: id, relays: [] });
3652
+ }
3447
3653
  /*
3448
3654
  A folder listed in another folder's state is a file there. Read off the
3449
3655
  states already in hand: an `a` naming a `kind:39000` is a channel, and its
@@ -3469,14 +3675,175 @@ export async function listFolders(query) {
3469
3675
  listedIn.set(identifier, containers);
3470
3676
  }
3471
3677
  }
3472
- await placeRecordChannels(events, byId, listedIn, query);
3678
+ const { recordsOf, archives } = await placeRecordChannels(events, byId, listedIn, query);
3473
3679
  for (const [id, containers] of listedIn) {
3474
3680
  const folder = byId.get(id);
3475
3681
  if (folder)
3476
3682
  folder.listedIn = containers;
3477
3683
  }
3684
+ markArchivedFolders(byId, recordsOf, archives);
3478
3685
  return [...byId.values()].sort((a, b) => (a.name ?? a.id).localeCompare(b.name ?? b.id));
3479
3686
  }
3687
+ /**
3688
+ * Which Folders are archived — FOL-46, from the changes {@link placeRecordChannels}
3689
+ * read with the record roots.
3690
+ *
3691
+ * A Folder is archived by a change naming its channel's address, the way any
3692
+ * file is. A record's channel — a Ship project's conversation — is archived
3693
+ * with its record, so an archived project's channel stops lighting its team's
3694
+ * dot the way the project stopped being listed — only when every record naming
3695
+ * the channel is archived, since two projects may share one. Its own archive
3696
+ * wins when it has one.
3697
+ *
3698
+ * A refused read throws before this, like the reads beside it: a listing that
3699
+ * silently reported every Folder live would put archived teams back in
3700
+ * everyone's sidebar.
3701
+ */
3702
+ function markArchivedFolders(byId, recordsOf, changes) {
3703
+ for (const folder of byId.values()) {
3704
+ const own = folder.channel ? archiveOf(changes, folder.channel, ARCHIVE_RULE) : undefined;
3705
+ if (own) {
3706
+ folder.archived = own;
3707
+ continue;
3708
+ }
3709
+ const records = recordsOf.get(folder.id) ?? [];
3710
+ const archives = records.map((record) => archiveOf(changes, record, ARCHIVE_RULE));
3711
+ if (records.length && archives.every(Boolean))
3712
+ folder.archived = { ...archives[0], with: records[0] };
3713
+ }
3714
+ }
3715
+ /** How many Folders deep {@link archiveImpact} follows nested Folders. A request per Folder. */
3716
+ const MAX_ARCHIVE_DEPTH = 3;
3717
+ /**
3718
+ * Count what archiving `address` would hide — the read behind the warning.
3719
+ *
3720
+ * "Hides 14 issues and 6 topics that are only here; 2 topics also in Estiva HQ
3721
+ * stay visible." The words are the app's; the counts are the same in every
3722
+ * app, which is why they are read here.
3723
+ *
3724
+ * - **A Folder** (a `kind:39000` address, `FolderSummary.channel`): what it
3725
+ * lists, split by whether another Folder lists it too, the children of what
3726
+ * would be hidden, and — three Folders deep — what a nested Folder only it
3727
+ * lists holds. Pass `folders` from the app's own `listFolders` to save that
3728
+ * read.
3729
+ * - **Any other file**: the children its kind declares (a project's issues), and
3730
+ * bare files placed under it (sub-topics), by their root's `a` tag.
3731
+ *
3732
+ * One level of children, as a listing draws them. A few requests, whatever the
3733
+ * size: the Folder, one per app's manifest (memoised by `cache`), the children,
3734
+ * and their archives.
3735
+ */
3736
+ export async function archiveImpact(address, query, options = {}) {
3737
+ const pointer = addressPointerOf(address);
3738
+ if (!pointer)
3739
+ return { hides: [], staysVisible: [] };
3740
+ const counts = new Map();
3741
+ const count = (kind, n = 1) => counts.set(kind, (counts.get(kind) ?? 0) + n);
3742
+ const staysVisible = [];
3743
+ let parents = [{ address, pointer }];
3744
+ if (pointer.kind === KIND_CHANNEL) {
3745
+ const folders = options.folders ?? (await listFolders(query));
3746
+ parents = [];
3747
+ /*
3748
+ A nested Folder only this one lists goes out of view with it, and so does
3749
+ everything only *that* one lists — walked the same way, a Folder at a
3750
+ time, to a small depth. "Only" is judged against the live Folders outside
3751
+ the tree being archived.
3752
+ */
3753
+ const inTree = new Set([pointer.identifier]);
3754
+ const walk = async (folder, depth) => {
3755
+ const contents = await resolveFolderContents(folder, query, async () => ({}), options.cache);
3756
+ for (const file of contents.files) {
3757
+ if (!file.address)
3758
+ continue;
3759
+ const others = folders.filter((other) => !inTree.has(other.id) && !other.archived && other.addresses?.includes(file.address));
3760
+ if (others.length) {
3761
+ staysVisible.push({ address: file.address, kind: file.kind, in: others.map(({ id, name }) => ({ id, name })) });
3762
+ continue;
3763
+ }
3764
+ count(file.kind);
3765
+ const filePointer = addressPointerOf(file.address);
3766
+ if (!filePointer)
3767
+ continue;
3768
+ if (filePointer.kind === KIND_CHANNEL) {
3769
+ if (depth < MAX_ARCHIVE_DEPTH && !inTree.has(filePointer.identifier)) {
3770
+ inTree.add(filePointer.identifier);
3771
+ await walk(filePointer.identifier, depth + 1);
3772
+ }
3773
+ }
3774
+ else {
3775
+ parents.push({ address: file.address, pointer: filePointer });
3776
+ }
3777
+ }
3778
+ };
3779
+ await walk(pointer.identifier, 0);
3780
+ }
3781
+ // A record channel lists a project *and* its issues; each is counted once.
3782
+ const counted = new Set(parents.map((p) => p.address));
3783
+ for (const [kind, n] of await countLiveChildren(parents, counted, query, options.cache))
3784
+ count(kind, n);
3785
+ return {
3786
+ hides: [...counts].map(([kind, n]) => ({ kind, count: n })),
3787
+ staysVisible,
3788
+ };
3789
+ }
3790
+ /** The children of each parent that are not archived already, by kind. */
3791
+ async function countLiveChildren(parents, counted, query, cache) {
3792
+ const byKind = new Map();
3793
+ if (parents.length === 0)
3794
+ return byKind;
3795
+ const byApp = new Map();
3796
+ for (const { pointer } of parents)
3797
+ byApp.set(manifestKeyOf(pointer), pointer);
3798
+ const manifests = new Map();
3799
+ await Promise.all([...byApp].map(async ([key, pointer]) => {
3800
+ const resolved = await resolveManifest(pointer, query, cache);
3801
+ if (resolved)
3802
+ manifests.set(key, resolved);
3803
+ }));
3804
+ const filters = [];
3805
+ const wanted = [];
3806
+ for (const { address, pointer } of parents) {
3807
+ const manifest = manifests.get(manifestKeyOf(pointer))?.manifest;
3808
+ const projection = manifest?.projections?.[String(pointer.kind)];
3809
+ const declared = projection && declaredChildSpec(projection);
3810
+ // A declared child is the parent's app's, and folds by its rule; a sub-topic is a bare file, SPEC's.
3811
+ const specs = [
3812
+ ...(declared ? [{ kind: declared.kind, via: declared.via, rule: archiveRuleOf(manifest) }] : []),
3813
+ // A sub-topic may sit under a file of any kind (SPEC §6.7).
3814
+ ...(declared?.kind === KIND_BARE_FILE && declared.via === 'a' ? [] : [{ kind: KIND_BARE_FILE, via: 'a', rule: ARCHIVE_RULE }]),
3815
+ ];
3816
+ for (const spec of specs) {
3817
+ wanted.push({ ...spec, parent: address });
3818
+ filters.push({ kinds: [spec.kind], [`#${spec.via}`]: [address], limit: RELAY_PAGE_CEILING });
3819
+ }
3820
+ }
3821
+ const events = [];
3822
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
3823
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
3824
+ }
3825
+ const children = new Map();
3826
+ for (const event of events) {
3827
+ const identifier = tagValue(event, 'd');
3828
+ if (identifier === undefined)
3829
+ continue;
3830
+ const match = wanted.find((w) => w.kind === event.kind && hasTagValue(event, w.via, w.parent));
3831
+ if (!match)
3832
+ continue;
3833
+ const child = pointerToAddress({ kind: event.kind, pubkey: event.pubkey, identifier, relays: [] });
3834
+ if (!counted.has(child))
3835
+ children.set(child, { kind: event.kind, rule: match.rule });
3836
+ }
3837
+ if (children.size === 0)
3838
+ return byKind;
3839
+ const changes = await readArchiveChanges([...children.keys()], query, [...children.values()].map((c) => c.rule));
3840
+ for (const [child, { kind, rule }] of children) {
3841
+ if (archiveOf(changes, child, rule))
3842
+ continue;
3843
+ byKind.set(kind, (byKind.get(kind) ?? 0) + 1);
3844
+ }
3845
+ return byKind;
3846
+ }
3480
3847
  /**
3481
3848
  * A record's own channel is listed wherever the record is (FOL-42).
3482
3849
  *
@@ -3547,8 +3914,18 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3547
3914
  containersOf.set(key, entry);
3548
3915
  }
3549
3916
  }
3550
- if (containersOf.size === 0)
3551
- return;
3917
+ // Every Folder's archive, and every listed record's, ride with the roots
3918
+ // (FOL-46): the channel addresses are in hand from the listing and the
3919
+ // record addresses are the keys above, so neither needs the roots first.
3920
+ const channels = [...byId.values()].flatMap((folder) => (folder.channel ? [folder.channel] : []));
3921
+ const archiveAsk = archiveFilters([...new Set([...channels, ...containersOf.keys()])]);
3922
+ if (containersOf.size === 0) {
3923
+ const archives = [];
3924
+ for (let start = 0; start < archiveAsk.length; start += MAX_FILTERS_PER_QUERY) {
3925
+ archives.push(...(await query(archiveAsk.slice(start, start + MAX_FILTERS_PER_QUERY))));
3926
+ }
3927
+ return { recordsOf: new Map(), archives };
3928
+ }
3552
3929
  const groups = new Map();
3553
3930
  for (const { pointer } of containersOf.values()) {
3554
3931
  const key = `${pointer.kind}:${pointer.pubkey}`;
@@ -3563,10 +3940,14 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3563
3940
  filters.push({ kinds: [kind], authors: [pubkey], '#d': chunk, limit: chunk.length });
3564
3941
  }
3565
3942
  }
3566
- const roots = [];
3943
+ filters.push(...archiveAsk);
3944
+ const answered = [];
3567
3945
  for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
3568
- roots.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
3946
+ answered.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
3569
3947
  }
3948
+ // A state lists files, never change events, so the kind tells them apart.
3949
+ const archives = answered.filter((e) => e.kind === ARCHIVE_RULE.changeKind);
3950
+ const roots = answered.filter((e) => e.kind !== ARCHIVE_RULE.changeKind);
3570
3951
  // Newest wins, as it does for any addressable event a relay has not yet replaced.
3571
3952
  const newest = new Map();
3572
3953
  for (const root of roots) {
@@ -3575,11 +3956,16 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3575
3956
  if (!held || root.created_at > held.created_at)
3576
3957
  newest.set(key, root);
3577
3958
  }
3959
+ const recordsOf = new Map();
3578
3960
  for (const [key, { containers }] of containersOf) {
3579
3961
  const root = newest.get(key);
3580
3962
  const channel = root && folderOf(root);
3581
3963
  if (!channel || byId.get(channel)?.hasState)
3582
3964
  continue;
3965
+ // A file published into the Folder that lists it names that Folder, and
3966
+ // does not own it: a topic's `h` is its team's.
3967
+ if (!containers.includes(channel))
3968
+ recordsOf.set(channel, [...(recordsOf.get(channel) ?? []), key]);
3583
3969
  for (const container of containers) {
3584
3970
  if (container === channel)
3585
3971
  continue;
@@ -3589,6 +3975,7 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3589
3975
  listedIn.set(channel, placed);
3590
3976
  }
3591
3977
  }
3978
+ return { recordsOf, archives };
3592
3979
  }
3593
3980
  /**
3594
3981
  * Everything in one folder, resolved through the manifests of the apps that own it.
@@ -3637,7 +4024,7 @@ export async function resolveFolderContents(folder, query,
3637
4024
  /** Defaults to asking the relay. The browser passes a cached lookup. */
3638
4025
  lookupPeople,
3639
4026
  /** See {@link ProjectionCache}. Omitting it is exactly the old behaviour. */
3640
- cache) {
4027
+ cache, options = {}) {
3641
4028
  // 1. The folder itself. Both kinds in one trip: the state is the model and
3642
4029
  // the channel is what names a folder that has none yet.
3643
4030
  const identity = await query([
@@ -3646,10 +4033,14 @@ cache) {
3646
4033
  ]);
3647
4034
  const state = identity.find((e) => e.kind === KIND_FOLDER_STATE && tagValue(e, 'd') === folder);
3648
4035
  const channel = identity.find((e) => e.kind === KIND_CHANNEL && tagValue(e, 'd') === folder);
4036
+ const channelAddress = channel
4037
+ ? pointerToAddress({ kind: KIND_CHANNEL, pubkey: channel.pubkey, identifier: folder, relays: [] })
4038
+ : undefined;
3649
4039
  const summary = {
3650
4040
  id: folder,
3651
4041
  name: nameOf(state) ?? nameOf(channel),
3652
4042
  hasState: !!state,
4043
+ ...(channelAddress ? { channel: channelAddress } : {}),
3653
4044
  ...(state
3654
4045
  ? { address: pointerToAddress({ kind: state.kind, pubkey: state.pubkey, identifier: folder, relays: [] }) }
3655
4046
  : {}),
@@ -3663,7 +4054,12 @@ cache) {
3663
4054
  }
3664
4055
  : await addressesByContainment(folder, query);
3665
4056
  if (addresses.length === 0) {
3666
- return { ...summary, files: [], source: state ? 'state' : 'channel' };
4057
+ // Nothing listed, so no change query to ride on: the Folder's own archive
4058
+ // is one small read of its own.
4059
+ const archived = channelAddress
4060
+ ? archiveOf(await readArchiveChanges([channelAddress], query), channelAddress, ARCHIVE_RULE)
4061
+ : undefined;
4062
+ return { ...summary, ...(archived ? { archived } : {}), files: [], source: state ? 'state' : 'channel' };
3667
4063
  }
3668
4064
  // 2. Group by (kind, author): one manifest answers for every file an app owns
3669
4065
  // in this folder, and the cache makes the second folder free.
@@ -3702,8 +4098,15 @@ cache) {
3702
4098
  // Change kinds are a set because two apps may fold differently, and a kind
3703
4099
  // is a u16 — the relay refuses an out-of-range one outright, so an app
3704
4100
  // declaring no `records` contributes no filter rather than an empty one.
4101
+ //
4102
+ // SPEC's change kind is always asked for, whatever the apps declare: any
4103
+ // file may be archived (FOL-46), a nested Folder included, and so may this
4104
+ // Folder, whose own address rides in the same filter.
3705
4105
  const changeKinds = [
3706
- ...new Set([...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : []))),
4106
+ ...new Set([
4107
+ ARCHIVE_RULE.changeKind,
4108
+ ...[...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : [])),
4109
+ ]),
3707
4110
  ];
3708
4111
  const events = await query([
3709
4112
  ...[...groups.values()].map(({ pointer, addresses: group }) => ({
@@ -3712,12 +4115,23 @@ cache) {
3712
4115
  '#d': group.map((a) => referenceToPointer(a).identifier),
3713
4116
  limit: group.length,
3714
4117
  })),
3715
- ...(changeKinds.length
3716
- ? [{ kinds: changeKinds, '#a': addresses, limit: 500 }]
3717
- : []),
4118
+ { kinds: changeKinds, '#a': addresses, limit: 500 },
4119
+ // The archives again, in groups small enough that a busy Folder's other
4120
+ // changes cannot push them off the page — the filter above holds 500
4121
+ // changes for every file together, and one Folder has already had 688.
4122
+ // Same request.
4123
+ ...archiveFilters(channelAddress ? [...addresses, channelAddress] : addresses),
3718
4124
  ]);
3719
- // 4. Build each file, in the order the folder listed them.
3720
- const files = [];
4125
+ const ownArchive = channelAddress ? archiveOf(events, channelAddress, ARCHIVE_RULE) : undefined;
4126
+ if (ownArchive)
4127
+ summary.archived = ownArchive;
4128
+ // 4. Build each file, in the order the folder listed them. Archived files are
4129
+ // held back until the cascade below has read their parents.
4130
+ const listed = [];
4131
+ const archiveByAddress = new Map();
4132
+ const parentByAddress = new Map();
4133
+ // How a parent outside this listing is read: its child's app's rule when that app draws it.
4134
+ const parentRuleOf = new Map();
3721
4135
  for (const { address, pointer } of pointers) {
3722
4136
  const resolved = manifests.get(manifestKeyOf(pointer));
3723
4137
  // No app claims this kind, so there is no projection to draw it with.
@@ -3732,11 +4146,19 @@ cache) {
3732
4146
  continue;
3733
4147
  const records = foldRuleOf(resolved.manifest);
3734
4148
  const folded = foldChanges(events.filter((e) => e.kind === records.changeKind && hasTagValue(e, records.targetTag, address)), records);
4149
+ const archive = archiveOf(events, address, archiveRuleOf(resolved.manifest));
4150
+ archiveByAddress.set(address, archive);
4151
+ const parent = parentRefOf(resolved.manifest, pointer.kind, root, folded);
4152
+ parentByAddress.set(address, parent);
4153
+ if (parent)
4154
+ parentRuleOf.set(parent, relatedRuleOf(resolved.manifest, parent));
3735
4155
  // An app hiding a record from its own lists is saying it is not part of the
3736
- // folder any more. `hiddenWhen` is the app's own declaration of that.
3737
- if (records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals) {
4156
+ // folder any more. `hiddenWhen` is the app's own declaration of that — the
4157
+ // archive above is the same statement for a kind whose app declared none.
4158
+ // Not reported as an archive: the app said "hidden", which may mean more.
4159
+ const hidden = !!records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals;
4160
+ if (hidden && !archive)
3738
4161
  continue;
3739
- }
3740
4162
  /*
3741
4163
  A placed file stays listed only while the placement is current.
3742
4164
 
@@ -3762,15 +4184,56 @@ cache) {
3762
4184
  if (!current)
3763
4185
  continue;
3764
4186
  }
3765
- files.push(buildObject({
3766
- root,
3767
- pointer,
3768
- manifest: resolved.manifest,
3769
- projection,
3770
- folded,
3771
- viaRecommendation: resolved.viaRecommendation,
3772
- webTemplate: resolved.webTemplate,
3773
- }));
4187
+ listed.push({
4188
+ archive,
4189
+ file: buildObject({
4190
+ root,
4191
+ pointer,
4192
+ manifest: resolved.manifest,
4193
+ projection,
4194
+ folded,
4195
+ viaRecommendation: resolved.viaRecommendation,
4196
+ webTemplate: resolved.webTemplate,
4197
+ }),
4198
+ });
4199
+ }
4200
+ /*
4201
+ 5. The cascade (FOL-46): a file under an archived file is hidden with it —
4202
+ an issue with its project, a sub-topic with its topic. Computed here and
4203
+ never written to the children, so unarchiving the parent restores
4204
+ exactly what was there.
4205
+
4206
+ The chain is walked through everything this Folder lists. A parent that
4207
+ lives in another Folder is read once for all such parents, one level: a
4208
+ project whose record channel lists its issues is the case that matters,
4209
+ and there the project is listed too.
4210
+
4211
+ Only by parent. A file this Folder lists is never hidden because some
4212
+ *other* Folder that lists it is archived — that is what lets a file
4213
+ placed in two Folders stay visible in the one that is not archived.
4214
+ */
4215
+ const outside = [
4216
+ ...new Set(listed.flatMap(({ file }) => {
4217
+ const parent = file.address && parentByAddress.get(file.address);
4218
+ return parent && !archiveByAddress.has(parent) && addressPointerOf(parent) ? [parent] : [];
4219
+ })),
4220
+ ];
4221
+ if (outside.length) {
4222
+ const ruleFor = (parent) => parentRuleOf.get(parent) ?? ARCHIVE_RULE;
4223
+ const changes = await readArchiveChanges(outside, query, outside.map(ruleFor));
4224
+ for (const parent of outside)
4225
+ archiveByAddress.set(parent, archiveOf(changes, parent, ruleFor(parent)));
4226
+ }
4227
+ const files = [];
4228
+ for (const { file, archive } of listed) {
4229
+ const effective = archive ??
4230
+ (file.address
4231
+ ? archivedAncestorOf(file.address, (a) => parentByAddress.get(a), (a) => archiveByAddress.get(a))
4232
+ : undefined);
4233
+ if (!effective)
4234
+ files.push(file);
4235
+ else if (options.includeArchived)
4236
+ files.push({ ...file, archived: effective });
3774
4237
  }
3775
4238
  const people = await (lookupPeople ?? peopleViaRelay(query))([
3776
4239
  ...new Set(files.flatMap(pubkeysIn)),