@941design/marmot 0.0.0-stage → 0.2.0-alpha.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.
Files changed (206) hide show
  1. package/CHANGELOG.md +739 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +190 -0
  25. package/dist/account/teardown.js +878 -0
  26. package/dist/client/admission-cleanup.d.ts +197 -0
  27. package/dist/client/admission-cleanup.js +635 -0
  28. package/dist/client/adoption-proof.d.ts +39 -0
  29. package/dist/client/adoption-proof.js +102 -0
  30. package/dist/client/before-create-group.d.ts +18 -0
  31. package/dist/client/before-create-group.js +65 -0
  32. package/dist/client/before-publish-hooks.d.ts +121 -0
  33. package/dist/client/before-publish-hooks.js +182 -0
  34. package/dist/client/client-config.d.ts +42 -0
  35. package/dist/client/client-config.js +13 -0
  36. package/dist/client/commit-redrive.d.ts +92 -0
  37. package/dist/client/commit-redrive.js +274 -0
  38. package/dist/client/component-update.d.ts +43 -0
  39. package/dist/client/component-update.js +53 -0
  40. package/dist/client/confirm-hooks.d.ts +55 -0
  41. package/dist/client/confirm-hooks.js +74 -0
  42. package/dist/client/create-client.d.ts +1126 -0
  43. package/dist/client/create-client.js +1232 -0
  44. package/dist/client/group-availability.d.ts +182 -0
  45. package/dist/client/group-availability.js +301 -0
  46. package/dist/client/group-disband.d.ts +28 -0
  47. package/dist/client/group-disband.js +64 -0
  48. package/dist/client/group-history.d.ts +461 -0
  49. package/dist/client/group-history.js +1365 -0
  50. package/dist/client/group-profile.d.ts +31 -0
  51. package/dist/client/group-profile.js +62 -0
  52. package/dist/client/group-records.d.ts +522 -0
  53. package/dist/client/group-records.js +1117 -0
  54. package/dist/client/group-removal.d.ts +36 -0
  55. package/dist/client/group-removal.js +127 -0
  56. package/dist/client/group-remove-member.d.ts +49 -0
  57. package/dist/client/group-remove-member.js +163 -0
  58. package/dist/client/group-runtime.d.ts +415 -0
  59. package/dist/client/group-runtime.js +2811 -0
  60. package/dist/client/group-snapshot.d.ts +104 -0
  61. package/dist/client/group-snapshot.js +474 -0
  62. package/dist/client/history-pages.d.ts +107 -0
  63. package/dist/client/history-pages.js +194 -0
  64. package/dist/client/inbox-send.d.ts +19 -0
  65. package/dist/client/inbox-send.js +71 -0
  66. package/dist/client/index.d.ts +24 -0
  67. package/dist/client/index.js +13 -0
  68. package/dist/client/ingest.d.ts +82 -0
  69. package/dist/client/ingest.js +1584 -0
  70. package/dist/client/invitation-outcomes.d.ts +50 -0
  71. package/dist/client/invitation-outcomes.js +135 -0
  72. package/dist/client/lifecycle-events.d.ts +63 -0
  73. package/dist/client/lifecycle-events.js +35 -0
  74. package/dist/client/opaque-candidates.d.ts +82 -0
  75. package/dist/client/opaque-candidates.js +170 -0
  76. package/dist/client/own-change-outbox.d.ts +66 -0
  77. package/dist/client/own-change-outbox.js +158 -0
  78. package/dist/client/pending-leaf.d.ts +116 -0
  79. package/dist/client/pending-leaf.js +378 -0
  80. package/dist/client/permissions.d.ts +9 -0
  81. package/dist/client/permissions.js +12 -0
  82. package/dist/client/pipeline.d.ts +583 -0
  83. package/dist/client/pipeline.js +3666 -0
  84. package/dist/client/reentrancy-guard.d.ts +102 -0
  85. package/dist/client/reentrancy-guard.js +159 -0
  86. package/dist/client/rekey.d.ts +58 -0
  87. package/dist/client/rekey.js +149 -0
  88. package/dist/client/transport-policy.d.ts +181 -0
  89. package/dist/client/transport-policy.js +214 -0
  90. package/dist/history/admission-lineage.d.ts +186 -0
  91. package/dist/history/admission-lineage.js +589 -0
  92. package/dist/history/equivocation.d.ts +55 -0
  93. package/dist/history/equivocation.js +113 -0
  94. package/dist/history/fencing.d.ts +66 -0
  95. package/dist/history/fencing.js +121 -0
  96. package/dist/history/hex.d.ts +3 -0
  97. package/dist/history/hex.js +10 -0
  98. package/dist/history/index.d.ts +74 -0
  99. package/dist/history/index.js +32 -0
  100. package/dist/history/notifications.d.ts +270 -0
  101. package/dist/history/notifications.js +264 -0
  102. package/dist/history/ordering-key.d.ts +24 -0
  103. package/dist/history/ordering-key.js +101 -0
  104. package/dist/history/own-change-fork.d.ts +112 -0
  105. package/dist/history/own-change-fork.js +196 -0
  106. package/dist/history/own-change.d.ts +118 -0
  107. package/dist/history/own-change.js +146 -0
  108. package/dist/history/policy.d.ts +48 -0
  109. package/dist/history/policy.js +52 -0
  110. package/dist/history/retained-window.d.ts +215 -0
  111. package/dist/history/retained-window.js +565 -0
  112. package/dist/inbox/demux.d.ts +90 -0
  113. package/dist/inbox/demux.js +78 -0
  114. package/dist/inbox/handler-registry.d.ts +42 -0
  115. package/dist/inbox/handler-registry.js +37 -0
  116. package/dist/inbox/index.d.ts +11 -0
  117. package/dist/inbox/index.js +10 -0
  118. package/dist/inbox/seen-set.d.ts +82 -0
  119. package/dist/inbox/seen-set.js +202 -0
  120. package/dist/inbox/subscription.d.ts +236 -0
  121. package/dist/inbox/subscription.js +644 -0
  122. package/dist/index.d.ts +10 -0
  123. package/dist/index.js +9 -0
  124. package/dist/invitations/competing-welcome.d.ts +223 -0
  125. package/dist/invitations/competing-welcome.js +128 -0
  126. package/dist/invitations/decline.d.ts +67 -0
  127. package/dist/invitations/decline.js +149 -0
  128. package/dist/invitations/delivery-evidence.d.ts +288 -0
  129. package/dist/invitations/delivery-evidence.js +766 -0
  130. package/dist/invitations/expect-welcome.d.ts +66 -0
  131. package/dist/invitations/expect-welcome.js +138 -0
  132. package/dist/invitations/index.d.ts +18 -0
  133. package/dist/invitations/index.js +18 -0
  134. package/dist/invitations/invitation-outcome.d.ts +110 -0
  135. package/dist/invitations/invitation-outcome.js +210 -0
  136. package/dist/invitations/invite.d.ts +358 -0
  137. package/dist/invitations/invite.js +1102 -0
  138. package/dist/invitations/offers.d.ts +79 -0
  139. package/dist/invitations/offers.js +115 -0
  140. package/dist/invitations/on-proposal.d.ts +47 -0
  141. package/dist/invitations/on-proposal.js +40 -0
  142. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  143. package/dist/invitations/pending-proposal-policy.js +139 -0
  144. package/dist/invitations/proposal-deadline.d.ts +133 -0
  145. package/dist/invitations/proposal-deadline.js +164 -0
  146. package/dist/invitations/relay-planes.d.ts +43 -0
  147. package/dist/invitations/relay-planes.js +70 -0
  148. package/dist/invitations/welcome-processor.d.ts +272 -0
  149. package/dist/invitations/welcome-processor.js +1241 -0
  150. package/dist/key-packages/device-key.d.ts +131 -0
  151. package/dist/key-packages/device-key.js +272 -0
  152. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  153. package/dist/key-packages/device-rotation-records.js +173 -0
  154. package/dist/key-packages/group-refs.d.ts +40 -0
  155. package/dist/key-packages/group-refs.js +79 -0
  156. package/dist/key-packages/index.d.ts +18 -0
  157. package/dist/key-packages/index.js +18 -0
  158. package/dist/key-packages/key-package-ref.d.ts +16 -0
  159. package/dist/key-packages/key-package-ref.js +21 -0
  160. package/dist/key-packages/observation-stream.d.ts +4 -0
  161. package/dist/key-packages/observation-stream.js +120 -0
  162. package/dist/key-packages/offer-rumor.d.ts +26 -0
  163. package/dist/key-packages/offer-rumor.js +69 -0
  164. package/dist/key-packages/publisher.d.ts +174 -0
  165. package/dist/key-packages/publisher.js +1247 -0
  166. package/dist/key-packages/select-key-package.d.ts +24 -0
  167. package/dist/key-packages/select-key-package.js +90 -0
  168. package/dist/key-packages/slot-manager.d.ts +167 -0
  169. package/dist/key-packages/slot-manager.js +327 -0
  170. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  171. package/dist/key-packages/validate-key-package-event.js +49 -0
  172. package/dist/media/cache.d.ts +14 -0
  173. package/dist/media/cache.js +10 -0
  174. package/dist/media/index.d.ts +52 -0
  175. package/dist/media/index.js +71 -0
  176. package/dist/mls.d.ts +15 -0
  177. package/dist/mls.js +15 -0
  178. package/dist/shared/account-pubkey.d.ts +4 -0
  179. package/dist/shared/account-pubkey.js +10 -0
  180. package/dist/shared/errors.d.ts +28 -0
  181. package/dist/shared/errors.js +96 -0
  182. package/dist/shared/hex.d.ts +4 -0
  183. package/dist/shared/hex.js +13 -0
  184. package/dist/shared/index.d.ts +14 -0
  185. package/dist/shared/index.js +14 -0
  186. package/dist/shared/kinds.d.ts +8 -0
  187. package/dist/shared/kinds.js +28 -0
  188. package/dist/shared/publish-classification.d.ts +26 -0
  189. package/dist/shared/publish-classification.js +31 -0
  190. package/dist/storage/envelope.d.ts +39 -0
  191. package/dist/storage/envelope.js +201 -0
  192. package/dist/storage/index.d.ts +237 -0
  193. package/dist/storage/index.js +491 -0
  194. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  195. package/dist/storage/indexeddb/idb-types.js +1 -0
  196. package/dist/storage/indexeddb/index.d.ts +17 -0
  197. package/dist/storage/indexeddb/index.js +141 -0
  198. package/dist/storage/lease.d.ts +54 -0
  199. package/dist/storage/lease.js +168 -0
  200. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  201. package/dist/storage/memory/deterministic-signer.js +65 -0
  202. package/dist/storage/memory/index.d.ts +32 -0
  203. package/dist/storage/memory/index.js +87 -0
  204. package/dist/storage/memory/lock-manager.d.ts +8 -0
  205. package/dist/storage/memory/lock-manager.js +71 -0
  206. package/package.json +66 -3
@@ -0,0 +1,78 @@
1
+ import { isMarmotError, MarmotError, RUMOR_KINDS } from '../shared/index.js';
2
+ import { classifyUnwrapFailure, HANDLER_FAILED_REASON } from './subscription.js';
3
+ const NATIVE_KINDS = new Set([RUMOR_KINDS.ENROLMENT_REQUEST, RUMOR_KINDS.KEYPACKAGE_OFFER]);
4
+ /** A deep-frozen copy (the fields as unwrapped; a consumer cannot mutate what the inbox still holds). */
5
+ function frozenCopy(event) {
6
+ return Object.freeze({ ...event, tags: Object.freeze(event.tags.map((tag) => Object.freeze([...tag]))) });
7
+ }
8
+ export function createRumorDemux(deps) {
9
+ const native = new Map();
10
+ async function deliver(surface, handler, rumor, wrap) {
11
+ if (deps.isDisposed())
12
+ throw new MarmotError('disposed', 'inbox: client has been disposed');
13
+ const rumorCopy = frozenCopy(rumor);
14
+ const wrapCopy = frozenCopy(wrap);
15
+ const budget = deps.handlerBudget;
16
+ const slowTimer = budget === undefined || budget.ms <= 0
17
+ ? undefined
18
+ : budget.timers.set(() => {
19
+ if (deps.isDisposed())
20
+ return;
21
+ try {
22
+ budget.onSlow({ surface, rumorKind: rumor.kind, wrapId: wrap.id, budgetMs: budget.ms });
23
+ }
24
+ catch {
25
+ // A diagnostic never breaks the delivery.
26
+ }
27
+ }, budget.ms);
28
+ try {
29
+ await deps.callConsumer(surface, () => handler(rumorCopy, wrapCopy));
30
+ }
31
+ catch {
32
+ // Disposed meanwhile: nothing is recorded, the next client redelivers it uncounted.
33
+ if (deps.isDisposed())
34
+ throw new MarmotError('disposed', 'inbox: client has been disposed');
35
+ return { kind: 'deferred', reason: HANDLER_FAILED_REASON, counted: true };
36
+ }
37
+ finally {
38
+ if (slowTimer !== undefined)
39
+ budget.timers.clear(slowTimer);
40
+ }
41
+ return { kind: 'delivered', rumorKind: rumor.kind, to: surface === 'inboxHandler' ? 'handler' : 'application' };
42
+ }
43
+ return {
44
+ async dispatch(rumor, wrap, ctx) {
45
+ if (rumor.kind === RUMOR_KINDS.WELCOME)
46
+ return deps.welcome(rumor, wrap, ctx);
47
+ if (rumor.kind === RUMOR_KINDS.DECLINE && deps.decline !== undefined) {
48
+ try {
49
+ await deps.decline(rumor);
50
+ }
51
+ catch (error) {
52
+ if (deps.isDisposed() || isMarmotError(error, 'disposed'))
53
+ throw new MarmotError('disposed', 'inbox: client has been disposed');
54
+ if (classifyUnwrapFailure(error).kind === 'deferred')
55
+ return { kind: 'deferred', reason: 'decline-bookkeeping' };
56
+ }
57
+ }
58
+ if (NATIVE_KINDS.has(rumor.kind)) {
59
+ const handler = native.get(rumor.kind);
60
+ return handler === undefined ? { kind: 'unhandled', rumorKind: rumor.kind } : handler(rumor, wrap, ctx);
61
+ }
62
+ const claimed = deps.handlers.get(rumor.kind);
63
+ if (claimed !== undefined)
64
+ return deliver('inboxHandler', claimed, rumor, wrap);
65
+ if (deps.application !== undefined)
66
+ return deliver('onApplicationRumor', deps.application, rumor, wrap);
67
+ return { kind: 'unhandled', rumorKind: rumor.kind };
68
+ },
69
+ setNativeHandler(kind, handler) {
70
+ if (!NATIVE_KINDS.has(kind))
71
+ throw new MarmotError('invalid-options', `inbox: kind ${kind} has no native handler slot`);
72
+ if (handler === undefined)
73
+ native.delete(kind);
74
+ else
75
+ native.set(kind, handler);
76
+ },
77
+ };
78
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `registerInboxHandler(kind, handler)` (S7, AC-INBOX-5): the consumer-claimed
3
+ * rumor kinds of the account inbox. A registered handler receives every rumor
4
+ * of its kind instead of `onApplicationRumor` (the demux, `demux.ts`, looks it
5
+ * up per rumor). This is how `account-sync` receives its bootstrap blobs.
6
+ *
7
+ * - The four `RUMOR_KINDS` values (AC-API-8) are `marmot`'s own and refused
8
+ * with `reserved-kind` — checked first, whatever else is registered.
9
+ * - A second registration for a kind already claimed throws `handler-exists`
10
+ * and leaves the first handler in place (it is never silently replaced).
11
+ * - The returned function unregisters exactly that registration (idempotent;
12
+ * a no-op once the kind was re-registered by someone else).
13
+ *
14
+ * Per-instance state only (one registry per client, INV-NO-SINGLETONS).
15
+ */
16
+ import type { NostrEvent, Rumor } from '@941design/nostr-events/event';
17
+ /**
18
+ * A consumer callback for inbox rumors (a registered handler, or
19
+ * `onApplicationRumor`). It receives the rumor exactly as unwrapped and the
20
+ * kind-1059 wrap that carried it (both frozen copies).
21
+ *
22
+ * Delivery is at-least-once: the wrap is marked seen only after the returned
23
+ * promise resolves, so a crash (or reload) in between, or the wrap's id being
24
+ * evicted from the bounded seen-set (AC-INBOX-4), redelivers the same rumor —
25
+ * handlers MUST tolerate redelivery (dedupe by `rumor.id`). A throw (or
26
+ * rejection) defers the wrap: it is retried by later inbox passes and, after
27
+ * the inbox's processing-failure cap, dropped as `rejected('processing-failed')`.
28
+ *
29
+ * It runs on the inbox queue and blocks all inbox dispatch until it settles:
30
+ * never await `group.send` or other long work — persist and return, or
31
+ * fire-and-forget.
32
+ */
33
+ export type InboxRumorHandler = (rumor: Rumor, wrap: NostrEvent) => void | Promise<void>;
34
+ /** Whether `kind` is one of the AC-API-8 constants `marmot` handles itself. */
35
+ export declare function isReservedRumorKind(kind: number): boolean;
36
+ export interface InboxHandlerRegistry {
37
+ /** Claims `kind` for `handler`; throws `invalid-options`, `reserved-kind` or `handler-exists`. Returns the unregister function. */
38
+ register(kind: number, handler: InboxRumorHandler): () => void;
39
+ /** The handler registered for `kind`, if any. */
40
+ get(kind: number): InboxRumorHandler | undefined;
41
+ }
42
+ export declare function createInboxHandlerRegistry(): InboxHandlerRegistry;
@@ -0,0 +1,37 @@
1
+ import { MarmotError, RUMOR_KINDS } from '../shared/index.js';
2
+ /** Largest kind a Nostr event can carry (NIP-01: kinds are 0..65535). */
3
+ const MAX_KIND = 65_535;
4
+ const RESERVED_KINDS = new Set(Object.values(RUMOR_KINDS));
5
+ /** Whether `kind` is one of the AC-API-8 constants `marmot` handles itself. */
6
+ export function isReservedRumorKind(kind) {
7
+ return RESERVED_KINDS.has(kind);
8
+ }
9
+ export function createInboxHandlerRegistry() {
10
+ // Keyed by kind; the value is a per-registration entry so an unregister of a
11
+ // replaced registration cannot remove its successor.
12
+ const handlers = new Map();
13
+ return {
14
+ register(kind, handler) {
15
+ if (typeof kind !== 'number' || !Number.isInteger(kind) || kind < 0 || kind > MAX_KIND) {
16
+ throw new MarmotError('invalid-options', `registerInboxHandler: kind must be an integer in [0, ${MAX_KIND}] (got ${JSON.stringify(kind)})`);
17
+ }
18
+ if (typeof handler !== 'function')
19
+ throw new MarmotError('invalid-options', 'registerInboxHandler: handler must be a function');
20
+ if (isReservedRumorKind(kind)) {
21
+ throw new MarmotError('reserved-kind', `registerInboxHandler: kind ${kind} is a marmot rumor kind (RUMOR_KINDS) and cannot be claimed`, { details: { kind } });
22
+ }
23
+ if (handlers.has(kind)) {
24
+ throw new MarmotError('handler-exists', `registerInboxHandler: a handler for kind ${kind} is already registered`, { details: { kind } });
25
+ }
26
+ const entry = { handler };
27
+ handlers.set(kind, entry);
28
+ return () => {
29
+ if (handlers.get(kind) === entry)
30
+ handlers.delete(kind);
31
+ };
32
+ },
33
+ get(kind) {
34
+ return handlers.get(kind)?.handler;
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `inbox` module barrel (S6: the single kind-1059 subscription and the
3
+ * bounded seen-set; S7: the demux and the `registerInboxHandler` registry).
4
+ * The in-repo seam `client` and `invitations` import through.
5
+ */
6
+ export { classifyUnwrapFailure, maintenanceFailureReason, createInboxSubscription, GIFT_WRAP_KIND, INBOX_BACKFILL_OVERLAP_S, INBOX_LIVE_COVERS_MAX_AGE_S, type DispatchContext, type InboxDisposition, type InboxSubscription, type InboxSubscriptionDeps, type RumorDisposition, } from './subscription.js';
7
+ export { type BackfillContinuation } from './seen-set.js';
8
+ export { readBackfillContinuation } from './seen-set.js';
9
+ export { DEFAULT_SEEN_SET_CAP, isSeen, markSeen, readInboxFloor, seenSetSize, writeInboxFloor } from './seen-set.js';
10
+ export { createRumorDemux, type InboxConsumerSurface, type NativeRumorHandler, type NativeRumorKind, type RumorDemux, type RumorDemuxDeps } from './demux.js';
11
+ export { createInboxHandlerRegistry, isReservedRumorKind, type InboxHandlerRegistry, type InboxRumorHandler } from './handler-registry.js';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `inbox` module barrel (S6: the single kind-1059 subscription and the
3
+ * bounded seen-set; S7: the demux and the `registerInboxHandler` registry).
4
+ * The in-repo seam `client` and `invitations` import through.
5
+ */
6
+ export { classifyUnwrapFailure, maintenanceFailureReason, createInboxSubscription, GIFT_WRAP_KIND, INBOX_BACKFILL_OVERLAP_S, INBOX_LIVE_COVERS_MAX_AGE_S, } from './subscription.js';
7
+ export { readBackfillContinuation } from './seen-set.js';
8
+ export { DEFAULT_SEEN_SET_CAP, isSeen, markSeen, readInboxFloor, seenSetSize, writeInboxFloor } from './seen-set.js';
9
+ export { createRumorDemux } from './demux.js';
10
+ export { createInboxHandlerRegistry, isReservedRumorKind } from './handler-registry.js';
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Codec of the account `inboxSeenSet` artifact (S6, AC-INBOX-3/4): the
3
+ * persisted, bounded set of kind-1059 wrap ids the inbox has finished with.
4
+ * Pure `KeyValueView` helpers — call them on a transaction's `tx` view.
5
+ *
6
+ * A FIFO over three key families, so an insert and its eviction cost O(1)
7
+ * reads and writes whatever the cap (no `keys()` scan):
8
+ *
9
+ * - `meta` — `{ v: 1, head, next, floor? }`: live sequence numbers
10
+ * are `[head, next)`; `floor` is the inbox backfill's
11
+ * `since` (unix seconds), kept here because the
12
+ * account artifact set (AC-STORE-9) has no other home
13
+ * for inbox state;
14
+ * - `w:<wrapId>` — `{ seq }`, the membership test;
15
+ * - `s:<seq>` — the wrap id at that position (seq zero-padded, so
16
+ * keys also sort in insertion order);
17
+ * - `d:<wrapId>` — a wrap whose last attempt was `deferred` (the event,
18
+ * its attempt count, and — for a counted
19
+ * `handler-failed` deferral only — the unwrapped rumor):
20
+ * retried by every pass, also after a reload, and
21
+ * holding the backfill floor below its `created_at`.
22
+ * `markSeen` clears it.
23
+ *
24
+ * `markSeen` appends at `next` and then evicts from `head` while the set
25
+ * holds more than `cap` ids: the oldest id goes first (AC-INBOX-4). An
26
+ * evicted id may be delivered and decrypted again; the Welcome path then
27
+ * recognises it by its Welcome identity (`already-member`), not by the wrap.
28
+ */
29
+ import { type NostrEvent, type Rumor } from '@941design/nostr-events/event';
30
+ import type { KeyValueView } from '../storage/index.js';
31
+ /** Default `seenSetCap` (AC-INBOX-4). */
32
+ export declare const DEFAULT_SEEN_SET_CAP = 10000;
33
+ /**
34
+ * An inbox backfill cut off by the page bound: every wrap above `until` was
35
+ * fetched FROM `relays` (sorted); the next pass on the same relays walks
36
+ * `[floor, until]`. `startedAt` (unix seconds) is when the walk began — the
37
+ * floor it earns once complete. A pass on other relays discards it.
38
+ */
39
+ export interface BackfillContinuation {
40
+ readonly until: number;
41
+ readonly startedAt: number;
42
+ readonly relays: readonly string[];
43
+ }
44
+ /** Whether `wrapId` is in the seen-set. */
45
+ export declare function isSeen(view: KeyValueView, wrapId: string): Promise<boolean>;
46
+ /** Number of ids the seen-set holds. */
47
+ export declare function seenSetSize(view: KeyValueView): Promise<number>;
48
+ /**
49
+ * Adds `wrapId` (a no-op when present) and evicts the oldest ids until at
50
+ * most `cap` remain. Returns the evicted ids, oldest first.
51
+ */
52
+ export declare function markSeen(view: KeyValueView, wrapId: string, cap: number): Promise<string[]>;
53
+ /** The inbox backfill's `since` floor (unix seconds), if one was recorded. */
54
+ export declare function readInboxFloor(view: KeyValueView): Promise<number | undefined>;
55
+ /** Records the backfill floor (the caller computes it; it may move down, e.g. below a deferred wrap). */
56
+ export declare function writeInboxFloor(view: KeyValueView, floor: number): Promise<void>;
57
+ /** The unfinished backfill walk, if any. */
58
+ export declare function readBackfillContinuation(view: KeyValueView): Promise<BackfillContinuation | undefined>;
59
+ /** Records (or, with `undefined`, clears) the unfinished backfill walk. */
60
+ export declare function writeBackfillContinuation(view: KeyValueView, resume: BackfillContinuation | undefined): Promise<void>;
61
+ export interface DeferredWrap {
62
+ readonly wrap: NostrEvent;
63
+ /** Deferrals so far whose cause was not a transient one (they count toward the retry cap). */
64
+ readonly failures: number;
65
+ /**
66
+ * handler-retry-reunwraps-wrap: the wrap's unwrapped rumor, kept with a COUNTED `handler-failed` deferral only (a
67
+ * consumer handler threw), so the retry redispatches it without asking the account signer to unwrap again. The
68
+ * same at-rest posture as a pending invitation's Welcome rumor; bounded by the processing-failure cap and cleared
69
+ * with the entry (`markSeen`). Absent — the retry unwraps — when it was not stored or does not decode as a rumor
70
+ * whose id matches its content.
71
+ */
72
+ readonly rumor?: Rumor;
73
+ }
74
+ export declare function readDeferred(view: KeyValueView, wrapId: string): Promise<DeferredWrap | undefined>;
75
+ /**
76
+ * Records (or updates) a deferred wrap; `failed` adds one counted failure. `rumor`: the wrap's unwrapped rumor, kept
77
+ * for the retry (see {@link DeferredWrap.rumor}); a deferral recorded without one drops any rumor stored before.
78
+ * Returns the stored entry.
79
+ */
80
+ export declare function recordDeferred(view: KeyValueView, wrap: NostrEvent, failed: boolean, rumor?: Rumor): Promise<DeferredWrap>;
81
+ /** Every deferred wrap, in no particular order. */
82
+ export declare function listDeferred(view: KeyValueView): Promise<DeferredWrap[]>;
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Codec of the account `inboxSeenSet` artifact (S6, AC-INBOX-3/4): the
3
+ * persisted, bounded set of kind-1059 wrap ids the inbox has finished with.
4
+ * Pure `KeyValueView` helpers — call them on a transaction's `tx` view.
5
+ *
6
+ * A FIFO over three key families, so an insert and its eviction cost O(1)
7
+ * reads and writes whatever the cap (no `keys()` scan):
8
+ *
9
+ * - `meta` — `{ v: 1, head, next, floor? }`: live sequence numbers
10
+ * are `[head, next)`; `floor` is the inbox backfill's
11
+ * `since` (unix seconds), kept here because the
12
+ * account artifact set (AC-STORE-9) has no other home
13
+ * for inbox state;
14
+ * - `w:<wrapId>` — `{ seq }`, the membership test;
15
+ * - `s:<seq>` — the wrap id at that position (seq zero-padded, so
16
+ * keys also sort in insertion order);
17
+ * - `d:<wrapId>` — a wrap whose last attempt was `deferred` (the event,
18
+ * its attempt count, and — for a counted
19
+ * `handler-failed` deferral only — the unwrapped rumor):
20
+ * retried by every pass, also after a reload, and
21
+ * holding the backfill floor below its `created_at`.
22
+ * `markSeen` clears it.
23
+ *
24
+ * `markSeen` appends at `next` and then evicts from `head` while the set
25
+ * holds more than `cap` ids: the oldest id goes first (AC-INBOX-4). An
26
+ * evicted id may be delivered and decrypted again; the Welcome path then
27
+ * recognises it by its Welcome identity (`already-member`), not by the wrap.
28
+ */
29
+ import { getEventHash } from '@941design/nostr-events/event';
30
+ import { MarmotError } from '../shared/index.js';
31
+ /** Default `seenSetCap` (AC-INBOX-4). */
32
+ export const DEFAULT_SEEN_SET_CAP = 10_000;
33
+ const META_KEY = 'meta';
34
+ const wrapKey = (wrapId) => `w:${wrapId}`;
35
+ const seqKey = (seq) => `s:${String(seq).padStart(16, '0')}`;
36
+ function malformed(detail) {
37
+ return new MarmotError('store-failed', `inboxSeenSet: malformed record (${detail})`, { details: { artifact: 'inboxSeenSet', malformed: true } });
38
+ }
39
+ async function readMeta(view) {
40
+ const raw = await view.get(META_KEY);
41
+ if (raw === undefined)
42
+ return { head: 0, next: 0 };
43
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
44
+ throw malformed('meta');
45
+ const { v, head, next, floor, resume } = raw;
46
+ if (v !== 1 || !Number.isInteger(head) || !Number.isInteger(next) || head > next)
47
+ throw malformed('meta fields');
48
+ if (floor !== undefined && typeof floor !== 'number')
49
+ throw malformed('meta floor');
50
+ if (resume !== undefined) {
51
+ const r = resume;
52
+ if (r === null || typeof r !== 'object' || typeof r.until !== 'number' || typeof r.startedAt !== 'number' || !Array.isArray(r.relays) || !r.relays.every((x) => typeof x === 'string')) {
53
+ throw malformed('meta resume');
54
+ }
55
+ }
56
+ return {
57
+ head: head,
58
+ next: next,
59
+ ...(floor === undefined ? {} : { floor: floor }),
60
+ ...(resume === undefined ? {} : { resume: resume }),
61
+ };
62
+ }
63
+ async function writeMeta(view, meta) {
64
+ await view.put(META_KEY, {
65
+ v: 1,
66
+ head: meta.head,
67
+ next: meta.next,
68
+ ...(meta.floor === undefined ? {} : { floor: meta.floor }),
69
+ ...(meta.resume === undefined ? {} : { resume: { until: meta.resume.until, startedAt: meta.resume.startedAt, relays: [...meta.resume.relays] } }),
70
+ });
71
+ }
72
+ /** Whether `wrapId` is in the seen-set. */
73
+ export async function isSeen(view, wrapId) {
74
+ return (await view.get(wrapKey(wrapId))) !== undefined;
75
+ }
76
+ /** Number of ids the seen-set holds. */
77
+ export async function seenSetSize(view) {
78
+ const meta = await readMeta(view);
79
+ return meta.next - meta.head;
80
+ }
81
+ /**
82
+ * Adds `wrapId` (a no-op when present) and evicts the oldest ids until at
83
+ * most `cap` remain. Returns the evicted ids, oldest first.
84
+ */
85
+ export async function markSeen(view, wrapId, cap) {
86
+ if (!Number.isInteger(cap) || cap < 1)
87
+ throw new MarmotError('invalid-options', 'inboxSeenSet: cap must be a positive integer');
88
+ await view.delete(deferredKey(wrapId));
89
+ if (await isSeen(view, wrapId))
90
+ return [];
91
+ const meta = await readMeta(view);
92
+ const seq = meta.next;
93
+ await view.put(wrapKey(wrapId), { seq });
94
+ await view.put(seqKey(seq), wrapId);
95
+ let head = meta.head;
96
+ const next = seq + 1;
97
+ const evicted = [];
98
+ while (next - head > cap) {
99
+ const oldest = await view.get(seqKey(head));
100
+ await view.delete(seqKey(head));
101
+ if (typeof oldest === 'string') {
102
+ await view.delete(wrapKey(oldest));
103
+ evicted.push(oldest);
104
+ }
105
+ head += 1;
106
+ }
107
+ await writeMeta(view, { ...meta, head, next });
108
+ return evicted;
109
+ }
110
+ /** The inbox backfill's `since` floor (unix seconds), if one was recorded. */
111
+ export async function readInboxFloor(view) {
112
+ return (await readMeta(view)).floor;
113
+ }
114
+ /** Records the backfill floor (the caller computes it; it may move down, e.g. below a deferred wrap). */
115
+ export async function writeInboxFloor(view, floor) {
116
+ const meta = await readMeta(view);
117
+ if (meta.floor === floor)
118
+ return;
119
+ await writeMeta(view, { ...meta, floor });
120
+ }
121
+ /** The unfinished backfill walk, if any. */
122
+ export async function readBackfillContinuation(view) {
123
+ return (await readMeta(view)).resume;
124
+ }
125
+ /** Records (or, with `undefined`, clears) the unfinished backfill walk. */
126
+ export async function writeBackfillContinuation(view, resume) {
127
+ const { resume: _old, ...meta } = await readMeta(view);
128
+ await writeMeta(view, resume === undefined ? meta : { ...meta, resume });
129
+ }
130
+ // ---------------------------------------------------------------------------
131
+ // Deferred wraps (AC-WEL-3: never terminal, retried by the next pass — also after a reload)
132
+ // ---------------------------------------------------------------------------
133
+ const DEFERRED_PREFIX = 'd:';
134
+ const deferredKey = (wrapId) => `${DEFERRED_PREFIX}${wrapId}`;
135
+ function isStringArray(value) {
136
+ return Array.isArray(value) && value.every((x) => typeof x === 'string');
137
+ }
138
+ /** A stored rumor, or `undefined` when it is not a well-formed rumor whose id is its NIP-01 hash. */
139
+ function decodeStoredRumor(raw) {
140
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
141
+ return undefined;
142
+ const r = raw;
143
+ if (typeof r.id !== 'string' || typeof r.pubkey !== 'string' || typeof r.kind !== 'number' || typeof r.created_at !== 'number' || typeof r.content !== 'string')
144
+ return undefined;
145
+ if (!Array.isArray(r.tags) || !r.tags.every(isStringArray))
146
+ return undefined;
147
+ const unsigned = { pubkey: r.pubkey, created_at: r.created_at, kind: r.kind, tags: r.tags.map((t) => [...t]), content: r.content };
148
+ try {
149
+ if (getEventHash(unsigned) !== r.id)
150
+ return undefined;
151
+ }
152
+ catch {
153
+ return undefined;
154
+ }
155
+ return { ...unsigned, id: r.id };
156
+ }
157
+ function decodeDeferred(key, raw) {
158
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
159
+ throw malformed(key);
160
+ const { wrap, failures, rumor } = raw;
161
+ if (typeof failures !== 'number' || typeof wrap !== 'object' || wrap === null)
162
+ throw malformed(`${key} fields`);
163
+ const w = wrap;
164
+ if (typeof w.id !== 'string' || typeof w.pubkey !== 'string' || typeof w.kind !== 'number' || typeof w.created_at !== 'number' || typeof w.content !== 'string' || typeof w.sig !== 'string' || !Array.isArray(w.tags)) {
165
+ throw malformed(`${key} wrap`);
166
+ }
167
+ const stored = rumor === undefined ? undefined : decodeStoredRumor(rumor);
168
+ return { wrap: wrap, failures, ...(stored === undefined ? {} : { rumor: stored }) };
169
+ }
170
+ export async function readDeferred(view, wrapId) {
171
+ const raw = await view.get(deferredKey(wrapId));
172
+ return raw === undefined ? undefined : decodeDeferred(deferredKey(wrapId), raw);
173
+ }
174
+ /**
175
+ * Records (or updates) a deferred wrap; `failed` adds one counted failure. `rumor`: the wrap's unwrapped rumor, kept
176
+ * for the retry (see {@link DeferredWrap.rumor}); a deferral recorded without one drops any rumor stored before.
177
+ * Returns the stored entry.
178
+ */
179
+ export async function recordDeferred(view, wrap, failed, rumor) {
180
+ const current = await readDeferred(view, wrap.id);
181
+ const entry = { wrap, failures: (current?.failures ?? 0) + (failed ? 1 : 0), ...(rumor === undefined ? {} : { rumor }) };
182
+ await view.put(deferredKey(wrap.id), {
183
+ wrap: { ...wrap, tags: wrap.tags.map((t) => [...t]) },
184
+ failures: entry.failures,
185
+ ...(rumor === undefined
186
+ ? {}
187
+ : { rumor: { id: rumor.id, pubkey: rumor.pubkey, created_at: rumor.created_at, kind: rumor.kind, tags: rumor.tags.map((t) => [...t]), content: rumor.content } }),
188
+ });
189
+ return entry;
190
+ }
191
+ /** Every deferred wrap, in no particular order. */
192
+ export async function listDeferred(view) {
193
+ const out = [];
194
+ for (const key of await view.keys()) {
195
+ if (!key.startsWith(DEFERRED_PREFIX))
196
+ continue;
197
+ const raw = await view.get(key);
198
+ if (raw !== undefined)
199
+ out.push(decodeDeferred(key, raw));
200
+ }
201
+ return out;
202
+ }