@estiva-app/interop 0.38.0 → 0.40.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
@@ -1089,6 +1089,46 @@ export interface ResolvedAction {
1089
1089
  /** The value this field holds right now, so a control can show it. */
1090
1090
  current?: string
1091
1091
  field?: string
1092
+ /**
1093
+ * The app that declared this action, **when it is not the object's own** —
1094
+ * MAN-8.
1095
+ *
1096
+ * Ship declares `add-project` on a Folder, and a Folder is Peek's kind: the
1097
+ * object is drawn by one manifest and the action comes from another. Only a
1098
+ * creation is ever borrowed like this (see {@link creatorsOn}), so this is
1099
+ * set only on a `form`. Absent on every action the owning app declares.
1100
+ *
1101
+ * A consumer acting on it must build with the manifest named here, not the
1102
+ * object's — `buildActionEvents` finds the action by id in the manifest it is
1103
+ * handed, and the owner's has no `add-project`. {@link resolveActingManifest}
1104
+ * is that lookup. `appName` is the declaring app's `name`, for a consumer
1105
+ * that says whose action it is.
1106
+ */
1107
+ declaredBy?: { address: string; appName?: string }
1108
+ }
1109
+
1110
+ /** How the owning app asks one of its kinds to be drawn (RFC 0.4 §13.3). */
1111
+ interface Projection {
1112
+ widget: string | string[]
1113
+ slots: Record<string, SlotSpec | SlotSpec[]>
1114
+ /**
1115
+ * What one of these is called, lower case and singular — "issue",
1116
+ * "project". Resolved onto {@link ForeignObject.noun}; see there.
1117
+ */
1118
+ noun?: string
1119
+ }
1120
+
1121
+ /**
1122
+ * The projection's `noun`, when it is one: a non-empty string, trimmed.
1123
+ *
1124
+ * A manifest is another app's self-description and nothing validates it on
1125
+ * the way in, so `"noun": 5` is publishable. Passed through, it reaches a
1126
+ * consumer typed as a string and breaks there — the first `.charAt` throws
1127
+ * while a menu draws. Anything else reads as "this app does not say" (§7.9).
1128
+ */
1129
+ function nounOf(projection: Projection): { noun?: string } {
1130
+ const noun = typeof projection.noun === 'string' ? projection.noun.trim() : ''
1131
+ return noun ? { noun } : {}
1092
1132
  }
1093
1133
 
1094
1134
  interface Manifest {
@@ -1096,7 +1136,7 @@ interface Manifest {
1096
1136
  about?: string
1097
1137
  actions?: ManifestAction[]
1098
1138
  records?: RecordsRule
1099
- projections?: Record<string, { widget: string | string[]; slots: Record<string, SlotSpec | SlotSpec[]> }>
1139
+ projections?: Record<string, Projection>
1100
1140
  vocabularies?: Record<string, { value: string; label: string; colour: string; stage?: string }[]>
1101
1141
  /**
1102
1142
  * Which aspect of *every* file this app renders — RFC 0.5 §10.7's one
@@ -1712,21 +1752,29 @@ async function resolveAspectApp(
1712
1752
  * without `share` (hand-written, or older) keeps the old behaviour exactly:
1713
1753
  * look up, read, remember.
1714
1754
  */
1715
- async function throughCache(
1755
+ async function throughCache<T extends CachedManifests>(
1716
1756
  cache: ProjectionCache | undefined,
1717
1757
  key: string,
1718
- read: () => Promise<ResolvedManifest | null>,
1719
- ): Promise<ResolvedManifest | null> {
1758
+ read: () => Promise<T>,
1759
+ ): Promise<T> {
1720
1760
  const now = Date.now()
1721
1761
  const memo = cache?.lookup(key, now)
1722
- if (memo) return memo.value
1762
+ // Each key is written by one reader, so what it holds is that reader's `T`.
1763
+ if (memo) return memo.value as T
1723
1764
  if (!cache) return read()
1724
- if (cache.share) return cache.share(key, now, read)
1765
+ if (cache.share) return cache.share(key, now, read) as Promise<T>
1725
1766
  const answer = await read()
1726
1767
  cache.remember(key, answer, now)
1727
1768
  return answer
1728
1769
  }
1729
1770
 
1771
+ /**
1772
+ * What a {@link ProjectionCache} entry holds: one app's manifest, or none — or,
1773
+ * for {@link creatorsOn}, every manifest declaring a creation on one kind
1774
+ * (MAN-8). Still only manifests, which is the whole of the cache's promise.
1775
+ */
1776
+ type CachedManifests = ResolvedManifest | null | readonly ResolvedManifest[]
1777
+
1730
1778
  /**
1731
1779
  * A memo for the half of a resolve that does not change between refreshes.
1732
1780
  *
@@ -1751,16 +1799,16 @@ export interface ProjectionCache {
1751
1799
  /** Forget everything. Worth calling after publishing a manifest. */
1752
1800
  clear(): void
1753
1801
  /** @internal */
1754
- lookup(key: string, now: number): { value: ResolvedManifest | null } | undefined
1802
+ lookup(key: string, now: number): { value: CachedManifests } | undefined
1755
1803
  /** @internal */
1756
- remember(key: string, value: ResolvedManifest | null, now: number): void
1804
+ remember(key: string, value: CachedManifests, now: number): void
1757
1805
  /**
1758
1806
  * @internal Run `read` for `key` unless a read for it is already running, in
1759
1807
  * which case join that one; remember the answer as `remember` would. Optional
1760
1808
  * so a hand-written cache still satisfies the interface — without it, a burst
1761
1809
  * of cold resolves asks once each, which is the old behaviour.
1762
1810
  */
1763
- share?(key: string, now: number, read: () => Promise<ResolvedManifest | null>): Promise<ResolvedManifest | null>
1811
+ share?(key: string, now: number, read: () => Promise<CachedManifests>): Promise<CachedManifests>
1764
1812
  }
1765
1813
 
1766
1814
  /**
@@ -1791,8 +1839,8 @@ export const MANIFEST_TTL_MS = 5 * 60_000
1791
1839
  * for the whole window over what may have been one refused request.
1792
1840
  */
1793
1841
  export function createProjectionCache(ttlMs: number = MANIFEST_TTL_MS): ProjectionCache {
1794
- const entries = new Map<string, { at: number; value: ResolvedManifest | null }>()
1795
- const flights = new Map<string, Promise<ResolvedManifest | null>>()
1842
+ const entries = new Map<string, { at: number; value: CachedManifests }>()
1843
+ const flights = new Map<string, Promise<CachedManifests>>()
1796
1844
  // Bumped by `clear`, so a read that was in flight when a manifest was
1797
1845
  // republished does not write its stale answer back afterwards.
1798
1846
  let generation = 0
@@ -1935,6 +1983,130 @@ async function resolveManifestUncached(
1935
1983
  return null
1936
1984
  }
1937
1985
 
1986
+ /**
1987
+ * Every app that declares a way to **create one of its own kinds on this one**
1988
+ * — MAN-8.
1989
+ *
1990
+ * {@link resolveManifest} answers with one manifest per kind, its owner's, and
1991
+ * the object's actions came from it alone. So an action one app declares on a
1992
+ * kind another app owns was on the relay and unreachable: Ship's `add-project`
1993
+ * says `appliesTo: "39000"`, a Folder is Peek's, and a Folder resolved with
1994
+ * Peek's `start-a-conversation` and nothing else. Measured on production
1995
+ * 2026-09-30 with Peek's own code.
1996
+ *
1997
+ * **Only a creation, and only of a kind the declaring app projects.** That is
1998
+ * the whole of what one app may say about another's kind: "one of mine can be
1999
+ * made here". A field it sets, a comment, a deletion are the owner's to
2000
+ * declare — the owner's `records` rule folds them, and a stranger declaring
2001
+ * `archived` on a Folder would be offering a change nobody folds as it says.
2002
+ * A creation needs nothing from the owner but an object to be made on, and
2003
+ * what it makes is drawn by the app that declared it.
2004
+ *
2005
+ * One read for every kind, the sweep {@link resolveAspectApp} already makes,
2006
+ * because nothing can ask for it by kind: a manifest's `k` tags name what it
2007
+ * draws, and Ship does not draw a Folder. Newest first, and **one manifest per
2008
+ * created kind**: an older manifest declaring the same kind on the same target
2009
+ * is a stale copy of the same claim, and offering both is two "New project"
2010
+ * rows. The owner is filtered out later ({@link borrowedFrom}), because who the
2011
+ * owner is depends on the object's author and this list does not.
2012
+ */
2013
+ async function creatorsOn(kind: number, query: QueryFn, cache?: ProjectionCache): Promise<readonly ResolvedManifest[]> {
2014
+ return throughCache(cache, `creators:${kind}`, async () => {
2015
+ const handlers = await query([{ kinds: [KIND_HANDLER_INFORMATION], limit: HANDLER_SWEEP_LIMIT }])
2016
+ const creators: ResolvedManifest[] = []
2017
+ const claimed = new Set<number>()
2018
+ for (const candidate of [...handlers].sort((a, b) => b.created_at - a.created_at)) {
2019
+ const manifest = parseManifest(candidate)
2020
+ if (!manifest) continue
2021
+ const makes = (manifest.actions ?? []).filter(
2022
+ (action) =>
2023
+ isCreationAction(action) &&
2024
+ asArray(action.appliesTo).includes(String(kind)) &&
2025
+ !!manifest.projections?.[String(action.emits.kind)] &&
2026
+ !claimed.has(action.emits.kind),
2027
+ )
2028
+ if (makes.length === 0) continue
2029
+ for (const action of makes) claimed.add(action.emits.kind)
2030
+ creators.push({
2031
+ // Only the creations: this manifest is what a consumer acts with, and
2032
+ // nothing it was not offered for must be buildable with it.
2033
+ manifest: { ...manifest, actions: makes },
2034
+ address: `${candidate.kind}:${candidate.pubkey}:${tagValue(candidate, 'd') ?? ''}`,
2035
+ viaRecommendation: false,
2036
+ webTemplate: webTemplate(candidate, 'naddr'),
2037
+ })
2038
+ }
2039
+ return creators
2040
+ })
2041
+ }
2042
+
2043
+ /**
2044
+ * {@link creatorsOn} for a read, where a failed sweep is no borrowed actions.
2045
+ *
2046
+ * The sweep is an addition to an object, not part of it: a relay that refuses
2047
+ * it (the meter is 300 reads a minute) must not take down a card whose own
2048
+ * read succeeded. Not remembered — `throughCache` never keeps a failure — so
2049
+ * the next resolve asks again. {@link resolveActingManifest} does not use
2050
+ * this: a write that cannot find its manifest should say so, not act with none.
2051
+ */
2052
+ function creatorsOrNone(kind: number, query: QueryFn, cache?: ProjectionCache): Promise<readonly ResolvedManifest[]> {
2053
+ return creatorsOn(kind, query, cache).catch(() => [])
2054
+ }
2055
+
2056
+ /**
2057
+ * {@link creatorsOn}, less the owner and less anything the owner makes itself.
2058
+ *
2059
+ * The owner's own actions are already on the object. And a kind the owner
2060
+ * creates here is the owner's to offer, so another manifest's claim to create
2061
+ * it — a staging copy of the same app, most likely — is dropped rather than
2062
+ * drawn as a second row.
2063
+ */
2064
+ function borrowedFrom(kind: number, owner: ResolvedManifest, creators: readonly ResolvedManifest[]): ResolvedManifest[] {
2065
+ const ownerMakes = new Set(
2066
+ (owner.manifest.actions ?? [])
2067
+ .filter((action) => isCreationAction(action) && asArray(action.appliesTo).includes(String(kind)))
2068
+ .map((action) => action.emits.kind),
2069
+ )
2070
+ return creators.flatMap((creator) => {
2071
+ if (creator.address === owner.address) return []
2072
+ const actions = (creator.manifest.actions ?? []).filter((action) => !ownerMakes.has(action.emits.kind))
2073
+ return actions.length ? [{ ...creator, manifest: { ...creator.manifest, actions } }] : []
2074
+ })
2075
+ }
2076
+
2077
+ /** Every borrowed creation, resolved as the owner's actions are, with its declaring app named. */
2078
+ function borrowedActions(kind: number, owner: ResolvedManifest, creators: readonly ResolvedManifest[]): ResolvedAction[] {
2079
+ return borrowedFrom(kind, owner, creators).flatMap((creator) =>
2080
+ resolveActions(creator.manifest, kind, {}).map((action) => ({
2081
+ ...action,
2082
+ declaredBy: { address: creator.address, ...(creator.manifest.name ? { appName: creator.manifest.name } : {}) },
2083
+ })),
2084
+ )
2085
+ }
2086
+
2087
+ /**
2088
+ * The manifest to build an action with — the object's own, or the one named by
2089
+ * the action's {@link ResolvedAction.declaredBy} (MAN-8).
2090
+ *
2091
+ * `declaredBy` omitted, or naming the owner, is exactly {@link resolveManifest}.
2092
+ * Otherwise the answer is that manifest **only if resolving the object would
2093
+ * have offered the action from it** — the same sweep, the same filtering — and
2094
+ * null if not. So a caller cannot act on a Folder with an arbitrary manifest by
2095
+ * naming its address; it can only act with one this module found declaring a
2096
+ * creation there. The manifest returned holds only those creations.
2097
+ */
2098
+ export async function resolveActingManifest(
2099
+ pointer: AddressPointer,
2100
+ declaredBy: string | undefined,
2101
+ query: QueryFn,
2102
+ cache?: ProjectionCache,
2103
+ ): Promise<ResolvedManifest | null> {
2104
+ const owner = await resolveManifest(pointer, query, cache)
2105
+ if (!owner || !declaredBy || declaredBy === owner.address) return owner
2106
+ const creators = await creatorsOn(pointer.kind, query, cache)
2107
+ return borrowedFrom(pointer.kind, owner, creators).find((creator) => creator.address === declaredBy) ?? null
2108
+ }
2109
+
1938
2110
  /**
1939
2111
  * Ordering key for an append-only event, per the manifest's `records.order`.
1940
2112
  *
@@ -2785,6 +2957,18 @@ export interface ForeignObject {
2785
2957
  */
2786
2958
  widget: string | string[]
2787
2959
  appName?: string
2960
+ /**
2961
+ * What the owning app calls one of these — "issue", "project" — read off
2962
+ * its projection's `noun`, lower case and singular (PEE-41).
2963
+ *
2964
+ * For a consumer that names the object in its own words: a menu's "Delete
2965
+ * issue", a confirm's "Delete this project?". Without it Peek called a Ship
2966
+ * issue a topic, because the only way to know better was to check the kind
2967
+ * number, which is the check a manifest exists to replace. Absent when the
2968
+ * owner declares none, and for the bare file, whose manifest lives here: a
2969
+ * consumer says its own word for a file nobody owns.
2970
+ */
2971
+ noun?: string
2788
2972
  /** Named single slots: title, subtitle, status. */
2789
2973
  slots: Record<string, ResolvedSlot>
2790
2974
  /** Repeating slots, e.g. `meta`. */
@@ -2859,7 +3043,7 @@ function buildObject(args: {
2859
3043
  root: SignedEvent
2860
3044
  pointer: AddressPointer
2861
3045
  manifest: Manifest
2862
- projection: { widget: string | string[]; slots: Record<string, SlotSpec | SlotSpec[]> }
3046
+ projection: Projection
2863
3047
  folded: Record<string, { value: string; format?: ContentFormat }>
2864
3048
  viaRecommendation: boolean
2865
3049
  webTemplate?: string
@@ -2900,6 +3084,7 @@ function buildObject(args: {
2900
3084
  kind: pointer.kind,
2901
3085
  widget: projection.widget,
2902
3086
  appName: manifest.name,
3087
+ ...nounOf(projection),
2903
3088
  slots,
2904
3089
  meta,
2905
3090
  comments: args.comments ?? [],
@@ -3033,12 +3218,29 @@ export async function resolveForeignObject(
3033
3218
  const plan = planObject(naddr, pointer, resolved, depth)
3034
3219
  if (!plan) return null
3035
3220
 
3036
- const answered = await query(plan.filters)
3221
+ // Beside the object's own read, not after it: the sweep is cached, and cold
3222
+ // it would otherwise add a round trip to every resolve that pays for it.
3223
+ const [answered, creators] = await Promise.all([query(plan.filters), creatorsOrNone(pointer.kind, query, cache)])
3037
3224
  const followUp = childChangeFilters(plan, answered)
3038
3225
  const assembled = assembleObject(plan, answered, followUp.length ? await queryChunked(followUp, query) : [])
3039
3226
  if (assembled.object.unreachable) return assembled.object
3040
3227
  if (options.archivedWith) await markArchivedParents([{ object: assembled.object, manifest: resolved.manifest }], query)
3041
- return withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled)))
3228
+ return withBorrowed(
3229
+ withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled))),
3230
+ borrowedActions(pointer.kind, resolved, creators),
3231
+ )
3232
+ }
3233
+
3234
+ /**
3235
+ * The object's own actions, then the ones other apps declare on it (MAN-8).
3236
+ *
3237
+ * The object's only, not its children's: a child is drawn inside its parent's
3238
+ * card, and a creation offered on every issue in a project's list is a form
3239
+ * nobody opens from there. An unreachable object gets none either — it has no
3240
+ * Folder to create anything in.
3241
+ */
3242
+ function withBorrowed(object: ForeignObject, borrowed: ResolvedAction[]): ForeignObject {
3243
+ return borrowed.length ? { ...object, actions: [...object.actions, ...borrowed] } : object
3042
3244
  }
3043
3245
 
3044
3246
  /**
@@ -3124,7 +3326,14 @@ export async function resolveForeignObjects(
3124
3326
  planned.add(plan.address)
3125
3327
  filters.push(...plan.filters)
3126
3328
  }
3127
- const events = await queryChunked(filters, query)
3329
+ // Who else creates on each kind in the set (MAN-8): one sweep per kind, not
3330
+ // per object, read beside the objects themselves.
3331
+ const kinds = [...new Set(plans.map(({ plan }) => plan.pointer.kind))]
3332
+ const [events, creatorLists] = await Promise.all([
3333
+ queryChunked(filters, query),
3334
+ Promise.all(kinds.map((kind) => creatorsOrNone(kind, query, cache))),
3335
+ ])
3336
+ const creatorsByKind = new Map(kinds.map((kind, i) => [kind, creatorLists[i]]))
3128
3337
 
3129
3338
  // Every card's children's changes in one more read for the whole set, not
3130
3339
  // one per card (MAN-7) — and none at all when no card has a fold to read.
@@ -3148,7 +3357,7 @@ export async function resolveForeignObjects(
3148
3357
  const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))]
3149
3358
  const reachable = assembled.some(({ built }) => !built.object.unreachable)
3150
3359
  const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {}
3151
- for (const { reference, built } of assembled) {
3360
+ for (const { reference, plan, built } of assembled) {
3152
3361
  if (built.object.unreachable) {
3153
3362
  results[reference] = built.object
3154
3363
  continue
@@ -3158,7 +3367,10 @@ export async function resolveForeignObjects(
3158
3367
  // it happened to be resolved beside.
3159
3368
  const own: People = {}
3160
3369
  for (const key of peopleOf(built)) if (key in people) own[key] = people[key]
3161
- results[reference] = withPeople(built, own)
3370
+ results[reference] = withBorrowed(
3371
+ withPeople(built, own),
3372
+ borrowedActions(plan.pointer.kind, plan.resolved, creatorsByKind.get(plan.pointer.kind) ?? []),
3373
+ )
3162
3374
  }
3163
3375
  return results
3164
3376
  }
@@ -3289,7 +3501,7 @@ interface ObjectPlan {
3289
3501
  pointer: AddressPointer
3290
3502
  address: string
3291
3503
  resolved: ResolvedManifest
3292
- projection: { widget: string | string[]; slots: Record<string, SlotSpec | SlotSpec[]> }
3504
+ projection: Projection
3293
3505
  records: RecordsRule
3294
3506
  commentKinds: number[]
3295
3507
  childFilter: ReturnType<typeof childFilterFor>
@@ -3391,6 +3603,7 @@ function assembleObject(plan: ObjectPlan, answered: SignedEvent[], childChanges:
3391
3603
  kind: pointer.kind,
3392
3604
  widget: projection.widget,
3393
3605
  appName: manifest.name,
3606
+ ...nounOf(projection),
3394
3607
  slots: {},
3395
3608
  meta: [],
3396
3609
  comments: [],
@@ -3619,7 +3832,7 @@ function listsChildrenOf(
3619
3832
  }
3620
3833
 
3621
3834
  function childFilterFor(args: {
3622
- projection: { widget: string | string[]; slots: Record<string, SlotSpec | SlotSpec[]> }
3835
+ projection: Projection
3623
3836
  manifest: Manifest
3624
3837
  pointer: AddressPointer
3625
3838
  depth: number
@@ -3781,7 +3994,7 @@ const CHILD_CHANGE_GROUP = 10
3781
3994
  function buildChildObject(args: {
3782
3995
  root: SignedEvent
3783
3996
  manifest: Manifest
3784
- projection: { widget: string | string[]; slots: Record<string, SlotSpec | SlotSpec[]> }
3997
+ projection: Projection
3785
3998
  records: RecordsRule
3786
3999
  webTemplate?: string
3787
4000
  viaRecommendation: boolean
@@ -3823,6 +4036,7 @@ function buildChildObject(args: {
3823
4036
  kind: root.kind,
3824
4037
  widget: projection.widget,
3825
4038
  appName: manifest.name,
4039
+ ...nounOf(projection),
3826
4040
  slots,
3827
4041
  meta,
3828
4042
  comments: [],