@estiva-app/interop 0.34.0 → 0.36.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.
@@ -15,6 +15,8 @@
15
15
  import { decodeNaddr, decodeNevent, encodeNaddr, encodeNevent, findNaddrs, pointerToAddress, referenceToPointer } from '@estiva-app/protocol';
16
16
  import { imetaOf, parseProfile } from '@estiva-app/protocol';
17
17
  import { MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING } from '@estiva-app/protocol';
18
+ import { attachmentsInDocument, BLOCK_DOCUMENT_FORMAT, CONTENT_FORMAT_TAG, imetaTag, parseBlockDocument, } from '@estiva-app/protocol';
19
+ import { planPlaceFile, planUnlistFile } from './folders.js';
18
20
  /** The default: one kind:0 query, straight to the relay. */
19
21
  /**
20
22
  * How long a *name* may be believed.
@@ -333,6 +335,88 @@ cache) {
333
335
  messages.sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : 1));
334
336
  return conversations;
335
337
  }
338
+ /**
339
+ * The replies under a file's comments — {@link conversationsOf}'s counterpart,
340
+ * read by `#e` (PRO-20, from Peek's FOL-19 thread pane).
341
+ *
342
+ * **Asked by `#e`, not by `#a`, and that is the whole reason this exists.** A
343
+ * reply's lowercase tags name its parent comment, not the file (SPEC §6.4), so
344
+ * the `#a` read that brings the roots never brings a reply — whichever app
345
+ * wrote it. `rootIds` are those roots, typically `conversationsOf`'s ids.
346
+ *
347
+ * **Every thread in one request.** The roots by `ids` and their replies by
348
+ * `#e` go in one POST, because a `#e` filter takes a list: a whole pane's
349
+ * replies cost the round trip of one thread's, which is what lets a comment
350
+ * carry an honest reply count. The roots come back beside them because NIP-22's
351
+ * lowercase `k` on a reply names the *parent's* kind, and no projection reports
352
+ * it.
353
+ *
354
+ * The kinds are the owning app's, from its manifest (`commentKindsOf`), so a
355
+ * NIP-22 `kind:1111` reply and Ship's `kind:9` ones both arrive. No manifest,
356
+ * or a reference that does not decode, answers empty rather than guessing 1111.
357
+ *
358
+ * Only *direct* replies: a reply's lowercase `e` names its immediate parent, so
359
+ * a reply to a reply hangs off that reply and is not here. The replies share
360
+ * one `limit`, by default `CONVERSATION_LIMIT` — the same budget as one file's
361
+ * comment read, and what Peek's pane asks for.
362
+ *
363
+ * A refused read is whatever `query` does with one — this adds no catch, so an
364
+ * unreadable thread and an unanswered one stay distinguishable.
365
+ */
366
+ export async function threadsOf(
367
+ /** The file's address, or any reference `referenceToPointer` reads. */
368
+ reference, rootIds, query, cache,
369
+ /** How many replies, across every thread, one read asks for. */
370
+ limit = CONVERSATION_LIMIT) {
371
+ const empty = { roots: {}, replies: {} };
372
+ if (rootIds.length === 0)
373
+ return empty;
374
+ let pointer;
375
+ try {
376
+ pointer = referenceToPointer(reference);
377
+ }
378
+ catch {
379
+ return empty;
380
+ }
381
+ const resolved = await resolveManifest(pointer, query, cache);
382
+ if (!resolved)
383
+ return empty;
384
+ const kinds = commentKindsOf(resolved.manifest);
385
+ const ids = [...new Set(rootIds)];
386
+ const events = await query([
387
+ { ids, limit: ids.length },
388
+ { kinds, '#e': ids, limit },
389
+ ]);
390
+ const wanted = new Set(ids);
391
+ const roots = {};
392
+ const replies = {};
393
+ const seen = new Set();
394
+ for (const event of events) {
395
+ if (seen.has(event.id))
396
+ continue;
397
+ seen.add(event.id);
398
+ if (wanted.has(event.id)) {
399
+ roots[event.id] = event;
400
+ continue;
401
+ }
402
+ /*
403
+ The parent. A NIP-10 `reply` marker says it outright, and then only that
404
+ one counts: a reply to a reply also carries the thread's `root`-marked
405
+ `e`, which names a wanted id and is not its parent. Unmarked (NIP-22's
406
+ single lowercase `e`, or a bare mention beside it), the `e` naming a root
407
+ of *this* conversation — picking the first would file it under a quote.
408
+ */
409
+ const es = event.tags.filter((tag) => tag[0] === 'e' && tag[1]);
410
+ const parent = (es.find((tag) => tag[3] === 'reply') ?? es.find((tag) => wanted.has(tag[1])))?.[1];
411
+ if (parent && wanted.has(parent))
412
+ (replies[parent] ??= []).push(event);
413
+ }
414
+ // Oldest first, ties by id so two replies in one second never swap places.
415
+ for (const thread of Object.values(replies)) {
416
+ thread.sort((a, b) => a.created_at - b.created_at || (a.id < b.id ? -1 : 1));
417
+ }
418
+ return { roots, replies };
419
+ }
336
420
  /**
337
421
  * How many targets a reaction read asks about — SPEC §6.6, decided by CON-1.
338
422
  *
@@ -514,6 +598,10 @@ export async function commentDecorationsOf(targets, query) {
514
598
  return { byId, reactionTargetsOmitted: ids.length - forReactions.length };
515
599
  }
516
600
  export const ACTION_EFFECTS = ['safe', 'writes', 'destructive'];
601
+ /** The declared format, when it is one this version writes. */
602
+ function proseFormatOf(declared) {
603
+ return declared === BLOCK_DOCUMENT_FORMAT ? BLOCK_DOCUMENT_FORMAT : undefined;
604
+ }
517
605
  /**
518
606
  * The aspects a generic app may declare — RFC 0.5 §10.2's three parts of a
519
607
  * file, minus `properties`, which is what a *type* adds and so what a
@@ -538,7 +626,7 @@ function resolveActions(manifest, kind, folded) {
538
626
  */
539
627
  const isChange = !!action.emits.field;
540
628
  const isComment = action.emits.scope === 'address';
541
- const isCreation = action.input?.type === 'object' && !!action.input.properties;
629
+ const isCreation = isCreationAction(action);
542
630
  // Four, since 0.25.0. Decided by the kind before the other three, so a
543
631
  // manifest that put `scope: 'address'` on its deletion — the target *is*
544
632
  // an address — is not mistaken for a comment.
@@ -552,6 +640,7 @@ function resolveActions(manifest, kind, folded) {
552
640
  ...(action.description ? { description: action.description } : {}),
553
641
  ...(action.effect ? { effect: action.effect } : {}),
554
642
  control: 'confirm',
643
+ ...(action.emits.listed === true ? { listed: true } : {}),
555
644
  });
556
645
  continue;
557
646
  }
@@ -578,6 +667,8 @@ function resolveActions(manifest, kind, folded) {
578
667
  a one-line input and drawing prose.
579
668
  */
580
669
  ...(spec.target ? { target: spec.target } : {}),
670
+ // Prose only where the value is `content` — a tag is a scalar (§7.3).
671
+ ...(spec.target === 'content' && proseFormatOf(spec.format) ? { format: proseFormatOf(spec.format) } : {}),
581
672
  ...(spec.enum && manifest.vocabularies?.[spec.enum]
582
673
  ? {
583
674
  options: manifest.vocabularies[spec.enum].map((v) => ({
@@ -592,16 +683,22 @@ function resolveActions(manifest, kind, folded) {
592
683
  // comes from `emits`, and a form that omitted it would publish an
593
684
  // orphan the owning app cannot show anywhere.
594
685
  ...(action.emits.toAddressOf ? { createsUnder: action.emits.toAddressOf } : {}),
686
+ ...(action.emits.listed === true ? { listed: true } : {}),
595
687
  });
596
688
  continue;
597
689
  }
598
690
  const vocab = action.input?.enum ? manifest.vocabularies?.[action.input.enum] : undefined;
691
+ const control = vocab ? 'select' : action.input?.type === 'pubkey' ? 'pubkey' : 'text';
692
+ // A change only: a comment's body is §13.2 marker text, and a format on
693
+ // one is nothing this version writes (`buildActionEvent` refuses it).
694
+ const format = control === 'text' && isChange ? proseFormatOf(action.input?.format) : undefined;
599
695
  out.push({
600
696
  id: action.id,
601
697
  label: action.label,
602
698
  ...(action.description ? { description: action.description } : {}),
603
699
  ...(action.effect ? { effect: action.effect } : {}),
604
- control: vocab ? 'select' : action.input?.type === 'pubkey' ? 'pubkey' : 'text',
700
+ control,
701
+ ...(format ? { format } : {}),
605
702
  options: vocab?.map((v) => ({ value: v.value, label: v.label, colour: v.colour })),
606
703
  current: action.emits.field ? folded[action.emits.field]?.value : undefined,
607
704
  field: action.emits.field,
@@ -851,8 +948,6 @@ export const KIND_BARE_FILE = 30840;
851
948
  * should fail loudly rather than find something.
852
949
  */
853
950
  export const BARE_FILE_MANIFEST_ADDRESS = 'spec:6.7';
854
- /** The field a bare file's `kind:1851` re-parent sets (SPEC §6.7). */
855
- const BARE_FILE_PARENT_FIELD = 'parent';
856
951
  const BARE_FILE_MANIFEST = {
857
952
  name: 'File',
858
953
  about: 'A file no app owns. Its conversation is what every file has; its type adds nothing.',
@@ -875,7 +970,11 @@ const BARE_FILE_MANIFEST = {
875
970
  // of *other* kinds are found the other way round, by their own `a`
876
971
  // (`parentRefOf` below), which is FOL-4's generic direction; this slot
877
972
  // is the one the existing `list` machinery can draw today.
878
- list: { children: { kind: KIND_BARE_FILE, via: 'a', limit: 200 } },
973
+ //
974
+ // `movedBy` is SPEC §6.7's `parent` field, declared rather than
975
+ // hard-coded since MAN-1, so a bare file moves by the rule every other
976
+ // kind does — the move action below sets the same field.
977
+ list: { children: { kind: KIND_BARE_FILE, via: 'a', limit: 200, movedBy: 'parent' } },
879
978
  },
880
979
  },
881
980
  /*
@@ -946,7 +1045,7 @@ const BARE_FILE_MANIFEST = {
946
1045
  'the team may; who can read the file does not change.',
947
1046
  effect: 'writes',
948
1047
  appliesTo: [String(KIND_BARE_FILE)],
949
- emits: { kind: 1851, field: BARE_FILE_PARENT_FIELD },
1048
+ emits: { kind: 1851, field: 'parent' },
950
1049
  input: { type: 'string' },
951
1050
  },
952
1051
  {
@@ -1476,6 +1575,47 @@ export function actionProblems(declared) {
1476
1575
  problems.push(`${name} writes ${targeted.length} properties to content (${targeted.join(', ')}), and an event has one. A consumer refuses the whole action rather than choosing between them.`);
1477
1576
  }
1478
1577
  }
1578
+ /*
1579
+ MAN-1's three declarations, each of which fails quietly on the consumer's
1580
+ side: an unknown placement or format is refused or ignored at the button,
1581
+ and a `listed` on a change is simply never acted on.
1582
+ */
1583
+ const emits = action.emits;
1584
+ const input = action.input;
1585
+ const creates = input?.type === 'object' && !!properties;
1586
+ if (emits?.placement !== undefined && !(creates && PLACEMENTS.includes(emits.placement))) {
1587
+ problems.push(creates
1588
+ ? `${name} places its object with ${JSON.stringify(emits.placement)}, and a Folder is named by ${PLACEMENTS.join(' or ')} — a consumer refuses the action.`
1589
+ : `${name} declares a placement and creates nothing; only a new root names its Folder, so it is ignored.`);
1590
+ }
1591
+ if (emits?.listed !== undefined && emits.listed !== true) {
1592
+ problems.push(`${name} declares listed ${JSON.stringify(emits.listed)}; the only value is true.`);
1593
+ }
1594
+ else if (emits?.listed === true && !creates && emits.kind !== KIND_DELETION) {
1595
+ problems.push(`${name} declares listed on an action that neither creates nor deletes, so no Folder command follows it.`);
1596
+ }
1597
+ const formats = [
1598
+ // A scalar format means something on a change only: a comment's body is
1599
+ // marker text, and a deletion takes no value.
1600
+ ...(input?.format !== undefined
1601
+ ? [['its input', input.format, !creates && !!emits?.field && emits.kind !== KIND_DELETION]]
1602
+ : []),
1603
+ ...Object.entries(properties && typeof properties === 'object' ? properties : {})
1604
+ .filter(([, spec]) => spec?.format !== undefined)
1605
+ .map(([property, spec]) => [
1606
+ `"${property}"`,
1607
+ spec.format,
1608
+ spec.target === 'content',
1609
+ ]),
1610
+ ];
1611
+ for (const [where, format, applies] of formats) {
1612
+ if (!applies) {
1613
+ problems.push(`${name} declares a format on ${where}, which is neither a creation's content nor a change's value, so it is ignored.`);
1614
+ }
1615
+ else if (!proseFormatOf(format)) {
1616
+ problems.push(`${name} declares format ${JSON.stringify(format)} on ${where}, and the only format is ${BLOCK_DOCUMENT_FORMAT}. A consumer draws it as plain text.`);
1617
+ }
1618
+ }
1479
1619
  return problems;
1480
1620
  }
1481
1621
  export function pickWidget(declared, implemented, fallback) {
@@ -1690,7 +1830,7 @@ function buildObject(args) {
1690
1830
  comments: args.comments ?? [],
1691
1831
  listsChildren: listsChildrenOf(projection, manifest),
1692
1832
  parentRef: parentRefOf(manifest, pointer.kind, root, folded),
1693
- ...(pointer.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
1833
+ ...parentFieldsOf(manifest, pointer.kind),
1694
1834
  folder: tagValue(root, 'h'),
1695
1835
  // Substituted here rather than in the component: `<bech32>` is a NIP-89
1696
1836
  // detail, and the widget's job is to draw a link, not to know the spec.
@@ -2134,16 +2274,24 @@ function parentRefOf(manifest, kind, root, folded = {}) {
2134
2274
  direction lets Ship's project list its issues without an issue knowing what
2135
2275
  a project is; this one lets a topic sit under a project, an issue, or a kind
2136
2276
  nobody has met, without that kind's owner declaring bare files as children.
2137
- Re-parenting is a `parent` change event, seeded by the root tag, the way an
2138
- issue's `project` field works (SPEC §6.7).
2277
+ Re-parenting is a change to the declared `movedBy` field, seeded by the
2278
+ root tag — `parent` on a bare file, `project` on a Ship issue (SPEC §7.2).
2139
2279
  */
2140
- if (kind === KIND_BARE_FILE) {
2280
+ const movedBy = movedByOf(manifest, kind);
2281
+ if (movedBy) {
2141
2282
  // A folded empty value is a move to the top, not an absence: falling back
2142
2283
  // to the root tag would put the file straight back under the parent it
2143
2284
  // was moved out of (FOL-4).
2144
- const moved = folded[BARE_FILE_PARENT_FIELD];
2145
- if (moved)
2146
- return moved.value || undefined;
2285
+ // A value that is not an address of the declared parent kind names nothing
2286
+ // this object can sit under, so it is a move to nowhere rather than a ref a
2287
+ // consumer might try to fetch.
2288
+ const moved = folded[movedBy.field];
2289
+ if (moved) {
2290
+ const prefix = movedBy.parentKind === undefined ? /^\d+:[0-9a-f]{64}:/ : new RegExp(`^${movedBy.parentKind}:[0-9a-f]{64}:`);
2291
+ return prefix.test(moved.value) ? moved.value : undefined;
2292
+ }
2293
+ }
2294
+ if (kind === KIND_BARE_FILE) {
2147
2295
  return root.tags.find((t) => t[0] === 'a' && t[1] && /^\d+:[0-9a-f]{64}:/.test(t[1]))?.[1];
2148
2296
  }
2149
2297
  for (const [parentKind, projection] of Object.entries(manifest.projections ?? {})) {
@@ -2166,6 +2314,34 @@ function parentRefOf(manifest, kind, root, folded = {}) {
2166
2314
  }
2167
2315
  return undefined;
2168
2316
  }
2317
+ /**
2318
+ * The field that moves a `kind` object to another parent, and the kind of
2319
+ * parent it names — SPEC §7.2's `movedBy`, read off whichever projection lists
2320
+ * `kind` as its children (MAN-1).
2321
+ *
2322
+ * `parentKind` is absent for a bare file: §6.7 lets one sit under a file of any
2323
+ * kind, so its own list naming bare files is not a limit on where it may go.
2324
+ * Absent too for `match: 'identifier'`, where `movedBy` is ignored because a
2325
+ * move's value is an address and that list compares identifiers.
2326
+ */
2327
+ function movedByOf(manifest, kind) {
2328
+ for (const [parentKind, projection] of Object.entries(manifest.projections ?? {})) {
2329
+ const children = declaredChildSpec(projection);
2330
+ if (!children || children.kind !== kind || !children.movedBy || children.match === 'identifier')
2331
+ continue;
2332
+ return kind === KIND_BARE_FILE ? { field: children.movedBy } : { field: children.movedBy, parentKind: Number(parentKind) };
2333
+ }
2334
+ return undefined;
2335
+ }
2336
+ /** {@link movedByOf} as the two `ForeignObject` fields, both builders' shape. */
2337
+ function parentFieldsOf(manifest, kind) {
2338
+ const moved = movedByOf(manifest, kind);
2339
+ if (!moved)
2340
+ return {};
2341
+ return moved.parentKind === undefined
2342
+ ? { parentField: moved.field }
2343
+ : { parentField: moved.field, parentKind: moved.parentKind };
2344
+ }
2169
2345
  /** Both halves of the question a disclosure control asks. */
2170
2346
  function listsChildrenOf(projection, manifest) {
2171
2347
  const children = declaredChildSpec(projection);
@@ -2264,7 +2440,7 @@ function buildChildObject(args) {
2264
2440
  // an inconsistent shape is what makes a consumer defensive about a value it
2265
2441
  // should be able to trust.
2266
2442
  parentRef: parentRefOf(manifest, root.kind, root),
2267
- ...(root.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
2443
+ ...parentFieldsOf(manifest, root.kind),
2268
2444
  folder: tagValue(root, 'h'),
2269
2445
  /*
2270
2446
  `<bech32>` is whichever form this object actually has.
@@ -2832,6 +3008,47 @@ cache) {
2832
3008
  * it where it looks.
2833
3009
  */
2834
3010
  const isAddressableKind = (kind) => kind >= 30000 && kind < 40000;
3011
+ /**
3012
+ * The tags a new root may name its Folder with — SPEC §7.3's `placement`.
3013
+ *
3014
+ * The two a relay indexes for a Folder's containment read and {@link folderOf}
3015
+ * reads. Closed, because a root placed in any other tag belongs to no Folder
3016
+ * and nothing would say so.
3017
+ */
3018
+ const PLACEMENTS = ['h', 'buzz-channel'];
3019
+ /**
3020
+ * The tags a prose value carries — SPEC §7.3's `format`, MAN-1.
3021
+ *
3022
+ * **Tagged only when the caller says the value is in the declared format**, and
3023
+ * then checked, because a reader decides the model by the tag alone (§13.4): a
3024
+ * `content-format` on marker text renders nothing, and one on a document the
3025
+ * relay cannot parse renders JSON at a person. Without `contentFormat` the value
3026
+ * is marker text and carries nothing, which every reader must accept — so a
3027
+ * consumer that draws a text box for a prose field still publishes correctly.
3028
+ *
3029
+ * A document's attachments are named again as `imeta`, which §13.3 requires of
3030
+ * every event holding one and which ingest verifies against stored blobs.
3031
+ */
3032
+ function proseTags(args) {
3033
+ const { label, declared, contentFormat, value } = args;
3034
+ if (contentFormat === undefined)
3035
+ return [];
3036
+ if (proseFormatOf(declared) !== contentFormat) {
3037
+ return proseFormatOf(declared)
3038
+ ? `"${label}" takes ${proseFormatOf(declared)}, not ${contentFormat}.`
3039
+ : `"${label}" declares no ${contentFormat} value, so it is written as plain text.`;
3040
+ }
3041
+ // Clearing a field is not a document; an empty value says nothing to tag.
3042
+ if (value === '')
3043
+ return [];
3044
+ try {
3045
+ parseBlockDocument(value);
3046
+ }
3047
+ catch (e) {
3048
+ return `"${label}" was handed ${contentFormat} that is ${e.message}.`;
3049
+ }
3050
+ return [[CONTENT_FORMAT_TAG, contentFormat], ...attachmentsInDocument(value, contentFormat).map(imetaTag)];
3051
+ }
2835
3052
  /**
2836
3053
  * The event an object-creating action publishes.
2837
3054
  *
@@ -2892,6 +3109,19 @@ function buildCreationEvent(args) {
2892
3109
  return `"${declared.label}" declares ${bodyFields.length} fields writing to content (${bodyFields.join(', ')}), and an event has one.`;
2893
3110
  }
2894
3111
  const bodyField = bodyFields[0];
3112
+ const placement = declared.emits.placement ?? 'h';
3113
+ if (!PLACEMENTS.includes(placement)) {
3114
+ return `"${declared.label}" places its object with "${placement}", and a Folder is named by ${PLACEMENTS.join(' or ')}.`;
3115
+ }
3116
+ // Only the content field can be prose, so only its value is ever tagged.
3117
+ const prose = proseTags({
3118
+ label: declared.label,
3119
+ declared: bodyField ? properties[bodyField]?.format : undefined,
3120
+ contentFormat: args.contentFormat,
3121
+ value: bodyField ? (value[bodyField] ?? '') : '',
3122
+ });
3123
+ if (typeof prose === 'string')
3124
+ return prose;
2895
3125
  const tags = [];
2896
3126
  if (isAddressableKind(declared.emits.kind))
2897
3127
  tags.push(['d', newId]);
@@ -2907,7 +3137,7 @@ function buildCreationEvent(args) {
2907
3137
  if (declared.emits.setTag && declared.emits.toAddressOf === 'self') {
2908
3138
  tags.push([declared.emits.setTag, address]);
2909
3139
  }
2910
- tags.push(['h', folder]);
3140
+ tags.push([placement, folder], ...prose);
2911
3141
  return {
2912
3142
  pubkey: args.pubkey,
2913
3143
  created_at: Math.floor(args.createdAtMs / 1000),
@@ -2916,8 +3146,74 @@ function buildCreationEvent(args) {
2916
3146
  content: bodyField ? (value[bodyField] ?? '') : '',
2917
3147
  };
2918
3148
  }
3149
+ /**
3150
+ * Build the event that performs a manifest-declared action — one event.
3151
+ *
3152
+ * **Refuses an action declaring `emits.listed`**, which is more than one event
3153
+ * (SPEC §7.3): building the root alone would publish an object its Folder does
3154
+ * not show, and report success. {@link buildActionEvents} builds those.
3155
+ */
2919
3156
  export function buildActionEvent(args) {
2920
- const { manifest, kind, address, folder, actionId, value } = args;
3157
+ const declared = args.manifest.actions?.find((a) => a.id === args.actionId);
3158
+ if (declared?.emits.listed === true && (declared.emits.kind === KIND_DELETION || isCreationAction(declared))) {
3159
+ return `"${declared.label}" is followed by a Folder command, so it is built with buildActionEvents.`;
3160
+ }
3161
+ return buildOneActionEvent(args);
3162
+ }
3163
+ /** An action that makes a new object rather than changing one — a form. */
3164
+ function isCreationAction(declared) {
3165
+ return declared.input?.type === 'object' && !!declared.input.properties;
3166
+ }
3167
+ /**
3168
+ * Every event an action publishes, **in publish order** — SPEC §7.3, MAN-1.
3169
+ *
3170
+ * The first is what {@link buildActionEvent} builds. An action declaring
3171
+ * `emits.listed` is followed by the Folder commands that keep its Folder's
3172
+ * listing true, planned by `planPlaceFile` / `planUnlistFile`:
3173
+ *
3174
+ * - a creation: `kind:1852 add` naming the new address in the Folder it was
3175
+ * placed in, when `folderHasState` — none when the Folder has no state, where
3176
+ * a command would hide everything else filed there;
3177
+ * - a deletion: `kind:1852 remove` from each of `listedIn` that has state.
3178
+ *
3179
+ * Both facts come from the caller's read of `kind:30890` and are required
3180
+ * rather than defaulted, because a guess here is silent loss. Publish in order
3181
+ * and stop at the first refusal: each event assumes the ones before it landed.
3182
+ */
3183
+ export function buildActionEvents(args) {
3184
+ const first = buildOneActionEvent(args);
3185
+ if (typeof first === 'string')
3186
+ return first;
3187
+ const declared = args.manifest.actions.find((a) => a.id === args.actionId);
3188
+ if (declared.emits.listed !== true)
3189
+ return [first];
3190
+ if (declared.emits.kind === KIND_DELETION) {
3191
+ if (!args.listedIn)
3192
+ return `"${declared.label}" unlists what it deletes, and needs the Folders that list it.`;
3193
+ // One remove per Folder, however many reads it came back from.
3194
+ const folders = [...new Map(args.listedIn.map((listing) => [listing.id, listing])).values()];
3195
+ return [
3196
+ first,
3197
+ ...folders.flatMap((listing) => planUnlistFile(args.pubkey, args.createdAtMs, { folder: listing.id, address: args.address, hasState: listing.hasState })),
3198
+ ];
3199
+ }
3200
+ if (isCreationAction(declared)) {
3201
+ if (args.folderHasState === undefined) {
3202
+ return `"${declared.label}" lists what it creates, and needs to know whether the Folder has state.`;
3203
+ }
3204
+ // A listing names addresses, and an object with no `d` has none.
3205
+ const identifier = first.tags.find((t) => t[0] === 'd')?.[1];
3206
+ if (identifier === undefined) {
3207
+ return `"${declared.label}" lists what it creates, and a kind ${first.kind} has no address to list.`;
3208
+ }
3209
+ const created = pointerToAddress({ kind: first.kind, pubkey: first.pubkey, identifier, relays: [] });
3210
+ return [first, ...planPlaceFile(args.pubkey, args.createdAtMs, { folder: args.folder, address: created, hasState: args.folderHasState })];
3211
+ }
3212
+ // A change or a comment adds nothing to a Folder and removes nothing from it.
3213
+ return [first];
3214
+ }
3215
+ function buildOneActionEvent(args) {
3216
+ const { manifest, kind, address, folder, actionId, value, replyTo } = args;
2921
3217
  const records = manifest.records;
2922
3218
  const declared = manifest.actions?.find((a) => a.id === actionId);
2923
3219
  if (!declared)
@@ -2926,9 +3222,21 @@ export function buildActionEvent(args) {
2926
3222
  if (!appliesTo.includes(String(kind))) {
2927
3223
  return `"${declared.label}" does not apply to a kind ${kind}.`;
2928
3224
  }
3225
+ const isCreation = isCreationAction(declared);
3226
+ // A reply is a comment with a parent — what the scalar path below builds for
3227
+ // an action that is neither a deletion nor a change. Refused here, before any
3228
+ // branch that would build something else and quietly drop the parent.
3229
+ if (replyTo && (isCreation || declared.emits.kind === KIND_DELETION || declared.emits.field)) {
3230
+ return `"${declared.label}" is not a comment, so it cannot reply to one.`;
3231
+ }
3232
+ // Prose is a creation's content or a change's value (§7.3). A deletion has
3233
+ // no value, and a comment's body is §13.2 marker text.
3234
+ if (args.contentFormat !== undefined && !isCreation && (!declared.emits.field || declared.emits.kind === KIND_DELETION)) {
3235
+ return `"${declared.label}" takes no prose value, so it takes no content format.`;
3236
+ }
2929
3237
  // An object-creating action is a different event entirely — a new object
2930
3238
  // rather than a change to one — so it branches before the scalar path.
2931
- if (declared.input?.type === 'object' && declared.input.properties) {
3239
+ if (isCreation) {
2932
3240
  return buildCreationEvent({ ...args, declared, vocabularies: manifest.vocabularies });
2933
3241
  }
2934
3242
  if (typeof value !== 'string') {
@@ -2988,24 +3296,42 @@ export function buildActionEvent(args) {
2988
3296
  return `"${value}" is not one of ${vocab.map((e) => e.value).join(', ')}.`;
2989
3297
  }
2990
3298
  }
3299
+ // A prose value's `content-format` and `imeta` — a change only, per the
3300
+ // refusal above. Ship's order: the tag before `ts`, the files after it.
3301
+ const prose = declared.emits.field
3302
+ ? proseTags({ label: declared.label, declared: declared.input?.format, contentFormat: args.contentFormat, value })
3303
+ : [];
3304
+ if (typeof prose === 'string')
3305
+ return prose;
3306
+ const [formatTag, ...files] = prose;
2991
3307
  const tags = declared.emits.field
2992
3308
  ? [
2993
3309
  [records.targetTag, address],
2994
3310
  [records.fieldTag, declared.emits.field],
2995
3311
  [records.valueTag, value],
2996
3312
  ['h', folder],
3313
+ ...(formatTag ? [formatTag] : []),
2997
3314
  ]
2998
3315
  : // NIP-22 comment. Built from the ratified NIP rather than from the
2999
3316
  // manifest, which is legitimate precisely because no app owns kind:1111 —
3000
3317
  // the same reason the owning app uses it. Uppercase tags name the thread
3001
- // root, lowercase the immediate parent.
3318
+ // root, lowercase the immediate parent: the file again for a top-level
3319
+ // comment, the comment answered for a reply (SPEC §6.4).
3002
3320
  [
3003
3321
  ['A', address],
3004
3322
  ['K', String(kind)],
3005
3323
  ['P', args.objectAuthor],
3006
- ['a', address],
3007
- ['k', String(kind)],
3008
- ['p', args.objectAuthor],
3324
+ ...(replyTo
3325
+ ? [
3326
+ ['e', replyTo.id],
3327
+ ['k', String(replyTo.kind)],
3328
+ ['p', replyTo.author],
3329
+ ]
3330
+ : [
3331
+ ['a', address],
3332
+ ['k', String(kind)],
3333
+ ['p', args.objectAuthor],
3334
+ ]),
3009
3335
  ['h', folder],
3010
3336
  ];
3011
3337
  // The manifest told us how it orders events; write events that can be ordered.
@@ -3014,6 +3340,7 @@ export function buildActionEvent(args) {
3014
3340
  // depending on which app you asked (FRICTION.md A6).
3015
3341
  if (records.order?.includes('ts'))
3016
3342
  tags.push(['ts', String(args.createdAtMs)]);
3343
+ tags.push(...files);
3017
3344
  return {
3018
3345
  pubkey: args.pubkey,
3019
3346
  created_at: Math.floor(args.createdAtMs / 1000),