@witbitz/sdk 0.0.0-stage → 4.4.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.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/sdkAccount.js ADDED
@@ -0,0 +1,483 @@
1
+ import { preferredAssociation, reconcileAccountLanes } from './laneAssociation.js'
2
+ // spaces/public/sdkAccount.js — `wb.account`: the account's LIVE index for a builder's app (2026-10-03; the owner, on what
3
+ // the SDK lacked next to the Spaces app: "And what about the index room etc." → "Yes"). wb.backup puts the room list in
4
+ // the vault for a RESTORE on a new device; this keeps two LIVE devices in step, the way the app's own index room does:
5
+ // the rooms (with their links), what was archived or forgotten, and the devices — with sign-out from another device.
6
+ //
7
+ // WHERE IT LIVES: a Witbitz room whose id and key are DERIVED from the backup's master secret (HKDF), so every device that
8
+ // holds the account — by enable() or restore({ code }) — finds the same room, and two devices can never make two indexes.
9
+ // The index is one state doc in it ('index', the account-doc size cap), and its content is sealed ON THE DEVICE under a
10
+ // third derived key before it is sent: the room's key reaches the standard tier like any room's, but what it carries —
11
+ // every room link the account holds — never does.
12
+ //
13
+ // HOW DEVICES AGREE: per-entry last-writer-wins. Every room entry carries `at` (the last change made to it), a forgotten
14
+ // room leaves a tombstone `{ room, at }`, and a device keeps `seenAt` and, once signed out, `out`. Merging is a union
15
+ // that keeps the newer of each — commutative, so devices converge whatever order they sync in; a write lost to a race
16
+ // is re-sent by its device on the next sync, because that device still sees its entry missing.
17
+ // ★ THE INDEX-CLOBBER RULE (the app lost an account's room list this way once — a fresh device wrote its EMPTY list over
18
+ // the real one): nothing is written unless the read before it was DEFINITIVE — a 200 whose content opened, or a 200
19
+ // with no doc yet. A failed, slow or unopenable read writes nothing and the sync reports { ok: false }.
20
+ // INSTANT (2026-10-03): every write to the index is announced on the index room's stream (agent/spaceService.mjs
21
+ // announceWrite), and a device that holds a socket on it syncs at once — a room made on the phone is on the laptop in
22
+ // about a second. The minute poll stays as the backstop for a socket that is down. Needs connect-src
23
+ // wss://code-relay.witbitz.chat in the page's CSP, like the room streams; without it the poll does the work.
24
+ import { healNames, isUnnamed } from './healNames.js'
25
+ import { latestTitle, titleFromDoc } from './roomName.js'
26
+ import { findEmptySpaces, removeEmptySpaces } from './emptySpaces.js'
27
+ import { indexGoneStep } from './indexGone.js'
28
+ import { openRoomStream } from './roomStreamClient.js'
29
+ import { sealDoc, openDoc, appStoreKey } from './accountSeal.js'
30
+ // THE APP'S FORMAT TOO (docs/sdk-account-format-plan.md phase 3, 3.24.0): the same room also holds the Spaces app's `xindex`,
31
+ // sealed under the app's account-store key. A sync reads BOTH docs and writes BOTH — the old `index` stays for every older
32
+ // release (they read only it), so an old and a new device of one account stay in step. sdkAccountDoc.js translates.
33
+ import { APP_DOC, toAppIndex, fromAppIndex, sameAppIndex } from './sdkAccountDoc.js'
34
+ // THE APP'S OPTIONAL SECTIONS (phase 5): wb.account.contacts / .name / .roomDefaults, in the app's docs of this same room — opt-in
35
+ import { attachSections, refreshSections } from './sdkAccountSections.js'
36
+ import { normUsageKey, pickUsageKey, newUsageKey, collectUsage, usageTotals, docNameFor, monthOf } from './usageReceipts.js' // the account's usage key (receipts on every turn; wb.account.usage)
37
+
38
+ const enc = new TextEncoder(), dec = new TextDecoder()
39
+ const SALT = enc.encode('witbitz-sdk-account-v1')
40
+ const DOC = 'index' // the server's account-doc cap (agent/spaceService.mjs INDEX_MAX_BYTES), not the 32 KB widget cap
41
+ const MAX_TOMBS = 500, MAX_DEVICES = 50
42
+ const SEEN_EVERY = 60 * 60 * 1000 // a device refreshes its "last seen" hourly, so an idle sync writes nothing
43
+ const fail = (code, msg, extra = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...extra })
44
+
45
+ const ub64 = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
46
+ const b64url = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
47
+ async function hkdf(secret, info, len) {
48
+ const km = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveBits'])
49
+ return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: enc.encode(info) }, km, len * 8))
50
+ }
51
+ /** The index room every device of the account derives: { room, mk, key } — `room` in the shape spaceConfig mints. */
52
+ export async function indexRoomOf(masterB64) {
53
+ const master = ub64(masterB64)
54
+ const id = await hkdf(master, 'index-room', 8)
55
+ const room = 'sp-' + [].slice.call(id).map((x) => x.toString(36)).join('').slice(0, 12)
56
+ const mk = b64url(await hkdf(master, 'index-mk', 32))
57
+ const key = await crypto.subtle.importKey('raw', await hkdf(master, 'index-seal', 32), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
58
+ return { room, mk, key }
59
+ }
60
+
61
+ // sealDoc / openDoc: accountSeal.js — the same sealing the Spaces app's account stores use
62
+
63
+ const num = (x) => (Number.isFinite(x) && x > 0 ? x : 0)
64
+ /** The union of two index views, the newer of each entry kept. Pure — the whole agreement between devices is here. */
65
+ export function mergeIndex(a, b, maxRooms = 500) {
66
+ const tomb = new Map()
67
+ for (const t of [...(a.tomb || []), ...(b.tomb || [])]) if (t && t.room) tomb.set(t.room, Math.max(tomb.get(t.room) || 0, num(t.at)))
68
+ const rooms = new Map()
69
+ for (const r of [...(a.rooms || []), ...(b.rooms || [])]) {
70
+ if (!r || !r.room) continue
71
+ const prev = rooms.get(r.room)
72
+ const latest = !prev || num(r.at) > num(prev.at) ? r : prev
73
+ const assoc = preferredAssociation(prev, r)
74
+ const newer = { ...latest, kind: assoc.kind, ...(assoc.associationAt ? { associationAt: assoc.associationAt } : {}) }
75
+ if (assoc.mintedFor || prev?.mintedFor || r.mintedFor) newer.mintedFor = assoc.mintedFor || prev?.mintedFor || r.mintedFor
76
+ if (assoc.laneOrigin === 'minted' && !assoc.detachedLane) newer.laneOrigin = 'minted'
77
+ else delete newer.laneOrigin
78
+ if (assoc.detachedLane) { newer.detachedLane = true; delete newer.shared }
79
+ else { delete newer.detachedLane; if (assoc.shared) newer.shared = assoc.shared; else delete newer.shared }
80
+ const pin = !prev || num(r.pinnedAt) > num(prev.pinnedAt) ? r : prev
81
+ rooms.set(r.room, pin.pinnedAt || pin.pinned ? { ...newer, pinned: !!pin.pinned, pinnedAt: num(pin.pinnedAt) } : newer)
82
+ }
83
+ for (const [room, r] of rooms) if (tomb.has(room) && tomb.get(room) >= num(r.at)) rooms.delete(room) // only a TOMBSTONE removes — an entry from a backup made before `at` existed has none
84
+ const devices = {}
85
+ for (const src of [a.devices || {}, b.devices || {}]) {
86
+ for (const [id, d] of Object.entries(src)) {
87
+ if (!d || typeof d !== 'object') continue
88
+ const p = devices[id]
89
+ devices[id] = !p ? { ...d } : { ...(num(d.seenAt) > num(p.seenAt) ? { ...p, ...d } : { ...d, ...p }), seenAt: Math.max(num(p.seenAt), num(d.seenAt)), ...((p.out || d.out) ? { out: Math.max(num(p.out), num(d.out)) } : {}) }
90
+ }
91
+ }
92
+ // LANE LINKS (lane.link): keyed by the pair, newest wins; an unlink is a `removed` entry, so it reaches every device too.
93
+ const links = new Map()
94
+ for (const l of [...(a.links || []), ...(b.links || [])]) {
95
+ if (!l || !l.a || !l.b) continue
96
+ const k = linkKey(l.a, l.b), prev = links.get(k)
97
+ if (!prev || num(l.at) > num(prev.at)) links.set(k, l)
98
+ }
99
+ const keepDevices = Object.entries(devices).sort((x, y) => num(y[1].seenAt) - num(x[1].seenAt)).slice(0, MAX_DEVICES)
100
+ return {
101
+ rooms: reconcileAccountLanes([...rooms.values()]).sort((x, y) => num(x.at) - num(y.at)).slice(-maxRooms),
102
+ tomb: [...tomb.entries()].map(([room, at]) => ({ room, at })).sort((x, y) => x.at - y.at).slice(-MAX_TOMBS),
103
+ devices: Object.fromEntries(keepDevices),
104
+ links: [...links.values()].sort((x, y) => num(x.at) - num(y.at)).slice(-200),
105
+ }
106
+ }
107
+ const linkKey = (a, b) => (a < b ? a + '|' + b : b + '|' + a)
108
+ /** THE ACCOUNT'S USAGE KEY (the owner, 2026-10-23: a builder's app records the account's usage too — docs/usage-receipts.md).
109
+ * One per account, in the index every device shares: the smaller id wins (as the app's pickUsageKey), and a key that lost
110
+ * stays among the old ones so receipts addressed to it are still collected. → { usage, usageOld } */
111
+ export function mergeUsage(a, b) {
112
+ const win = pickUsageKey(a && a.usage, b && b.usage)
113
+ const old = new Map()
114
+ for (const k of [...((a && a.usageOld) || []), ...((b && b.usageOld) || []), a && a.usage, b && b.usage].map(normUsageKey)) if (k && (!win || k.id !== win.id)) old.set(k.id, k)
115
+ return { usage: win, usageOld: [...old.values()].slice(-5) }
116
+ }
117
+ const usageCanon = (x) => JSON.stringify([(normUsageKey(x && x.usage) || {}).id || '', ((x && x.usageOld) || []).map((k) => k && k.id).sort()])
118
+ const canon = (x) => JSON.stringify({ u: usageCanon(x),
119
+ rooms: [...(x.rooms || [])].sort((p, q) => (p.room < q.room ? -1 : 1)).map((r) => Object.fromEntries(Object.entries(r).sort())),
120
+ tomb: [...(x.tomb || [])].sort((p, q) => (p.room < q.room ? -1 : 1)),
121
+ links: [...(x.links || [])].sort((p, q) => (linkKey(p.a, p.b) < linkKey(q.a, q.b) ? -1 : 1)).map((l) => Object.fromEntries(Object.entries(l).sort())),
122
+ devices: Object.fromEntries(Object.entries(x.devices || {}).sort().map(([k, v]) => [k, Object.fromEntries(Object.entries(v).sort())])),
123
+ })
124
+
125
+ export class AccountIndex {
126
+ /** @param {object} o { backup: AccountBackup, client: () => spaceClient, deviceName?, viewer? } */
127
+ constructor({ backup, client, deviceName = '', viewer = '', live = () => null, openStream = openRoomStream, version = '' } = {}) {
128
+ this._version = String(version || '').slice(0, 40) // devices[].sdk: the release this device runs (plan § 4.2, decision 6)
129
+ this._live = live
130
+ this._openStream = openStream
131
+ this._stream = null
132
+ this._backup = backup
133
+ this._client = client
134
+ this._deviceName = String(deviceName || '').slice(0, 80)
135
+ this._viewer = viewer
136
+ this._devices = {}
137
+ this._loc = null // { master, room, mk, key } for the backup's current master
138
+ const cur = new Map(); this._usageCursor = { get: (k) => cur.get(k), set: (k, v) => { cur.set(k, v) } } // where each room's receipts were read up to (this page)
139
+ this._pushT = null
140
+ this._poll = null
141
+ this._running = null
142
+ /** Called after a sync changed what this device holds (rooms or devices). */
143
+ this.onChange = null
144
+ /** Called once when another device signed THIS one out: the SDK has dropped the account here — clear what your app keeps. */
145
+ this.onSignedOut = null
146
+ this.lastError = null
147
+ backup._onLocal = () => this._schedule()
148
+ // enable() / restore(): the account now exists on this device — a browser starts keeping it in step at once.
149
+ backup._onStart = () => { this._schedule(); if (typeof window !== 'undefined') this.start() }
150
+ attachSections(this) // this.contacts, this.name, this.roomDefaults: nothing is read until the app uses one
151
+ }
152
+
153
+ get enabled() { return this._backup.enabled }
154
+ /** This device's id in the account (stable while its state is kept). */
155
+ get deviceId() { return (this._backup._s && this._backup._s.device && this._backup._s.device.id) || '' }
156
+ /** The account's rooms: [{ room, link, kind, label?, shared?, archived? }] — archived ones included, so filter as you like. */
157
+ get rooms() { return this._backup.rooms }
158
+ /** The account's devices: [{ id, name, seenAt, signedOut, current }]. */
159
+ get devices() {
160
+ return Object.entries(this._devices).map(([id, d]) => ({ id, name: d.name || '', seenAt: num(d.seenAt), signedOut: !!d.out, current: id === this.deviceId, ...(typeof d.sdk === 'string' && d.sdk ? { sdk: d.sdk } : {}) }))
161
+ .sort((x, y) => y.seenAt - x.seenAt)
162
+ }
163
+
164
+ /** The member's linked lanes (lane.link), on every device: [{ a, b, cap? }] — two lane rooms. Links run where BOTH lanes
165
+ * are open, so a device that opens them links them again: `laneA.link(laneB)` for each pair listed here. */
166
+ get links() { return ((this._backup._s && this._backup._s.links) || []).filter((l) => !l.removed).map(({ a, b, cap }) => ({ a, b, ...(Number.isFinite(cap) ? { cap } : {}) })) }
167
+
168
+ /** @private the account's usage key (null until the index has given one) — and with the ones it replaced, for collecting. */
169
+ _usageKey() { const s = this._backup._s; return (s && normUsageKey(s.usage)) || null }
170
+ _usageKeys() { const s = this._backup._s; return s ? [normUsageKey(s.usage), ...((s.usageOld || []).map(normUsageKey))].filter(Boolean) : [] }
171
+
172
+ _noteLink(a, b, cap) {
173
+ const s = this._backup._s; if (!s) return
174
+ const k = linkKey(a, b)
175
+ const prev = (s.links || []).find((l) => linkKey(l.a, l.b) === k)
176
+ if (prev && !prev.removed && prev.cap === cap) return
177
+ s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, cap, at: Date.now() }].slice(-200)
178
+ this._backup._changed(); this._schedule()
179
+ }
180
+ _dropLink(a, b) {
181
+ const s = this._backup._s; if (!s) return
182
+ const k = linkKey(a, b)
183
+ s.links = [...(s.links || []).filter((l) => linkKey(l.a, l.b) !== k), { a, b, removed: true, at: Date.now() }].slice(-200)
184
+ this._backup._changed(); this._schedule()
185
+ }
186
+
187
+ /** Mark a room archived (or not) on every device. It stays in the account and in the backup. */
188
+ archive(room, on = true) { return this._edit(room, (r) => ({ ...r, archived: !!on })) }
189
+ pin(room, on = true) { return this._edit(room, (r) => ({ ...r, pinned: !!on, pinnedAt: Math.max(Date.now(), num(r.pinnedAt) + 1) })) }
190
+ /** Rename a room in the account (the label a restore and your list show). */
191
+ rename(room, label) { return this._edit(room, (r) => ({ ...r, label: String(label || '').slice(0, 120), renamed: true })) }
192
+ /** Drop a room from the account on EVERY device — the room itself is not deleted (that is wb.rooms.delete, for a
193
+ * tenant). Opening its link again later brings it back. */
194
+ forget(room) {
195
+ for (const child of this._backup.rooms || []) if (child.shared === room) this._backup._detachLane(child.room, room)
196
+ this._backup.remove(room)
197
+ this._pruneAgents?.()
198
+ return this
199
+ }
200
+ async repairNames() { return this._repairNames(this._readName) }
201
+ async _repairNames(read) {
202
+ const state = this._backup._s
203
+ if (!state || !this.enabled) return 0
204
+ const rows = () => this._backup._s === state ? state.rooms : []
205
+ const view = r => ({ room: r.room, title: r.label, renamed: r.renamed })
206
+ return healNames({
207
+ rows: () => rows().map(view), latestTitle, titleFromDoc,
208
+ read: async room => {
209
+ const row = rows().find(r => r.room === room)
210
+ return row ? read(row) : null
211
+ },
212
+ apply: (room, title, manual) => {
213
+ const row = rows().find(r => r.room === room)
214
+ if (!row || !isUnnamed(view(row))) return false
215
+ this._edit(room, r => ({ ...r, label: title, renamed: manual }))
216
+ return true
217
+ },
218
+ }, new Set())
219
+ }
220
+ async previewEmptySpaces({ detailed = false } = {}) {
221
+ let unreadable = 0
222
+ const rooms = await findEmptySpaces({ onUnreadable: () => { unreadable++ } }, this._emptyHooks())
223
+ return detailed ? { rooms, unreadable } : rooms
224
+ }
225
+ async removeEmptySpaces({ rooms, confirm } = {}) {
226
+ if (confirm !== true || !Array.isArray(rooms) || rooms.some(id => typeof id !== 'string')) throw fail('confirmation_required', 'Pass the selected room ids and confirm: true')
227
+ const hooks = this._emptyHooks(), selected = new Set(rooms)
228
+ const candidates = hooks.rooms().filter(r => selected.has(r.room))
229
+ return removeEmptySpaces(candidates, hooks)
230
+ }
231
+ async listDevices() {
232
+ const b = this._backup, state = b._s
233
+ const rows = this.devices.map(d => ({ ...d, spk: this._devices[d.id]?.spk || null }))
234
+ if (!b._v2 || b.service !== 'account' || !b.enabled) return rows
235
+ const serviceRows = await b._v2.listDevices(b)
236
+ if (b._s !== state) throw fail('account_changed', 'The account changed while listing devices')
237
+ for (const d of serviceRows || []) {
238
+ if (!d || typeof d.spk !== 'string' || !d.spk) continue
239
+ const indexed = rows.find(r => r.spk === d.spk || (r.current && d.me))
240
+ const registration = { ...(typeof d.state === 'string' ? { state: d.state } : {}), ...(Number.isFinite(d.at) ? { addedAt: d.at * 1000 } : {}) }
241
+ if (indexed) { Object.assign(indexed, { spk: d.spk, ...registration }); continue }
242
+ rows.push({ id: 'service:' + d.spk, spk: d.spk, name: d.label || 'Device', seenAt: 0, ...registration, current: !!d.me, signedOut: false })
243
+ }
244
+ return rows
245
+ }
246
+ async signOutDevice(id, { getCode } = {}) {
247
+ const b = this._backup, state = b._s
248
+ const row = (await this.listDevices()).find(d => d.id === id)
249
+ if (!row || row.current || b._s !== state) throw fail('unknown_device', 'Choose another device currently on this account')
250
+ if (row.spk && b.service === 'account') await b._v2.signOutDevice(b, { spk: row.spk, getCode })
251
+ if (b._s !== state) throw fail('account_changed', 'The account changed during sign-out')
252
+ if (Object.hasOwn(this._devices, id)) this.signOut(id)
253
+ return { revoked: true }
254
+ }
255
+
256
+ /** Sign another device out: at its next sync it drops the account and your app is told (onSignedOut). */
257
+ signOut(deviceId, { reason } = {}) {
258
+ const d = this._devices[deviceId]
259
+ if (!d) throw fail('unknown_device', 'no such device in this account')
260
+ const at = Date.now()
261
+ this._devices[deviceId] = { ...d, out: at, ...(['erased', 'moved'].includes(reason) ? { outWhy: reason } : {}) }
262
+ // KEPT until the index carries it (pass 6, K#7): a sign-out lived only in memory — a page closed before the next write lost it
263
+ const s = this._backup._s
264
+ if (s) { s.outs = { ...(s.outs || {}), [deviceId]: at }; this._backup._changed() }
265
+ this._schedule()
266
+ return this
267
+ }
268
+
269
+ /** Pull the index, merge, push what this device knows that it lacks. → { ok, rooms, devices } — ok:false (nothing
270
+ * written) when the index could not be READ, so a failed read can never cost the account its list. */
271
+ /** WHAT THIS ACCOUNT USED in a month, across its rooms and whoever paid (docs/usage-receipts.md — the app's Settings → Your
272
+ * usage; the owner, 2026-10-23: a builder's app records it too). Every turn this account's devices send carries a
273
+ * receipt address; the server seals each reply's cost to it, in the room. This folds the new receipts into the account's
274
+ * monthly sidecar (kept in the index room, sealed like the index) and reads the month.
275
+ * @param {object} [o] { month?: 'YYYY-MM' } (default this month, UTC)
276
+ * → { month, replies, costMicros, costUsd, byPayer: { you, admin, app, witbitz } (micros), byDay, in, out } */
277
+ async usage({ month } = {}) {
278
+ if (!this.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore)')
279
+ const m = month === undefined ? monthOf(Date.now()) : String(month)
280
+ if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(m)) throw fail('invalid_argument', 'month is YYYY-MM')
281
+ await this.sync() // the usage key comes from the index (made by the first device that finds none)
282
+ const loc = await this._where(), c = this._client()
283
+ const vOf = new Map() // name → the version last read: a write lands only over it (sync sweep 11-08 #32); collectUsage reads back and retries
284
+ const readDoc = async (name) => {
285
+ const r = await c.state(loc.room, loc.mk, name)
286
+ if (!r || r.status !== 200) throw fail('unreadable', 'the usage record could not be read', { status: r && r.status })
287
+ if (Number.isInteger(r.v)) vOf.set(name, r.v); else vOf.delete(name)
288
+ const st = r.state
289
+ return st == null || (typeof st === 'object' && !Object.keys(st).length) ? null : openDoc(loc.key, st)
290
+ }
291
+ const writeDoc = async (name, doc) => {
292
+ const w = await c.state(loc.room, loc.mk, name, await sealDoc(loc.key, doc), 'usage', 'device', vOf.has(name) ? vOf.get(name) : undefined)
293
+ if (!w || w.status !== 200) throw fail('save_failed', 'the usage record could not be saved', { status: w && w.status })
294
+ }
295
+ if (typeof c.receipts === 'function') {
296
+ const rooms = this.rooms.map((r) => r.room)
297
+ for (const key of this._usageKeys()) await collectUsage({ key, rooms, read: (room, drop, since) => c.receipts(room, drop, since), ack: (room, drop, upTo) => c.receiptsAck(room, drop, upTo), readDoc, writeDoc, cursor: this._usageCursor }).catch(() => null)
298
+ }
299
+ const t = usageTotals(await readDoc(docNameFor(m)))
300
+ return { month: m, ...t, costUsd: t.costMicros / 1e6 }
301
+ }
302
+
303
+ async sync() {
304
+ if (!this._backup.enabled) throw fail('not_enabled', 'no account on this device — call wb.backup.enable() or restore({ code }) first')
305
+ // A CHANGE MADE WHILE A PASS IS OUT (pass 6, K#7): the running pass may have read and merged before it — it was left for
306
+ // the next sync (a minute). One more pass runs as soon as this one settles, and the caller waits for that one.
307
+ if (this._running) {
308
+ if (!this._again) this._again = this._running.catch(() => null).then(() => { this._again = null; return this.enabled ? this.sync() : { ok: false, rooms: this.rooms, devices: this.devices } })
309
+ return this._again
310
+ }
311
+ this._running = this._sync().finally(() => { this._running = null; this._syncSettled?.(); this._pruneAgents?.() })
312
+ return this._running
313
+ }
314
+
315
+ /** Keep in step on their own: a sync every `every` ms while the page is visible, and when it becomes visible. */
316
+ start({ every = 60_000 } = {}) {
317
+ this.stop()
318
+ if (typeof setInterval !== 'function') return this
319
+ const visible = () => typeof document === 'undefined' || document.visibilityState !== 'hidden'
320
+ this._poll = setInterval(() => { if (this.enabled && visible()) this.sync().catch((e) => { this.lastError = e }) }, Math.max(5_000, every))
321
+ if (typeof document !== 'undefined' && document.addEventListener) {
322
+ this._onVis = () => { if (this.enabled && visible()) this.sync().catch((e) => { this.lastError = e }) }
323
+ document.addEventListener('visibilitychange', this._onVis)
324
+ }
325
+ this._listen()
326
+ return this
327
+ }
328
+
329
+ // The socket on the index room's stream: any write to the index (another device's, or this one's) → sync now.
330
+ _listen() {
331
+ const l = this._live && this._live()
332
+ if (!l || !l.WebSocketImpl || this._stream || !this.enabled) return
333
+ const master = this._backup._s.master
334
+ this._where().then((loc) => {
335
+ if (this._stream || !this.enabled || this._backup._s.master !== master || !this._poll) return
336
+ this._stream = this._openStream({
337
+ mk: loc.mk, path: 's', WebSocketImpl: l.WebSocketImpl,
338
+ onEvent: (ev) => { if (ev && ev.k === 'poll' && this.enabled) this.sync().catch((e) => { this.lastError = e }) },
339
+ })
340
+ }).catch(() => { /* the poll still runs */ })
341
+ }
342
+ stop() {
343
+ if (this._poll) { clearInterval(this._poll); this._poll = null }
344
+ if (this._onVis && typeof document !== 'undefined') { document.removeEventListener('visibilitychange', this._onVis); this._onVis = null }
345
+ clearTimeout(this._pushT); this._pushT = null
346
+ if (this._stream) { try { this._stream.stop() } catch { /* */ } this._stream = null }
347
+ return this
348
+ }
349
+
350
+ // ── internals ───────────────────────────────────────────────────────────────────────────────────────────────────
351
+ _edit(room, fn) {
352
+ const s = this._backup._s
353
+ const i = s ? s.rooms.findIndex((r) => r.room === room) : -1
354
+ if (i < 0) throw fail('unknown_room', 'that room is not in this account')
355
+ s.rooms[i] = { ...fn(s.rooms[i]), at: Date.now() }
356
+ this._backup._schedule()
357
+ return this
358
+ }
359
+ _schedule() { if (!this.enabled) return; clearTimeout(this._pushT); this._pushT = setTimeout(() => { this._pushT = null; this.sync().catch((e) => { this.lastError = e }) }, 300) }
360
+
361
+ async _where() {
362
+ const master = this._backup._s.master
363
+ if (!this._loc || this._loc.master !== master) this._loc = { master, ...(await indexRoomOf(master)), app: await appStoreKey(ub64(master)) }
364
+ return this._loc
365
+ }
366
+ _me() {
367
+ const s = this._backup._s
368
+ if (!s.device || !s.device.id) { s.device = { id: 'd_' + b64url(crypto.getRandomValues(new Uint8Array(9))), name: this._deviceName }; this._backup._changed() }
369
+ if (this._deviceName && s.device.name !== this._deviceName) { s.device = { ...s.device, name: this._deviceName }; this._backup._changed() }
370
+ return s.device
371
+ }
372
+ async _read(loc, name = DOC, key = loc.key) {
373
+ const c = this._client()
374
+ let r
375
+ try { r = await c.state(loc.room, loc.mk, name) } catch { return { ok: false } }
376
+ if (!r || r.status !== 200) return { ok: false, status: r && r.status }
377
+ const st = r.state
378
+ const v = Number.isInteger(r.v) ? r.v : 0 // the version this read saw — the write is conditional on it
379
+ if (st == null || (typeof st === 'object' && !Object.keys(st).length)) return { ok: true, doc: null, v }
380
+ try { return { ok: true, doc: await openDoc(key, st), v } } catch { return { ok: false, unopenable: true } }
381
+ }
382
+ async _ensureRoom(loc) {
383
+ if (loc.made) return
384
+ try { await this._client().create({ room: loc.room, mk: loc.mk }, { base: this._viewer || undefined }) } catch (e) { if (!/409|exists/.test(String(e && e.message))) throw e }
385
+ loc.made = true
386
+ }
387
+ // Read → merge → write ONLY IF the index has not moved since the read (ifV); another device that wrote in between makes
388
+ // the server answer 409, and the merge runs again on what it wrote — two devices syncing at once both keep their rooms
389
+ // (a reviewer's finding, 2026-10-05; spaces/test/sdkAccountIndex.test.mjs).
390
+ async _sync() {
391
+ for (let i = 0; i < 5; i++) {
392
+ const r = await this._syncOnce()
393
+ if (!r.conflict) { if (r.ok && !r.signedOut) await refreshSections(this); return r } // a section in use: read again (its 'change' event)
394
+ await new Promise((res) => setTimeout(res, 20 + Math.floor(Math.random() * 80) * (i + 1)))
395
+ }
396
+ this.lastError = fail('save_failed', 'the account index kept changing under this device — try again', { status: 409 })
397
+ return { ok: false, rooms: this.rooms, devices: this.devices }
398
+ }
399
+ async _syncOnce() {
400
+ // ★ ONE ACCOUNT PER PASS (pass 6, docs/state-machines.md K#2): a vault switching accounts swaps the backup's state (_adopt,
401
+ // _drop, restore) while a pass awaits; the pass then merged account B's rooms into account A's index under A's key, and A's
402
+ // rooms into B's backup. The pass keeps the state it began with and stops the moment another is in its place.
403
+ const s0 = this._backup._s
404
+ const moved = () => this._backup._s !== s0
405
+ const stopped = () => ({ ok: false, rooms: this.rooms, devices: this.devices })
406
+ if (!s0) return stopped()
407
+ const loc = await this._where()
408
+ if (moved()) return stopped()
409
+ // CREATE BEFORE THE FIRST READ, once per device (an existing room answers 409). A read of an unknown room is not
410
+ // refused — the server adopts it with no owner — so waiting for a 404 would leave the index outside the app's tenant.
411
+ const me0 = this._me()
412
+ if (!me0.made) {
413
+ try { await this._ensureRoom(loc) } catch (e) { this.lastError = e; return { ok: false, rooms: this.rooms, devices: this.devices } }
414
+ if (moved()) return stopped()
415
+ this._backup._s.device = { ...me0, made: true }; this._backup._changed()
416
+ }
417
+ const got = await this._read(loc)
418
+ if (moved()) return stopped()
419
+ // THE ACCOUNT WAS DELETED while this device was away (sync sweep 2026-11-18 #11): its index answers 410 — twice, a minute apart,
420
+ // and this device signs itself out as erased, as the app does (indexGone.js, the one rule)
421
+ {
422
+ const s0 = this._backup._s || {}, g = indexGoneStep(s0.indexGoneAt || 0, got.ok ? 200 : got.status)
423
+ if ((s0.indexGoneAt || 0) !== g.first) { if (g.first) s0.indexGoneAt = g.first; else delete s0.indexGoneAt; this._backup._changed() }
424
+ if (g.erased) return this._signedOut('erased')
425
+ }
426
+ const gotX = got.ok ? await this._read(loc, APP_DOC, loc.app) : got // the app-format doc: the same clobber rule — unknown is not empty
427
+ if (moved()) return stopped()
428
+ if (!gotX.ok) { this.lastError = fail(gotX.unopenable ? 'unopenable' : 'unreadable', gotX.unopenable ? 'the account index could not be opened' : 'the account index could not be read', { status: gotX.status }); return { ok: false, rooms: this.rooms, devices: this.devices } }
429
+ const old = got.doc ? { rooms: got.doc.rooms || [], tomb: got.doc.tomb || [], links: got.doc.links || [], devices: got.doc.devices || {}, usage: normUsageKey(got.doc.usage), usageOld: (got.doc.usageOld || []).map(normUsageKey).filter(Boolean) } : { rooms: [], tomb: [], links: [], devices: {}, usage: null, usageOld: [] }
430
+ const fromApp = fromAppIndex(gotX.doc)
431
+ const remote = { ...mergeIndex(old, fromApp), ...mergeUsage(old, fromApp) } // READ-THROUGH: both docs, the newer of each entry (one rule, mergeIndex)
432
+ const s = this._backup._s
433
+ const me = this._me()
434
+ const mine = this._devices[me.id] || {}
435
+ // a sign-out this device made and kept (K#7): back into the list after a reload, until the index carries it
436
+ const outs = s.outs || {}
437
+ const localDevices = { ...this._devices }
438
+ for (const [id, at] of Object.entries(outs)) { const d = localDevices[id] || remote.devices[id]; if (d && num(d.out) < at) localDevices[id] = { ...d, out: at } }
439
+ const local = { rooms: s.rooms, tomb: s.tomb || [], links: s.links || [], devices: { ...localDevices, [me.id]: { ...mine, name: me.name || mine.name || '', seenAt: num(mine.seenAt), ...(typeof this._spk === 'string' && this._spk ? { spk: this._spk } : {}), ...(this._version ? { sdk: this._version } : {}) } } }
440
+ const merged = mergeIndex(local, remote)
441
+ // the usage key: made by the first device that finds none — only after this DEFINITIVE read, so two keys meet only in a race
442
+ Object.assign(merged, mergeUsage({ usage: s.usage, usageOld: s.usageOld }, remote))
443
+ if (!merged.usage) merged.usage = await newUsageKey()
444
+ if (moved()) return stopped()
445
+ const self = merged.devices[me.id]
446
+ if (self.out) return this._signedOut(['erased', 'moved'].includes(self.outWhy) ? self.outWhy : undefined)
447
+ if (Date.now() - num(self.seenAt) > SEEN_EVERY) merged.devices[me.id] = { ...self, seenAt: Date.now() }
448
+ const before = canon({ rooms: s.rooms, tomb: s.tomb || [], links: s.links || [], devices: this._devices, usage: s.usage, usageOld: s.usageOld })
449
+ const usageBefore = usageCanon(s)
450
+ const roomsBefore = canon({ rooms: s.rooms, tomb: s.tomb || [] })
451
+ this._devices = merged.devices
452
+ s.rooms = merged.rooms; s.tomb = merged.tomb; s.links = merged.links; s.usage = merged.usage; s.usageOld = merged.usageOld
453
+ const after = canon(merged)
454
+ // DUAL WRITE: the old doc for every older release, then the app's; each only when it differs from what it holds, each over
455
+ // the version read. A 409 on either re-reads both and merges again.
456
+ const appDoc = toAppIndex(merged, gotX.doc)
457
+ for (const [differs, name, key, body, v] of [[after !== canon(old), DOC, loc.key, { v: 1, rooms: merged.rooms, tomb: merged.tomb, links: merged.links, devices: merged.devices, usage: merged.usage, ...(merged.usageOld.length ? { usageOld: merged.usageOld } : {}) }, got.v],
458
+ [!sameAppIndex(appDoc, gotX.doc), APP_DOC, loc.app, { ...appDoc, at: Date.now() }, gotX.v]]) {
459
+ if (!differs) continue
460
+ const w = await this._client().state(loc.room, loc.mk, name, await sealDoc(key, body), 'account index', 'device', v)
461
+ if (w && w.status === 409) return { conflict: true } // the merged state is kept locally; the next pass re-reads and merges again
462
+ if (!w || w.status !== 200) { this.lastError = fail('save_failed', 'the account index could not be saved', { status: w && w.status }); return { ok: false, rooms: this.rooms, devices: this.devices } }
463
+ }
464
+ // the index now carries each kept sign-out (written above, or it already had it) — or the device is gone from it: let go
465
+ if (Object.keys(outs).length) {
466
+ const left = Object.fromEntries(Object.entries(outs).filter(([id, at]) => merged.devices[id] && num(merged.devices[id].out) < at))
467
+ if (Object.keys(left).length) s.outs = left; else delete s.outs
468
+ this._backup._changed()
469
+ }
470
+ if (canon({ rooms: merged.rooms, tomb: merged.tomb }) !== roomsBefore) this._backup._persist() // the vault copy holds rooms + tombs, not devices
471
+ if (usageCanon(merged) !== usageBefore) this._backup._changed() // this device keeps the account's usage key
472
+ if (after !== before) { if (canon({ links: merged.links }) !== canon({ links: local.links })) this._backup._changed(); if (typeof this.onChange === 'function') { try { this.onChange({ rooms: this.rooms, devices: this.devices }) } catch { /* the app's callback */ } } }
473
+ this.lastError = null
474
+ return { ok: true, rooms: this.rooms, devices: this.devices }
475
+ }
476
+ _signedOut(reason) {
477
+ this.stop()
478
+ this._devices = {}
479
+ this._backup._drop()
480
+ if (typeof this.onSignedOut === 'function') { try { this.onSignedOut(reason ? { reason } : undefined) } catch { /* the app's callback */ } }
481
+ return { ok: true, signedOut: true, rooms: [], devices: [], ...(reason ? { reason } : {}) }
482
+ }
483
+ }
@@ -0,0 +1,89 @@
1
+ // sdkAccountDoc.js — the SDK's live account index IN THE SPACES APP'S FORMAT (docs/sdk-account-format-plan.md phase 3; the
2
+ // owner, 2026-11-13: "yes. Do 1-5"). The SDK keeps its index in its DERIVED room (sdkAccount.js indexRoomOf), and there it now
3
+ // also keeps the app's `xindex` doc, built by the app's own rules (accountIndexDoc.js), sealed under the app's account-store
4
+ // key. Pure: the SDK's view ({ rooms[], tomb[], links[], devices{}, usage, usageOld }) ↔ the app's doc, both ways.
5
+ //
6
+ // TRANSLATE, DO NOT DROP (§4.1): a room's entry is the app's ({ mk, title, titleAt, manual, at, archived, archivedAt, pinned,
7
+ // pinnedAt }) plus what only the SDK reopens a room with — `link`, `kind`, a lane's `shared`, a label the app's title cannot
8
+ // hold, a split room's ASSEMBLED key (decision 5). A forgotten room is `forgot: <at>` — the SDK's RE-OPENABLE mark — never the
9
+ // app's final `deleted` (decision 4). Devices: { name, seenAt, out } ↔ { label, lastSeenAt } + `signouts`; `sdk` (the release a
10
+ // device runs) rides along. Entries the SDK cannot read (no link, no mark) are carried over as they were.
11
+ import { preferredAssociation } from './laneAssociation.js'
12
+ import { indexDoc, indexRoomEntry } from './accountIndexDoc.js'
13
+ import { keyInLink, roomPin } from './accountRecord.js'
14
+ import { normUsageKey } from './usageReceipts.js'
15
+
16
+ export const APP_DOC = 'xindex' // the app's sealed 'index' (accountStores.js SEALED)
17
+ const ERASED_MARK = '@erased' // = devices.js ERASED_MARK: Delete my account's pseudo-entry in the index's sign-outs
18
+ const MOVED_MARK = '@moved'
19
+ const num = (x) => (Number.isFinite(x) && x > 0 ? x : 0)
20
+ const obj = (x) => (x && typeof x === 'object' && !Array.isArray(x) ? x : {})
21
+
22
+ /** The SDK's view → the app's `xindex` doc. `prev`: the doc as read (its fields the SDK does not own are kept). */
23
+ export function toAppIndex ({ rooms = [], tomb = [], links = [], devices = {}, usage, usageOld = [] } = {}, prev = null) {
24
+ const p = obj(prev), map = {}
25
+ for (const r of rooms) {
26
+ if (!r || !r.room || typeof r.link !== 'string' || !r.link) continue
27
+ const mk = keyInLink(r.link) || (typeof r.mk === 'string' ? r.mk : '')
28
+ const at = num(r.at), e = indexRoomEntry({ room: r.room, title: r.label || '', titleAt: at, ...roomPin(r), renamed: typeof r.renamed === 'boolean' ? r.renamed : !!(r.label && r.label !== 'Space' && r.label !== r.room), at, archived: !!r.archived, archivedAt: at }, obj(p.rooms)[r.room] || undefined, mk ? { mk } : {}) // prev: the app's per-field rules, and the "always on" mark it keeps (sync sweep 2026-11-23 #13 — every SDK write dropped it)
29
+ const association = preferredAssociation(r, obj(p.rooms)[r.room])
30
+ const detached = !!association.detachedLane
31
+ map[r.room] = { ...e, ...(num(association.associationAt) ? { associationAt: association.associationAt } : {}), ...(detached ? { detachedLane: true } : {}), link: r.link, kind: !detached && association.kind === 'lane' ? 'lane' : 'space', ...(association.kind === 'lane' && association.shared ? { shared: association.shared } : {}), ...(r.label && e.title !== r.label ? { label: r.label } : {}) }
32
+ if (association.mintedFor || r.mintedFor || e.mintedFor) map[r.room].mintedFor = association.mintedFor || r.mintedFor || e.mintedFor
33
+ if (association.laneOrigin === 'minted' && !detached) map[r.room].laneOrigin = 'minted'
34
+ else delete map[r.room].laneOrigin
35
+ if (detached) delete map[r.room].shared
36
+ else delete map[r.room].detachedLane
37
+ }
38
+ for (const t of tomb) if (t && t.room) map[t.room] = { ...(map[t.room] || {}), forgot: Math.max(num(t.at), num((map[t.room] || {}).forgot)) || 1 }
39
+ for (const [room, e] of Object.entries(obj(p.rooms))) if (!(room in map) && e && typeof e === 'object' && !e.link && !e.forgot) map[room] = e
40
+ // SIGN-OUTS ARE CARRIED, NOT REBUILT (sync sweep 11-18): the app's marks ride here too — `@erased` (Delete my account: every other
41
+ // device signs out) and `@moved` — and a device the SDK's view does not list. Rebuilt from the SDK's devices alone, an SDK write
42
+ // between the app's mark and the index's deletion dropped it. A mark only grows (the later time wins).
43
+ // A DEVICE SIGNED OUT BECAUSE THE ACCOUNT WAS DELETED (`outWhy: 'erased'`) is the app's ERASED mark too (sync sweep 11-22 #8): the
44
+ // app reads only the mark (devices.js remoteSignoutReason — a stamp no newer than it is 'erased'), so an app device of an account
45
+ // deleted through the SDK said "signed out remotely".
46
+ const devs = {}, signouts = {}
47
+ let erasedAt = 0, movedAt = 0
48
+ for (const [id, at] of Object.entries(obj(p.signouts))) if (num(at)) signouts[id] = at
49
+ for (const [id, d] of Object.entries(obj(devices))) {
50
+ if (!d || typeof d !== 'object') continue
51
+ const { name, seenAt, out, ...rest } = d
52
+ devs[id] = { ...rest, ...(name !== undefined ? { label: name } : {}), ...(seenAt !== undefined ? { lastSeenAt: seenAt } : {}) }
53
+ if (num(out)) signouts[id] = Math.max(out, num(signouts[id]))
54
+ if (num(out) && rest.outWhy === 'erased') erasedAt = Math.max(erasedAt, signouts[id])
55
+ if (num(out) && rest.outWhy === 'moved') movedAt = Math.max(movedAt, signouts[id])
56
+ }
57
+ if (erasedAt) signouts[ERASED_MARK] = Math.max(erasedAt, num(signouts[ERASED_MARK]))
58
+ if (movedAt) signouts[MOVED_MARK] = Math.max(movedAt, num(signouts[MOVED_MARK]))
59
+ const u = normUsageKey(usage)
60
+ return { ...indexDoc({ rooms: map, devices: devs, signouts, name: typeof p.name === 'string' ? p.name : '', seen: p.seen, vseen: p.vseen, inviteKey: p.inviteKey, usageKey: u, usageKeysOld: (usageOld || []).map(normUsageKey).filter(Boolean), pipesRoom: p.pipesRoom, msgsRoom: p.msgsRoom }),
61
+ ...(Array.isArray(links) && links.length ? { links } : {}) }
62
+ }
63
+
64
+ /** The app's `xindex` doc (as the SDK wrote it) → the SDK's view; an empty view for none. */
65
+ export function fromAppIndex (doc) {
66
+ const d = obj(doc), rooms = [], tomb = []
67
+ for (const [room, e] of Object.entries(obj(d.rooms))) {
68
+ if (!e || typeof e !== 'object') continue
69
+ const deletedAt = Math.max(num(e.forgot), e.deleted ? num(e.at) : 0)
70
+ if (deletedAt) tomb.push({ room, at: deletedAt })
71
+ if (typeof e.link !== 'string' || !e.link || e.deleted) continue
72
+ const label = e.label !== undefined ? e.label : (e.title && e.title !== 'Space' && e.title !== room || e.manual ? e.title : undefined)
73
+ rooms.push({ room, ...roomPin(e), ...(e.mintedFor ? { mintedFor: e.mintedFor } : {}), ...(e.laneOrigin === 'minted' && !e.detachedLane ? { laneOrigin: 'minted' } : {}), ...(num(e.associationAt) ? { associationAt: e.associationAt } : {}), ...(e.detachedLane ? { detachedLane: true } : {}), ...(num(e.at) ? { at: e.at } : {}), ...(e.archived ? { archived: true } : {}), link: e.link, kind: !e.detachedLane && e.kind === 'lane' ? 'lane' : 'space',
74
+ ...(label ? { label } : {}), ...(label && !e.manual ? { renamed: false } : e.manual && (label === 'Space' || label === room) ? { renamed: true } : {}), ...(!e.detachedLane && e.kind === 'lane' && e.shared ? { shared: e.shared } : {}), ...(typeof e.mk === 'string' && e.mk && e.mk !== keyInLink(e.link) ? { mk: e.mk } : {}) })
75
+ }
76
+ // …and the app's ERASED mark is the SDK's reason (#8): an SDK device whose stamp is no newer than the mark was signed out by Delete my
77
+ // account in the app — its onSignedOut hears { reason: 'erased' }, as when the SDK deleted it
78
+ const devices = {}, so = obj(d.signouts), erased = num(so[ERASED_MARK]), moved = num(so[MOVED_MARK])
79
+ for (const [id, e] of Object.entries(obj(d.devices))) {
80
+ if (!e || typeof e !== 'object') continue
81
+ const { label, lastSeenAt, ...rest } = e
82
+ devices[id] = { ...rest, ...(label !== undefined ? { name: label } : {}), ...(lastSeenAt !== undefined ? { seenAt: lastSeenAt } : {}), ...(num(so[id]) ? { out: so[id] } : {}), ...(num(so[id]) && erased >= so[id] ? { outWhy: 'erased' } : num(so[id]) && moved >= so[id] ? { outWhy: 'moved' } : {}) }
83
+ }
84
+ return { rooms, tomb, links: Array.isArray(d.links) ? d.links : [], devices, usage: normUsageKey(d.usageKey), usageOld: (Array.isArray(d.usageKeysOld) ? d.usageKeysOld : []).map(normUsageKey).filter(Boolean) }
85
+ }
86
+
87
+ const stable = (x) => (Array.isArray(x) ? '[' + x.map(stable).join(',') + ']' : x && typeof x === 'object' ? '{' + Object.keys(x).filter((k) => x[k] !== undefined).sort().map((k) => JSON.stringify(k) + ':' + stable(x[k])).join(',') + '}' : JSON.stringify(x))
88
+ /** The same doc, its write time and key order aside (the app's sameDoc rule) — an unknown doc is never the same. */
89
+ export const sameAppIndex = (a, b) => !!(a && b) && stable({ ...a, at: 0 }) === stable({ ...b, at: 0 })