@estiva-app/interop 0.39.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,22 @@ 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 }
1092
1108
  }
1093
1109
 
1094
1110
  /** How the owning app asks one of its kinds to be drawn (RFC 0.4 §13.3). */
@@ -1736,21 +1752,29 @@ async function resolveAspectApp(
1736
1752
  * without `share` (hand-written, or older) keeps the old behaviour exactly:
1737
1753
  * look up, read, remember.
1738
1754
  */
1739
- async function throughCache(
1755
+ async function throughCache<T extends CachedManifests>(
1740
1756
  cache: ProjectionCache | undefined,
1741
1757
  key: string,
1742
- read: () => Promise<ResolvedManifest | null>,
1743
- ): Promise<ResolvedManifest | null> {
1758
+ read: () => Promise<T>,
1759
+ ): Promise<T> {
1744
1760
  const now = Date.now()
1745
1761
  const memo = cache?.lookup(key, now)
1746
- 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
1747
1764
  if (!cache) return read()
1748
- if (cache.share) return cache.share(key, now, read)
1765
+ if (cache.share) return cache.share(key, now, read) as Promise<T>
1749
1766
  const answer = await read()
1750
1767
  cache.remember(key, answer, now)
1751
1768
  return answer
1752
1769
  }
1753
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
+
1754
1778
  /**
1755
1779
  * A memo for the half of a resolve that does not change between refreshes.
1756
1780
  *
@@ -1775,16 +1799,16 @@ export interface ProjectionCache {
1775
1799
  /** Forget everything. Worth calling after publishing a manifest. */
1776
1800
  clear(): void
1777
1801
  /** @internal */
1778
- lookup(key: string, now: number): { value: ResolvedManifest | null } | undefined
1802
+ lookup(key: string, now: number): { value: CachedManifests } | undefined
1779
1803
  /** @internal */
1780
- remember(key: string, value: ResolvedManifest | null, now: number): void
1804
+ remember(key: string, value: CachedManifests, now: number): void
1781
1805
  /**
1782
1806
  * @internal Run `read` for `key` unless a read for it is already running, in
1783
1807
  * which case join that one; remember the answer as `remember` would. Optional
1784
1808
  * so a hand-written cache still satisfies the interface — without it, a burst
1785
1809
  * of cold resolves asks once each, which is the old behaviour.
1786
1810
  */
1787
- share?(key: string, now: number, read: () => Promise<ResolvedManifest | null>): Promise<ResolvedManifest | null>
1811
+ share?(key: string, now: number, read: () => Promise<CachedManifests>): Promise<CachedManifests>
1788
1812
  }
1789
1813
 
1790
1814
  /**
@@ -1815,8 +1839,8 @@ export const MANIFEST_TTL_MS = 5 * 60_000
1815
1839
  * for the whole window over what may have been one refused request.
1816
1840
  */
1817
1841
  export function createProjectionCache(ttlMs: number = MANIFEST_TTL_MS): ProjectionCache {
1818
- const entries = new Map<string, { at: number; value: ResolvedManifest | null }>()
1819
- 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>>()
1820
1844
  // Bumped by `clear`, so a read that was in flight when a manifest was
1821
1845
  // republished does not write its stale answer back afterwards.
1822
1846
  let generation = 0
@@ -1959,6 +1983,130 @@ async function resolveManifestUncached(
1959
1983
  return null
1960
1984
  }
1961
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
+
1962
2110
  /**
1963
2111
  * Ordering key for an append-only event, per the manifest's `records.order`.
1964
2112
  *
@@ -3070,12 +3218,29 @@ export async function resolveForeignObject(
3070
3218
  const plan = planObject(naddr, pointer, resolved, depth)
3071
3219
  if (!plan) return null
3072
3220
 
3073
- 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)])
3074
3224
  const followUp = childChangeFilters(plan, answered)
3075
3225
  const assembled = assembleObject(plan, answered, followUp.length ? await queryChunked(followUp, query) : [])
3076
3226
  if (assembled.object.unreachable) return assembled.object
3077
3227
  if (options.archivedWith) await markArchivedParents([{ object: assembled.object, manifest: resolved.manifest }], query)
3078
- 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
3079
3244
  }
3080
3245
 
3081
3246
  /**
@@ -3161,7 +3326,14 @@ export async function resolveForeignObjects(
3161
3326
  planned.add(plan.address)
3162
3327
  filters.push(...plan.filters)
3163
3328
  }
3164
- 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]]))
3165
3337
 
3166
3338
  // Every card's children's changes in one more read for the whole set, not
3167
3339
  // one per card (MAN-7) — and none at all when no card has a fold to read.
@@ -3185,7 +3357,7 @@ export async function resolveForeignObjects(
3185
3357
  const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))]
3186
3358
  const reachable = assembled.some(({ built }) => !built.object.unreachable)
3187
3359
  const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {}
3188
- for (const { reference, built } of assembled) {
3360
+ for (const { reference, plan, built } of assembled) {
3189
3361
  if (built.object.unreachable) {
3190
3362
  results[reference] = built.object
3191
3363
  continue
@@ -3195,7 +3367,10 @@ export async function resolveForeignObjects(
3195
3367
  // it happened to be resolved beside.
3196
3368
  const own: People = {}
3197
3369
  for (const key of peopleOf(built)) if (key in people) own[key] = people[key]
3198
- 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
+ )
3199
3374
  }
3200
3375
  return results
3201
3376
  }