@seedprotocol/sdk 0.7.3-next.613.g79a8dfd → 0.7.4-next.711.gce2b766

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 (239) hide show
  1. package/dist/{db-CQt-gcAl.js → BasePathResolver-Cm4apKRb.js} +2041 -127
  2. package/dist/BasePathResolver-Cm4apKRb.js.map +1 -0
  3. package/dist/{ClientManager-DDA9956Y.js → ClientManager-i3nJASkg.js} +664 -277
  4. package/dist/ClientManager-i3nJASkg.js.map +1 -0
  5. package/dist/{Item-D4FigtYS.js → Item-DBFchXpC.js} +495 -219
  6. package/dist/Item-DBFchXpC.js.map +1 -0
  7. package/dist/{ModelProperty-BDt6AU2h.js → ModelProperty-BS49g01Y.js} +167 -47
  8. package/dist/ModelProperty-BS49g01Y.js.map +1 -0
  9. package/dist/{Schema-B8xqLWkL.js → Schema-CpMNEnUO.js} +53 -42
  10. package/dist/Schema-CpMNEnUO.js.map +1 -0
  11. package/dist/{SchemaValidationService-BPxkfDLU.js → SchemaValidationService-DieV4KL-.js} +13 -14
  12. package/dist/{SchemaValidationService-BPxkfDLU.js.map → SchemaValidationService-DieV4KL-.js.map} +1 -1
  13. package/dist/{backfillMetadataPropertyIds-DuTPcv8t.js → backfillMetadataPropertyIds-DSoOoTnX.js} +14 -7
  14. package/dist/{backfillMetadataPropertyIds-DuTPcv8t.js.map → backfillMetadataPropertyIds-DSoOoTnX.js.map} +1 -1
  15. package/dist/{configurePlatform-YcOiDQBZ.js → configurePlatform-D0lQGAMQ.js} +8 -7
  16. package/dist/{configurePlatform-YcOiDQBZ.js.map → configurePlatform-D0lQGAMQ.js.map} +1 -1
  17. package/dist/detachRowsBeforeDelete-S0q-DJPT.js +50 -0
  18. package/dist/detachRowsBeforeDelete-S0q-DJPT.js.map +1 -0
  19. package/dist/{eas-CpOD74Ke.js → eas-6pjU-OuX.js} +9 -8
  20. package/dist/eas-6pjU-OuX.js.map +1 -0
  21. package/dist/{getItem-B_OoFkd7.js → getItem-CxBNZ-WL.js} +13 -11
  22. package/dist/{getItem-B_OoFkd7.js.map → getItem-CxBNZ-WL.js.map} +1 -1
  23. package/dist/{getPublishPayload-Xl3sRkR-.js → getPublishPayload-CTCvRUoU.js} +50 -18
  24. package/dist/getPublishPayload-CTCvRUoU.js.map +1 -0
  25. package/dist/getPublishUploads-SFHCbf_y.js +648 -0
  26. package/dist/getPublishUploads-SFHCbf_y.js.map +1 -0
  27. package/dist/{index-Xl1_4Lmb.js → index-8O3Uow-Y.js} +125 -57
  28. package/dist/index-8O3Uow-Y.js.map +1 -0
  29. package/dist/{index-CSOQFAOn.js → index-AVFTVp1m.js} +2 -2
  30. package/dist/index-AVFTVp1m.js.map +1 -0
  31. package/dist/index-Cvt5UBz4.js +30 -0
  32. package/dist/index-Cvt5UBz4.js.map +1 -0
  33. package/dist/{index.browser-CjTe0vt1.js → index.browser-DBhxRoe8.js} +554 -165
  34. package/dist/index.browser-DBhxRoe8.js.map +1 -0
  35. package/dist/{index.node-Cfa7npS6.js → index.node-CJhlcNHM.js} +25 -13
  36. package/dist/index.node-CJhlcNHM.js.map +1 -0
  37. package/dist/main.js +30 -47
  38. package/dist/main.js.map +1 -1
  39. package/dist/mimeTypes-DHAHC4eZ.js +204 -0
  40. package/dist/mimeTypes-DHAHC4eZ.js.map +1 -0
  41. package/dist/node.js +19 -21
  42. package/dist/node.js.map +1 -1
  43. package/dist/platform.browser.js +13 -11
  44. package/dist/platform.browser.js.map +1 -1
  45. package/dist/platform.node.js +18 -5
  46. package/dist/platform.node.js.map +1 -1
  47. package/dist/{property-BrXkY1Rg.js → property-DwPD283A.js} +14 -12
  48. package/dist/property-DwPD283A.js.map +1 -0
  49. package/dist/{publishDraftGraph-X0Wr9txE.js → publishDraftGraph-BOn3_Occ.js} +6 -9
  50. package/dist/{publishDraftGraph-X0Wr9txE.js.map → publishDraftGraph-BOn3_Occ.js.map} +1 -1
  51. package/dist/{resetAmbiguousLegacyItemData-Ci6PM_vC.js → resetAmbiguousLegacyItemData-BkYmBeJc.js} +14 -3
  52. package/dist/{resetAmbiguousLegacyItemData-Ci6PM_vC.js.map → resetAmbiguousLegacyItemData-BkYmBeJc.js.map} +1 -1
  53. package/dist/{resolveModelForSyncedSeed-DFVdnYq8.js → resolveModelForSyncedSeed-BL24nLa7.js} +2 -2
  54. package/dist/{resolveModelForSyncedSeed-DFVdnYq8.js.map → resolveModelForSyncedSeed-BL24nLa7.js.map} +1 -1
  55. package/dist/src/Item/Item.d.ts +21 -3
  56. package/dist/src/Item/Item.d.ts.map +1 -1
  57. package/dist/src/Item/service/actors/runPublish.d.ts +11 -2
  58. package/dist/src/Item/service/actors/runPublish.d.ts.map +1 -1
  59. package/dist/src/Item/service/itemMachineSingle.d.ts +12 -2
  60. package/dist/src/Item/service/itemMachineSingle.d.ts.map +1 -1
  61. package/dist/src/ItemProperty/ItemProperty.d.ts +5 -3
  62. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  63. package/dist/src/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  64. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveItemStorage.d.ts.map +1 -1
  65. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  66. package/dist/src/Model/Model.d.ts +10 -4
  67. package/dist/src/Model/Model.d.ts.map +1 -1
  68. package/dist/src/Model/index.d.ts +2 -2
  69. package/dist/src/ModelProperty/ModelProperty.d.ts +10 -2
  70. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  71. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts +3 -0
  72. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  73. package/dist/src/Schema/Schema.d.ts +2 -2
  74. package/dist/src/Schema/Schema.d.ts.map +1 -1
  75. package/dist/src/Schema/index.d.ts +0 -1
  76. package/dist/src/Schema/index.d.ts.map +1 -1
  77. package/dist/src/browser/helpers/FileManager.d.ts +4 -1
  78. package/dist/src/browser/helpers/FileManager.d.ts.map +1 -1
  79. package/dist/src/browser/helpers/tolerantWebAccess.d.ts +79 -4
  80. package/dist/src/browser/helpers/tolerantWebAccess.d.ts.map +1 -1
  81. package/dist/src/browser/workers/FileDownloader.d.ts +19 -4
  82. package/dist/src/browser/workers/FileDownloader.d.ts.map +1 -1
  83. package/dist/src/browser/workers/filesDownload.d.ts.map +1 -1
  84. package/dist/src/client/ClientManager.d.ts +30 -11
  85. package/dist/src/client/ClientManager.d.ts.map +1 -1
  86. package/dist/src/client/actors/platformClassesInit.d.ts +6 -0
  87. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  88. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  89. package/dist/src/client/actors/saveConfig.d.ts +13 -6
  90. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  91. package/dist/src/client/clientManagerMachine.d.ts.map +1 -1
  92. package/dist/src/db/migrateLegacyItemStorageRows.d.ts +57 -0
  93. package/dist/src/db/migrateLegacyItemStorageRows.d.ts.map +1 -0
  94. package/dist/src/db/read/getCompositeChildPaths.d.ts +13 -0
  95. package/dist/src/db/read/getCompositeChildPaths.d.ts.map +1 -0
  96. package/dist/src/db/read/getItems.d.ts.map +1 -1
  97. package/dist/src/db/read/getPublishPayload.d.ts +1 -1
  98. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  99. package/dist/src/db/read/getPublishUploads.d.ts +32 -3
  100. package/dist/src/db/read/getPublishUploads.d.ts.map +1 -1
  101. package/dist/src/db/read/summarizePublishWork.d.ts.map +1 -1
  102. package/dist/src/db/write/claimUnpublishedDrafts.d.ts +2 -0
  103. package/dist/src/db/write/claimUnpublishedDrafts.d.ts.map +1 -1
  104. package/dist/src/db/write/convertVerbatimItemStorageRow.d.ts +44 -0
  105. package/dist/src/db/write/convertVerbatimItemStorageRow.d.ts.map +1 -0
  106. package/dist/src/db/write/createNewItem.d.ts.map +1 -1
  107. package/dist/src/eventBus.d.ts +5 -0
  108. package/dist/src/eventBus.d.ts.map +1 -1
  109. package/dist/src/events/files/download.d.ts.map +1 -1
  110. package/dist/src/helpers/FileManager/BaseFileManager.d.ts +3 -3
  111. package/dist/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  112. package/dist/src/helpers/FileManager/IFileManager.d.ts +25 -1
  113. package/dist/src/helpers/FileManager/IFileManager.d.ts.map +1 -1
  114. package/dist/src/helpers/arweaveContentTags.d.ts +33 -0
  115. package/dist/src/helpers/arweaveContentTags.d.ts.map +1 -0
  116. package/dist/src/helpers/cachedPropertyRefresh.d.ts +12 -0
  117. package/dist/src/helpers/cachedPropertyRefresh.d.ts.map +1 -0
  118. package/dist/src/helpers/compositeUpload.d.ts +28 -0
  119. package/dist/src/helpers/compositeUpload.d.ts.map +1 -0
  120. package/dist/src/helpers/db.d.ts +3 -0
  121. package/dist/src/helpers/db.d.ts.map +1 -1
  122. package/dist/src/helpers/easSdk.d.ts +16 -0
  123. package/dist/src/helpers/easSdk.d.ts.map +1 -0
  124. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts +16 -0
  125. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts.map +1 -0
  126. package/dist/src/helpers/entity/entityDestroy.d.ts +2 -0
  127. package/dist/src/helpers/entity/entityDestroy.d.ts.map +1 -1
  128. package/dist/src/helpers/itemStorageFile.d.ts +57 -0
  129. package/dist/src/helpers/itemStorageFile.d.ts.map +1 -0
  130. package/dist/src/helpers/mapWithConcurrency.d.ts +7 -0
  131. package/dist/src/helpers/mapWithConcurrency.d.ts.map +1 -0
  132. package/dist/src/helpers/mimeTypes.d.ts +43 -0
  133. package/dist/src/helpers/mimeTypes.d.ts.map +1 -0
  134. package/dist/src/helpers/ownership.d.ts +28 -4
  135. package/dist/src/helpers/ownership.d.ts.map +1 -1
  136. package/dist/src/helpers/property/index.d.ts +37 -51
  137. package/dist/src/helpers/property/index.d.ts.map +1 -1
  138. package/dist/src/helpers/publishConfig.d.ts +27 -8
  139. package/dist/src/helpers/publishConfig.d.ts.map +1 -1
  140. package/dist/src/helpers/storageDir.d.ts +16 -0
  141. package/dist/src/helpers/storageDir.d.ts.map +1 -0
  142. package/dist/src/helpers/tabCoordinator.d.ts +5 -1
  143. package/dist/src/helpers/tabCoordinator.d.ts.map +1 -1
  144. package/dist/src/helpers/tabEvents.d.ts +23 -2
  145. package/dist/src/helpers/tabEvents.d.ts.map +1 -1
  146. package/dist/src/helpers/updateSchema.d.ts +5 -0
  147. package/dist/src/helpers/updateSchema.d.ts.map +1 -1
  148. package/dist/src/helpers/waitForEntityIdle.d.ts +5 -0
  149. package/dist/src/helpers/waitForEntityIdle.d.ts.map +1 -1
  150. package/dist/src/imports/json.d.ts +9 -0
  151. package/dist/src/imports/json.d.ts.map +1 -1
  152. package/dist/src/index.d.ts +11 -7
  153. package/dist/src/index.d.ts.map +1 -1
  154. package/dist/src/interfaces/IItem.d.ts +7 -1
  155. package/dist/src/interfaces/IItem.d.ts.map +1 -1
  156. package/dist/src/node/db/Db.d.ts.map +1 -1
  157. package/dist/src/node/helpers/PathResolver.d.ts.map +1 -1
  158. package/dist/src/node/index.d.ts +8 -1
  159. package/dist/src/node/index.d.ts.map +1 -1
  160. package/dist/src/platform/index.browser.d.ts +2 -0
  161. package/dist/src/platform/index.browser.d.ts.map +1 -1
  162. package/dist/src/platform/index.node.d.ts +2 -0
  163. package/dist/src/platform/index.node.d.ts.map +1 -1
  164. package/dist/src/types/fileManager.d.ts +3 -14
  165. package/dist/src/types/fileManager.d.ts.map +1 -1
  166. package/dist/src/types/index.d.ts +12 -1
  167. package/dist/src/types/index.d.ts.map +1 -1
  168. package/dist/src/types/machines.d.ts +2 -0
  169. package/dist/src/types/machines.d.ts.map +1 -1
  170. package/dist/src/types/property.d.ts +8 -0
  171. package/dist/src/types/property.d.ts.map +1 -1
  172. package/dist/src/types/publish.d.ts +14 -0
  173. package/dist/src/types/publish.d.ts.map +1 -1
  174. package/dist/{syncDbWithEas-BU-jZ5bJ.js → syncDbWithEas-Bv2Fe38J.js} +17 -17
  175. package/dist/{syncDbWithEas-BU-jZ5bJ.js.map → syncDbWithEas-Bv2Fe38J.js.map} +1 -1
  176. package/dist/tabEvents-9s2WCYw-.js +335 -0
  177. package/dist/tabEvents-9s2WCYw-.js.map +1 -0
  178. package/dist/tolerantWebAccess-iUu80pAP.js +551 -0
  179. package/dist/tolerantWebAccess-iUu80pAP.js.map +1 -0
  180. package/dist/{updateSeedRevokedAt-iLpzae1i.js → updateSeedRevokedAt-zBfi931j.js} +3 -3
  181. package/dist/{updateSeedRevokedAt-iLpzae1i.js.map → updateSeedRevokedAt-zBfi931j.js.map} +1 -1
  182. package/package.json +11 -12
  183. package/src/node/easLodashRegister.js +4 -0
  184. package/dist/BasePathResolver-BdxCSIzn.js +0 -679
  185. package/dist/BasePathResolver-BdxCSIzn.js.map +0 -1
  186. package/dist/ClientManager-DDA9956Y.js.map +0 -1
  187. package/dist/Item-D4FigtYS.js.map +0 -1
  188. package/dist/ModelProperty-BDt6AU2h.js.map +0 -1
  189. package/dist/Schema-B8xqLWkL.js.map +0 -1
  190. package/dist/cjs/ModelProperty-B-cZm1yU.js +0 -1977
  191. package/dist/cjs/ModelProperty-B-cZm1yU.js.map +0 -1
  192. package/dist/cjs/Schema-STP972Xw.js +0 -5256
  193. package/dist/cjs/Schema-STP972Xw.js.map +0 -1
  194. package/dist/cjs/SchemaValidationService-CKNW1bKg.js +0 -778
  195. package/dist/cjs/SchemaValidationService-CKNW1bKg.js.map +0 -1
  196. package/dist/cjs/backfillMetadataPropertyIds-CP3y1skt.js +0 -89
  197. package/dist/cjs/backfillMetadataPropertyIds-CP3y1skt.js.map +0 -1
  198. package/dist/cjs/eas-CAnUC4wd.js +0 -138
  199. package/dist/cjs/eas-CAnUC4wd.js.map +0 -1
  200. package/dist/cjs/getItem-CWgb3e9G.js +0 -58
  201. package/dist/cjs/getItem-CWgb3e9G.js.map +0 -1
  202. package/dist/cjs/getPublishPayload-BsZWiJ03.js +0 -1603
  203. package/dist/cjs/getPublishPayload-BsZWiJ03.js.map +0 -1
  204. package/dist/cjs/getPublishUploads-BQr8aMVP.js +0 -495
  205. package/dist/cjs/getPublishUploads-BQr8aMVP.js.map +0 -1
  206. package/dist/cjs/index-nA5PxBSs.js +0 -70
  207. package/dist/cjs/index-nA5PxBSs.js.map +0 -1
  208. package/dist/cjs/index-usKaANAq.js +0 -22171
  209. package/dist/cjs/index-usKaANAq.js.map +0 -1
  210. package/dist/cjs/index.browser-BSf8HpnU.js +0 -22
  211. package/dist/cjs/index.browser-BSf8HpnU.js.map +0 -1
  212. package/dist/cjs/property-xMwPhQ5N.js +0 -327
  213. package/dist/cjs/property-xMwPhQ5N.js.map +0 -1
  214. package/dist/cjs/publishDraftGraph-BRWlR1KO.js +0 -403
  215. package/dist/cjs/publishDraftGraph-BRWlR1KO.js.map +0 -1
  216. package/dist/cjs/resetAmbiguousLegacyItemData-8nfkj9rz.js +0 -116
  217. package/dist/cjs/resetAmbiguousLegacyItemData-8nfkj9rz.js.map +0 -1
  218. package/dist/cjs/resolveModelForSyncedSeed-kYRuDWYw.js +0 -49
  219. package/dist/cjs/resolveModelForSyncedSeed-kYRuDWYw.js.map +0 -1
  220. package/dist/cjs/syncDbWithEas-DqRhV8o2.js +0 -886
  221. package/dist/cjs/syncDbWithEas-DqRhV8o2.js.map +0 -1
  222. package/dist/db-CQt-gcAl.js.map +0 -1
  223. package/dist/eas-CpOD74Ke.js.map +0 -1
  224. package/dist/getPublishPayload-Xl3sRkR-.js.map +0 -1
  225. package/dist/getPublishUploads-DHP01KgU.js +0 -484
  226. package/dist/getPublishUploads-DHP01KgU.js.map +0 -1
  227. package/dist/index-BGt4_oPO.js +0 -31
  228. package/dist/index-BGt4_oPO.js.map +0 -1
  229. package/dist/index-CSOQFAOn.js.map +0 -1
  230. package/dist/index-Xl1_4Lmb.js.map +0 -1
  231. package/dist/index.browser-CjTe0vt1.js.map +0 -1
  232. package/dist/index.node-Cfa7npS6.js.map +0 -1
  233. package/dist/main.cjs +0 -84
  234. package/dist/main.cjs.map +0 -1
  235. package/dist/property-BrXkY1Rg.js.map +0 -1
  236. package/dist/tabEvents-BZJMY5uK.js +0 -1344
  237. package/dist/tabEvents-BZJMY5uK.js.map +0 -1
  238. package/dist/tolerantWebAccess-BZ2RA_mb.js +0 -160
  239. package/dist/tolerantWebAccess-BZ2RA_mb.js.map +0 -1
@@ -1,1344 +0,0 @@
1
- import debug from 'debug';
2
- import { a as BaseDb, m as metadata, B as BaseFileManager, b as appState, D as ImageSize, E as EAS_SEED_DATA_SYNCED_TO_DB_EVENT } from './BasePathResolver-BdxCSIzn.js';
3
- import { isEasAttestationExplorerUrl, BaseArweaveClient, ensureReadGatewaySelected, getArweaveReadBaseUrls } from '@seedprotocol/arweave';
4
- import { BaseQueryClient, BaseEasClient, GET_FILES_METADATA } from '@seedprotocol/eas';
5
- import { waitFor } from 'xstate';
6
- import 'pluralize';
7
- import { t as getAllAddressesFromDb, m as eventEmitter } from './db-CQt-gcAl.js';
8
- import { and, eq, or, isNotNull } from 'drizzle-orm';
9
- import { customAlphabet } from 'nanoid';
10
- import { alphanumeric } from 'nanoid-dictionary';
11
- import '@seedprotocol/query';
12
- import { throttle } from 'lodash-es';
13
-
14
- /** Same rules as getCorrectId in helpers/index (avoid barrel circular import). */
15
- function parseLocalIdOrUid(localIdOrUid) {
16
- const id = { localId: undefined, uid: undefined };
17
- if (!localIdOrUid)
18
- return id;
19
- if (localIdOrUid.length === 10) {
20
- id.localId = localIdOrUid;
21
- }
22
- if (localIdOrUid.startsWith('0x') && localIdOrUid.length === 66) {
23
- id.uid = localIdOrUid;
24
- }
25
- return id;
26
- }
27
- /** Relation/image refs may be string ids or `{ seedLocalId?, seedUid? }`. */
28
- function normalizeRelationPropertyValue(value) {
29
- if (value == null)
30
- return undefined;
31
- if (typeof value === 'string') {
32
- const t = value.trim();
33
- return t !== '' ? t : undefined;
34
- }
35
- if (typeof value === 'object' && value !== null) {
36
- const o = value;
37
- if (typeof o.seedLocalId === 'string' && o.seedLocalId.trim() !== '') {
38
- return o.seedLocalId.trim();
39
- }
40
- if (typeof o.seedUid === 'string' && o.seedUid.trim() !== '') {
41
- return o.seedUid.trim();
42
- }
43
- }
44
- return undefined;
45
- }
46
- /** getCorrectId only accepts 10-char local ids and 0x66 uids; local seed refs can be up to 21 chars. */
47
- const LOCAL_SEED_REF = /^[a-zA-Z0-9_-]{10,21}$/;
48
- /** Resolve seed ids from a single string (context propertyValue or DB row). */
49
- function resolveSeedIdsFromRefString(s) {
50
- const fromCorrect = parseLocalIdOrUid(s);
51
- if (fromCorrect.localId || fromCorrect.uid) {
52
- return { seedLocalId: fromCorrect.localId, seedUid: fromCorrect.uid };
53
- }
54
- if (LOCAL_SEED_REF.test(s) && !s.startsWith('0x')) {
55
- return { seedLocalId: s };
56
- }
57
- return {};
58
- }
59
- /**
60
- * True when a relation ref is an attested seed uid (0x…) rather than a local id. A uid only exists once
61
- * the seed is on EAS, so publish can attest the uid as-is when no local copy exists (e.g. a server
62
- * publishing on someone's behalf that only holds the uids it was given). Callers must not walk into it.
63
- */
64
- function isPublishedSeedRef(value) {
65
- const ref = normalizeRelationPropertyValue(value);
66
- if (!ref)
67
- return false;
68
- const { seedLocalId, seedUid } = resolveSeedIdsFromRefString(ref);
69
- return !!seedUid && !seedLocalId;
70
- }
71
- /**
72
- * Storage seed local id (nanoid) or 0x uid. Stricter than resolveSeedIdsFromRefString, which accepts
73
- * any 10-char string (so a 10-char html snippet like "<p>raw</p>" would pass as a local id).
74
- */
75
- const STORAGE_SEED_REF = /^(?:[A-Za-z0-9_-]{10,21}|0x[0-9a-fA-F]{64})$/;
76
- /** True when a File/Image/Html value is already a storage seed reference rather than raw content. */
77
- function isStorageSeedRef(value) {
78
- return typeof value === 'string' && STORAGE_SEED_REF.test(value.trim());
79
- }
80
-
81
- const seedUidToStorageTransactionId = new Map();
82
- const getStorageTransactionIdForSeedUid = async (seedUid) => {
83
- if (seedUidToStorageTransactionId.has(seedUid)) {
84
- return seedUidToStorageTransactionId.get(seedUid);
85
- }
86
- const appDb = BaseDb.getAppDb();
87
- const results = (await appDb
88
- .select({
89
- storageTransactionId: metadata.propertyValue,
90
- })
91
- .from(metadata)
92
- .where(and(eq(metadata.seedUid, seedUid), eq(metadata.propertyName, 'storageTransactionId'))));
93
- if (!results || results.length === 0) {
94
- return;
95
- }
96
- seedUidToStorageTransactionId.set(seedUid, results[0].storageTransactionId);
97
- return results[0].storageTransactionId;
98
- };
99
-
100
- const logger$5 = debug('seedSdk:helpers:mediaRef');
101
- /** Typical Arweave transaction id: 43 URL-safe base64 characters. */
102
- const ARWEAVE_TX_ID = /^[a-zA-Z0-9_-]{43}$/;
103
- function trimOrEmpty(raw) {
104
- if (raw == null)
105
- return '';
106
- return typeof raw === 'string' ? raw.trim() : String(raw).trim();
107
- }
108
- function coalesceStringField(item, key) {
109
- const v = item[key];
110
- if (v == null)
111
- return '';
112
- if (typeof v === 'string')
113
- return v.trim();
114
- if (typeof v === 'number' || typeof v === 'boolean')
115
- return String(v);
116
- return '';
117
- }
118
- /**
119
- * Try JSON relation payloads and plain relation id strings.
120
- */
121
- function unwrapRelationString(raw) {
122
- const t = raw.trim();
123
- if (!t)
124
- return t;
125
- try {
126
- const parsed = JSON.parse(t);
127
- const fromObj = normalizeRelationPropertyValue(parsed);
128
- if (fromObj)
129
- return fromObj;
130
- }
131
- catch {
132
- // not JSON
133
- }
134
- return t;
135
- }
136
- /**
137
- * Pure, sync classification of a media-related string from feeds or XML.
138
- */
139
- function classifyMediaRef(raw, options) {
140
- const s = trimOrEmpty(raw);
141
- if (!s) {
142
- return { kind: 'empty' };
143
- }
144
- const treatAs = options?.treatAs;
145
- if (treatAs === 'url') {
146
- return { kind: 'url', href: s };
147
- }
148
- if (treatAs === 'arweaveTx') {
149
- return { kind: 'arweaveTxId', txId: s };
150
- }
151
- if (treatAs === 'seedUid') {
152
- if (s.startsWith('0x') && s.length === 66) {
153
- return { kind: 'seedUid', uid: s };
154
- }
155
- return { kind: 'unknown', raw: s };
156
- }
157
- if (s.startsWith('http://') || s.startsWith('https://') || s.startsWith('blob:') || s.startsWith('data:')) {
158
- if (isEasAttestationExplorerUrl(s)) {
159
- return { kind: 'nonMediaUrl', href: s };
160
- }
161
- return { kind: 'url', href: s };
162
- }
163
- const unwrapped = unwrapRelationString(s);
164
- const ids = resolveSeedIdsFromRefString(unwrapped);
165
- if (ids.seedUid) {
166
- return { kind: 'seedUid', uid: ids.seedUid };
167
- }
168
- if (ids.seedLocalId) {
169
- return { kind: 'seedLocalId', localId: ids.seedLocalId };
170
- }
171
- if (unwrapped.startsWith('0x') && unwrapped.length === 66) {
172
- return { kind: 'seedUid', uid: unwrapped };
173
- }
174
- if (ARWEAVE_TX_ID.test(unwrapped) && !unwrapped.startsWith('0x')) {
175
- return { kind: 'arweaveTxId', txId: unwrapped };
176
- }
177
- return { kind: 'unknown', raw: s };
178
- }
179
- /**
180
- * Same as convertTxIdToImage but local to this module to avoid circular imports with helpers/index.
181
- */
182
- async function tryLocalBlobUrlFromTxId(txId) {
183
- const imageFilePath = BaseFileManager.getFilesPath('images', txId);
184
- const fileExists = await BaseFileManager.pathExists(imageFilePath);
185
- if (!fileExists) {
186
- logger$5(`[tryLocalBlobUrlFromTxId] ${imageFilePath} does not exist`);
187
- return undefined;
188
- }
189
- const buffer = await BaseFileManager.readFileAsBuffer(imageFilePath);
190
- let arrayBuffer;
191
- if (buffer instanceof Blob) {
192
- arrayBuffer = await buffer.arrayBuffer();
193
- }
194
- else if (buffer instanceof ArrayBuffer) {
195
- arrayBuffer = buffer;
196
- }
197
- else {
198
- const sliced = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
199
- if (sliced instanceof SharedArrayBuffer) {
200
- const uint8Array = new Uint8Array(sliced);
201
- arrayBuffer = uint8Array.buffer.slice(0);
202
- }
203
- else {
204
- arrayBuffer = sliced;
205
- }
206
- }
207
- const uint = new Uint8Array(arrayBuffer);
208
- const imageBlob = new Blob([uint]);
209
- return URL.createObjectURL(imageBlob);
210
- }
211
- async function resolveTxId(txId) {
212
- const local = await tryLocalBlobUrlFromTxId(txId);
213
- if (local) {
214
- return { status: 'ready', href: local, source: 'localBlob' };
215
- }
216
- return {
217
- status: 'ready',
218
- href: BaseArweaveClient.getRawUrl(txId),
219
- source: 'gateway',
220
- };
221
- }
222
- /**
223
- * Resolve a classified media reference to a display URL (https/blob/data), using local files when present.
224
- */
225
- async function resolveMediaRef(raw, options) {
226
- const classification = classifyMediaRef(raw, options);
227
- switch (classification.kind) {
228
- case 'empty':
229
- return { status: 'empty' };
230
- case 'url':
231
- return {
232
- status: 'ready',
233
- href: classification.href,
234
- source: 'direct',
235
- };
236
- case 'nonMediaUrl':
237
- return {
238
- status: 'unresolved',
239
- reason: 'non_media_url',
240
- classification,
241
- };
242
- case 'seedLocalId':
243
- return {
244
- status: 'unresolved',
245
- reason: 'seed_local_id_not_portable',
246
- classification,
247
- };
248
- case 'unknown':
249
- return {
250
- status: 'unresolved',
251
- reason: 'unknown_ref',
252
- classification,
253
- };
254
- case 'arweaveTxId':
255
- return resolveTxId(classification.txId);
256
- case 'seedUid': {
257
- const appDb = BaseDb.getAppDb();
258
- if (!appDb) {
259
- return {
260
- status: 'unresolved',
261
- reason: 'seed_uid_requires_app_db',
262
- classification,
263
- };
264
- }
265
- const storageTransactionId = await getStorageTransactionIdForSeedUid(classification.uid);
266
- if (!storageTransactionId) {
267
- return {
268
- status: 'unresolved',
269
- reason: 'seed_uid_no_storage_transaction',
270
- classification,
271
- };
272
- }
273
- return resolveTxId(storageTransactionId);
274
- }
275
- default:
276
- return {
277
- status: 'unresolved',
278
- reason: 'unknown_ref',
279
- classification,
280
- };
281
- }
282
- }
283
- /**
284
- * Read a string field from a parsed item, trying camelCase and snake_case keys.
285
- */
286
- function getFeedItemStringField(item, key) {
287
- const direct = coalesceStringField(item, key);
288
- if (direct)
289
- return direct;
290
- const snake = key.replace(/[A-Z]/g, (l) => `_${l.toLowerCase()}`);
291
- if (snake !== key) {
292
- const alt = coalesceStringField(item, snake);
293
- if (alt)
294
- return alt;
295
- }
296
- const parts = key.split('_');
297
- if (parts.length > 1) {
298
- const camel = parts[0] + parts.slice(1).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
299
- const alt2 = coalesceStringField(item, camel);
300
- if (alt2)
301
- return alt2;
302
- }
303
- return '';
304
- }
305
- /**
306
- * Apply a field manifest to a plain feed item: classify media/file fields; pass through html/text.
307
- */
308
- function normalizeFeedItemFields(item, manifest) {
309
- const out = {};
310
- for (const [fieldKey, descriptor] of Object.entries(manifest)) {
311
- const raw = getFeedItemStringField(item, fieldKey);
312
- if (!raw) {
313
- out[fieldKey] = undefined;
314
- continue;
315
- }
316
- if (descriptor.role === 'html') {
317
- out[fieldKey] = { role: 'html', raw };
318
- continue;
319
- }
320
- if (descriptor.role === 'text') {
321
- out[fieldKey] = { role: 'text', raw };
322
- continue;
323
- }
324
- const classification = classifyMediaRef(raw, { treatAs: descriptor.treatAs });
325
- out[fieldKey] = {
326
- role: descriptor.role,
327
- raw,
328
- classification,
329
- };
330
- }
331
- return out;
332
- }
333
-
334
- const getMetadata = async (props) => {
335
- const appDb = BaseDb.getAppDb();
336
- let storageTransactionId;
337
- if (props) {
338
- storageTransactionId = props.storageTransactionId;
339
- }
340
- const whereClauses = [];
341
- if (storageTransactionId) {
342
- whereClauses.push(eq(metadata.propertyName, 'storageTransactionId'));
343
- whereClauses.push(eq(metadata.propertyValue, storageTransactionId));
344
- }
345
- const metadataRows = await appDb
346
- .select()
347
- .from(metadata)
348
- .where(and(...whereClauses));
349
- if (!metadataRows || metadataRows.length === 0) {
350
- return;
351
- }
352
- return metadataRows[0];
353
- };
354
-
355
- const saveMetadata = async (metadataRecord, metadataValues) => {
356
- if (!metadataRecord.localId) {
357
- return;
358
- }
359
- const appDb = BaseDb.getAppDb();
360
- await appDb
361
- .update(metadata)
362
- .set({
363
- ...metadataValues,
364
- updatedAt: Date.now(),
365
- })
366
- .where(eq(metadata.localId, metadataRecord.localId));
367
- };
368
-
369
- const isNode = () => {
370
- return (typeof process !== 'undefined' &&
371
- process.versions != null &&
372
- process.versions.node != null);
373
- };
374
- const isBrowser = () => {
375
- return !isElectron() && typeof document !== 'undefined' && typeof window !== 'undefined';
376
- };
377
- const isElectron = () => {
378
- return typeof process !== 'undefined' && process.versions != null && process.versions.electron != null;
379
- };
380
- /**
381
- * Detects if code is running in an Electron renderer process.
382
- *
383
- * Uses multiple detection methods for robustness:
384
- * 1. Checks process.type === 'renderer' (most reliable)
385
- * 2. Falls back to checking if Electron is present and window/document exist
386
- *
387
- * @returns true if running in Electron renderer process, false otherwise
388
- */
389
- const isElectronRenderer = () => {
390
- // Method 1: Check process.type (most reliable - official Electron API)
391
- if (typeof process !== 'undefined' &&
392
- process.type === 'renderer') {
393
- return true;
394
- }
395
- // Method 2: Fallback - Electron + browser-like environment
396
- // Renderer processes have window/document, main process doesn't (in modern Electron)
397
- if (isElectron() &&
398
- typeof window !== 'undefined' &&
399
- typeof document !== 'undefined') {
400
- return true;
401
- }
402
- return false;
403
- };
404
- /**
405
- * True where OPFS-backed Arweave file downloads should run: normal browsers and
406
- * Electron renderer. {@link isBrowser} is false for every Electron build (including renderer).
407
- */
408
- const supportsOpfsFileDownloads = () => {
409
- return isBrowser() || isElectronRenderer();
410
- };
411
-
412
- const logger$4 = debug('seedSdk:files:download');
413
- const AUTO_BULK_DOWNLOAD_THROTTLE_MS = 10000;
414
- /** Avoid refetch-on-every-call: transient empty indexer responses were overwriting good cache (see trailing throttle ~10s after success). */
415
- const GET_FILES_METADATA_STALE_MS = 120000;
416
- let bulkDownloadInFlight = null;
417
- const lazyDownloadInFlightByTransactionId = new Map();
418
- // syncDbFiles helper - internal service removed, functionality moved here
419
- const syncDbFiles = async (endpoints) => {
420
- // TODO: Implement syncDbFiles functionality if needed
421
- // This was previously in @/services/internal/helpers
422
- logger$4('[download] syncDbFiles called but not yet implemented');
423
- return Promise.resolve();
424
- };
425
- const getAppDbReady = async () => {
426
- if (!BaseDb.isAppDbReady()) {
427
- // Wait for ClientManager to be ready (DB_INIT state or later)
428
- const _mod_0 = await import('./ClientManager-DDA9956Y.js');
429
- const _ns_0 = _mod_0.H;
430
- const clientManagerMod = _ns_0;
431
- const { getClient } = clientManagerMod;
432
- const clientManager = getClient();
433
- const clientService = clientManager.getService();
434
- await waitFor(clientService, (snapshot) => {
435
- const state = snapshot.value;
436
- return state === 'dbInit' ||
437
- state === 'saveConfig' ||
438
- state === 'processSchemaFiles' ||
439
- state === 'addModelsToStore' ||
440
- state === 'addModelsToDb' ||
441
- state === 'idle';
442
- }, { timeout: 30000 });
443
- }
444
- return BaseDb.getAppDb();
445
- };
446
- const getExcludedTransactions = async () => {
447
- const appDb = await getAppDbReady();
448
- if (!appDb) {
449
- return new Set();
450
- }
451
- const excludedTransactionsQuery = await appDb
452
- .select()
453
- .from(appState)
454
- .where(eq(appState.key, 'excludedTransactions'));
455
- const excludedTransactions = new Set();
456
- if (excludedTransactionsQuery && excludedTransactionsQuery.length === 1) {
457
- const valueString = excludedTransactionsQuery[0].value;
458
- if (valueString) {
459
- const excludedTransactionsArray = JSON.parse(valueString);
460
- for (const txId of excludedTransactionsArray) {
461
- excludedTransactions.add(txId);
462
- }
463
- }
464
- }
465
- return excludedTransactions;
466
- };
467
- /** Arweave transaction ids are 43 chars in the URL-safe base64 alphabet. */
468
- const ARWEAVE_TX_ID_RE$1 = /^[a-z0-9_-]{43}$/i;
469
- const normalizeArweaveTxId = (raw) => {
470
- if (raw == null || raw === '')
471
- return undefined;
472
- const t = String(raw).trim();
473
- if (ARWEAVE_TX_ID_RE$1.test(t))
474
- return t;
475
- const m = t.match(/^([a-z0-9_-]{43})(?:\.[^/]+)?$/i);
476
- if (m)
477
- return m[1];
478
- // Values may be full gateway URLs or paths; scan for the embedded tx id.
479
- const embedded = t.match(/[a-z0-9_-]{43}/gi);
480
- if (embedded) {
481
- for (const candidate of embedded) {
482
- if (ARWEAVE_TX_ID_RE$1.test(candidate))
483
- return candidate;
484
- }
485
- }
486
- return undefined;
487
- };
488
- const mergeAddressLists = (a, b) => {
489
- const seen = new Set();
490
- const out = [];
491
- for (const addr of [...(a ?? []), ...(b ?? [])]) {
492
- if (!addr || !addr.trim())
493
- continue;
494
- const k = addr.toLowerCase();
495
- if (seen.has(k))
496
- continue;
497
- seen.add(k);
498
- out.push(addr);
499
- }
500
- return out;
501
- };
502
- const collectTransactionIdsFromLocalMetadata = async () => {
503
- const appDb = await getAppDbReady();
504
- if (!appDb) {
505
- return [];
506
- }
507
- const nameOr = or(eq(metadata.propertyName, 'storageTransactionId'), eq(metadata.propertyName, 'storage_transaction_id'), eq(metadata.propertyName, 'transactionId'));
508
- const propRows = await appDb
509
- .select({ propertyValue: metadata.propertyValue })
510
- .from(metadata)
511
- .where(and(nameOr, isNotNull(metadata.propertyValue)));
512
- const refRows = await appDb
513
- .select({ refResolvedValue: metadata.refResolvedValue })
514
- .from(metadata)
515
- .where(isNotNull(metadata.refResolvedValue));
516
- const ids = new Set();
517
- for (const row of propRows) {
518
- const id = normalizeArweaveTxId(row.propertyValue ?? undefined);
519
- if (id)
520
- ids.add(id);
521
- }
522
- for (const row of refRows) {
523
- const id = normalizeArweaveTxId(row.refResolvedValue ?? undefined);
524
- if (id)
525
- ids.add(id);
526
- }
527
- return Array.from(ids);
528
- };
529
- const parseTransactionIdsFromMetadata = (filesMetadata, excludedTransactions) => {
530
- const transactionIds = [];
531
- for (const fileMetadata of filesMetadata) {
532
- // Validate and parse decodedDataJson
533
- if (!fileMetadata.decodedDataJson || fileMetadata.decodedDataJson.trim() === '') {
534
- console.warn('[events/files] [download] empty decodedDataJson for fileMetadata: ', fileMetadata.id);
535
- continue;
536
- }
537
- let json;
538
- try {
539
- json = JSON.parse(fileMetadata.decodedDataJson);
540
- }
541
- catch (error) {
542
- console.warn('[events/files] [download] failed to parse decodedDataJson for fileMetadata: ', fileMetadata.id, error);
543
- continue;
544
- }
545
- if (!Array.isArray(json) || json.length === 0 || !json[0]?.value?.value) {
546
- console.warn('[events/files] [download] invalid decodedDataJson structure for fileMetadata: ', fileMetadata.id);
547
- continue;
548
- }
549
- const rawTx = json[0].value.value;
550
- if (typeof rawTx !== 'string' || rawTx.trim().length === 0) {
551
- continue;
552
- }
553
- const transactionId = normalizeArweaveTxId(rawTx.trim());
554
- if (!transactionId) {
555
- continue;
556
- }
557
- if (excludedTransactions.has(transactionId) || excludedTransactions.has(rawTx.trim())) {
558
- continue;
559
- }
560
- transactionIds.push(transactionId);
561
- }
562
- return transactionIds;
563
- };
564
- const downloadTransactionIds = async (rawTransactionIds, options) => {
565
- if (!supportsOpfsFileDownloads()) {
566
- return false;
567
- }
568
- const transactionIds = Array.from(new Set(rawTransactionIds.filter((tx) => !!tx && tx.trim().length > 0)));
569
- if (transactionIds.length === 0) {
570
- return false;
571
- }
572
- const excludedTransactions = await getExcludedTransactions();
573
- const queryClient = BaseQueryClient.getQueryClient();
574
- const transactionIdsToDownload = [];
575
- await ensureReadGatewaySelected();
576
- for (const transactionId of transactionIds) {
577
- if (excludedTransactions.has(transactionId)) {
578
- continue;
579
- }
580
- try {
581
- // Browser: do not call getTransactionStatus() — many gateways (e.g. g8way.io) redirect or omit
582
- // CORS headers, so fetch() fails and we would wrongly exclude txs. The OPFS worker fetch decides success.
583
- let tags = [];
584
- try {
585
- tags = await queryClient.fetchQuery({
586
- queryKey: ['getTransactionTags', transactionId],
587
- queryFn: async () => BaseArweaveClient.getTransactionTags(transactionId),
588
- });
589
- }
590
- catch {
591
- tags = [];
592
- }
593
- if (tags && tags.length > 0) {
594
- for (const { name, value } of tags) {
595
- if (name !== 'Content-SHA-256')
596
- continue;
597
- const metadataRecord = await getMetadata({
598
- storageTransactionId: transactionId,
599
- });
600
- if (metadataRecord) {
601
- await saveMetadata(metadataRecord, {
602
- contentHash: value,
603
- });
604
- }
605
- }
606
- }
607
- transactionIdsToDownload.push(transactionId);
608
- }
609
- catch (error) {
610
- logger$4(error);
611
- }
612
- }
613
- if (transactionIdsToDownload.length === 0) {
614
- return false;
615
- }
616
- // Preferred gateways first: a just-published item is only on the gateway it was uploaded through.
617
- const arweaveBaseUrls = getArweaveReadBaseUrls();
618
- if (transactionIdsToDownload.length === 1) {
619
- await BaseFileManager.downloadFileByTransactionId({
620
- transactionId: transactionIdsToDownload[0],
621
- arweaveHost: BaseArweaveClient.getBaseUrl(),
622
- arweaveBaseUrls,
623
- excludedTransactions,
624
- });
625
- }
626
- else {
627
- await BaseFileManager.downloadAllFiles({
628
- transactionIds: transactionIdsToDownload,
629
- arweaveHost: BaseArweaveClient.getBaseUrl(),
630
- arweaveBaseUrls,
631
- excludedTransactions,
632
- });
633
- }
634
- if (options?.resizeAllImages !== false) {
635
- await BaseFileManager.resizeAllImages({
636
- width: 480,
637
- height: 480,
638
- });
639
- }
640
- return true;
641
- };
642
- const runBulkDownloadWithDedupe = async (transactionIds) => {
643
- if (bulkDownloadInFlight) {
644
- return bulkDownloadInFlight;
645
- }
646
- bulkDownloadInFlight = (async () => {
647
- try {
648
- await downloadTransactionIds(transactionIds, { resizeAllImages: true });
649
- }
650
- finally {
651
- bulkDownloadInFlight = null;
652
- }
653
- })();
654
- return bulkDownloadInFlight;
655
- };
656
- const downloadAllFilesRequestHandler = async ({ endpoints, eventId, }) => {
657
- if (!supportsOpfsFileDownloads()) {
658
- return;
659
- }
660
- await syncDbFiles();
661
- eventEmitter.emit('fs.downloadAll.success', { eventId });
662
- eventEmitter.emit('fs.downloadAllBinary.request', { endpoints });
663
- };
664
- const downloadAllFilesBinaryRequestHandler = async (addressesHintOrPayload) => {
665
- if (!supportsOpfsFileDownloads()) {
666
- return;
667
- }
668
- const addressesHint = Array.isArray(addressesHintOrPayload)
669
- ? addressesHintOrPayload
670
- : undefined;
671
- let fromDb = [];
672
- if (BaseDb.isAppDbReady()) {
673
- fromDb = await getAllAddressesFromDb();
674
- }
675
- if (!BaseDb.isAppDbReady()) {
676
- await getAppDbReady();
677
- fromDb = await getAllAddressesFromDb();
678
- }
679
- const addresses = mergeAddressLists(addressesHint, fromDb);
680
- if (!addresses || addresses.length === 0) {
681
- return;
682
- }
683
- const queryClient = BaseQueryClient.getQueryClient();
684
- const easClient = BaseEasClient.getEasClient();
685
- const filesMetadataQueryKey = ['getFilesMetadata', ...addresses];
686
- const fetchFilesMetadata = () => easClient.request(GET_FILES_METADATA, {
687
- where: {
688
- attester: {
689
- in: addresses,
690
- },
691
- schema: {
692
- is: {
693
- id: {
694
- equals: '0x55fdefb36fcbbaebeb7d6b41dc3a1a9666e4e42154267c889de064faa7ede517',
695
- },
696
- },
697
- },
698
- },
699
- });
700
- let { filesMetadata } = await queryClient.fetchQuery({
701
- queryKey: filesMetadataQueryKey,
702
- queryFn: fetchFilesMetadata,
703
- staleTime: GET_FILES_METADATA_STALE_MS,
704
- });
705
- if ((!Array.isArray(filesMetadata) || filesMetadata.length === 0) && addresses.length > 0) {
706
- await queryClient.removeQueries({ queryKey: filesMetadataQueryKey });
707
- ({ filesMetadata } = await queryClient.fetchQuery({
708
- queryKey: filesMetadataQueryKey,
709
- queryFn: fetchFilesMetadata,
710
- staleTime: GET_FILES_METADATA_STALE_MS,
711
- }));
712
- }
713
- const filesRoot = BaseFileManager.getWorkingDir();
714
- await BaseFileManager.createDirIfNotExists(filesRoot);
715
- await BaseFileManager.createDirIfNotExists(BaseFileManager.getFilesPath('html'));
716
- await BaseFileManager.createDirIfNotExists(BaseFileManager.getFilesPath('json'));
717
- await BaseFileManager.createDirIfNotExists(BaseFileManager.getFilesPath('images'));
718
- const excludedTransactions = await getExcludedTransactions();
719
- const fromEas = parseTransactionIdsFromMetadata(filesMetadata ?? [], excludedTransactions);
720
- const fromLocal = await collectTransactionIdsFromLocalMetadata();
721
- const transactionIds = Array.from(new Set([...fromEas, ...fromLocal]));
722
- await runBulkDownloadWithDedupe(transactionIds);
723
- };
724
- const downloadTransactionIdWithDedupe = async (transactionId) => {
725
- if (!supportsOpfsFileDownloads() || !transactionId || transactionId.trim().length === 0) {
726
- return false;
727
- }
728
- const normalizedTxId = normalizeArweaveTxId(transactionId) ?? transactionId.trim();
729
- const existing = lazyDownloadInFlightByTransactionId.get(normalizedTxId);
730
- if (existing) {
731
- return existing;
732
- }
733
- const inFlight = (async () => {
734
- try {
735
- const ok = await downloadTransactionIds([normalizedTxId], { resizeAllImages: false });
736
- return ok;
737
- }
738
- finally {
739
- lazyDownloadInFlightByTransactionId.delete(normalizedTxId);
740
- }
741
- })();
742
- lazyDownloadInFlightByTransactionId.set(normalizedTxId, inFlight);
743
- return inFlight;
744
- };
745
- const scheduleBulkFilesDownloadFromEasSyncThrottled = throttle((addressesHint) => {
746
- void downloadAllFilesBinaryRequestHandler(addressesHint).catch((error) => {
747
- logger$4('[scheduleBulkFilesDownloadFromEasSync] failed', error);
748
- });
749
- }, AUTO_BULK_DOWNLOAD_THROTTLE_MS, { leading: true, trailing: false });
750
- const scheduleBulkFilesDownloadFromEasSync = (addressesHint) => {
751
- if (!supportsOpfsFileDownloads()) {
752
- return;
753
- }
754
- scheduleBulkFilesDownloadFromEasSyncThrottled(addressesHint);
755
- };
756
-
757
- var download = /*#__PURE__*/Object.freeze({
758
- __proto__: null,
759
- downloadAllFilesBinaryRequestHandler: downloadAllFilesBinaryRequestHandler,
760
- downloadAllFilesRequestHandler: downloadAllFilesRequestHandler,
761
- downloadTransactionIdWithDedupe: downloadTransactionIdWithDedupe,
762
- scheduleBulkFilesDownloadFromEasSync: scheduleBulkFilesDownloadFromEasSync
763
- });
764
-
765
- const logger$3 = debug('seedSdk:helpers:ensureImageLocal');
766
- /** Arweave transaction ids are 43 chars in the URL-safe base64 alphabet. */
767
- const ARWEAVE_TX_ID_RE = /^[a-z0-9_-]{43}$/i;
768
- const IMAGE_SIZES = [
769
- ImageSize.EXTRA_SMALL,
770
- ImageSize.SMALL,
771
- ImageSize.MEDIUM,
772
- ImageSize.LARGE,
773
- ImageSize.EXTRA_LARGE,
774
- ];
775
- const inFlightByKey = new Map();
776
- const normalizeArweaveTxIdForEnsure = (raw) => {
777
- if (raw == null || raw === '')
778
- return undefined;
779
- const t = String(raw).trim();
780
- if (ARWEAVE_TX_ID_RE.test(t))
781
- return t;
782
- const m = t.match(/^([a-z0-9_-]{43})(?:\.[^/]+)?$/i);
783
- if (m)
784
- return m[1];
785
- const embedded = t.match(/[a-z0-9_-]{43}/gi);
786
- if (embedded) {
787
- for (const candidate of embedded) {
788
- if (ARWEAVE_TX_ID_RE.test(candidate))
789
- return candidate;
790
- }
791
- }
792
- return undefined;
793
- };
794
- const closestImageSize = (width) => {
795
- let best = ImageSize.EXTRA_SMALL;
796
- let bestDist = Math.abs(best - width);
797
- for (const size of IMAGE_SIZES) {
798
- const dist = Math.abs(size - width);
799
- if (dist < bestDist) {
800
- best = size;
801
- bestDist = dist;
802
- }
803
- }
804
- return best;
805
- };
806
- const mapRequestedWidthsToImageSizes = (widths) => {
807
- const requested = widths && widths.length > 0 ? widths : [ImageSize.EXTRA_SMALL];
808
- const unique = new Set();
809
- for (const w of requested) {
810
- if (typeof w !== 'number' || !Number.isFinite(w) || w <= 0)
811
- continue;
812
- unique.add(closestImageSize(w));
813
- }
814
- if (unique.size === 0) {
815
- unique.add(ImageSize.EXTRA_SMALL);
816
- }
817
- return Array.from(unique).sort((a, b) => a - b);
818
- };
819
- const getBasename = (filePath) => {
820
- const path = BaseFileManager.getPathModule();
821
- return path.basename(filePath);
822
- };
823
- const getBasenameWithoutExtension = (fileName) => {
824
- const match = fileName.match(/^(.*[\/\\])?([^\/\\]+?)(\.[^.\/\\]*)?$/);
825
- return match?.[2] ?? fileName;
826
- };
827
- const resolveMatchingImagePath = async (needle) => {
828
- const dirPath = BaseFileManager.getFilesPath('images');
829
- const dirExists = await BaseFileManager.pathExists(dirPath);
830
- if (!dirExists)
831
- return undefined;
832
- const fs = await BaseFileManager.getFs();
833
- const path = BaseFileManager.getPathModule();
834
- const files = await fs.promises.readdir(dirPath);
835
- // Prefer exact basename match (files only); skip size dirs.
836
- const exact = files.find((file) => path.basename(file) === needle);
837
- if (exact) {
838
- const candidate = BaseFileManager.getFilesPath('images', exact);
839
- try {
840
- const zenfs = await BaseFileManager.getFs();
841
- const stat = await zenfs.promises.stat(candidate);
842
- if (stat.isFile())
843
- return candidate;
844
- }
845
- catch {
846
- // fall through
847
- }
848
- }
849
- const matchingFiles = files.filter((file) => {
850
- const base = path.basename(file);
851
- return base.includes(needle);
852
- });
853
- for (const file of matchingFiles) {
854
- const candidate = BaseFileManager.getFilesPath('images', file);
855
- try {
856
- const zenfs = await BaseFileManager.getFs();
857
- const stat = await zenfs.promises.stat(candidate);
858
- if (stat.isFile())
859
- return candidate;
860
- }
861
- catch {
862
- continue;
863
- }
864
- }
865
- return undefined;
866
- };
867
- const sizedVariantPath = (originalFilePath, size) => {
868
- const path = BaseFileManager.getPathModule();
869
- const dir = path.dirname(originalFilePath);
870
- const base = getBasenameWithoutExtension(getBasename(originalFilePath));
871
- return path.join(dir, String(size), `${base}.webp`);
872
- };
873
- const ensureKey = (txId, fileName, sizes) => {
874
- const idPart = txId ?? fileName ?? '';
875
- return `${idPart}|${sizes.join(',')}`;
876
- };
877
- const runEnsureImageLocal = async (params) => {
878
- if (!supportsOpfsFileDownloads()) {
879
- return { status: 'unsupported' };
880
- }
881
- const fileName = params.fileName?.trim() || undefined;
882
- const txId = normalizeArweaveTxIdForEnsure(params.transactionId) ??
883
- normalizeArweaveTxIdForEnsure(fileName);
884
- if (!txId && !fileName) {
885
- return { status: 'missing-id' };
886
- }
887
- const targetSizes = mapRequestedWidthsToImageSizes(params.widths);
888
- const needles = [fileName, txId].filter((n) => typeof n === 'string' && n.length > 0);
889
- try {
890
- let filePath;
891
- for (const needle of needles) {
892
- filePath = await resolveMatchingImagePath(needle);
893
- if (filePath)
894
- break;
895
- }
896
- if (!filePath && txId) {
897
- await downloadTransactionIdWithDedupe(txId);
898
- for (const needle of needles) {
899
- filePath = await resolveMatchingImagePath(needle);
900
- if (filePath)
901
- break;
902
- }
903
- // Downloads store as bare tx id
904
- if (!filePath) {
905
- const direct = BaseFileManager.getFilesPath('images', txId);
906
- if (await BaseFileManager.pathExists(direct)) {
907
- filePath = direct;
908
- }
909
- }
910
- }
911
- if (!filePath) {
912
- return { status: 'failed' };
913
- }
914
- const createdWidths = [];
915
- for (const size of targetSizes) {
916
- const variantPath = sizedVariantPath(filePath, size);
917
- const exists = await BaseFileManager.pathExists(variantPath);
918
- if (exists)
919
- continue;
920
- await BaseFileManager.resizeImage({
921
- filePath,
922
- width: size,
923
- height: size,
924
- });
925
- createdWidths.push(size);
926
- }
927
- return {
928
- status: 'ready',
929
- filePath,
930
- createdWidths,
931
- };
932
- }
933
- catch (error) {
934
- logger$3('ensureImageLocal failed', error);
935
- return { status: 'failed' };
936
- }
937
- };
938
- /**
939
- * Ensure an image original exists in OPFS (downloading from Arweave if needed)
940
- * and create only the requested ImageSize variant(s) for that one file.
941
- */
942
- const ensureImageLocal = async (params) => {
943
- if (!supportsOpfsFileDownloads()) {
944
- return { status: 'unsupported' };
945
- }
946
- const fileName = params.fileName?.trim() || undefined;
947
- const txId = normalizeArweaveTxIdForEnsure(params.transactionId) ??
948
- normalizeArweaveTxIdForEnsure(fileName);
949
- if (!txId && !fileName) {
950
- return { status: 'missing-id' };
951
- }
952
- const targetSizes = mapRequestedWidthsToImageSizes(params.widths);
953
- const key = ensureKey(txId, fileName, targetSizes);
954
- const existing = inFlightByKey.get(key);
955
- if (existing) {
956
- return existing;
957
- }
958
- const inFlight = (async () => {
959
- try {
960
- return await runEnsureImageLocal({
961
- transactionId: txId,
962
- fileName,
963
- widths: targetSizes,
964
- });
965
- }
966
- finally {
967
- inFlightByKey.delete(key);
968
- }
969
- })();
970
- inFlightByKey.set(key, inFlight);
971
- return inFlight;
972
- };
973
-
974
- const randomId = customAlphabet(alphanumeric, 10);
975
- /**
976
- * A 10-character local id. Never starts with "0x" (about 1 in 3,844 random ids would), so code that
977
- * tells local ids from EAS uids by that prefix can't mistake one for the other.
978
- */
979
- const generateId = () => {
980
- let id = randomId();
981
- while (id.startsWith('0x'))
982
- id = randomId();
983
- return id;
984
- };
985
-
986
- var generateId$1 = /*#__PURE__*/Object.freeze({
987
- __proto__: null,
988
- generateId: generateId
989
- });
990
-
991
- const logger$2 = debug('seedSdk:shared:helpers');
992
- const toSnakeCase = (str) => {
993
- return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
994
- };
995
- const getMimeType = (base64) => {
996
- if (!base64) {
997
- return null;
998
- }
999
- const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/);
1000
- if (result && result.length > 1) {
1001
- return result[1];
1002
- }
1003
- else {
1004
- return null; // MIME type could not be determined
1005
- }
1006
- };
1007
- const getCorrectId = (localIdOrUid) => {
1008
- const id = {
1009
- localId: undefined,
1010
- uid: undefined,
1011
- };
1012
- if (!localIdOrUid) {
1013
- return id;
1014
- }
1015
- if (localIdOrUid.length === 10) {
1016
- id.localId = localIdOrUid;
1017
- }
1018
- if (localIdOrUid.startsWith('0x') && localIdOrUid.length === 66) {
1019
- id.uid = localIdOrUid;
1020
- }
1021
- return id;
1022
- };
1023
- const getDataTypeFromString = (data) => {
1024
- const nonImageBase64Regex = /^(?!data:image\/(?:jpeg|png|gif|bmp|webp);base64,)[A-Za-z0-9+/=]+$/;
1025
- if (nonImageBase64Regex.test(data)) {
1026
- return 'base64';
1027
- }
1028
- // Regular expression for base64 (simple version, checking for base64 format)
1029
- const imageBase64Regex = /^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/;
1030
- if (imageBase64Regex.test(data)) {
1031
- return 'imageBase64';
1032
- }
1033
- // Blob URLs are fetchable but session-scoped; recognize them as url type
1034
- if (data.startsWith('blob:')) {
1035
- return 'url';
1036
- }
1037
- // Regular expression for URL (simple version, checking for common URL format)
1038
- const urlRegex = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/;
1039
- if (urlRegex.test(data)) {
1040
- return 'url';
1041
- }
1042
- return null;
1043
- };
1044
- const convertTxIdToImage = async (txId) => {
1045
- const imageFilePath = BaseFileManager.getFilesPath('images', txId);
1046
- const fileExists = await BaseFileManager.pathExists(imageFilePath);
1047
- if (!fileExists) {
1048
- logger$2(`[ItemView] [updateImage] ${imageFilePath} does not exist`);
1049
- return;
1050
- }
1051
- const buffer = await BaseFileManager.readFileAsBuffer(imageFilePath);
1052
- // Convert Blob to ArrayBuffer if needed, or use Buffer directly
1053
- let arrayBuffer;
1054
- if (buffer instanceof Blob) {
1055
- arrayBuffer = await buffer.arrayBuffer();
1056
- }
1057
- else if (buffer instanceof ArrayBuffer) {
1058
- arrayBuffer = buffer;
1059
- }
1060
- else {
1061
- // Node.js Buffer
1062
- const sliced = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
1063
- // Handle SharedArrayBuffer case by creating a new ArrayBuffer
1064
- if (sliced instanceof SharedArrayBuffer) {
1065
- const uint8Array = new Uint8Array(sliced);
1066
- arrayBuffer = uint8Array.buffer.slice(0);
1067
- }
1068
- else {
1069
- arrayBuffer = sliced;
1070
- }
1071
- }
1072
- const uint = new Uint8Array(arrayBuffer);
1073
- const imageBlob = new Blob([uint]);
1074
- return URL.createObjectURL(imageBlob);
1075
- };
1076
- /**
1077
- * Constructs an Arweave URL for a storage transaction ID
1078
- * @param storageTransactionId - The Arweave transaction ID
1079
- * @returns The full URL to access the transaction data on Arweave (e.g., https://arweave.net/raw/{transactionId})
1080
- * @deprecated Use BaseArweaveClient.getRawUrl() instead for better consistency and testability
1081
- */
1082
- const getArweaveUrlForTransaction = (storageTransactionId) => {
1083
- return BaseArweaveClient.getRawUrl(storageTransactionId);
1084
- };
1085
-
1086
- /** Emitted by the client manager after `app_state.addresses` is written (post-`setAddresses`). */
1087
- const ADDRESSES_PERSISTED_EVENT = 'addresses.persisted';
1088
- /** Emitted after hard-deleting local on-chain seed copies for publisher addresses. */
1089
- const LOCAL_COPIES_REMOVED_EVENT = 'localCopies.removed';
1090
- function parseAddressesPersistedPayload(value) {
1091
- if (!value || typeof value !== 'object') {
1092
- return { owned: [], watched: [] };
1093
- }
1094
- const v = value;
1095
- const owned = Array.isArray(v.owned)
1096
- ? v.owned.filter((a) => typeof a === 'string')
1097
- : [];
1098
- const watched = Array.isArray(v.watched)
1099
- ? v.watched.filter((a) => typeof a === 'string')
1100
- : [];
1101
- return { owned, watched };
1102
- }
1103
-
1104
- /**
1105
- * Cross-tab exclusive sections, using the Web Locks API. All tabs of an origin share one SQLite
1106
- * database and OPFS tree; the browser releases a tab's locks when it closes or crashes, so a lock
1107
- * can't go stale. See docs/MULTI_TAB.md.
1108
- *
1109
- * Node has Web Locks from 24.5, scoped to the process. Where they're missing (older Node, old
1110
- * browsers), sections still run one at a time within this JS realm (see `withProcessLock`), which
1111
- * covers a single Node process but not other tabs or worker threads.
1112
- * Not re-entrant: requesting a name the caller already holds waits forever, so take each lock
1113
- * only at the outermost call site.
1114
- */
1115
- /** Long enough for a slow init in another tab; short enough that a hung tab doesn't block forever. */
1116
- const TAB_LOCK_WAIT_TIMEOUT_MS = 60000;
1117
- function seedDbLockName(scope, filesDir) {
1118
- return `seed:${scope}:${filesDir}/db/seed.db`;
1119
- }
1120
- /** `withTabLock` on the database under `filesDir`; runs `fn` directly when there's no `filesDir` yet. */
1121
- function withSeedDbLock(scope, filesDir, fn) {
1122
- return filesDir ? withTabLock(seedDbLockName(scope, filesDir), fn) : fn();
1123
- }
1124
- class TabLockTimeoutError extends Error {
1125
- constructor(lockName, timeoutMs) {
1126
- super(`Timed out after ${timeoutMs}ms waiting for another tab to release "${lockName}".`);
1127
- this.lockName = lockName;
1128
- this.code = 'TAB_LOCK_TIMEOUT';
1129
- this.name = 'TabLockTimeoutError';
1130
- }
1131
- }
1132
- async function withTabLock(name, fn, { timeoutMs = TAB_LOCK_WAIT_TIMEOUT_MS } = {}) {
1133
- const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined;
1134
- if (!locks)
1135
- return withProcessLock(name, fn, { timeoutMs });
1136
- try {
1137
- // The timeout bounds the wait only; once granted, fn runs to completion. Infinity waits for as
1138
- // long as the holder runs (it can't outlive its tab).
1139
- const signal = Number.isFinite(timeoutMs) ? AbortSignal.timeout(timeoutMs) : undefined;
1140
- return await locks.request(name, { mode: 'exclusive', signal }, fn);
1141
- }
1142
- catch (error) {
1143
- if (error?.name === 'TimeoutError') {
1144
- throw new TabLockTimeoutError(name, timeoutMs);
1145
- }
1146
- throw error;
1147
- }
1148
- }
1149
- /** Tail of each name's queue: resolves once every section queued so far has finished or given up. */
1150
- const processLockTails = new Map();
1151
- /**
1152
- * The `withTabLock` fallback without Web Locks: an exclusive, first-come-first-served lock per name
1153
- * within this JS realm. Like Web Locks, `timeoutMs` bounds the wait only, and a waiter that times
1154
- * out doesn't let later waiters in before the current holder finishes.
1155
- */
1156
- async function withProcessLock(name, fn, { timeoutMs = TAB_LOCK_WAIT_TIMEOUT_MS } = {}) {
1157
- const previous = processLockTails.get(name) ?? Promise.resolve();
1158
- let release;
1159
- const done = new Promise((resolve) => (release = resolve));
1160
- const tail = previous.then(() => done);
1161
- processLockTails.set(name, tail);
1162
- void tail.then(() => {
1163
- if (processLockTails.get(name) === tail)
1164
- processLockTails.delete(name);
1165
- });
1166
- try {
1167
- await waitForTurn(previous, name, timeoutMs);
1168
- }
1169
- catch (error) {
1170
- release();
1171
- throw error;
1172
- }
1173
- try {
1174
- return await fn();
1175
- }
1176
- finally {
1177
- release();
1178
- }
1179
- }
1180
- function waitForTurn(previous, name, timeoutMs) {
1181
- if (!Number.isFinite(timeoutMs))
1182
- return previous;
1183
- let timer;
1184
- const timedOut = new Promise((_, reject) => {
1185
- timer = setTimeout(() => reject(new TabLockTimeoutError(name, timeoutMs)), timeoutMs);
1186
- });
1187
- return Promise.race([previous, timedOut]).finally(() => clearTimeout(timer));
1188
- }
1189
-
1190
- const logger$1 = debug('seedSdk:helpers:tabCoordinator');
1191
- let state;
1192
- let leader = false;
1193
- let leaderWaiters = [];
1194
- const messageHandlers = new Set();
1195
- /** Starts once per page; later calls (re-init) keep the first database. */
1196
- function startTabCoordination({ filesDir, mode = 'coordinate' }) {
1197
- if (state)
1198
- return;
1199
- const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined;
1200
- const dbKey = `${filesDir}/db/seed.db`;
1201
- const coordinating = mode === 'coordinate' && isBrowser() && !!locks && typeof BroadcastChannel !== 'undefined';
1202
- state = { dbKey, coordinating };
1203
- if (!coordinating) {
1204
- becomeLeader();
1205
- return;
1206
- }
1207
- const channel = new BroadcastChannel(`seed:tabs:${dbKey}`);
1208
- channel.onmessage = (event) => {
1209
- for (const handler of messageHandlers)
1210
- handler(event.data);
1211
- };
1212
- state.channel = channel;
1213
- const current = state;
1214
- void locks.request(`seed:leader:${dbKey}`, () => {
1215
- // Reset (tests) before the grant: hand the lock straight back.
1216
- if (state !== current)
1217
- return undefined;
1218
- becomeLeader();
1219
- // Held until the tab closes (or a test resets coordination).
1220
- return new Promise((release) => {
1221
- current.releaseLeadership = release;
1222
- });
1223
- });
1224
- }
1225
- function becomeLeader() {
1226
- if (leader)
1227
- return;
1228
- leader = true;
1229
- logger$1(`this tab leads ${state?.dbKey}`);
1230
- const waiters = leaderWaiters;
1231
- leaderWaiters = [];
1232
- for (const resolve of waiters)
1233
- resolve();
1234
- }
1235
- function isLeaderTab() {
1236
- return !state || leader;
1237
- }
1238
- /** Resolves when this tab leads (at once if it already does). */
1239
- function whenLeaderTab() {
1240
- if (isLeaderTab())
1241
- return Promise.resolve();
1242
- return new Promise((resolve) => leaderWaiters.push(resolve));
1243
- }
1244
- /** Sends to the other tabs of this database; a no-op when not coordinating. */
1245
- function postTabMessage(message) {
1246
- state?.channel?.postMessage(message);
1247
- }
1248
- function onTabMessage(handler) {
1249
- messageHandlers.add(handler);
1250
- return () => messageHandlers.delete(handler);
1251
- }
1252
- /** `withTabLock` named for this database (`seed:<scope>:<db>`); runs `fn` directly before init. */
1253
- function withDbTabLock(scope, fn, options) {
1254
- return state ? withTabLock(`seed:${scope}:${state.dbKey}`, fn, options) : fn();
1255
- }
1256
-
1257
- const logger = debug('seedSdk:helpers:tabEvents');
1258
- /**
1259
- * Keeps other tabs current (docs/MULTI_TAB.md). The event bus is per tab, so events that mean "the
1260
- * shared database or OPFS changed" are also posted to the other tabs, which refresh their caches
1261
- * and emit the same event locally. Events are posted only where they originate, so a relayed event
1262
- * is never relayed again.
1263
- */
1264
- /** Emitted with the changed paths when files change outside this tab's file-system cache. */
1265
- const FILES_CHANGED_EVENT = 'fs.files.changed';
1266
- /** Emits on this tab's event bus and in every other tab of this database. */
1267
- function emitAcrossTabs(name, payload) {
1268
- if (payload === undefined) {
1269
- eventEmitter.emit(name);
1270
- }
1271
- else {
1272
- eventEmitter.emit(name, payload);
1273
- }
1274
- postTabMessage({ type: 'event', name, payload });
1275
- }
1276
- /**
1277
- * A file saved through this tab's file system: emits `file-saved` here (as before) and tells other
1278
- * tabs, whose caches don't see it.
1279
- */
1280
- function notifyFileSaved(filePath) {
1281
- eventEmitter.emit('file-saved', filePath);
1282
- postTabMessage({ type: 'files-changed', paths: [filePath] });
1283
- }
1284
- /**
1285
- * Files written straight to OPFS by a worker: refreshes this tab's file-system cache, emits
1286
- * FILES_CHANGED_EVENT, and tells other tabs to do the same.
1287
- */
1288
- async function notifyFilesWrittenOutsideCache(paths) {
1289
- if (paths.length === 0)
1290
- return;
1291
- await BaseFileManager.invalidateCachedPaths(paths);
1292
- eventEmitter.emit(FILES_CHANGED_EVENT, paths);
1293
- postTabMessage({ type: 'files-changed', paths });
1294
- }
1295
- /** Refreshes this tab's in-memory state for an event another tab emitted, before re-emitting it. */
1296
- async function catchUpOn(name, payload) {
1297
- if (name === EAS_SEED_DATA_SYNCED_TO_DB_EVENT) {
1298
- const _mod_1 = await import('./Item-D4FigtYS.js');
1299
- const _ns_1 = _mod_1.Y;
1300
- const { Item } = _ns_1;
1301
- await Item.rehydrateCachedItemsFromDbAfterEasSync();
1302
- }
1303
- else if (name === LOCAL_COPIES_REMOVED_EVENT) {
1304
- const { removedSeedLocalIds = [], removedSeedUids = [] } = (payload ?? {});
1305
- const _mod_2 = await import('./Item-D4FigtYS.js');
1306
- const _ns_2 = _mod_2.Y;
1307
- const { Item } = _ns_2;
1308
- Item.dropCachedInstancesForSeedIds([...removedSeedLocalIds, ...removedSeedUids]);
1309
- }
1310
- }
1311
- const RELAYED_EVENTS = new Set([
1312
- EAS_SEED_DATA_SYNCED_TO_DB_EVENT,
1313
- ADDRESSES_PERSISTED_EVENT,
1314
- LOCAL_COPIES_REMOVED_EVENT,
1315
- ]);
1316
- let listening = false;
1317
- /** Applies other tabs' events and file changes in this tab. */
1318
- function listenForOtherTabsEvents() {
1319
- if (listening)
1320
- return;
1321
- listening = true;
1322
- onTabMessage((message) => {
1323
- if (message.type === 'event' && RELAYED_EVENTS.has(message.name)) {
1324
- void catchUpOn(message.name, message.payload)
1325
- .catch((error) => logger(`catching up on ${message.name} failed`, error))
1326
- .then(() => {
1327
- if (message.payload === undefined) {
1328
- eventEmitter.emit(message.name);
1329
- }
1330
- else {
1331
- eventEmitter.emit(message.name, message.payload);
1332
- }
1333
- });
1334
- }
1335
- else if (message.type === 'files-changed') {
1336
- void BaseFileManager.invalidateCachedPaths(message.paths)
1337
- .catch((error) => logger('refreshing changed files failed', error))
1338
- .then(() => eventEmitter.emit(FILES_CHANGED_EVENT, message.paths));
1339
- }
1340
- });
1341
- }
1342
-
1343
- export { ADDRESSES_PERSISTED_EVENT as A, isNode as B, isBrowser as C, startTabCoordination as D, downloadAllFilesRequestHandler as E, FILES_CHANGED_EVENT as F, downloadAllFilesBinaryRequestHandler as G, getStorageTransactionIdForSeedUid as H, convertTxIdToImage as I, downloadTransactionIdWithDedupe as J, getDataTypeFromString as K, LOCAL_COPIES_REMOVED_EVENT as L, getMimeType as M, notifyFileSaved as N, download as O, generateId$1 as P, TabLockTimeoutError as T, isStorageSeedRef as a, generateId as b, getArweaveUrlForTransaction as c, classifyMediaRef as d, emitAcrossTabs as e, closestImageSize as f, getCorrectId as g, ensureImageLocal as h, isPublishedSeedRef as i, getFeedItemStringField as j, isLeaderTab as k, normalizeArweaveTxIdForEnsure as l, normalizeFeedItemFields as m, normalizeRelationPropertyValue as n, resolveMediaRef as o, parseAddressesPersistedPayload as p, withDbTabLock as q, resolveSeedIdsFromRefString as r, scheduleBulkFilesDownloadFromEasSync as s, toSnakeCase as t, notifyFilesWrittenOutsideCache as u, withSeedDbLock as v, whenLeaderTab as w, postTabMessage as x, onTabMessage as y, listenForOtherTabsEvents as z };
1344
- //# sourceMappingURL=tabEvents-BZJMY5uK.js.map