@openclaw/matrix 2026.7.1-beta.6 → 2026.7.2-beta.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 (87) hide show
  1. package/dist/{account-selection-5e4mHR1m.js → account-selection-Bz00QTmQ.js} +4 -3
  2. package/dist/api.js +8 -8
  3. package/dist/{approval-handler.runtime-DI5x9r8I.js → approval-handler.runtime--Ei44Vo2.js} +27 -17
  4. package/dist/{approval-ids-ZgqbspmS.js → approval-ids-C_2kSMdJ.js} +1 -1
  5. package/dist/{approval-reaction-auth-D9LijQhr.js → approval-reaction-auth-TdVPcgxP.js} +2 -2
  6. package/dist/approval-reactions-BgU51JGd.js +202 -0
  7. package/dist/auth-presence.js +1 -1
  8. package/dist/{channel-jUTBsjHU.js → channel-CxqDh7mS.js} +102 -143
  9. package/dist/channel-plugin-api.js +1 -1
  10. package/dist/{channel.runtime-DO1Nv9ed.js → channel.runtime-wNfJc57I.js} +7 -7
  11. package/dist/{cli-metadata-CfiEO-CE.js → cli-metadata-Gf3HSJ2c.js} +1 -1
  12. package/dist/cli-metadata.js +1 -1
  13. package/dist/{cli-CEfWwCKx.js → cli-o00oTJhx.js} +12 -12
  14. package/dist/{client-FRuyCNju.js → client-ClHisZbf.js} +2 -2
  15. package/dist/{client-tgnlQJk4.js → client-DP0nmFxK.js} +4 -4
  16. package/dist/{client-bootstrap-DjFJ7e0N.js → client-bootstrap-PqYOS-mO.js} +1 -1
  17. package/dist/{config-schema-DtnhNYd-.js → config-schema-CG9goLWp.js} +21 -55
  18. package/dist/contract-api.js +2 -2
  19. package/dist/{create-client-CNakT7zF.js → create-client-D9z9RjCM.js} +3 -3
  20. package/dist/{credentials-Ds9V1mn2.js → credentials-DnhsLAuR.js} +1 -1
  21. package/dist/{credentials-read-BlkvsNFg.js → credentials-read-BtS-HRT5.js} +3 -3
  22. package/dist/{credentials-write.runtime-CTqqxcut.js → credentials-write.runtime-J_EUt5WP.js} +1 -1
  23. package/dist/{crypto-runtime-B74cTS6A.js → crypto-runtime-BHcxauC4.js} +75 -45
  24. package/dist/{deps-CdjHvnmh.js → deps-DDbghaZH.js} +23 -90
  25. package/dist/{directory-live-Ufd4qSpX.js → directory-live-DPy2aaPF.js} +3 -3
  26. package/dist/doctor-BGTs609f.js +64 -0
  27. package/dist/{doctor-contract-BAja_fmb.js → doctor-contract-D2qTLe-C.js} +72 -6
  28. package/dist/doctor-contract-api.js +323 -45
  29. package/dist/{draft-stream-D4EH25gv.js → draft-stream-De7uikGn.js} +1 -1
  30. package/dist/{encryption-guidance-D8walY04.js → encryption-guidance-BFfgq7c7.js} +1 -1
  31. package/dist/{env-auth-DIzOApj0.js → env-auth-CQsYbz-p.js} +1 -1
  32. package/dist/{env-vars-KzaYveuy.js → env-vars-B0NxQnPk.js} +3 -1
  33. package/dist/{exec-approval-resolver-f9j6staN.js → exec-approval-resolver-BCgqRtZS.js} +2 -1
  34. package/dist/{file-sync-store-DVm0ACml.js → file-sync-store-Cxb0ckyX.js} +4 -5
  35. package/dist/helper-api.js +4 -4
  36. package/dist/{http-client-nSmFiVgk.js → http-client-W4TJQM6r.js} +17 -33
  37. package/dist/{idb-persistence-BHm97th-.js → idb-persistence-iUZoHZkp.js} +2 -2
  38. package/dist/inbound-dedupe-DcMs0YXL.js +67 -0
  39. package/dist/index.js +1 -1
  40. package/dist/{logger-D0GCSDQq.js → logger-BMClpI5b.js} +1 -1
  41. package/dist/{logging-QH-48Gr6.js → logging-CFJrbDAN.js} +1 -1
  42. package/dist/{media-text-p-LP21qs.js → media-text-DWaotsZB.js} +1 -1
  43. package/dist/{messages-DRKkiEY-.js → messages-Dm3K4ZvM.js} +3 -3
  44. package/dist/{monitor-CsGOGdwu.js → monitor-C_kgPPeV.js} +44 -382
  45. package/dist/plugin-entry.handlers.runtime.js +1 -1
  46. package/dist/probe.runtime-Dry8PTWC.js +3 -0
  47. package/dist/{profile-update-Ucc8RrJL.js → profile-update-iUHCoks3.js} +3 -3
  48. package/dist/{reaction-events-DentrVii.js → reaction-events-0tubdHRM.js} +60 -10
  49. package/dist/record-shared-CvzjvHRn.js +2 -0
  50. package/dist/{recovery-key-store-DSeLFvNx.js → recovery-key-store-Bx0zTJcB.js} +2 -2
  51. package/dist/{resolve-targets-DcV_KfgX.js → resolve-targets-DlLrfWDy.js} +1 -1
  52. package/dist/{resolver.runtime-Hr6bO5zl.js → resolver.runtime-MeaT1zXx.js} +1 -1
  53. package/dist/room-info-B6vKD5DF.js +86 -0
  54. package/dist/{runtime-6S3DNFNv.js → runtime-CveSqMOP.js} +1 -1
  55. package/dist/{runtime-api-CsBoesCU.js → runtime-api-D1xI_cvh.js} +3 -3
  56. package/dist/runtime-api.js +6 -6
  57. package/dist/runtime-setter-api.js +1 -1
  58. package/dist/{sdk-AZYVl34z.js → sdk-CI8E2TKg.js} +12 -17
  59. package/dist/{secret-contract-DTgQyQxc.js → secret-contract-OZoQf0kI.js} +7 -48
  60. package/dist/secret-contract-api.js +1 -1
  61. package/dist/{send-D92v6Yy0.js → send-C7xuGWpv.js} +10 -4
  62. package/dist/session-binding-contract-api.js +2 -2
  63. package/dist/{setup-bootstrap-Da564w5f.js → setup-bootstrap-CCsexWTZ.js} +2 -2
  64. package/dist/{setup-core-BGgbrdaJ.js → setup-core-DlmTyIP0.js} +9 -7
  65. package/dist/setup-plugin-api.js +3 -3
  66. package/dist/{setup-surface-iJ6pd-t5.js → setup-surface-2SS94JV0.js} +7 -7
  67. package/dist/{shared-DkFfq7mH.js → shared-DgvN5rBx.js} +14 -9
  68. package/dist/{startup-verification-BKMAXvcV.js → startup-verification-CbIyF7z1.js} +3 -4
  69. package/dist/storage-BtSOar8T.js +718 -0
  70. package/dist/{storage-paths-BWo_ZEMC.js → storage-paths-B4_I9iqO.js} +1 -12
  71. package/dist/{thread-bindings-BX5nmWpw.js → thread-bindings-BI8MHWp9.js} +4 -5
  72. package/dist/{tool-actions.runtime-C1d5fxE_.js → tool-actions.runtime-CnyhVPoY.js} +242 -53
  73. package/dist/{verification-BGCMiO1p.js → verification-DLSe3sP7.js} +2 -2
  74. package/npm-shrinkwrap.json +3 -3
  75. package/openclaw.plugin.json +66 -55
  76. package/package.json +4 -4
  77. package/dist/approval-reactions-BdUaUXVw.js +0 -113
  78. package/dist/crypto-state-store-Jy3qwhdy.js +0 -352
  79. package/dist/doctor-DfaOqFtr.js +0 -167
  80. package/dist/legacy-crypto-inspector-vzXSkm18.js +0 -42
  81. package/dist/legacy-crypto-restore-CIBfOmLn.js +0 -93
  82. package/dist/matrix-migration.runtime-BMCyrANT.js +0 -524
  83. package/dist/migration-snapshot-backup-YcCrSjbE.js +0 -69
  84. package/dist/migration-snapshot.runtime-VGD4QfeS.js +0 -2
  85. package/dist/probe.runtime-2MZLc6ng.js +0 -3
  86. package/dist/runtime-heavy-api.js +0 -3
  87. package/dist/storage-CQdyKcGg.js +0 -430
@@ -0,0 +1,718 @@
1
+ import { t as isRecord } from "./record-shared-CvzjvHRn.js";
2
+ import { t as getMatrixRuntime } from "./runtime-CveSqMOP.js";
3
+ import { n as resolveMatrixAccountStorageRoot } from "./storage-paths-B4_I9iqO.js";
4
+ import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import { loadJsonFile } from "openclaw/plugin-sdk/json-store";
10
+ //#region extensions/matrix/src/matrix/sqlite-state.ts
11
+ function resolveStateDirOverride(options) {
12
+ if (!options) return;
13
+ if (options.stateDir) return options.stateDir;
14
+ if (options.stateRootDir) return options.stateRootDir;
15
+ return getMatrixRuntime().state.resolveStateDir(options.env ?? process.env, os.homedir);
16
+ }
17
+ function resolveMatrixSqliteStateKey(options) {
18
+ return resolveStateDirOverride(options) ?? "";
19
+ }
20
+ function resolveMatrixSqliteStateEnv(options) {
21
+ const stateDir = resolveStateDirOverride(options);
22
+ if (!stateDir) return options?.env;
23
+ return {
24
+ ...options?.env ?? process.env,
25
+ OPENCLAW_STATE_DIR: stateDir
26
+ };
27
+ }
28
+ //#endregion
29
+ //#region extensions/matrix/src/matrix/crypto-state-store.ts
30
+ const STATE_KEY = "current";
31
+ const RECOVERY_KEY_NAMESPACE = "recovery-key";
32
+ const LEGACY_CRYPTO_MIGRATION_NAMESPACE = "legacy-crypto-migration";
33
+ const IDB_SNAPSHOT_NAMESPACE = "idb-snapshot";
34
+ const SMALL_STATE_MAX_ENTRIES = 10;
35
+ const IDB_SNAPSHOT_MAX_ENTRIES = 2e4;
36
+ const IDB_SNAPSHOT_MAX_CHUNKS = Math.floor((IDB_SNAPSHOT_MAX_ENTRIES - 1) / 2);
37
+ const IDB_SNAPSHOT_CHUNK_BYTES = 24e3;
38
+ const MATRIX_RECOVERY_KEY_FILENAME = "recovery-key.json";
39
+ const MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME = "legacy-crypto-migration.json";
40
+ const MATRIX_IDB_SNAPSHOT_FILENAME = "crypto-idb-snapshot.json";
41
+ function openMatrixRecoveryKeyStoreOptions(storageRootDir) {
42
+ return {
43
+ namespace: RECOVERY_KEY_NAMESPACE,
44
+ maxEntries: SMALL_STATE_MAX_ENTRIES,
45
+ env: resolveMatrixSqliteStateEnv({ stateDir: storageRootDir })
46
+ };
47
+ }
48
+ function openMatrixLegacyCryptoMigrationStoreOptions(storageRootDir) {
49
+ return {
50
+ namespace: LEGACY_CRYPTO_MIGRATION_NAMESPACE,
51
+ maxEntries: SMALL_STATE_MAX_ENTRIES,
52
+ env: resolveMatrixSqliteStateEnv({ stateDir: storageRootDir })
53
+ };
54
+ }
55
+ function openMatrixIdbSnapshotStoreOptions(storageRootDir) {
56
+ return {
57
+ namespace: IDB_SNAPSHOT_NAMESPACE,
58
+ maxEntries: IDB_SNAPSHOT_MAX_ENTRIES,
59
+ env: resolveMatrixSqliteStateEnv({ stateDir: storageRootDir })
60
+ };
61
+ }
62
+ function readMatrixRecoveryKeyState(storageRootDir) {
63
+ return readMatrixRecoveryKeyStateWithKey({
64
+ storageRootDir,
65
+ stateKey: STATE_KEY
66
+ });
67
+ }
68
+ function readMatrixRecoveryKeyStateForPath(recoveryKeyPath) {
69
+ return readMatrixRecoveryKeyStateWithKey({
70
+ storageRootDir: path.dirname(recoveryKeyPath),
71
+ stateKey: resolveRecoveryKeyStateKeyForPath(recoveryKeyPath)
72
+ });
73
+ }
74
+ function readMatrixRecoveryKeyStateWithKey(params) {
75
+ return normalizeMatrixStoredRecoveryKey(openSyncStore(openMatrixRecoveryKeyStoreOptions(params.storageRootDir)).lookup(params.stateKey));
76
+ }
77
+ function writeMatrixRecoveryKeyStateForPath(params) {
78
+ writeMatrixRecoveryKeyStateWithKey({
79
+ storageRootDir: path.dirname(params.recoveryKeyPath),
80
+ stateKey: resolveRecoveryKeyStateKeyForPath(params.recoveryKeyPath),
81
+ payload: params.payload
82
+ });
83
+ }
84
+ function writeMatrixRecoveryKeyStateWithKey(params) {
85
+ const payload = normalizeMatrixStoredRecoveryKey(params.payload);
86
+ if (!payload) throw new Error("Invalid Matrix recovery key state");
87
+ openSyncStore(openMatrixRecoveryKeyStoreOptions(params.storageRootDir)).register(params.stateKey, payload);
88
+ }
89
+ async function hasMatrixRecoveryKeyStateInStore(params) {
90
+ return normalizeMatrixStoredRecoveryKey(await params.store.lookup(STATE_KEY)) !== null;
91
+ }
92
+ async function writeMatrixRecoveryKeyStateToStore(params) {
93
+ const payload = normalizeMatrixStoredRecoveryKey(params.payload);
94
+ if (!payload) throw new Error("Invalid Matrix recovery key state");
95
+ await params.store.register(STATE_KEY, payload);
96
+ }
97
+ function readMatrixLegacyCryptoMigrationState(storageRootDir) {
98
+ return normalizeMatrixLegacyCryptoMigrationState(openSyncStore(openMatrixLegacyCryptoMigrationStoreOptions(storageRootDir)).lookup(STATE_KEY));
99
+ }
100
+ function writeMatrixLegacyCryptoMigrationState(params) {
101
+ const state = normalizeMatrixLegacyCryptoMigrationState(params.state);
102
+ if (!state) throw new Error("Invalid Matrix legacy crypto migration state");
103
+ openSyncStore(openMatrixLegacyCryptoMigrationStoreOptions(params.storageRootDir)).register(STATE_KEY, state);
104
+ }
105
+ async function hasMatrixLegacyCryptoMigrationStateInStore(params) {
106
+ return normalizeMatrixLegacyCryptoMigrationState(await params.store.lookup(STATE_KEY)) !== null;
107
+ }
108
+ async function writeMatrixLegacyCryptoMigrationStateToStore(params) {
109
+ const state = normalizeMatrixLegacyCryptoMigrationState(params.state);
110
+ if (!state) throw new Error("Invalid Matrix legacy crypto migration state");
111
+ await params.store.register(STATE_KEY, state);
112
+ }
113
+ function readMatrixIdbSnapshotJson(storageRootDir) {
114
+ return readIdbSnapshotJsonFromStore(openSyncStore(openMatrixIdbSnapshotStoreOptions(storageRootDir)));
115
+ }
116
+ function hasMatrixIdbSnapshotState(storageRootDir) {
117
+ return isIdbSnapshotMeta(openSyncStore(openMatrixIdbSnapshotStoreOptions(storageRootDir)).lookup(idbMetaKey()));
118
+ }
119
+ function writeMatrixIdbSnapshotJson(params) {
120
+ writeIdbSnapshotJsonToStore({
121
+ snapshotJson: params.snapshotJson,
122
+ databaseCount: params.databaseCount,
123
+ store: openSyncStore(openMatrixIdbSnapshotStoreOptions(params.storageRootDir))
124
+ });
125
+ }
126
+ async function hasMatrixIdbSnapshotStateInStore(params) {
127
+ return await readIdbSnapshotJsonFromAsyncStore(params.store) !== null;
128
+ }
129
+ async function writeMatrixIdbSnapshotJsonToStore(params) {
130
+ const rows = buildIdbSnapshotRows(params.snapshotJson, params.databaseCount);
131
+ for (const row of rows.chunks) await params.store.register(row.key, row.value);
132
+ await params.store.register(rows.meta.key, rows.meta.value);
133
+ for (const row of await params.store.entries()) if (row.key.startsWith(idbChunkKeyPrefix()) && !rows.nextChunkKeys.has(row.key)) await params.store.delete(row.key);
134
+ }
135
+ function migrateLegacyMatrixRecoveryKeyFileToStore(storageRootDir) {
136
+ return migrateLegacyMatrixRecoveryKeyFilePathToStore(path.join(storageRootDir, MATRIX_RECOVERY_KEY_FILENAME));
137
+ }
138
+ function migrateLegacyMatrixRecoveryKeyFilePathToStore(recoveryKeyPath) {
139
+ const existing = readMatrixRecoveryKeyStateForPath(recoveryKeyPath);
140
+ const legacy = readLegacyMatrixRecoveryKeyFile(recoveryKeyPath);
141
+ if (!existing && legacy) writeMatrixRecoveryKeyStateForPath({
142
+ recoveryKeyPath,
143
+ payload: legacy
144
+ });
145
+ return archiveLegacyStateFileIfPossible(recoveryKeyPath);
146
+ }
147
+ function migrateLegacyMatrixLegacyCryptoMigrationFileToStore(storageRootDir) {
148
+ const existing = readMatrixLegacyCryptoMigrationState(storageRootDir);
149
+ const legacy = readLegacyMatrixLegacyCryptoMigrationState(storageRootDir);
150
+ if (!existing && legacy) writeMatrixLegacyCryptoMigrationState({
151
+ storageRootDir,
152
+ state: legacy
153
+ });
154
+ return archiveLegacyStateFileIfPossible(path.join(storageRootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME));
155
+ }
156
+ function readLegacyMatrixRecoveryKeyState(storageRootDir) {
157
+ return readLegacyMatrixRecoveryKeyFile(path.join(storageRootDir, MATRIX_RECOVERY_KEY_FILENAME));
158
+ }
159
+ function readLegacyMatrixRecoveryKeyFile(filePath) {
160
+ return readJsonFileSync(filePath, normalizeMatrixStoredRecoveryKey);
161
+ }
162
+ function readLegacyMatrixLegacyCryptoMigrationState(storageRootDir) {
163
+ return readJsonFileSync(path.join(storageRootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME), normalizeMatrixLegacyCryptoMigrationState);
164
+ }
165
+ function scoreMatrixCryptoStateInStore(storageRootDir) {
166
+ if (!matrixCryptoStateDatabaseExists(storageRootDir)) return 0;
167
+ let score = 0;
168
+ try {
169
+ if (readMatrixLegacyCryptoMigrationState(storageRootDir)) score += 3;
170
+ } catch {}
171
+ try {
172
+ if (readMatrixRecoveryKeyState(storageRootDir)) score += 2;
173
+ } catch {}
174
+ try {
175
+ if (hasMatrixIdbSnapshotState(storageRootDir)) score += 2;
176
+ } catch {}
177
+ return score;
178
+ }
179
+ function matrixCryptoStateDatabaseExists(storageRootDir) {
180
+ return fs.existsSync(path.join(storageRootDir, "state", "openclaw.sqlite"));
181
+ }
182
+ function resolveRecoveryKeyStateKeyForPath(recoveryKeyPath) {
183
+ const basename = path.basename(recoveryKeyPath);
184
+ if (basename === "recovery-key.json") return STATE_KEY;
185
+ return `file:${createHash("sha256").update(basename, "utf8").digest("hex").slice(0, 32)}`;
186
+ }
187
+ function normalizeMatrixStoredRecoveryKey(value) {
188
+ if (!isRecord(value) || value.version !== 1 || typeof value.createdAt !== "string" || typeof value.privateKeyBase64 !== "string" || !value.privateKeyBase64.trim()) return null;
189
+ return {
190
+ version: 1,
191
+ createdAt: value.createdAt,
192
+ keyId: typeof value.keyId === "string" ? value.keyId : null,
193
+ ...typeof value.encodedPrivateKey === "string" ? { encodedPrivateKey: value.encodedPrivateKey } : {},
194
+ privateKeyBase64: value.privateKeyBase64,
195
+ ...isRecord(value.keyInfo) ? { keyInfo: {
196
+ ...value.keyInfo.passphrase !== void 0 ? { passphrase: value.keyInfo.passphrase } : {},
197
+ ...typeof value.keyInfo.name === "string" ? { name: value.keyInfo.name } : {}
198
+ } } : {}
199
+ };
200
+ }
201
+ function normalizeMatrixLegacyCryptoMigrationState(value) {
202
+ if (!isRecord(value) || value.version !== 1 || typeof value.accountId !== "string") return null;
203
+ if (value.restoreStatus !== "pending" && value.restoreStatus !== "completed" && value.restoreStatus !== "manual-action-required") return null;
204
+ const roomKeyCounts = isRecord(value.roomKeyCounts) && typeof value.roomKeyCounts.total === "number" && typeof value.roomKeyCounts.backedUp === "number" ? {
205
+ total: value.roomKeyCounts.total,
206
+ backedUp: value.roomKeyCounts.backedUp
207
+ } : null;
208
+ return {
209
+ version: 1,
210
+ ...value.source === "matrix-bot-sdk-rust" ? { source: value.source } : {},
211
+ accountId: value.accountId,
212
+ ...typeof value.deviceId === "string" || value.deviceId === null ? { deviceId: value.deviceId } : {},
213
+ roomKeyCounts,
214
+ ...typeof value.backupVersion === "string" || value.backupVersion === null ? { backupVersion: value.backupVersion } : {},
215
+ ...typeof value.decryptionKeyImported === "boolean" ? { decryptionKeyImported: value.decryptionKeyImported } : {},
216
+ restoreStatus: value.restoreStatus,
217
+ ...typeof value.detectedAt === "string" ? { detectedAt: value.detectedAt } : {},
218
+ ...typeof value.restoredAt === "string" ? { restoredAt: value.restoredAt } : {},
219
+ ...typeof value.importedCount === "number" ? { importedCount: value.importedCount } : {},
220
+ ...typeof value.totalCount === "number" ? { totalCount: value.totalCount } : {},
221
+ ...typeof value.lastError === "string" || value.lastError === null ? { lastError: value.lastError } : {}
222
+ };
223
+ }
224
+ function openSyncStore(options) {
225
+ return getMatrixRuntime().state.openSyncKeyedStore(options);
226
+ }
227
+ function readJsonFileSync(filePath, normalize) {
228
+ try {
229
+ return normalize(JSON.parse(fs.readFileSync(filePath, "utf8")));
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+ function archiveLegacyStateFileIfPossible(filePath) {
235
+ if (!fs.existsSync(filePath)) return false;
236
+ const archivedPath = `${filePath}.migrated`;
237
+ if (fs.existsSync(archivedPath)) return false;
238
+ fs.renameSync(filePath, archivedPath);
239
+ return true;
240
+ }
241
+ function readIdbSnapshotJsonFromStore(store) {
242
+ const meta = store.lookup(idbMetaKey());
243
+ if (!isIdbSnapshotMeta(meta)) return null;
244
+ const chunks = readIdbSnapshotChunks(meta, (key) => store.lookup(key));
245
+ return chunks ? chunks.join("") : null;
246
+ }
247
+ async function readIdbSnapshotJsonFromAsyncStore(store) {
248
+ const meta = await store.lookup(idbMetaKey());
249
+ if (!isIdbSnapshotMeta(meta)) return null;
250
+ const chunks = await readIdbSnapshotChunksAsync(meta, (key) => store.lookup(key));
251
+ return chunks ? chunks.join("") : null;
252
+ }
253
+ function readIdbSnapshotChunks(meta, lookup) {
254
+ const chunks = [];
255
+ for (let index = 0; index < meta.chunkCount; index += 1) {
256
+ const chunk = lookup(idbChunkKey(meta.generation, index));
257
+ if (!isIdbSnapshotChunk(chunk) || chunk.index !== index) return null;
258
+ chunks.push(chunk.data);
259
+ }
260
+ const snapshotJson = chunks.join("");
261
+ if (meta.digest !== digestText(snapshotJson)) return null;
262
+ return chunks;
263
+ }
264
+ async function readIdbSnapshotChunksAsync(meta, lookup) {
265
+ const chunks = [];
266
+ for (let index = 0; index < meta.chunkCount; index += 1) {
267
+ const chunk = await lookup(idbChunkKey(meta.generation, index));
268
+ if (!isIdbSnapshotChunk(chunk) || chunk.index !== index) return null;
269
+ chunks.push(chunk.data);
270
+ }
271
+ const snapshotJson = chunks.join("");
272
+ if (meta.digest !== digestText(snapshotJson)) return null;
273
+ return chunks;
274
+ }
275
+ function writeIdbSnapshotJsonToStore(params) {
276
+ const rows = buildIdbSnapshotRows(params.snapshotJson, params.databaseCount);
277
+ for (const row of rows.chunks) params.store.register(row.key, row.value);
278
+ params.store.register(rows.meta.key, rows.meta.value);
279
+ for (const row of params.store.entries()) if (row.key.startsWith(idbChunkKeyPrefix()) && !rows.nextChunkKeys.has(row.key)) params.store.delete(row.key);
280
+ }
281
+ function buildIdbSnapshotRows(snapshotJson, databaseCount) {
282
+ const generation = randomUUID().replaceAll("-", "");
283
+ const chunks = chunkText(snapshotJson).map((data, index) => ({
284
+ key: idbChunkKey(generation, index),
285
+ value: {
286
+ kind: "snapshot-chunk",
287
+ index,
288
+ data
289
+ }
290
+ }));
291
+ return {
292
+ chunks,
293
+ nextChunkKeys: new Set(chunks.map((chunk) => chunk.key)),
294
+ meta: {
295
+ key: idbMetaKey(),
296
+ value: {
297
+ kind: "meta",
298
+ version: 1,
299
+ generation,
300
+ chunkCount: chunks.length,
301
+ digest: digestText(snapshotJson),
302
+ databaseCount,
303
+ persistedAt: (/* @__PURE__ */ new Date()).toISOString()
304
+ }
305
+ }
306
+ };
307
+ }
308
+ function idbMetaKey() {
309
+ return `${STATE_KEY}:meta`;
310
+ }
311
+ function idbChunkKeyPrefix() {
312
+ return `${STATE_KEY}:snapshot:`;
313
+ }
314
+ function idbChunkKey(generation, index) {
315
+ return `${idbChunkKeyPrefix()}${generation}:${index}`;
316
+ }
317
+ function chunkText(value) {
318
+ const chunks = [];
319
+ let current = "";
320
+ let currentBytes = 0;
321
+ for (const char of value) {
322
+ const charBytes = Buffer.byteLength(char, "utf8");
323
+ if (current && currentBytes + charBytes > IDB_SNAPSHOT_CHUNK_BYTES) {
324
+ pushChunk(chunks, current);
325
+ current = "";
326
+ currentBytes = 0;
327
+ }
328
+ current += char;
329
+ currentBytes += charBytes;
330
+ }
331
+ if (current) pushChunk(chunks, current);
332
+ return chunks;
333
+ }
334
+ function pushChunk(chunks, chunk) {
335
+ if (chunks.length >= IDB_SNAPSHOT_MAX_CHUNKS) throw new Error("Matrix IndexedDB snapshot exceeds SQLite chunk limit");
336
+ chunks.push(chunk);
337
+ }
338
+ function digestText(value) {
339
+ return createHash("sha256").update(value, "utf8").digest("hex");
340
+ }
341
+ function isIdbSnapshotMeta(value) {
342
+ return isRecord(value) && value.kind === "meta" && value.version === 1 && typeof value.generation === "string" && value.generation.trim() !== "" && typeof value.chunkCount === "number" && Number.isSafeInteger(value.chunkCount) && value.chunkCount >= 0 && value.chunkCount <= IDB_SNAPSHOT_MAX_CHUNKS && typeof value.digest === "string" && typeof value.databaseCount === "number" && Number.isSafeInteger(value.databaseCount) && value.databaseCount >= 0 && typeof value.persistedAt === "string";
343
+ }
344
+ function isIdbSnapshotChunk(value) {
345
+ return isRecord(value) && value.kind === "snapshot-chunk" && typeof value.index === "number" && Number.isSafeInteger(value.index) && value.index >= 0 && typeof value.data === "string";
346
+ }
347
+ //#endregion
348
+ //#region extensions/matrix/src/matrix/client/storage.ts
349
+ const DEFAULT_ACCOUNT_KEY = "default";
350
+ const STORAGE_META_FILENAME = "storage-meta.json";
351
+ const THREAD_BINDINGS_FILENAME = "thread-bindings.json";
352
+ const STORAGE_META_NAMESPACE = "storage-meta";
353
+ const STORAGE_META_STATE_KEY = "current";
354
+ const STORAGE_META_MAX_ENTRIES = 10;
355
+ function openMatrixStorageMetaStoreOptions(storageRootDir) {
356
+ return {
357
+ namespace: STORAGE_META_NAMESPACE,
358
+ maxEntries: STORAGE_META_MAX_ENTRIES,
359
+ env: resolveMatrixSqliteStateEnv({ stateDir: storageRootDir })
360
+ };
361
+ }
362
+ function openStorageMetaStore(rootDir) {
363
+ return getMatrixRuntime().state.openSyncKeyedStore(openMatrixStorageMetaStoreOptions(rootDir));
364
+ }
365
+ function scoreStorageRoot(rootDir) {
366
+ let score = 0;
367
+ const metadata = readStoredRootMetadata(rootDir);
368
+ if (Object.keys(metadata).length > 0) score += 1;
369
+ if (metadata.currentTokenStateClaimed === true) score += 8;
370
+ if (fs.existsSync(path.join(rootDir, "crypto"))) score += 8;
371
+ if (fs.existsSync(path.join(rootDir, THREAD_BINDINGS_FILENAME))) score += 4;
372
+ if (fs.existsSync(path.join(rootDir, "legacy-crypto-migration.json"))) score += 3;
373
+ if (fs.existsSync(path.join(rootDir, "recovery-key.json"))) score += 2;
374
+ if (fs.existsSync(path.join(rootDir, "crypto-idb-snapshot.json"))) score += 2;
375
+ score += scoreMatrixCryptoStateInStore(rootDir);
376
+ return score;
377
+ }
378
+ function resolveStorageRootMtimeMs(rootDir) {
379
+ try {
380
+ return fs.statSync(rootDir).mtimeMs;
381
+ } catch {
382
+ return 0;
383
+ }
384
+ }
385
+ function normalizeMatrixStorageMetadata(value) {
386
+ if (!isRecord(value)) return null;
387
+ const metadata = {};
388
+ if (typeof value.homeserver === "string" && value.homeserver.trim()) metadata.homeserver = value.homeserver.trim();
389
+ if (typeof value.userId === "string" && value.userId.trim()) metadata.userId = value.userId.trim();
390
+ if (typeof value.accountId === "string" && value.accountId.trim()) metadata.accountId = value.accountId.trim();
391
+ if (typeof value.accessTokenHash === "string" && value.accessTokenHash.trim()) metadata.accessTokenHash = value.accessTokenHash.trim();
392
+ if (typeof value.deviceId === "string" && value.deviceId.trim()) metadata.deviceId = value.deviceId.trim();
393
+ if (value.currentTokenStateClaimed === true) metadata.currentTokenStateClaimed = true;
394
+ if (typeof value.createdAt === "string" && value.createdAt.trim()) metadata.createdAt = value.createdAt.trim();
395
+ return Object.keys(metadata).length > 0 ? metadata : null;
396
+ }
397
+ async function hasMatrixStorageMetaStateInStore(params) {
398
+ return normalizeMatrixStorageMetadata(await params.store.lookup(STORAGE_META_STATE_KEY)) !== null;
399
+ }
400
+ async function writeMatrixStorageMetaStateToStore(params) {
401
+ await params.store.register(STORAGE_META_STATE_KEY, params.payload);
402
+ }
403
+ function readStoredRootMetadata(rootDir) {
404
+ if (fs.existsSync(path.join(rootDir, "state", "openclaw.sqlite"))) try {
405
+ const stored = normalizeMatrixStorageMetadata(openStorageMetaStore(rootDir).lookup(STORAGE_META_STATE_KEY));
406
+ if (stored) return stored;
407
+ } catch {}
408
+ return normalizeMatrixStorageMetadata(loadJsonFile(path.join(rootDir, STORAGE_META_FILENAME))) ?? {};
409
+ }
410
+ function isCompatibleStorageRoot(params) {
411
+ const metadata = readStoredRootMetadata(params.candidateRootDir);
412
+ if (metadata.homeserver && metadata.homeserver !== params.homeserver) return false;
413
+ if (metadata.userId && metadata.userId !== params.userId) return false;
414
+ if (metadata.accountId && normalizeAccountId(metadata.accountId) !== normalizeAccountId(params.accountKey)) return false;
415
+ if (params.deviceId && metadata.deviceId && metadata.deviceId.trim() && metadata.deviceId.trim() !== params.deviceId.trim()) return false;
416
+ if (params.requireExplicitDeviceMatch && params.deviceId && (!metadata.deviceId || metadata.deviceId.trim() !== params.deviceId.trim())) return false;
417
+ return true;
418
+ }
419
+ function resolvePreferredMatrixStorageRoot(params) {
420
+ const parentDir = path.dirname(params.canonicalRootDir);
421
+ const bestCurrentScore = scoreStorageRoot(params.canonicalRootDir);
422
+ const bestCurrentMtimeMs = resolveStorageRootMtimeMs(params.canonicalRootDir);
423
+ let best = {
424
+ rootDir: params.canonicalRootDir,
425
+ tokenHash: params.canonicalTokenHash,
426
+ score: bestCurrentScore,
427
+ mtimeMs: bestCurrentMtimeMs
428
+ };
429
+ if (!params.deviceId?.trim()) return {
430
+ rootDir: best.rootDir,
431
+ tokenHash: best.tokenHash
432
+ };
433
+ let siblingEntries;
434
+ try {
435
+ siblingEntries = fs.readdirSync(parentDir, { withFileTypes: true });
436
+ } catch {
437
+ return {
438
+ rootDir: best.rootDir,
439
+ tokenHash: best.tokenHash
440
+ };
441
+ }
442
+ const compatiblePopulatedSiblings = [];
443
+ const populatedTokenHashes = bestCurrentScore > 0 ? [params.canonicalTokenHash] : [];
444
+ for (const entry of siblingEntries.toSorted((a, b) => a.name.localeCompare(b.name))) {
445
+ if (!entry.isDirectory()) continue;
446
+ if (entry.name === params.canonicalTokenHash) continue;
447
+ const candidateRootDir = path.join(parentDir, entry.name);
448
+ if (!isCompatibleStorageRoot({
449
+ candidateRootDir,
450
+ homeserver: params.homeserver,
451
+ userId: params.userId,
452
+ accountKey: params.accountKey,
453
+ deviceId: params.deviceId,
454
+ requireExplicitDeviceMatch: Boolean(params.deviceId)
455
+ })) continue;
456
+ const candidateScore = scoreStorageRoot(candidateRootDir);
457
+ if (candidateScore <= 0) continue;
458
+ populatedTokenHashes.push(entry.name);
459
+ compatiblePopulatedSiblings.push({
460
+ rootDir: candidateRootDir,
461
+ tokenHash: entry.name,
462
+ score: candidateScore,
463
+ mtimeMs: resolveStorageRootMtimeMs(candidateRootDir)
464
+ });
465
+ }
466
+ const canonicalMetadata = readStoredRootMetadata(params.canonicalRootDir);
467
+ if (!(canonicalMetadata.accessTokenHash === params.canonicalTokenHash && canonicalMetadata.deviceId?.trim() === params.deviceId.trim() && canonicalMetadata.currentTokenStateClaimed === true)) {
468
+ for (const candidate of compatiblePopulatedSiblings) if (candidate.score > best.score || best.rootDir !== params.canonicalRootDir && candidate.score === best.score && candidate.mtimeMs > best.mtimeMs) best = {
469
+ rootDir: candidate.rootDir,
470
+ tokenHash: candidate.tokenHash,
471
+ score: candidate.score,
472
+ mtimeMs: candidate.mtimeMs
473
+ };
474
+ }
475
+ if (populatedTokenHashes.length > 1) getMatrixRuntime().logging.getChildLogger({ module: "matrix-storage" }).warn("matrix: multiple populated token-hash storage roots detected", {
476
+ parentDir,
477
+ canonicalTokenHash: params.canonicalTokenHash,
478
+ selectedTokenHash: best.tokenHash,
479
+ populatedTokenHashes,
480
+ populatedSiblingTokenHashes: compatiblePopulatedSiblings.map((root) => root.tokenHash),
481
+ populatedRootCount: populatedTokenHashes.length
482
+ });
483
+ return {
484
+ rootDir: best.rootDir,
485
+ tokenHash: best.tokenHash
486
+ };
487
+ }
488
+ function resolveMatrixStoragePaths(params) {
489
+ const env = params.env ?? process.env;
490
+ const canonical = resolveMatrixAccountStorageRoot({
491
+ stateDir: params.stateDir ?? getMatrixRuntime().state.resolveStateDir(env, os.homedir),
492
+ homeserver: params.homeserver,
493
+ userId: params.userId,
494
+ accessToken: params.accessToken,
495
+ accountId: params.accountId
496
+ });
497
+ const { rootDir, tokenHash } = resolvePreferredMatrixStorageRoot({
498
+ canonicalRootDir: canonical.rootDir,
499
+ canonicalTokenHash: canonical.tokenHash,
500
+ homeserver: params.homeserver,
501
+ userId: params.userId,
502
+ accountKey: canonical.accountKey,
503
+ deviceId: params.deviceId
504
+ });
505
+ return {
506
+ rootDir,
507
+ storagePath: path.join(rootDir, "bot-storage.json"),
508
+ cryptoPath: path.join(rootDir, "crypto"),
509
+ recoveryKeyPath: path.join(rootDir, MATRIX_RECOVERY_KEY_FILENAME),
510
+ idbSnapshotPath: path.join(rootDir, MATRIX_IDB_SNAPSHOT_FILENAME),
511
+ accountKey: canonical.accountKey,
512
+ tokenHash
513
+ };
514
+ }
515
+ function resolveMatrixStateFilePath(params) {
516
+ const storagePaths = resolveMatrixStoragePaths({
517
+ homeserver: params.auth.homeserver,
518
+ userId: params.auth.userId,
519
+ accessToken: params.auth.accessToken,
520
+ accountId: params.accountId ?? params.auth.accountId,
521
+ deviceId: params.auth.deviceId,
522
+ env: params.env,
523
+ stateDir: params.stateDir
524
+ });
525
+ return path.join(storagePaths.rootDir, params.filename);
526
+ }
527
+ async function maybeMigrateLegacyStorage(params) {
528
+ const hasAccountScopedLegacyStorageFile = fs.existsSync(params.storagePaths.storagePath);
529
+ const syncCache = hasAccountScopedLegacyStorageFile ? await import("./file-sync-store-Cxb0ckyX.js").then((n) => n.n) : null;
530
+ const hasAccountScopedLegacyStorage = hasAccountScopedLegacyStorageFile && await syncCache?.readLegacyMatrixSyncCacheState(params.storagePaths.rootDir) !== null;
531
+ const hasAccountScopedRecoveryKey = fs.existsSync(params.storagePaths.recoveryKeyPath);
532
+ const hasAccountScopedIdbSnapshot = fs.existsSync(params.storagePaths.idbSnapshotPath);
533
+ const hasAccountScopedLegacyCryptoMigration = fs.existsSync(path.join(params.storagePaths.rootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME));
534
+ if (!hasAccountScopedLegacyStorage && !hasAccountScopedRecoveryKey && !hasAccountScopedIdbSnapshot && !hasAccountScopedLegacyCryptoMigration) return;
535
+ const logger = getMatrixRuntime().logging.getChildLogger({ module: "matrix-storage" });
536
+ fs.mkdirSync(params.storagePaths.rootDir, { recursive: true });
537
+ const moved = [];
538
+ const pendingArchives = [];
539
+ const skippedExistingTargets = [];
540
+ try {
541
+ if (hasAccountScopedLegacyStorage) await migrateLegacySyncCacheToSqlite({
542
+ sourceRootDir: params.storagePaths.rootDir,
543
+ sourcePath: params.storagePaths.storagePath,
544
+ targetRootDir: params.storagePaths.rootDir,
545
+ label: "account sync cache",
546
+ moved,
547
+ pendingArchives
548
+ });
549
+ if (hasAccountScopedRecoveryKey) {
550
+ migrateLegacyMatrixRecoveryKeyFileToStore(params.storagePaths.rootDir);
551
+ moved.push({
552
+ sourcePath: params.storagePaths.recoveryKeyPath,
553
+ targetPath: `${params.storagePaths.rootDir} SQLite recovery key state`,
554
+ label: "recovery key"
555
+ });
556
+ }
557
+ if (hasAccountScopedLegacyCryptoMigration) {
558
+ migrateLegacyMatrixLegacyCryptoMigrationFileToStore(params.storagePaths.rootDir);
559
+ moved.push({
560
+ sourcePath: path.join(params.storagePaths.rootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME),
561
+ targetPath: `${params.storagePaths.rootDir} SQLite legacy crypto migration state`,
562
+ label: "legacy crypto migration"
563
+ });
564
+ }
565
+ if (hasAccountScopedIdbSnapshot) await migrateLegacyIdbSnapshotToSqlite({
566
+ storageRootDir: params.storagePaths.rootDir,
567
+ snapshotPath: params.storagePaths.idbSnapshotPath,
568
+ moved,
569
+ pendingArchives
570
+ });
571
+ } catch (err) {
572
+ const rollbackError = rollbackLegacyMoves(moved);
573
+ throw new Error(rollbackError ? `Failed migrating legacy Matrix client storage: ${String(err)}. Rollback also failed: ${rollbackError}` : `Failed migrating legacy Matrix client storage: ${String(err)}`, { cause: err });
574
+ }
575
+ for (const archive of pendingArchives) archiveLegacyStoragePath({
576
+ ...archive,
577
+ skippedExistingTargets
578
+ });
579
+ if (moved.length > 0) logger.info(`matrix: migrated legacy client storage into ${params.storagePaths.rootDir}\n${moved.map((entry) => `- ${entry.label}: ${entry.sourcePath} -> ${entry.targetPath}`).join("\n")}`);
580
+ if (skippedExistingTargets.length > 0) logger.warn?.(`matrix: legacy client storage files were left in place because their migrated targets already existed.\n${skippedExistingTargets.join("\n")}`);
581
+ }
582
+ async function migrateLegacyIdbSnapshotToSqlite(params) {
583
+ if (readMatrixIdbSnapshotJson(params.storageRootDir)) {
584
+ params.pendingArchives.push({
585
+ sourcePath: params.snapshotPath,
586
+ label: "IndexedDB snapshot"
587
+ });
588
+ return;
589
+ }
590
+ const { readLegacyMatrixIdbSnapshotState } = await import("./idb-persistence-iUZoHZkp.js").then((n) => n.t);
591
+ const snapshot = await readLegacyMatrixIdbSnapshotState(params.storageRootDir);
592
+ if (!snapshot) return;
593
+ writeMatrixIdbSnapshotJson({
594
+ storageRootDir: params.storageRootDir,
595
+ snapshotJson: JSON.stringify(snapshot),
596
+ databaseCount: snapshot.length
597
+ });
598
+ params.moved.push({
599
+ sourcePath: params.snapshotPath,
600
+ targetPath: `${params.storageRootDir} SQLite IndexedDB snapshot state`,
601
+ label: "IndexedDB snapshot"
602
+ });
603
+ params.pendingArchives.push({
604
+ sourcePath: params.snapshotPath,
605
+ label: "IndexedDB snapshot"
606
+ });
607
+ }
608
+ async function migrateLegacySyncCacheToSqlite(params) {
609
+ const syncCache = await import("./file-sync-store-Cxb0ckyX.js").then((n) => n.n);
610
+ const persisted = await syncCache.readLegacyMatrixSyncCacheState(params.sourceRootDir);
611
+ if (!persisted) return;
612
+ const store = getMatrixRuntime().state.openKeyedStore(syncCache.openMatrixSyncCacheStoreOptions(params.targetRootDir));
613
+ if (!await syncCache.hasMatrixSyncCacheStateInStore({
614
+ storageRootDir: params.targetRootDir,
615
+ store
616
+ })) {
617
+ await syncCache.writeMatrixSyncCacheStateToStore({
618
+ storageRootDir: params.targetRootDir,
619
+ payload: persisted,
620
+ store
621
+ });
622
+ claimCurrentTokenStorageState({ rootDir: params.targetRootDir });
623
+ params.moved.push({
624
+ sourcePath: params.sourcePath,
625
+ targetPath: `${params.targetRootDir} SQLite sync cache`,
626
+ label: params.label
627
+ });
628
+ }
629
+ params.pendingArchives.push({
630
+ sourcePath: params.sourcePath,
631
+ label: params.label
632
+ });
633
+ }
634
+ function archiveLegacyStoragePath(params) {
635
+ const archivedLegacyStoragePath = `${params.sourcePath}.migrated`;
636
+ if (fs.existsSync(archivedLegacyStoragePath)) {
637
+ params.skippedExistingTargets.push(`- ${params.label} remains at ${params.sourcePath} because ${archivedLegacyStoragePath} already exists`);
638
+ return;
639
+ }
640
+ fs.renameSync(params.sourcePath, archivedLegacyStoragePath);
641
+ }
642
+ function rollbackLegacyMoves(moved) {
643
+ for (const entry of moved.toReversed()) try {
644
+ if (!fs.existsSync(entry.targetPath) || fs.existsSync(entry.sourcePath)) continue;
645
+ fs.renameSync(entry.targetPath, entry.sourcePath);
646
+ } catch (err) {
647
+ return `${entry.label} (${entry.targetPath} -> ${entry.sourcePath}): ${String(err)}`;
648
+ }
649
+ return null;
650
+ }
651
+ function writeStoredRootMetadata(rootDir, payload) {
652
+ try {
653
+ const normalized = normalizeMatrixStorageMetadata(payload);
654
+ if (!normalized) return false;
655
+ openStorageMetaStore(rootDir).register(STORAGE_META_STATE_KEY, normalized);
656
+ return true;
657
+ } catch {
658
+ return false;
659
+ }
660
+ }
661
+ function writeStorageMeta(params) {
662
+ const existing = readStoredRootMetadata(params.storagePaths.rootDir);
663
+ return writeStoredRootMetadata(params.storagePaths.rootDir, {
664
+ homeserver: params.homeserver,
665
+ userId: params.userId,
666
+ accountId: params.accountId ?? DEFAULT_ACCOUNT_KEY,
667
+ accessTokenHash: params.storagePaths.tokenHash,
668
+ deviceId: params.deviceId ?? null,
669
+ currentTokenStateClaimed: params.currentTokenStateClaimed ?? existing.currentTokenStateClaimed === true,
670
+ createdAt: existing.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
671
+ });
672
+ }
673
+ function claimCurrentTokenStorageState(params) {
674
+ const metadata = readStoredRootMetadata(params.rootDir);
675
+ if (!metadata.accessTokenHash?.trim()) return false;
676
+ return writeStoredRootMetadata(params.rootDir, {
677
+ homeserver: metadata.homeserver,
678
+ userId: metadata.userId,
679
+ accountId: metadata.accountId ?? DEFAULT_ACCOUNT_KEY,
680
+ accessTokenHash: metadata.accessTokenHash,
681
+ deviceId: metadata.deviceId ?? null,
682
+ currentTokenStateClaimed: true,
683
+ createdAt: metadata.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
684
+ });
685
+ }
686
+ function recordCurrentStorageMetaDeviceId(params) {
687
+ const deviceId = params.deviceId.trim();
688
+ if (!deviceId) return false;
689
+ const metadata = readStoredRootMetadata(params.rootDir);
690
+ if (!metadata.accessTokenHash?.trim()) return false;
691
+ return writeStoredRootMetadata(params.rootDir, {
692
+ homeserver: metadata.homeserver,
693
+ userId: metadata.userId,
694
+ accountId: metadata.accountId ?? DEFAULT_ACCOUNT_KEY,
695
+ accessTokenHash: metadata.accessTokenHash,
696
+ deviceId,
697
+ currentTokenStateClaimed: metadata.currentTokenStateClaimed === true,
698
+ createdAt: metadata.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
699
+ });
700
+ }
701
+ function repairCurrentTokenStorageMetaDeviceId(params) {
702
+ return writeStorageMeta({
703
+ storagePaths: resolveMatrixStoragePaths({
704
+ homeserver: params.homeserver,
705
+ userId: params.userId,
706
+ accessToken: params.accessToken,
707
+ accountId: params.accountId,
708
+ env: params.env,
709
+ stateDir: params.stateDir
710
+ }),
711
+ homeserver: params.homeserver,
712
+ userId: params.userId,
713
+ accountId: params.accountId,
714
+ deviceId: params.deviceId
715
+ });
716
+ }
717
+ //#endregion
718
+ export { writeMatrixRecoveryKeyStateForPath as A, readLegacyMatrixRecoveryKeyFile as C, writeMatrixIdbSnapshotJson as D, readMatrixRecoveryKeyStateForPath as E, resolveMatrixSqliteStateEnv as M, resolveMatrixSqliteStateKey as N, writeMatrixIdbSnapshotJsonToStore as O, readLegacyMatrixLegacyCryptoMigrationState as S, readMatrixIdbSnapshotJson as T, hasMatrixRecoveryKeyStateInStore as _, openMatrixStorageMetaStoreOptions as a, openMatrixLegacyCryptoMigrationStoreOptions as b, resolveMatrixStateFilePath as c, writeStorageMeta as d, MATRIX_IDB_SNAPSHOT_FILENAME as f, hasMatrixLegacyCryptoMigrationStateInStore as g, hasMatrixIdbSnapshotStateInStore as h, normalizeMatrixStorageMetadata as i, writeMatrixRecoveryKeyStateToStore as j, writeMatrixLegacyCryptoMigrationStateToStore as k, resolveMatrixStoragePaths as l, MATRIX_RECOVERY_KEY_FILENAME as m, hasMatrixStorageMetaStateInStore as n, recordCurrentStorageMetaDeviceId as o, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME as p, maybeMigrateLegacyStorage as r, repairCurrentTokenStorageMetaDeviceId as s, claimCurrentTokenStorageState as t, writeMatrixStorageMetaStateToStore as u, migrateLegacyMatrixRecoveryKeyFilePathToStore as v, readLegacyMatrixRecoveryKeyState as w, openMatrixRecoveryKeyStoreOptions as x, openMatrixIdbSnapshotStoreOptions as y };