@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,141 @@
1
+ /**
2
+ * `@941design/marmot/storage/indexeddb` — the IndexedDB reference backend
3
+ * (ADR-007 §6, AC-STORE-4).
4
+ *
5
+ * One database per account (`<dbPrefix><pubkey>`), one object store per
6
+ * artifact plus one `extension` object store, out-of-line array keys
7
+ * (`[scope, key]` / `[scope, extensionId, key]`). A store transaction's
8
+ * buffered writes are flushed in ONE readwrite IDB transaction spanning every
9
+ * object store they touch, so the flush is all-or-nothing; a request that
10
+ * throws aborts it. The lease's lock is keyed by the database name, so two
11
+ * tabs (or two backend instances) on one account's database contend.
12
+ */
13
+ import { MarmotError } from '../../shared/index.js';
14
+ import { createStorageBackend, ALL_BUCKETS } from '../index.js';
15
+ import { defaultLockManager } from '../lease.js';
16
+ export const DEFAULT_DB_PREFIX = 'marmot:';
17
+ export const DB_VERSION = 1;
18
+ function request(req) {
19
+ return new Promise((resolve, reject) => {
20
+ req.onsuccess = () => resolve(req.result);
21
+ req.onerror = () => reject(req.error);
22
+ });
23
+ }
24
+ function completion(tx) {
25
+ return new Promise((resolve, reject) => {
26
+ tx.oncomplete = () => resolve();
27
+ // A failing request's error event reaches the transaction BEFORE the
28
+ // transaction's own `error` is set (and an explicit abort() never sets it),
29
+ // so fall back to the request's error rather than rejecting with `null`.
30
+ tx.onerror = (ev) => reject(tx.error ?? ev?.target?.error ?? new Error('IndexedDB transaction failed'));
31
+ tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted'));
32
+ });
33
+ }
34
+ export function createIndexedDbStorage(options = {}) {
35
+ const g = globalThis;
36
+ const factory = options.indexedDB ?? g.indexedDB;
37
+ const keyRange = options.IDBKeyRange ?? g.IDBKeyRange;
38
+ const locks = options.locks ?? defaultLockManager();
39
+ const prefix = options.dbPrefix ?? DEFAULT_DB_PREFIX;
40
+ if (factory === undefined || keyRange === undefined) {
41
+ throw new MarmotError('invalid-options', 'createIndexedDbStorage: no IndexedDB in this host — pass options.indexedDB and options.IDBKeyRange');
42
+ }
43
+ if (locks === undefined) {
44
+ throw new MarmotError('invalid-options', 'createIndexedDbStorage: no Web Locks (navigator.locks) in this host — pass options.locks');
45
+ }
46
+ if (typeof prefix !== 'string')
47
+ throw new MarmotError('invalid-options', 'createIndexedDbStorage: dbPrefix must be a string');
48
+ const databases = new Map();
49
+ function database(account) {
50
+ const name = prefix + account;
51
+ let db = databases.get(name);
52
+ if (db === undefined) {
53
+ db = new Promise((resolve, reject) => {
54
+ const req = factory.open(name, DB_VERSION);
55
+ req.onupgradeneeded = () => {
56
+ const created = req.result;
57
+ for (const bucket of ALL_BUCKETS)
58
+ if (!created.objectStoreNames.contains(bucket))
59
+ created.createObjectStore(bucket);
60
+ };
61
+ req.onsuccess = () => {
62
+ const opened = req.result;
63
+ const evict = () => {
64
+ if (databases.get(name) === db)
65
+ databases.delete(name);
66
+ };
67
+ // Let another context upgrade or delete the database instead of blocking it.
68
+ opened.onversionchange = () => {
69
+ opened.close();
70
+ evict();
71
+ };
72
+ // The browser closed the connection itself (storage failure, site data cleared): reopen on next use.
73
+ opened.onclose = evict;
74
+ resolve(opened);
75
+ };
76
+ req.onerror = () => reject(req.error);
77
+ req.onblocked = () => reject(new Error(`IndexedDB open of ${name} blocked by another connection`));
78
+ });
79
+ databases.set(name, db);
80
+ db.catch(() => databases.delete(name));
81
+ }
82
+ return db;
83
+ }
84
+ const driver = {
85
+ locks,
86
+ lockName: (account) => prefix + account,
87
+ async read(account, bucket, path) {
88
+ const db = await database(account);
89
+ return request(db.transaction(bucket, 'readonly').objectStore(bucket).get([...path]));
90
+ },
91
+ async keys(account, bucket, pathPrefix) {
92
+ const db = await database(account);
93
+ // Array keys sort after strings, so `[...prefix, []]` bounds every key extending `prefix`.
94
+ const range = keyRange.bound([...pathPrefix], [...pathPrefix, []]);
95
+ const keys = await request(db.transaction(bucket, 'readonly').objectStore(bucket).getAllKeys(range));
96
+ return keys
97
+ .filter((k) => Array.isArray(k) && k.length === pathPrefix.length + 1)
98
+ .map((k) => k[k.length - 1])
99
+ .sort();
100
+ },
101
+ async commit(account, writes) {
102
+ const db = await database(account);
103
+ const clears = writes.some((w) => w.type === 'clear' || w.type === 'clearScope');
104
+ const touched = clears ? [...ALL_BUCKETS] : [...new Set(writes.flatMap((w) => (w.type === 'clear' || w.type === 'clearScope' ? [] : [w.bucket])))];
105
+ const tx = db.transaction(touched, 'readwrite');
106
+ const done = completion(tx);
107
+ try {
108
+ for (const write of writes) {
109
+ if (write.type === 'clear') {
110
+ for (const bucket of ALL_BUCKETS)
111
+ tx.objectStore(bucket).clear();
112
+ }
113
+ else if (write.type === 'clearScope') {
114
+ // Array keys sort after strings, so `[scope, []]` bounds every key under `scope` (artifacts and extensions).
115
+ const range = keyRange.bound([write.scope], [write.scope, []]);
116
+ for (const bucket of ALL_BUCKETS)
117
+ tx.objectStore(bucket).delete(range);
118
+ }
119
+ else if (write.type === 'put') {
120
+ tx.objectStore(write.bucket).put(write.envelope, [...write.path]);
121
+ }
122
+ else {
123
+ tx.objectStore(write.bucket).delete([...write.path]);
124
+ }
125
+ }
126
+ }
127
+ catch (err) {
128
+ try {
129
+ tx.abort();
130
+ }
131
+ catch {
132
+ // Already finished or aborted.
133
+ }
134
+ await done.catch(() => undefined);
135
+ throw err;
136
+ }
137
+ await done;
138
+ },
139
+ };
140
+ return createStorageBackend(driver, options);
141
+ }
@@ -0,0 +1,54 @@
1
+ export interface LockLike {
2
+ readonly name: string;
3
+ }
4
+ export interface LockRequestOptions {
5
+ readonly mode?: 'exclusive' | 'shared';
6
+ readonly ifAvailable?: boolean;
7
+ readonly signal?: AbortSignal;
8
+ }
9
+ /** The subset of the Web Locks `LockManager` the lease uses. */
10
+ export interface LockManagerLike {
11
+ request<T>(name: string, options: LockRequestOptions, callback: (lock: LockLike | null) => Promise<T> | T): Promise<T>;
12
+ }
13
+ export interface Lease {
14
+ readonly account: string;
15
+ /** Lock name the lease holds. */
16
+ readonly name: string;
17
+ /** False once released or lost (e.g. a Web Locks `steal` by another context). */
18
+ readonly held: boolean;
19
+ /** Releases the lock; resolves once the lock manager has let go. Idempotent. */
20
+ release(): Promise<void>;
21
+ }
22
+ export declare const DEFAULT_LEASE_TIMEOUT_MS = 5000;
23
+ /**
24
+ * Runs `barrier` inside `lease.release()`, before the lock is let go, on every
25
+ * release path (a store's `close()`, `stores.lease.release()`, or a caller's
26
+ * own reference to the lease). Package-internal: not re-exported.
27
+ */
28
+ export declare function setReleaseBarrier(lease: Lease, barrier: () => Promise<void>): void;
29
+ /**
30
+ * Runs one lease-end listener: a throw is swallowed, and so is the rejection of a thenable it returns (an `async`
31
+ * listener type-checks against `() => void`) — attached without awaiting, so the call stays synchronous and the
32
+ * rejection never surfaces as an unhandled one. A listener never breaks the release, its registration, or the others.
33
+ * Package-internal: not re-exported.
34
+ */
35
+ export declare function runLeaseEndListener(listener: () => void): void;
36
+ /**
37
+ * Calls `listener` once when `lease` stops being held — released, or lost to another context (a Web Locks steal ends
38
+ * the hold without any release barrier running). Synchronously at once when it already ended. Each listener runs
39
+ * through {@link runLeaseEndListener}. Returns the unregister function. Package-internal: not re-exported.
40
+ */
41
+ export declare function onLeaseEnded(lease: Lease, listener: () => void): () => void;
42
+ /** `navigator.locks` when the host has Web Locks, else `undefined`. */
43
+ export declare function defaultLockManager(): LockManagerLike | undefined;
44
+ export declare function validateLeaseTimeout(value: unknown, where: string): number;
45
+ /**
46
+ * Acquires `name` exclusively. Rejects `lease-held` when the lock is not
47
+ * granted within `timeoutMs` (the pending request is aborted, and a grant
48
+ * that still arrives afterwards is released immediately). A lock manager
49
+ * that throws, or rejects before granting, rejects `store-failed` with the
50
+ * original error as `cause`.
51
+ */
52
+ export declare function acquireLease(locks: LockManagerLike, name: string, account: string, opts: {
53
+ readonly timeoutMs: number;
54
+ }): Promise<Lease>;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Single-writer lease (ADR-007 §5, AC-STORE-3).
3
+ *
4
+ * A lease is an exclusive lock held through a Web Locks-shaped
5
+ * {@link LockManagerLike} for as long as the lease is not released. The lock
6
+ * name is chosen by the backend so the lease is scoped to
7
+ * (backend instance, account): the IndexedDB backend uses the account's
8
+ * database name (so two tabs on one database contend), the memory kit uses
9
+ * its persistence's in-process lock manager (so kits over one persistence
10
+ * contend and independent kits never do).
11
+ *
12
+ * `navigator.locks` is the default when present; Node has none, so tests
13
+ * and non-browser hosts inject one.
14
+ */
15
+ import { MarmotError } from '../shared/index.js';
16
+ export const DEFAULT_LEASE_TIMEOUT_MS = 5_000;
17
+ const releaseBarriers = new WeakMap();
18
+ /**
19
+ * Runs `barrier` inside `lease.release()`, before the lock is let go, on every
20
+ * release path (a store's `close()`, `stores.lease.release()`, or a caller's
21
+ * own reference to the lease). Package-internal: not re-exported.
22
+ */
23
+ export function setReleaseBarrier(lease, barrier) {
24
+ releaseBarriers.set(lease, barrier);
25
+ }
26
+ /** One entry per registration (not per function): each unregister removes only its own. */
27
+ const leaseEndListeners = new WeakMap();
28
+ const endedLeases = new WeakSet();
29
+ /**
30
+ * Runs one lease-end listener: a throw is swallowed, and so is the rejection of a thenable it returns (an `async`
31
+ * listener type-checks against `() => void`) — attached without awaiting, so the call stays synchronous and the
32
+ * rejection never surfaces as an unhandled one. A listener never breaks the release, its registration, or the others.
33
+ * Package-internal: not re-exported.
34
+ */
35
+ export function runLeaseEndListener(listener) {
36
+ try {
37
+ const returned = listener();
38
+ if (typeof returned?.then === 'function') {
39
+ returned.then(undefined, () => undefined);
40
+ }
41
+ }
42
+ catch {
43
+ // Swallowed: see above.
44
+ }
45
+ }
46
+ /**
47
+ * Calls `listener` once when `lease` stops being held — released, or lost to another context (a Web Locks steal ends
48
+ * the hold without any release barrier running). Synchronously at once when it already ended. Each listener runs
49
+ * through {@link runLeaseEndListener}. Returns the unregister function. Package-internal: not re-exported.
50
+ */
51
+ export function onLeaseEnded(lease, listener) {
52
+ if (endedLeases.has(lease)) {
53
+ runLeaseEndListener(listener);
54
+ return () => undefined;
55
+ }
56
+ let set = leaseEndListeners.get(lease);
57
+ if (set === undefined)
58
+ leaseEndListeners.set(lease, (set = new Set()));
59
+ const registration = { listener };
60
+ set.add(registration);
61
+ return () => {
62
+ set.delete(registration);
63
+ };
64
+ }
65
+ /** `lease` stopped being held: every {@link onLeaseEnded} listener, once. */
66
+ function leaseEnded(lease) {
67
+ if (endedLeases.has(lease))
68
+ return;
69
+ endedLeases.add(lease);
70
+ const listeners = [...(leaseEndListeners.get(lease) ?? [])];
71
+ leaseEndListeners.delete(lease);
72
+ for (const { listener } of listeners)
73
+ runLeaseEndListener(listener);
74
+ }
75
+ /** `navigator.locks` when the host has Web Locks, else `undefined`. */
76
+ export function defaultLockManager() {
77
+ const nav = globalThis.navigator;
78
+ const locks = nav?.locks;
79
+ return locks !== undefined && typeof locks.request === 'function' ? locks : undefined;
80
+ }
81
+ export function validateLeaseTimeout(value, where) {
82
+ if (value === undefined)
83
+ return DEFAULT_LEASE_TIMEOUT_MS;
84
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
85
+ throw new MarmotError('invalid-options', `${where}: leaseTimeoutMs must be a finite, non-negative number`);
86
+ }
87
+ return value;
88
+ }
89
+ function lockFailure(name, account, cause) {
90
+ return new MarmotError('store-failed', `lease ${name}: the lock manager failed the request`, { cause, details: { account, name } });
91
+ }
92
+ /**
93
+ * Acquires `name` exclusively. Rejects `lease-held` when the lock is not
94
+ * granted within `timeoutMs` (the pending request is aborted, and a grant
95
+ * that still arrives afterwards is released immediately). A lock manager
96
+ * that throws, or rejects before granting, rejects `store-failed` with the
97
+ * original error as `cause`.
98
+ */
99
+ export function acquireLease(locks, name, account, opts) {
100
+ return new Promise((resolve, reject) => {
101
+ const abort = new AbortController();
102
+ let settled = false;
103
+ let held = false;
104
+ let letGo = () => { };
105
+ const hold = new Promise((r) => {
106
+ letGo = r;
107
+ });
108
+ const timer = setTimeout(() => {
109
+ if (settled)
110
+ return;
111
+ settled = true;
112
+ abort.abort();
113
+ reject(new MarmotError('lease-held', `lease ${name} is held elsewhere (not granted within ${opts.timeoutMs} ms)`, { details: { account, name } }));
114
+ }, opts.timeoutMs);
115
+ // Declared before `request`: a lock manager may grant synchronously.
116
+ let released = Promise.resolve();
117
+ let releasing;
118
+ const lease = {
119
+ account,
120
+ name,
121
+ get held() {
122
+ return held;
123
+ },
124
+ release() {
125
+ releasing ??= (async () => {
126
+ try {
127
+ await releaseBarriers.get(lease)?.();
128
+ }
129
+ finally {
130
+ letGo();
131
+ }
132
+ await released;
133
+ })();
134
+ return releasing;
135
+ },
136
+ };
137
+ let requestDone;
138
+ try {
139
+ requestDone = locks.request(name, { mode: 'exclusive', signal: abort.signal }, (lock) => {
140
+ if (settled || lock === null)
141
+ return undefined;
142
+ settled = true;
143
+ clearTimeout(timer);
144
+ held = true;
145
+ resolve(lease);
146
+ return hold;
147
+ });
148
+ }
149
+ catch (err) {
150
+ clearTimeout(timer);
151
+ settled = true;
152
+ reject(lockFailure(name, account, err));
153
+ return;
154
+ }
155
+ released = requestDone.then(() => {
156
+ held = false;
157
+ leaseEnded(lease);
158
+ }, (err) => {
159
+ held = false;
160
+ leaseEnded(lease);
161
+ if (settled)
162
+ return;
163
+ settled = true;
164
+ clearTimeout(timer);
165
+ reject(lockFailure(name, account, err));
166
+ });
167
+ });
168
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * FIXTURE-02-001 — deterministic in-process signer with fault injection.
3
+ *
4
+ * A real `nostr-events` private-key signer over a fixed secret key, so
5
+ * signatures and NIP-44 payloads are genuine, plus `failNext(n, reason)`:
6
+ * the next `n` asynchronous signer operations (`signEvent`,
7
+ * `nip44.encrypt/decrypt`, `nip04.encrypt/decrypt`) reject with
8
+ * `SignerError(reason)` without reaching the key, modelling a transient
9
+ * remote-signer failure. `getPublicKey` never fails (identity is not an
10
+ * operation a remote signer fails transiently in these scenarios).
11
+ *
12
+ * The key for `index` is 31 zero bytes followed by `index`.
13
+ * {@link deterministicSecretKey} is the single owner of that derivation:
14
+ * `fixtures/consumers/harness`'s `fixtureSecretKey` re-exports it and the
15
+ * package's own test support imports it, so `createDeterministicSigner(i)`
16
+ * and the harness's fixture account `i` are the same account.
17
+ */
18
+ import { type Signer, type SignerErrorCode } from '@941design/nostr-events/signer';
19
+ export interface DeterministicSigner extends Signer {
20
+ /** Makes the next `n` operations reject `SignerError(reason)` (default `'transport'`). Adds to failures already queued. */
21
+ failNext(n: number, reason?: SignerErrorCode): void;
22
+ /** Failures still queued. */
23
+ readonly pendingFailures: number;
24
+ }
25
+ /** The fixture secret key for account `index` (31 zero bytes, then `index`). Throws `invalid-options` outside [1, 255]. */
26
+ export declare function deterministicSecretKey(index: number): Uint8Array;
27
+ export declare function createDeterministicSigner(index?: number): DeterministicSigner;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * FIXTURE-02-001 — deterministic in-process signer with fault injection.
3
+ *
4
+ * A real `nostr-events` private-key signer over a fixed secret key, so
5
+ * signatures and NIP-44 payloads are genuine, plus `failNext(n, reason)`:
6
+ * the next `n` asynchronous signer operations (`signEvent`,
7
+ * `nip44.encrypt/decrypt`, `nip04.encrypt/decrypt`) reject with
8
+ * `SignerError(reason)` without reaching the key, modelling a transient
9
+ * remote-signer failure. `getPublicKey` never fails (identity is not an
10
+ * operation a remote signer fails transiently in these scenarios).
11
+ *
12
+ * The key for `index` is 31 zero bytes followed by `index`.
13
+ * {@link deterministicSecretKey} is the single owner of that derivation:
14
+ * `fixtures/consumers/harness`'s `fixtureSecretKey` re-exports it and the
15
+ * package's own test support imports it, so `createDeterministicSigner(i)`
16
+ * and the harness's fixture account `i` are the same account.
17
+ */
18
+ import { SignerError } from '@941design/nostr-events/signer';
19
+ import { createPrivateKeySigner } from '@941design/nostr-events/signer/private-key';
20
+ import { MarmotError } from '../../shared/index.js';
21
+ /** The fixture secret key for account `index` (31 zero bytes, then `index`). Throws `invalid-options` outside [1, 255]. */
22
+ export function deterministicSecretKey(index) {
23
+ if (!Number.isInteger(index) || index < 1 || index > 255) {
24
+ throw new MarmotError('invalid-options', 'deterministicSecretKey: index must be an integer in [1, 255]');
25
+ }
26
+ const key = new Uint8Array(32);
27
+ key[31] = index;
28
+ return key;
29
+ }
30
+ export function createDeterministicSigner(index = 1) {
31
+ const inner = createPrivateKeySigner(deterministicSecretKey(index));
32
+ const failures = [];
33
+ async function guarded(operation, run) {
34
+ const reason = failures.shift();
35
+ if (reason !== undefined)
36
+ throw new SignerError(reason, `injected failure (failNext) on ${operation}`);
37
+ return run();
38
+ }
39
+ const nip04 = inner.nip04;
40
+ return {
41
+ getPublicKey: () => inner.getPublicKey(),
42
+ signEvent: (template, opts) => guarded('signEvent', () => inner.signEvent(template, opts)),
43
+ nip44: {
44
+ encrypt: (pubkey, plaintext, opts) => guarded('nip44.encrypt', () => inner.nip44.encrypt(pubkey, plaintext, opts)),
45
+ decrypt: (pubkey, ciphertext, opts) => guarded('nip44.decrypt', () => inner.nip44.decrypt(pubkey, ciphertext, opts)),
46
+ },
47
+ ...(nip04 === undefined
48
+ ? {}
49
+ : {
50
+ nip04: {
51
+ encrypt: (pubkey, plaintext) => guarded('nip04.encrypt', () => nip04.encrypt(pubkey, plaintext)),
52
+ decrypt: (pubkey, ciphertext) => guarded('nip04.decrypt', () => nip04.decrypt(pubkey, ciphertext)),
53
+ },
54
+ }),
55
+ failNext(n, reason = 'transport') {
56
+ if (!Number.isInteger(n) || n < 0)
57
+ throw new MarmotError('invalid-options', 'failNext: n must be a non-negative integer');
58
+ for (let i = 0; i < n; i++)
59
+ failures.push(reason);
60
+ },
61
+ get pendingFailures() {
62
+ return failures.length;
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `@941design/marmot/storage/memory` — the in-memory test kit (ADR-007 §6).
3
+ *
4
+ * `createMemoryStorage()` is a full {@link StorageBackend} over plain maps,
5
+ * satisfying the same conformance suite as the IndexedDB backend
6
+ * (AC-STORE-5). Rows and the lease's lock manager live in a
7
+ * {@link MemoryPersistence}: kits sharing one persistence contend for the
8
+ * lease like two tabs on one database, while independent kits (each with
9
+ * its own persistence) never contend, so two kits for one account in one
10
+ * process both hold their lease (AC-STORE-3). Pass one persistence to two
11
+ * kits in sequence to model a reload (or, with other `codecVersions`, an
12
+ * engine upgrade) over the same data.
13
+ */
14
+ import { type BackendOptions, type StorageBackend } from '../index.js';
15
+ import type { LockManagerLike } from '../lease.js';
16
+ export { createInProcessLockManager } from './lock-manager.js';
17
+ export { createDeterministicSigner, deterministicSecretKey, type DeterministicSigner } from './deterministic-signer.js';
18
+ /** One simulated database. Opaque to callers. */
19
+ export interface MemoryPersistence {
20
+ /** Rows of every account, keyed by account, then bucket, then encoded path. */
21
+ readonly accounts: Map<string, Map<string, Map<string, unknown>>>;
22
+ /** The lock manager every kit over this persistence uses by default (as `navigator.locks` spans one origin's tabs). */
23
+ readonly locks: LockManagerLike;
24
+ }
25
+ export declare function createMemoryPersistence(): MemoryPersistence;
26
+ export interface MemoryStorageOptions extends BackendOptions {
27
+ /** Defaults to the persistence's lock manager. */
28
+ readonly locks?: LockManagerLike;
29
+ /** Defaults to a new, empty persistence (with its own lock manager) owned by this kit. */
30
+ readonly persistence?: MemoryPersistence;
31
+ }
32
+ export declare function createMemoryStorage(options?: MemoryStorageOptions): StorageBackend;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * `@941design/marmot/storage/memory` — the in-memory test kit (ADR-007 §6).
3
+ *
4
+ * `createMemoryStorage()` is a full {@link StorageBackend} over plain maps,
5
+ * satisfying the same conformance suite as the IndexedDB backend
6
+ * (AC-STORE-5). Rows and the lease's lock manager live in a
7
+ * {@link MemoryPersistence}: kits sharing one persistence contend for the
8
+ * lease like two tabs on one database, while independent kits (each with
9
+ * its own persistence) never contend, so two kits for one account in one
10
+ * process both hold their lease (AC-STORE-3). Pass one persistence to two
11
+ * kits in sequence to model a reload (or, with other `codecVersions`, an
12
+ * engine upgrade) over the same data.
13
+ */
14
+ import { createStorageBackend, ALL_BUCKETS } from '../index.js';
15
+ import { createInProcessLockManager } from './lock-manager.js';
16
+ export { createInProcessLockManager } from './lock-manager.js';
17
+ export { createDeterministicSigner, deterministicSecretKey } from './deterministic-signer.js';
18
+ export function createMemoryPersistence() {
19
+ return { accounts: new Map(), locks: createInProcessLockManager() };
20
+ }
21
+ const encodePath = (path) => JSON.stringify(path);
22
+ export function createMemoryStorage(options = {}) {
23
+ const persistence = options.persistence ?? createMemoryPersistence();
24
+ const locks = options.locks ?? persistence.locks;
25
+ function bucketOf(account, bucket, create) {
26
+ let buckets = persistence.accounts.get(account);
27
+ if (buckets === undefined) {
28
+ if (!create)
29
+ return undefined;
30
+ buckets = new Map();
31
+ persistence.accounts.set(account, buckets);
32
+ }
33
+ let rows = buckets.get(bucket);
34
+ if (rows === undefined && create) {
35
+ rows = new Map();
36
+ buckets.set(bucket, rows);
37
+ }
38
+ return rows;
39
+ }
40
+ const driver = {
41
+ locks,
42
+ lockName: (account) => `marmot:${account}`,
43
+ async read(account, bucket, path) {
44
+ return bucketOf(account, bucket, false)?.get(encodePath(path));
45
+ },
46
+ async keys(account, bucket, prefix) {
47
+ const rows = bucketOf(account, bucket, false);
48
+ if (rows === undefined)
49
+ return [];
50
+ const out = [];
51
+ for (const encoded of rows.keys()) {
52
+ const path = JSON.parse(encoded);
53
+ if (path.length === prefix.length + 1 && prefix.every((p, i) => path[i] === p))
54
+ out.push(path[path.length - 1]);
55
+ }
56
+ return out.sort();
57
+ },
58
+ async commit(account, writes) {
59
+ // Every write below is infallible, so applying them in one synchronous
60
+ // pass is all-or-nothing.
61
+ for (const write of writes) {
62
+ if (write.type !== 'clear' && write.type !== 'clearScope' && !ALL_BUCKETS.includes(write.bucket))
63
+ throw new Error(`unknown bucket ${write.bucket}`);
64
+ }
65
+ for (const write of writes) {
66
+ if (write.type === 'clear') {
67
+ persistence.accounts.delete(account);
68
+ continue;
69
+ }
70
+ if (write.type === 'clearScope') {
71
+ for (const rows of persistence.accounts.get(account)?.values() ?? []) {
72
+ for (const encoded of [...rows.keys()])
73
+ if (JSON.parse(encoded)[0] === write.scope)
74
+ rows.delete(encoded);
75
+ }
76
+ continue;
77
+ }
78
+ const rows = bucketOf(account, write.bucket, true);
79
+ if (write.type === 'put')
80
+ rows.set(encodePath(write.path), write.envelope);
81
+ else
82
+ rows.delete(encodePath(write.path));
83
+ }
84
+ },
85
+ };
86
+ return createStorageBackend(driver, options);
87
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * In-process {@link LockManagerLike} for the memory kit and for hosts
3
+ * without Web Locks (Node). Every mode is treated as exclusive; waiters are
4
+ * granted in request order; an aborted waiter leaves the queue and rejects
5
+ * with the signal's reason (an `AbortError`). State is per instance.
6
+ */
7
+ import type { LockManagerLike } from '../lease.js';
8
+ export declare function createInProcessLockManager(): LockManagerLike;
@@ -0,0 +1,71 @@
1
+ function abortReason(signal) {
2
+ if (signal.reason !== undefined)
3
+ return signal.reason;
4
+ const err = new Error('lock request aborted');
5
+ err.name = 'AbortError';
6
+ return err;
7
+ }
8
+ export function createInProcessLockManager() {
9
+ const held = new Set();
10
+ const waiters = new Map();
11
+ function grantNext(name) {
12
+ const queue = waiters.get(name);
13
+ const next = queue?.shift();
14
+ if (queue !== undefined && queue.length === 0)
15
+ waiters.delete(name);
16
+ if (next === undefined)
17
+ held.delete(name);
18
+ else
19
+ next();
20
+ }
21
+ return {
22
+ request(name, options, callback) {
23
+ return new Promise((resolve, reject) => {
24
+ const signal = options.signal;
25
+ if (signal?.aborted) {
26
+ reject(abortReason(signal));
27
+ return;
28
+ }
29
+ const run = () => {
30
+ held.add(name);
31
+ signal?.removeEventListener('abort', onAbort);
32
+ let outcome;
33
+ try {
34
+ outcome = Promise.resolve(callback({ name }));
35
+ }
36
+ catch (err) {
37
+ outcome = Promise.reject(err);
38
+ }
39
+ outcome.then(resolve, reject).finally(() => grantNext(name));
40
+ };
41
+ const onAbort = () => {
42
+ const queue = waiters.get(name);
43
+ const i = queue?.indexOf(run) ?? -1;
44
+ if (queue !== undefined && i >= 0) {
45
+ queue.splice(i, 1);
46
+ if (queue.length === 0)
47
+ waiters.delete(name);
48
+ reject(abortReason(signal));
49
+ }
50
+ };
51
+ if (!held.has(name)) {
52
+ run();
53
+ return;
54
+ }
55
+ if (options.ifAvailable === true) {
56
+ Promise.resolve()
57
+ .then(() => callback(null))
58
+ .then(resolve, reject);
59
+ return;
60
+ }
61
+ let queue = waiters.get(name);
62
+ if (queue === undefined) {
63
+ queue = [];
64
+ waiters.set(name, queue);
65
+ }
66
+ queue.push(run);
67
+ signal?.addEventListener('abort', onAbort, { once: true });
68
+ });
69
+ },
70
+ };
71
+ }