@seedprotocol/sdk 0.4.31 → 0.5.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 (323) hide show
  1. package/dist/BasePathResolver-BDgc7c4T.js +485 -0
  2. package/dist/BasePathResolver-BDgc7c4T.js.map +1 -0
  3. package/dist/{ModelProperty-e_hXSFvf.js → ModelProperty-D-ysg8zA.js} +37 -43
  4. package/dist/ModelProperty-D-ysg8zA.js.map +1 -0
  5. package/dist/{Schema-DonRkUOJ.js → Schema-CyCftnKI.js} +40 -40
  6. package/dist/{Schema-DonRkUOJ.js.map → Schema-CyCftnKI.js.map} +1 -1
  7. package/dist/{SchemaValidationService-DcmfhQae.js → SchemaValidationService-POM6jHbJ.js} +9 -5
  8. package/dist/{SchemaValidationService-DcmfhQae.js.map → SchemaValidationService-POM6jHbJ.js.map} +1 -1
  9. package/dist/{backfillMetadataPropertyIds-CKTfvFgQ.js → backfillMetadataPropertyIds-DzZw57iJ.js} +3 -11
  10. package/dist/{backfillMetadataPropertyIds-CKTfvFgQ.js.map → backfillMetadataPropertyIds-DzZw57iJ.js.map} +1 -1
  11. package/dist/cjs/{ModelProperty-BQYU5hPQ.js → ModelProperty-CmuGJvyi.js} +25 -26
  12. package/dist/cjs/{ModelProperty-BQYU5hPQ.js.map → ModelProperty-CmuGJvyi.js.map} +1 -1
  13. package/dist/cjs/{Schema-BcRHcQ0W.js → Schema-gpFnZMhB.js} +28 -29
  14. package/dist/cjs/{Schema-BcRHcQ0W.js.map → Schema-gpFnZMhB.js.map} +1 -1
  15. package/dist/cjs/{SchemaValidationService-CQNDgyZl.js → SchemaValidationService-E3xTSRai.js} +9 -10
  16. package/dist/cjs/{SchemaValidationService-CQNDgyZl.js.map → SchemaValidationService-E3xTSRai.js.map} +1 -1
  17. package/dist/cjs/{backfillMetadataPropertyIds-Dn4oVmEv.js → backfillMetadataPropertyIds-_bivrvRs.js} +11 -12
  18. package/dist/cjs/{backfillMetadataPropertyIds-Dn4oVmEv.js.map → backfillMetadataPropertyIds-_bivrvRs.js.map} +1 -1
  19. package/dist/cjs/eas-BwDKJmlb.js +112 -0
  20. package/dist/cjs/eas-BwDKJmlb.js.map +1 -0
  21. package/dist/cjs/{getItem-DpnPrzl3.js → getItem-MShQw3sz.js} +11 -12
  22. package/dist/cjs/{getItem-DpnPrzl3.js.map → getItem-MShQw3sz.js.map} +1 -1
  23. package/dist/cjs/{getPublishPayload-CGKMEL3H.js → getPublishPayload-C1nOOXp_.js} +93 -83
  24. package/dist/cjs/getPublishPayload-C1nOOXp_.js.map +1 -0
  25. package/dist/cjs/{getPublishUploads-DeI0f2UN.js → getPublishUploads-BjgxgrKD.js} +17 -18
  26. package/dist/cjs/{getPublishUploads-DeI0f2UN.js.map → getPublishUploads-BjgxgrKD.js.map} +1 -1
  27. package/dist/cjs/{getSegmentedItemProperties-BgS_FhAx.js → getSegmentedItemProperties-Cuw7wcxb.js} +64 -15
  28. package/dist/cjs/getSegmentedItemProperties-Cuw7wcxb.js.map +1 -0
  29. package/dist/cjs/{index-BnAqr2le.js → index-9Z2FOvLD.js} +12 -13
  30. package/dist/cjs/index-9Z2FOvLD.js.map +1 -0
  31. package/dist/cjs/{index-ByozbTn_.js → index-vk2DeF2D.js} +1237 -3235
  32. package/dist/cjs/index-vk2DeF2D.js.map +1 -0
  33. package/dist/cjs/index.browser-BSf8HpnU.js +22 -0
  34. package/dist/cjs/index.browser-BSf8HpnU.js.map +1 -0
  35. package/dist/cjs/{ownership-CsWuaNfH.js → ownership-DhWda0J9.js} +11 -25
  36. package/dist/cjs/{ownership-CsWuaNfH.js.map → ownership-DhWda0J9.js.map} +1 -1
  37. package/dist/cjs/{property-CeR45LMx.js → property-D3Ww2_Qh.js} +13 -14
  38. package/dist/cjs/{property-CeR45LMx.js.map → property-D3Ww2_Qh.js.map} +1 -1
  39. package/dist/cjs/{syncDbWithEas-CA2Lum5V.js → syncDbWithEas-Dht3_7UD.js} +26 -39
  40. package/dist/cjs/syncDbWithEas-Dht3_7UD.js.map +1 -0
  41. package/dist/configurePlatform-R5neRbQ9.js +27 -0
  42. package/dist/configurePlatform-R5neRbQ9.js.map +1 -0
  43. package/dist/constants-B5S5JPDK.js +660 -0
  44. package/dist/constants-B5S5JPDK.js.map +1 -0
  45. package/dist/constants-DMHTYMgJ.js +120 -0
  46. package/dist/constants-DMHTYMgJ.js.map +1 -0
  47. package/dist/db-Cvh84NY7.js +1972 -0
  48. package/dist/db-Cvh84NY7.js.map +1 -0
  49. package/dist/eas-D9b7z2Wn.js +68 -0
  50. package/dist/eas-D9b7z2Wn.js.map +1 -0
  51. package/dist/{getItem-GOXWo_Iy.js → getItem-B81V3m4S.js} +10 -6
  52. package/dist/{getItem-GOXWo_Iy.js.map → getItem-B81V3m4S.js.map} +1 -1
  53. package/dist/{getPublishPayload-D16enahU.js → getPublishPayload-CNYsn8-6.js} +87 -74
  54. package/dist/getPublishPayload-CNYsn8-6.js.map +1 -0
  55. package/dist/{getPublishUploads-wGqH19UY.js → getPublishUploads-D9rPHkB7.js} +14 -10
  56. package/dist/{getPublishUploads-wGqH19UY.js.map → getPublishUploads-D9rPHkB7.js.map} +1 -1
  57. package/dist/{getSegmentedItemProperties-Be3kYWY3.js → getSegmentedItemProperties-Bg3_b-b1.js} +18 -15
  58. package/dist/getSegmentedItemProperties-Bg3_b-b1.js.map +1 -0
  59. package/dist/{index-BcXKZQpX.js → index--F3Wolt5.js} +1171 -5452
  60. package/dist/index--F3Wolt5.js.map +1 -0
  61. package/dist/{index-BFyMxc7e.js → index-QMrBK-L3.js} +2 -2
  62. package/dist/index-QMrBK-L3.js.map +1 -0
  63. package/dist/index-oi4roUVf.js +22 -0
  64. package/dist/index-oi4roUVf.js.map +1 -0
  65. package/dist/index.node-Bow8kHew.js +503 -0
  66. package/dist/index.node-Bow8kHew.js.map +1 -0
  67. package/dist/main.cjs +16 -15
  68. package/dist/main.cjs.map +1 -1
  69. package/dist/main.js +31 -22
  70. package/dist/main.js.map +1 -1
  71. package/dist/node.js +37 -363
  72. package/dist/node.js.map +1 -1
  73. package/dist/{ownership-C17YhE7J.js → ownership-BF_ZUKIp.js} +13 -9
  74. package/dist/{ownership-C17YhE7J.js.map → ownership-BF_ZUKIp.js.map} +1 -1
  75. package/dist/platform.browser.js +3499 -0
  76. package/dist/platform.browser.js.map +1 -0
  77. package/dist/platform.node.js +19 -0
  78. package/dist/platform.node.js.map +1 -0
  79. package/dist/{property-CRAau-Q-.js → property-BdyDfcSc.js} +14 -11
  80. package/dist/property-BdyDfcSc.js.map +1 -0
  81. package/dist/src/Item/Item.d.ts.map +1 -1
  82. package/dist/src/Item/service/actors/fetchDataFromEas.d.ts.map +1 -1
  83. package/dist/src/Model/service/actors/createModelProperties.d.ts.map +1 -1
  84. package/dist/src/Model/service/modelMachine.d.ts +1 -1
  85. package/dist/src/browser/db/Db.d.ts +17 -18
  86. package/dist/src/browser/db/Db.d.ts.map +1 -1
  87. package/dist/src/browser/helpers/ArweaveClient.d.ts +10 -27
  88. package/dist/src/browser/helpers/ArweaveClient.d.ts.map +1 -1
  89. package/dist/src/browser/helpers/EasClient.d.ts +6 -4
  90. package/dist/src/browser/helpers/EasClient.d.ts.map +1 -1
  91. package/dist/src/browser/helpers/FileManager.d.ts +27 -26
  92. package/dist/src/browser/helpers/FileManager.d.ts.map +1 -1
  93. package/dist/src/browser/helpers/PathResolver.d.ts +6 -5
  94. package/dist/src/browser/helpers/PathResolver.d.ts.map +1 -1
  95. package/dist/src/browser/helpers/QueryClient.d.ts +6 -5
  96. package/dist/src/browser/helpers/QueryClient.d.ts.map +1 -1
  97. package/dist/src/browser/workers/filesDownload.d.ts.map +1 -1
  98. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  99. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  100. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  101. package/dist/src/db/Db/BaseDb.d.ts +6 -26
  102. package/dist/src/db/Db/BaseDb.d.ts.map +1 -1
  103. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  104. package/dist/src/db/write/createMetadata.d.ts.map +1 -1
  105. package/dist/src/db/write/updateMetadata.d.ts.map +1 -1
  106. package/dist/src/eas.d.ts +4 -37
  107. package/dist/src/eas.d.ts.map +1 -1
  108. package/dist/src/helpers/ArweaveClient/BaseArweaveClient.d.ts +1 -101
  109. package/dist/src/helpers/ArweaveClient/BaseArweaveClient.d.ts.map +1 -1
  110. package/dist/src/helpers/ArweaveClient/arweaveL1UploadApi.d.ts +1 -51
  111. package/dist/src/helpers/ArweaveClient/arweaveL1UploadApi.d.ts.map +1 -1
  112. package/dist/src/helpers/ArweaveClient/index.d.ts +2 -2
  113. package/dist/src/helpers/ArweaveClient/index.d.ts.map +1 -1
  114. package/dist/src/helpers/ArweaveClient/selectReadGateway.d.ts +1 -15
  115. package/dist/src/helpers/ArweaveClient/selectReadGateway.d.ts.map +1 -1
  116. package/dist/src/helpers/ArweaveClient/uploadApiVerification.d.ts +1 -22
  117. package/dist/src/helpers/ArweaveClient/uploadApiVerification.d.ts.map +1 -1
  118. package/dist/src/helpers/EasClient/BaseEasClient.d.ts +1 -9
  119. package/dist/src/helpers/EasClient/BaseEasClient.d.ts.map +1 -1
  120. package/dist/src/helpers/FileManager/BaseFileManager.d.ts +4 -2
  121. package/dist/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  122. package/dist/src/helpers/FileManager/IFileManager.d.ts +44 -0
  123. package/dist/src/helpers/FileManager/IFileManager.d.ts.map +1 -0
  124. package/dist/src/helpers/PathResolver/BasePathResolver.d.ts +16 -12
  125. package/dist/src/helpers/PathResolver/BasePathResolver.d.ts.map +1 -1
  126. package/dist/src/helpers/PathResolver/IPathResolver.d.ts +16 -0
  127. package/dist/src/helpers/PathResolver/IPathResolver.d.ts.map +1 -0
  128. package/dist/src/helpers/QueryClient/BaseQueryClient.d.ts +1 -6
  129. package/dist/src/helpers/QueryClient/BaseQueryClient.d.ts.map +1 -1
  130. package/dist/src/helpers/constants.d.ts +4 -22
  131. package/dist/src/helpers/constants.d.ts.map +1 -1
  132. package/dist/src/helpers/db.d.ts.map +1 -1
  133. package/dist/src/helpers/easPropertyCanonical.d.ts +1 -14
  134. package/dist/src/helpers/easPropertyCanonical.d.ts.map +1 -1
  135. package/dist/src/helpers/easRevokedFilter.d.ts +1 -9
  136. package/dist/src/helpers/easRevokedFilter.d.ts.map +1 -1
  137. package/dist/src/helpers/easUid.d.ts +1 -12
  138. package/dist/src/helpers/easUid.d.ts.map +1 -1
  139. package/dist/src/helpers/ethereumUtils.d.ts +5 -0
  140. package/dist/src/helpers/ethereumUtils.d.ts.map +1 -0
  141. package/dist/src/helpers/file/fetchAll/index.d.ts +1 -1
  142. package/dist/src/helpers/file/fetchAll/index.d.ts.map +1 -1
  143. package/dist/src/helpers/gateway/gatewayState.d.ts +2 -0
  144. package/dist/src/helpers/gateway/gatewayState.d.ts.map +1 -0
  145. package/dist/src/helpers/gateway/resolveSeedGatewayEndpoints.d.ts +2 -0
  146. package/dist/src/helpers/gateway/resolveSeedGatewayEndpoints.d.ts.map +1 -0
  147. package/dist/src/helpers/gateway/seedGatewayConfig.d.ts +2 -0
  148. package/dist/src/helpers/gateway/seedGatewayConfig.d.ts.map +1 -0
  149. package/dist/src/helpers/generateId.d.ts +2 -0
  150. package/dist/src/helpers/generateId.d.ts.map +1 -0
  151. package/dist/src/helpers/getSchemaForItemProperty.d.ts +1 -1
  152. package/dist/src/helpers/getSchemaForItemProperty.d.ts.map +1 -1
  153. package/dist/src/helpers/getSegmentedItemProperties.d.ts.map +1 -1
  154. package/dist/src/helpers/index.d.ts +15 -10
  155. package/dist/src/helpers/index.d.ts.map +1 -1
  156. package/dist/src/helpers/isSqliteUniqueConstraintError.d.ts +7 -0
  157. package/dist/src/helpers/isSqliteUniqueConstraintError.d.ts.map +1 -0
  158. package/dist/src/helpers/mediaRef.d.ts.map +1 -1
  159. package/dist/src/helpers/property/index.d.ts.map +1 -1
  160. package/dist/src/index.d.ts +9 -7
  161. package/dist/src/index.d.ts.map +1 -1
  162. package/dist/src/interfaces/IDb.d.ts +11 -0
  163. package/dist/src/interfaces/IDb.d.ts.map +1 -1
  164. package/dist/src/node/db/Db.d.ts +22 -37
  165. package/dist/src/node/db/Db.d.ts.map +1 -1
  166. package/dist/src/node/helpers/ArweaveClient.d.ts +4 -30
  167. package/dist/src/node/helpers/ArweaveClient.d.ts.map +1 -1
  168. package/dist/src/node/helpers/EasClient.d.ts +4 -6
  169. package/dist/src/node/helpers/EasClient.d.ts.map +1 -1
  170. package/dist/src/node/helpers/FileManager.d.ts +26 -25
  171. package/dist/src/node/helpers/FileManager.d.ts.map +1 -1
  172. package/dist/src/node/helpers/PathResolver.d.ts +6 -5
  173. package/dist/src/node/helpers/PathResolver.d.ts.map +1 -1
  174. package/dist/src/node/helpers/QueryClient.d.ts +4 -6
  175. package/dist/src/node/helpers/QueryClient.d.ts.map +1 -1
  176. package/dist/src/node/helpers/scripts.d.ts +5 -7
  177. package/dist/src/node/helpers/scripts.d.ts.map +1 -1
  178. package/dist/src/node/index.d.ts +2 -9
  179. package/dist/src/node/index.d.ts.map +1 -1
  180. package/dist/src/node/webpack/index.d.ts +1 -1
  181. package/dist/src/node/webpack/index.d.ts.map +1 -1
  182. package/dist/src/platform/configurePlatform.d.ts +6 -0
  183. package/dist/src/platform/configurePlatform.d.ts.map +1 -0
  184. package/dist/src/platform/index.browser.d.ts +3 -0
  185. package/dist/src/platform/index.browser.d.ts.map +1 -0
  186. package/dist/src/platform/index.d.ts +9 -0
  187. package/dist/src/platform/index.d.ts.map +1 -0
  188. package/dist/src/platform/index.node.d.ts +3 -0
  189. package/dist/src/platform/index.node.d.ts.map +1 -0
  190. package/dist/src/platform/types.d.ts +14 -0
  191. package/dist/src/platform/types.d.ts.map +1 -0
  192. package/dist/src/stores/eas.d.ts +1 -18
  193. package/dist/src/stores/eas.d.ts.map +1 -1
  194. package/dist/src/testing/platformTestHandle.d.ts +8 -0
  195. package/dist/src/testing/platformTestHandle.d.ts.map +1 -0
  196. package/dist/src/types/gateway.d.ts +2 -0
  197. package/dist/src/types/gateway.d.ts.map +1 -0
  198. package/dist/src/types/index.d.ts +5 -0
  199. package/dist/src/types/index.d.ts.map +1 -1
  200. package/dist/src/types/item.d.ts +1 -1
  201. package/dist/src/types/item.d.ts.map +1 -1
  202. package/dist/src/types/machines.d.ts +10 -0
  203. package/dist/src/types/machines.d.ts.map +1 -1
  204. package/dist/src/types/seedProtocol.d.ts +1 -1
  205. package/dist/src/types/seedProtocol.d.ts.map +1 -1
  206. package/dist/src/vite/index.d.ts +2 -47
  207. package/dist/src/vite/index.d.ts.map +1 -1
  208. package/dist/{syncDbWithEas-CB5aXPtf.js → syncDbWithEas-DMOJHtkP.js} +20 -15
  209. package/dist/syncDbWithEas-DMOJHtkP.js.map +1 -0
  210. package/dist/{updateSeedRevokedAt-BIu5Q4Po.js → updateSeedRevokedAt-Ba0OhDQj.js} +2 -2
  211. package/dist/{updateSeedRevokedAt-BIu5Q4Po.js.map → updateSeedRevokedAt-Ba0OhDQj.js.map} +1 -1
  212. package/dist/vite.cjs +5 -470
  213. package/dist/vite.cjs.map +1 -1
  214. package/dist/vite.js +1 -472
  215. package/dist/vite.js.map +1 -1
  216. package/package.json +42 -37
  217. package/dist/ArweaveClient-CZpZgmR2.js +0 -204
  218. package/dist/ArweaveClient-CZpZgmR2.js.map +0 -1
  219. package/dist/ArweaveClient-Cs7AL9dp.js +0 -204
  220. package/dist/ArweaveClient-Cs7AL9dp.js.map +0 -1
  221. package/dist/Db-CF6R7HIy.js +0 -2098
  222. package/dist/Db-CF6R7HIy.js.map +0 -1
  223. package/dist/Db-CZkONsdT.js +0 -248
  224. package/dist/Db-CZkONsdT.js.map +0 -1
  225. package/dist/EasClient-PXOzSzPG.js +0 -29
  226. package/dist/EasClient-PXOzSzPG.js.map +0 -1
  227. package/dist/EasClient-qfTiM2we.js +0 -29
  228. package/dist/EasClient-qfTiM2we.js.map +0 -1
  229. package/dist/FileManager-5GkHtxF7.js +0 -1256
  230. package/dist/FileManager-5GkHtxF7.js.map +0 -1
  231. package/dist/FileManager-jORQ8Bb6.js +0 -177
  232. package/dist/FileManager-jORQ8Bb6.js.map +0 -1
  233. package/dist/ModelProperty-e_hXSFvf.js.map +0 -1
  234. package/dist/PathResolver-B4_X69Rd.js +0 -204
  235. package/dist/PathResolver-B4_X69Rd.js.map +0 -1
  236. package/dist/PathResolver-Dz0RVGIz.js +0 -78
  237. package/dist/PathResolver-Dz0RVGIz.js.map +0 -1
  238. package/dist/QueryClient-CXHZ239d.js +0 -51
  239. package/dist/QueryClient-CXHZ239d.js.map +0 -1
  240. package/dist/QueryClient-D_UK4YLm.js +0 -35
  241. package/dist/QueryClient-D_UK4YLm.js.map +0 -1
  242. package/dist/arweave-default-shim.js +0 -6
  243. package/dist/cjs/getPublishPayload-CGKMEL3H.js.map +0 -1
  244. package/dist/cjs/getSegmentedItemProperties-BgS_FhAx.js.map +0 -1
  245. package/dist/cjs/index-BnAqr2le.js.map +0 -1
  246. package/dist/cjs/index-ByozbTn_.js.map +0 -1
  247. package/dist/cjs/syncDbWithEas-CA2Lum5V.js.map +0 -1
  248. package/dist/debug-default-shim.js +0 -27
  249. package/dist/getPublishPayload-D16enahU.js.map +0 -1
  250. package/dist/getSegmentedItemProperties-Be3kYWY3.js.map +0 -1
  251. package/dist/index-BFyMxc7e.js.map +0 -1
  252. package/dist/index-BcXKZQpX.js.map +0 -1
  253. package/dist/index-C9p-skT3.js +0 -18
  254. package/dist/index-C9p-skT3.js.map +0 -1
  255. package/dist/property-CRAau-Q-.js.map +0 -1
  256. package/dist/queries-Ct7CcQ3g.js +0 -16
  257. package/dist/queries-Ct7CcQ3g.js.map +0 -1
  258. package/dist/src/Item/queries.d.ts +0 -27
  259. package/dist/src/Item/queries.d.ts.map +0 -1
  260. package/dist/src/graphql/fragments/Attestation.d.ts +0 -2
  261. package/dist/src/graphql/fragments/Attestation.d.ts.map +0 -1
  262. package/dist/src/graphql/fragments/Schema.d.ts +0 -2
  263. package/dist/src/graphql/fragments/Schema.d.ts.map +0 -1
  264. package/dist/src/graphql/fragments/index.d.ts +0 -3
  265. package/dist/src/graphql/fragments/index.d.ts.map +0 -1
  266. package/dist/src/graphql/gql/fragment-masking.d.ts +0 -20
  267. package/dist/src/graphql/gql/fragment-masking.d.ts.map +0 -1
  268. package/dist/src/graphql/gql/gql.d.ts +0 -107
  269. package/dist/src/graphql/gql/gql.d.ts.map +0 -1
  270. package/dist/src/graphql/gql/graphql.d.ts +0 -2969
  271. package/dist/src/graphql/gql/graphql.d.ts.map +0 -1
  272. package/dist/src/graphql/gql/index.d.ts +0 -3
  273. package/dist/src/graphql/gql/index.d.ts.map +0 -1
  274. package/dist/src/helpers/ArweaveClient/queries.d.ts +0 -13
  275. package/dist/src/helpers/ArweaveClient/queries.d.ts.map +0 -1
  276. package/dist/src/helpers/file/queries.d.ts +0 -9
  277. package/dist/src/helpers/file/queries.d.ts.map +0 -1
  278. package/dist/src/helpers/image/queries.d.ts +0 -7
  279. package/dist/src/helpers/image/queries.d.ts.map +0 -1
  280. package/dist/src/node/codegen/drizzle.d.ts +0 -5
  281. package/dist/src/node/codegen/drizzle.d.ts.map +0 -1
  282. package/dist/src/node/codegen/index.d.ts +0 -2
  283. package/dist/src/node/codegen/index.d.ts.map +0 -1
  284. package/dist/src/node/codegen/ts-to-proto.d.ts +0 -9
  285. package/dist/src/node/codegen/ts-to-proto.d.ts.map +0 -1
  286. package/dist/src/node/db/node.app.db.config.d.ts +0 -4
  287. package/dist/src/node/db/node.app.db.config.d.ts.map +0 -1
  288. package/dist/src/node/helpers/index.d.ts +0 -3
  289. package/dist/src/node/helpers/index.d.ts.map +0 -1
  290. package/dist/src/vite/arweave-default-shim.d.ts +0 -4
  291. package/dist/src/vite/arweave-default-shim.d.ts.map +0 -1
  292. package/dist/src/vite/debug-default-shim.d.ts +0 -3
  293. package/dist/src/vite/debug-default-shim.d.ts.map +0 -1
  294. package/dist/src/vite/easFix.d.ts +0 -2
  295. package/dist/src/vite/easFix.d.ts.map +0 -1
  296. package/dist/syncDbWithEas-CB5aXPtf.js.map +0 -1
  297. /package/dist/db/drizzle/{drizzle/0000_married_malice.sql → 0000_married_malice.sql} +0 -0
  298. /package/dist/db/drizzle/{drizzle/0001_sweet_bruce_banner.sql → 0001_sweet_bruce_banner.sql} +0 -0
  299. /package/dist/db/drizzle/{drizzle/0002_bitter_proudstar.sql → 0002_bitter_proudstar.sql} +0 -0
  300. /package/dist/db/drizzle/{drizzle/0003_cultured_senator_kelly.sql → 0003_cultured_senator_kelly.sql} +0 -0
  301. /package/dist/db/drizzle/{drizzle/0004_add_publisher_to_seeds.sql → 0004_add_publisher_to_seeds.sql} +0 -0
  302. /package/dist/db/drizzle/{drizzle/0005_bright_lily_hollister.sql → 0005_bright_lily_hollister.sql} +0 -0
  303. /package/dist/db/drizzle/{drizzle/0006_add_publisher_to_versions_and_metadata.sql → 0006_add_publisher_to_versions_and_metadata.sql} +0 -0
  304. /package/dist/db/drizzle/{drizzle/0007_add_required_to_properties.sql → 0007_add_required_to_properties.sql} +0 -0
  305. /package/dist/db/drizzle/{drizzle/0008_add_revoked_at_to_seeds.sql → 0008_add_revoked_at_to_seeds.sql} +0 -0
  306. /package/dist/db/drizzle/{drizzle/0009_happy_namor.sql → 0009_happy_namor.sql} +0 -0
  307. /package/dist/db/drizzle/{drizzle/0010_add_arweave_l1_finalize_jobs.sql → 0010_add_arweave_l1_finalize_jobs.sql} +0 -0
  308. /package/dist/db/drizzle/{drizzle/0011_normalize_placeholder_uids.sql → 0011_normalize_placeholder_uids.sql} +0 -0
  309. /package/dist/db/drizzle/{drizzle/0012_html_embedded_image_co_publish.sql → 0012_html_embedded_image_co_publish.sql} +0 -0
  310. /package/dist/db/drizzle/{drizzle/0013_eas_sync_processes.sql → 0013_eas_sync_processes.sql} +0 -0
  311. /package/dist/db/drizzle/{drizzle/meta → meta}/0000_snapshot.json +0 -0
  312. /package/dist/db/drizzle/{drizzle/meta → meta}/0001_snapshot.json +0 -0
  313. /package/dist/db/drizzle/{drizzle/meta → meta}/0002_snapshot.json +0 -0
  314. /package/dist/db/drizzle/{drizzle/meta → meta}/0003_snapshot.json +0 -0
  315. /package/dist/db/drizzle/{drizzle/meta → meta}/0004_snapshot.json +0 -0
  316. /package/dist/db/drizzle/{drizzle/meta → meta}/0005_snapshot.json +0 -0
  317. /package/dist/db/drizzle/{drizzle/meta → meta}/0006_snapshot.json +0 -0
  318. /package/dist/db/drizzle/{drizzle/meta → meta}/0007_snapshot.json +0 -0
  319. /package/dist/db/drizzle/{drizzle/meta → meta}/0008_snapshot.json +0 -0
  320. /package/dist/db/drizzle/{drizzle/meta → meta}/0009_snapshot.json +0 -0
  321. /package/dist/db/drizzle/{drizzle/meta → meta}/0010_snapshot.json +0 -0
  322. /package/dist/db/drizzle/{drizzle/meta → meta}/0013_snapshot.json +0 -0
  323. /package/dist/db/drizzle/{drizzle/meta → meta}/_journal.json +0 -0
@@ -1,1256 +0,0 @@
1
- import { p as BaseDb, a1 as appState, v as BaseFileManager } from './index-BcXKZQpX.js';
2
- import debug from 'debug';
3
- import 'xstate';
4
- import 'drizzle-orm/sqlite-core';
5
- import 'drizzle-orm';
6
- import 'nanoid';
7
- import 'nanoid-dictionary';
8
- import 'ethers';
9
- import 'pluralize';
10
- import '@sinclair/typebox';
11
- import 'drizzle-orm/casing';
12
- import 'lodash-es';
13
- import 'rxjs';
14
- import 'arweave';
15
- import 'js-sha3';
16
-
17
- const saveAppState = async (key, value) => {
18
- const appDb = BaseDb.getAppDb();
19
- await appDb
20
- .insert(appState)
21
- .values({
22
- key,
23
- value,
24
- })
25
- .onConflictDoUpdate({
26
- target: appState.key,
27
- set: {
28
- value,
29
- },
30
- });
31
- };
32
-
33
- var filesDownload = `(
34
- ${function () {
35
- const identifyString = (str) => {
36
- try {
37
- JSON.parse(str);
38
- return 'json';
39
- }
40
- catch (e) {
41
- // Not JSON
42
- }
43
- if (!str) {
44
- return;
45
- }
46
- if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
47
- return 'html';
48
- }
49
- // Simple markdown checks (very naive)
50
- if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
51
- return 'markdown';
52
- }
53
- if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
54
- return 'base64';
55
- }
56
- // Default to plain text if unsure
57
- return 'text';
58
- };
59
- const getMimeType = (base64) => {
60
- if (!base64) {
61
- return null;
62
- }
63
- const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/);
64
- if (result && result.length > 1) {
65
- return result[1];
66
- }
67
- else {
68
- return null; // MIME type could not be determined
69
- }
70
- };
71
- const getDataTypeFromString = (data) => {
72
- const nonImageBase64Regex = /^(?!data:image\/(?:jpeg|png|gif|bmp|webp);base64,)[A-Za-z0-9+/=]+$/;
73
- if (nonImageBase64Regex.test(data)) {
74
- return 'base64';
75
- }
76
- // Regular expression for base64 (simple version, checking for base64 format)
77
- const imageBase64Regex = /^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/;
78
- if (imageBase64Regex.test(data)) {
79
- return 'imageBase64';
80
- }
81
- // Regular expression for URL (simple version, checking for common URL format)
82
- const urlRegex = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/;
83
- if (urlRegex.test(data)) {
84
- return 'url';
85
- }
86
- return null;
87
- };
88
- const isBinary = (arrayBuffer) => {
89
- const view = new Uint8Array(arrayBuffer);
90
- let nonTextCount = 0;
91
- const threshold = 0.2; // Adjust as needed (e.g., 20% non-text implies binary)
92
- for (let i = 0; i < view.length; i++) {
93
- const byte = view[i];
94
- // ASCII printable characters (32-126) and common whitespace (9, 10, 13)
95
- if ((byte >= 32 && byte <= 126) || // Printable ASCII
96
- byte === 9 || byte === 10 || byte === 13 // Tab, LF, CR
97
- ) {
98
- continue;
99
- }
100
- nonTextCount++;
101
- if (nonTextCount / view.length > threshold) {
102
- return true; // More than threshold are non-text bytes
103
- }
104
- }
105
- return false; // Fewer than threshold are non-text bytes
106
- };
107
- const saveBufferToOPFS = async (filePath, buffer) => {
108
- // Access the OPFS root directory
109
- const rootHandle = await navigator.storage.getDirectory();
110
- // Split the filePath into directory segments and file name
111
- const segments = filePath.split('/').filter(Boolean);
112
- const fileName = segments.pop(); // Extract the file name
113
- if (!fileName) {
114
- throw new Error('Invalid file path: No file name provided.');
115
- }
116
- // Traverse or create directories as needed
117
- let currentDirHandle = rootHandle;
118
- for (const segment of segments) {
119
- currentDirHandle = await currentDirHandle.getDirectoryHandle(segment, { create: true });
120
- }
121
- // Create or open the file in OPFS
122
- const fileHandleAsync = await currentDirHandle.getFileHandle(fileName, { create: true });
123
- const fileHandle = await fileHandleAsync.createSyncAccessHandle();
124
- // Write the buffer to the file
125
- fileHandle.write(buffer);
126
- fileHandle.flush();
127
- fileHandle.close();
128
- };
129
- const getFilesPath = (filesRoot, ...parts) => {
130
- const root = filesRoot.replace(/\/$/, '');
131
- return [root, ...parts].filter(Boolean).join('/').replace(/\/+/g, '/');
132
- };
133
- const downloadFiles = async ({ transactionIds, arweaveHost, filesRoot = '/files', }) => {
134
- let arrayBuffer;
135
- for (const transactionId of transactionIds) {
136
- try {
137
- const response = await fetch(`https://${arweaveHost}/raw/${transactionId}`);
138
- arrayBuffer = await response.arrayBuffer();
139
- }
140
- catch (error) {
141
- globalThis.postMessage({
142
- message: 'excludeTransaction',
143
- transactionId,
144
- });
145
- continue;
146
- }
147
- let dataString;
148
- const isBinaryData = isBinary(arrayBuffer);
149
- if (!isBinaryData) {
150
- const decoder = new TextDecoder('utf-8');
151
- const text = decoder.decode(arrayBuffer);
152
- dataString = text;
153
- }
154
- if (dataString && dataString.startsWith('===FILE_SEPARATOR===')) {
155
- const dataStringParts = dataString
156
- .split('===FILE_SEPARATOR===')
157
- .slice(1);
158
- if (dataStringParts.length % 2 !== 0) {
159
- throw new Error('Input array must have an even number of elements.');
160
- }
161
- for (let i = 0; i < dataStringParts.length; i += 2) {
162
- const contentType = dataStringParts[i];
163
- const content = dataStringParts[i + 1];
164
- const encoder = new TextEncoder();
165
- if (contentType === 'html') {
166
- const fileName = `${transactionId}.html`;
167
- const buffer = encoder.encode(content);
168
- saveBufferToOPFS(getFilesPath(filesRoot, 'html', fileName), buffer);
169
- }
170
- if (contentType === 'json') {
171
- const fileName = `${transactionId}.json`;
172
- const buffer = encoder.encode(content);
173
- saveBufferToOPFS(getFilesPath(filesRoot, 'json', fileName), buffer);
174
- }
175
- }
176
- continue;
177
- }
178
- if (!dataString && arrayBuffer) {
179
- saveBufferToOPFS(getFilesPath(filesRoot, 'images', transactionId), new Uint8Array(arrayBuffer));
180
- continue;
181
- }
182
- if (!dataString) {
183
- continue;
184
- }
185
- let contentType = identifyString(dataString);
186
- if (contentType !== 'json' &&
187
- contentType !== 'base64' &&
188
- contentType !== 'html') {
189
- const possibleImageType = getDataTypeFromString(dataString);
190
- if (!possibleImageType) {
191
- continue;
192
- }
193
- contentType = possibleImageType;
194
- }
195
- if (contentType === 'url') {
196
- const url = dataString;
197
- let buffer;
198
- try {
199
- const response = await fetch(url);
200
- buffer = await response.arrayBuffer();
201
- }
202
- catch (error) {
203
- globalThis.postMessage({
204
- message: 'excludeTransaction',
205
- transactionId,
206
- });
207
- continue;
208
- }
209
- const bufferUint8Array = new Uint8Array(buffer);
210
- // Extract the file extension from the URL
211
- const extensionMatch = url.match(/\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i);
212
- if (!extensionMatch) {
213
- throw new Error('Unable to determine the file extension from the URL.');
214
- }
215
- extensionMatch[0]; // e.g., ".jpg"
216
- // Set the file name (you can customize this)
217
- // const fileNameFromUrl = `${transactionId}${fileExtension}`
218
- await saveBufferToOPFS(getFilesPath(filesRoot, 'images', transactionId), bufferUint8Array);
219
- continue;
220
- }
221
- const mimeType = getMimeType(dataString);
222
- let fileExtension = mimeType;
223
- if (fileExtension && fileExtension?.startsWith('image')) {
224
- fileExtension = fileExtension.replace('image/', '');
225
- }
226
- let fileName = transactionId;
227
- if (contentType === 'base64') {
228
- if (fileExtension) {
229
- fileName += `.${fileExtension}`;
230
- }
231
- // Remove the Base64 header if it exists (e.g., "data:image/png;base64,")
232
- const base64Data = dataString.split(',').pop() || '';
233
- // Decode the Base64 string to binary
234
- const binaryString = atob(base64Data);
235
- const length = binaryString.length;
236
- const binaryData = new Uint8Array(length);
237
- for (let i = 0; i < length; i++) {
238
- binaryData[i] = binaryString.charCodeAt(i);
239
- }
240
- await saveBufferToOPFS(getFilesPath(filesRoot, 'images', fileName), binaryData);
241
- }
242
- if (contentType === 'html') {
243
- fileName += '.html';
244
- const encoder = new TextEncoder();
245
- const buffer = encoder.encode(dataString);
246
- await saveBufferToOPFS(getFilesPath(filesRoot, 'html', fileName), buffer);
247
- }
248
- if (contentType === 'json') {
249
- fileName += '.json';
250
- const encoder = new TextEncoder();
251
- const buffer = encoder.encode(dataString);
252
- await saveBufferToOPFS(getFilesPath(filesRoot, 'json', fileName), buffer);
253
- }
254
- }
255
- };
256
- onmessage = async (e) => {
257
- const { debug, filesRoot } = e.data;
258
- if (!debug) {
259
- console.log = () => { };
260
- }
261
- await downloadFiles({ ...e.data, filesRoot });
262
- globalThis.postMessage({
263
- message: 'filesDownload onmessage done',
264
- done: true,
265
- });
266
- };
267
- }.toString()}
268
- )()`;
269
-
270
- const logger$2 = debug('seedSdk:browser:workers:FileDownloader');
271
- class FileDownloader {
272
- constructor() {
273
- this.workersArchive = [];
274
- this.downloadAll = async ({ transactionIds, arweaveHost, excludedTransactions }) => {
275
- if (this.workersArchive.length > 0) {
276
- for (let i = 0; i < this.workersArchive.length; i++) {
277
- this.workersArchive[i].terminate();
278
- delete this.workersArchive[i];
279
- }
280
- this.workersArchive = [];
281
- }
282
- const worker = new Worker(this.workerBlobUrl);
283
- this.workersArchive.push(worker);
284
- const localExcludedTransactions = new Set(excludedTransactions);
285
- return new Promise((resolve, reject) => {
286
- worker.onmessage = (e) => {
287
- logger$2('filesDownload main thread onmessage', e.data);
288
- if (e.data.message === 'excludeTransaction') {
289
- localExcludedTransactions.add(e.data.transactionId);
290
- }
291
- if (e.data.done) {
292
- saveAppState('excludedTransactions', JSON.stringify(Array.from(localExcludedTransactions)))
293
- .then(() => {
294
- resolve(e.data);
295
- })
296
- .catch((error) => {
297
- reject(error);
298
- });
299
- }
300
- if (e.data.error) {
301
- reject(e.data.error);
302
- }
303
- };
304
- worker.postMessage({
305
- transactionIds,
306
- arweaveHost,
307
- debug: logger$2.enabled,
308
- filesRoot: BaseFileManager.getWorkingDir(),
309
- });
310
- });
311
- };
312
- this.cores = Math.min(navigator.hardwareConcurrency || 4, 4);
313
- this.workerBlobUrl = globalThis.URL.createObjectURL(new Blob([filesDownload], { type: 'application/javascript' }));
314
- }
315
- }
316
-
317
- var imageResize = `(
318
- ${function () {
319
- async function listFilesInDirectory(directoryHandle) {
320
- const entries = [];
321
- for await (const [name, handle] of directoryHandle.entries()) {
322
- entries.push({
323
- name,
324
- kind: handle.kind,
325
- });
326
- }
327
- return entries;
328
- }
329
- const getFileHandle = async (path, rootHandle = null) => {
330
- // Split the path into segments
331
- const segments = path.split('/').filter(Boolean);
332
- // Start from the root directory if not provided
333
- if (!rootHandle) {
334
- rootHandle = await navigator.storage.getDirectory();
335
- }
336
- let currentHandle = rootHandle;
337
- // Traverse the path segments
338
- for (let i = 0; i < segments.length; i++) {
339
- const segment = segments[i];
340
- const isLastSegment = i === segments.length - 1;
341
- try {
342
- for await (const [name, handle] of currentHandle.entries()) {
343
- if (name !== segment) {
344
- continue;
345
- }
346
- if (isLastSegment) {
347
- if (handle.kind === 'file') {
348
- return handle; // Return the file handle if found
349
- }
350
- else {
351
- throw new Error(`Path '${path}' refers to a directory, not a file.`);
352
- }
353
- }
354
- else if (handle.kind === 'directory') {
355
- currentHandle = handle; // Traverse into the directory
356
- }
357
- else {
358
- throw new Error(`Invalid path segment '${segment}'`);
359
- }
360
- }
361
- }
362
- catch (err) {
363
- if (err instanceof Error && err.name === 'NotFoundError') {
364
- throw new Error(`Path '${path}' does not exist.`);
365
- }
366
- else {
367
- throw err;
368
- }
369
- }
370
- }
371
- throw new Error(`Path '${path}' could not be resolved.`);
372
- };
373
- async function getFileFromOPFS(path) {
374
- const fileHandleAsync = await getFileHandle(path);
375
- const file = await fileHandleAsync.getFile();
376
- return file;
377
- }
378
- /** Infer MIME from magic bytes. OPFS File may have empty type, causing createImageBitmap to fail. */
379
- async function getBlobWithInferredMime(file) {
380
- const buf = await file.arrayBuffer();
381
- const bytes = new Uint8Array(buf);
382
- let mime = file.type;
383
- if (!mime || mime === '') {
384
- if (bytes[0] === 0xff && bytes[1] === 0xd8)
385
- mime = 'image/jpeg';
386
- else if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)
387
- mime = 'image/png';
388
- else if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x52 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50)
389
- mime = 'image/webp';
390
- else if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46)
391
- mime = 'image/gif';
392
- else if (bytes[0] === 0x42 && bytes[1] === 0x4d)
393
- mime = 'image/bmp';
394
- else if (bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70 && bytes[8] === 0x61 && bytes[9] === 0x76 && bytes[10] === 0x69 && bytes[11] === 0x66)
395
- mime = 'image/avif';
396
- else if (bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70 && bytes[8] === 0x68 && bytes[9] === 0x65 && bytes[10] === 0x69 && bytes[11] === 0x63)
397
- mime = 'image/heic';
398
- else
399
- mime = 'image/jpeg';
400
- }
401
- return new Blob([buf], { type: mime });
402
- }
403
- const DEFAULT_CONFIG = {
404
- argorithm: 'null',
405
- processByHalf: true,
406
- quality: 0.5,
407
- maxWidth: 800,
408
- maxHeight: 600,
409
- debug: false,
410
- mimeType: 'image/jpeg',
411
- };
412
- function isIos() {
413
- if (typeof navigator === 'undefined')
414
- return false;
415
- if (!navigator.userAgent)
416
- return false;
417
- return /iPad|iPhone|iPod/.test(navigator.userAgent);
418
- }
419
- const getTargetHeight = (srcHeight, scale, config) => {
420
- return Math.min(Math.floor(srcHeight * scale), config.maxHeight);
421
- };
422
- const findMaxWidth = (config, canvas) => {
423
- //Let's find the max available width for scaled image
424
- const ratio = canvas.width / canvas.height;
425
- let mWidth = Math.min(canvas.width, config.maxWidth, ratio * config.maxHeight);
426
- if (config.maxSize &&
427
- config.maxSize > 0 &&
428
- config.maxSize < (canvas.width * canvas.height) / 1000)
429
- mWidth = Math.min(mWidth, Math.floor((config.maxSize * 1000) / canvas.height));
430
- if (!!config.scaleRatio)
431
- mWidth = Math.min(mWidth, Math.floor(config.scaleRatio * canvas.width));
432
- const rHeight = getTargetHeight(canvas.height, mWidth / canvas.width, config);
433
- // console.log(
434
- // 'browser-image-resizer: original image size = ' +
435
- // canvas.width +
436
- // ' px (width) X ' +
437
- // canvas.height +
438
- // ' px (height)'
439
- // );
440
- // console.log(
441
- // 'browser-image-resizer: scaled image size = ' +
442
- // mWidth +
443
- // ' px (width) X ' +
444
- // rHeight +
445
- // ' px (height)'
446
- // );
447
- if (mWidth <= 0) {
448
- mWidth = 1;
449
- console.warn("browser-image-resizer: image size is too small");
450
- }
451
- if (isIos() && mWidth * rHeight > 167777216) {
452
- console.error("browser-image-resizer: image size is too large for iOS WebKit.", mWidth, rHeight);
453
- throw new Error("browser-image-resizer: image size is too large for iOS WebKit.");
454
- }
455
- return mWidth;
456
- };
457
- /**
458
- * Hermite resize, multicore version - fast image resize/resample using Hermite filter.
459
- */
460
- const resample = (srcCanvas, destCanvas, config) => {
461
- return new Promise((resolve, reject) => {
462
- const ratio_h = srcCanvas.height / destCanvas.height;
463
- const cores = Math.min(navigator.hardwareConcurrency || 4, 4);
464
- //prepare source and target data for workers
465
- const ctx = srcCanvas.getContext('2d');
466
- if (!ctx)
467
- return reject('Canvas is empty (resample)');
468
- const data_part = [];
469
- const block_height = Math.ceil(srcCanvas.height / cores / 2) * 2;
470
- let end_y = -1;
471
- for (let c = 0; c < cores; c++) {
472
- //source
473
- const offset_y = end_y + 1;
474
- if (offset_y >= srcCanvas.height) {
475
- //size too small, nothing left for this core
476
- continue;
477
- }
478
- end_y = Math.min(offset_y + block_height - 1, srcCanvas.height - 1);
479
- const current_block_height = Math.min(block_height, srcCanvas.height - offset_y);
480
- data_part.push({
481
- source: ctx.getImageData(0, offset_y, srcCanvas.width, block_height),
482
- startY: Math.ceil(offset_y / ratio_h),
483
- height: current_block_height
484
- });
485
- }
486
- //start
487
- const destCtx = destCanvas.getContext('2d');
488
- if (!destCtx)
489
- return reject('Canvas is empty (resample dest)');
490
- for (let c = 0; c < data_part.length; c++) {
491
- //draw
492
- const height_part = Math.ceil(data_part[c].height / ratio_h);
493
- const target = destCtx.createImageData(destCanvas.width, height_part);
494
- // target.data.set(event.data.target);
495
- destCtx.putImageData(target, 0, data_part[c].startY);
496
- }
497
- });
498
- };
499
- /**
500
- * Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
501
- */
502
- const resampleSingle = (srcCanvasData, destCanvasData) => {
503
- const ratio_w = srcCanvasData.width / destCanvasData.width;
504
- const ratio_h = srcCanvasData.height / destCanvasData.height;
505
- const ratio_w_half = Math.ceil(ratio_w / 2);
506
- const ratio_h_half = Math.ceil(ratio_h / 2);
507
- const data = srcCanvasData.data;
508
- const data2 = destCanvasData.data;
509
- for (let j = 0; j < destCanvasData.height; j++) {
510
- for (let i = 0; i < destCanvasData.width; i++) {
511
- const x2 = (i + j * destCanvasData.width) * 4;
512
- let weight = 0;
513
- let weights = 0;
514
- let weights_alpha = 0;
515
- let gx_r = 0;
516
- let gx_g = 0;
517
- let gx_b = 0;
518
- let gx_a = 0;
519
- const center_y = j * ratio_h;
520
- const xx_start = Math.floor(i * ratio_w);
521
- const xx_stop = Math.min(Math.ceil((i + 1) * ratio_w), srcCanvasData.width);
522
- const yy_start = Math.floor(j * ratio_h);
523
- const yy_stop = Math.min(Math.ceil((j + 1) * ratio_h), srcCanvasData.height);
524
- for (let yy = yy_start; yy < yy_stop; yy++) {
525
- let dy = Math.abs(center_y - yy) / ratio_h_half;
526
- let center_x = i * ratio_w;
527
- let w0 = dy * dy; //pre-calc part of w
528
- for (let xx = xx_start; xx < xx_stop; xx++) {
529
- let dx = Math.abs(center_x - xx) / ratio_w_half;
530
- let w = Math.sqrt(w0 + dx * dx);
531
- if (w >= 1) {
532
- //pixel too far
533
- continue;
534
- }
535
- //hermite filter
536
- weight = 2 * w * w * w - 3 * w * w + 1;
537
- let pos_x = 4 * (xx + yy * srcCanvasData.width);
538
- //alpha
539
- gx_a += weight * data[pos_x + 3];
540
- weights_alpha += weight;
541
- //colors
542
- if (data[pos_x + 3] < 255)
543
- weight = weight * data[pos_x + 3] / 250;
544
- gx_r += weight * data[pos_x];
545
- gx_g += weight * data[pos_x + 1];
546
- gx_b += weight * data[pos_x + 2];
547
- weights += weight;
548
- }
549
- }
550
- data2[x2] = gx_r / weights;
551
- data2[x2 + 1] = gx_g / weights;
552
- data2[x2 + 2] = gx_b / weights;
553
- data2[x2 + 3] = gx_a / weights_alpha;
554
- }
555
- }
556
- };
557
- /**
558
- * Hermite resize. Detect cpu count and use best option for user.
559
- */
560
- const resampleAuto = (srcCanvas, destCanvas, config) => {
561
- if (!!globalThis.Worker && navigator.hardwareConcurrency > 1 && config?.argorithm !== 'hermite_single') {
562
- //workers supported and we have at least 2 cpu cores - using multithreading
563
- return resample(srcCanvas, destCanvas);
564
- }
565
- else {
566
- //1 cpu version
567
- const { srcImgData, destImgData } = getImageData(srcCanvas, destCanvas);
568
- resampleSingle(srcImgData, destImgData);
569
- destCanvas.getContext('2d').putImageData(destImgData, 0, 0);
570
- return;
571
- }
572
- };
573
- async function scaleCanvasWithAlgorithm(canvas, config) {
574
- const scale = config.outputWidth / canvas.width;
575
- const scaled = new OffscreenCanvas(Math.floor(config.outputWidth), getTargetHeight(canvas.height, scale, config));
576
- switch (config.algorithm) {
577
- case 'hermite': {
578
- await resampleAuto(canvas, scaled, config);
579
- break;
580
- }
581
- case 'hermite_single': {
582
- const { srcImgData, destImgData } = getImageData(canvas, scaled);
583
- resampleSingle(srcImgData, destImgData);
584
- scaled?.getContext('2d')?.putImageData(destImgData, 0, 0);
585
- break;
586
- }
587
- case 'bilinear': {
588
- // const { srcImgData, destImgData } = getImageData(canvas, scaled);
589
- // bilinear(srcImgData, destImgData, scale);
590
- // scaled?.getContext('2d')?.putImageData(destImgData, 0, 0);
591
- break;
592
- }
593
- default: {
594
- scaled.getContext('2d')?.drawImage(canvas, 0, 0, scaled.width, scaled.height);
595
- break;
596
- }
597
- }
598
- return scaled;
599
- }
600
- const getHalfScaleCanvas = (src) => {
601
- const half = new OffscreenCanvas(src.width / 2, src.height / 2);
602
- half
603
- ?.getContext('2d')
604
- ?.drawImage(src, 0, 0, half.width, half.height);
605
- return half;
606
- };
607
- const getImageData = (canvas, scaled) => {
608
- const srcImgData = canvas
609
- ?.getContext('2d')
610
- ?.getImageData(0, 0, canvas.width, canvas.height);
611
- const destImgData = scaled
612
- ?.getContext('2d')
613
- ?.createImageData(scaled.width, scaled.height);
614
- if (!srcImgData || !destImgData)
615
- throw Error('Canvas is empty (scaleCanvasWithAlgorithm). You should run this script after the document is ready.');
616
- return { srcImgData, destImgData };
617
- };
618
- async function saveBlobToOPFS(filePath, blob) {
619
- // Access the OPFS root directory
620
- const rootHandle = await navigator.storage.getDirectory();
621
- // Split the filePath into directory segments and file name
622
- const segments = filePath.split('/').filter(Boolean);
623
- const fileName = segments.pop(); // Extract the file name
624
- if (!fileName) {
625
- throw new Error('Invalid file path: No file name provided.');
626
- }
627
- // Traverse or create directories as needed
628
- let currentDirHandle = rootHandle;
629
- for (const segment of segments) {
630
- currentDirHandle = await currentDirHandle.getDirectoryHandle(segment, { create: true });
631
- }
632
- // Create or open the file in OPFS
633
- const fileHandle = await currentDirHandle.getFileHandle(fileName, { create: true });
634
- // Write the Blob to the file
635
- const writableStream = await fileHandle.createWritable();
636
- await writableStream.write(blob);
637
- await writableStream.close();
638
- }
639
- const imageResize = async (filePath, width, height) => {
640
- const config = {
641
- ...DEFAULT_CONFIG,
642
- algorithm: 'hermite_single',
643
- mimeType: 'image/webp',
644
- maxWidth: width,
645
- maxHeight: height,
646
- };
647
- const rootHandle = await navigator.storage.getDirectory();
648
- // List files in the root directory
649
- await listFilesInDirectory(rootHandle);
650
- const file = await getFileFromOPFS(filePath);
651
- const blobWithMime = await getBlobWithInferredMime(file);
652
- const imageBitmap = await createImageBitmap(blobWithMime);
653
- let converting;
654
- if (isIos() && imageBitmap.width * imageBitmap.height > 16777216) {
655
- const scale = Math.sqrt(16777216 / (imageBitmap.width * imageBitmap.height));
656
- converting = new OffscreenCanvas(Math.floor(imageBitmap.width * scale), Math.floor(imageBitmap.height * scale));
657
- converting.getContext('2d')?.drawImage(imageBitmap, 0, 0, converting.width, converting.height);
658
- }
659
- else {
660
- converting = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
661
- converting.getContext('2d')?.drawImage(imageBitmap, 0, 0);
662
- }
663
- const maxWidth = findMaxWidth(config, converting);
664
- if (!maxWidth) {
665
- throw Error(`browser-image-resizer: maxWidth is ${maxWidth}!!`);
666
- }
667
- while (config.processByHalf && converting.width >= 2 * maxWidth) {
668
- converting = getHalfScaleCanvas(converting);
669
- }
670
- if (converting.width > maxWidth) {
671
- converting = await scaleCanvasWithAlgorithm(converting, Object.assign(config, { outputWidth: maxWidth }));
672
- }
673
- if (config.mimeType === null) {
674
- return converting;
675
- }
676
- const resizedBlob = await converting.convertToBlob({ type: config.mimeType, quality: config.quality });
677
- const pathSegments = filePath.split('/');
678
- const fileName = pathSegments.pop();
679
- if (!fileName) {
680
- throw Error('Invalid file path: No file name provided.');
681
- }
682
- const newSegments = [
683
- ...pathSegments,
684
- width,
685
- ];
686
- const fileNameParts = fileName.split('.');
687
- const newFileName = `${fileNameParts[0]}.webp`;
688
- const newDirPath = newSegments.join('/');
689
- const newFilePath = `${newDirPath}/${newFileName}`;
690
- await saveBlobToOPFS(newFilePath, resizedBlob);
691
- globalThis.postMessage({
692
- done: true,
693
- filePath: newFilePath,
694
- });
695
- };
696
- onmessage = async (e) => {
697
- const { filePath, width, height, debug } = e.data;
698
- if (!debug) {
699
- console.log = () => { };
700
- }
701
- try {
702
- await imageResize(filePath, width, height);
703
- }
704
- catch (err) {
705
- globalThis.postMessage({ error: err instanceof Error ? err.message : String(err) });
706
- }
707
- };
708
- }.toString()}
709
- )()`;
710
-
711
- const logger$1 = debug('seedSdk:browser:workers:ImageResizer');
712
- class ImageResizer {
713
- constructor() {
714
- this.workersArchive = new Map();
715
- this.cores = Math.min(navigator.hardwareConcurrency || 4, 4);
716
- this.workerBlobUrl = globalThis.URL.createObjectURL(new Blob([imageResize], { type: 'application/javascript' }));
717
- }
718
- async resize({ filePath, width, height }) {
719
- if (this.workersArchive.has(filePath)) {
720
- const savedWorker = this.workersArchive.get(filePath);
721
- savedWorker?.terminate();
722
- logger$1('[ImageResizer.resize] Terminated worker for filePath due to incoming request', filePath);
723
- this.workersArchive.delete(filePath);
724
- }
725
- const worker = new Worker(this.workerBlobUrl);
726
- this.workersArchive.set(filePath, worker);
727
- return new Promise((resolve, reject) => {
728
- worker.onmessage = (e) => {
729
- logger$1('[ImageResizer.resize] main thread onmessage', e.data);
730
- if (e.data.done) {
731
- const savedWorker = this.workersArchive.get(filePath);
732
- savedWorker?.terminate();
733
- logger$1('[ImageResizer.resize] Terminated worker for filePath due to done', filePath);
734
- this.workersArchive.delete(filePath);
735
- resolve(e.data);
736
- }
737
- if (e.data.error) {
738
- reject(e.data.error);
739
- }
740
- };
741
- worker.onerror = (err) => {
742
- reject(err);
743
- };
744
- worker.postMessage({
745
- filePath,
746
- width,
747
- height,
748
- debug: logger$1.enabled,
749
- });
750
- });
751
- }
752
- async resizeAll({ width, height }) {
753
- const fs = await BaseFileManager.getFs();
754
- const imageDir = BaseFileManager.getFilesPath('images');
755
- let imageFilesStats = await fs.promises.readdir(imageDir, {
756
- withFileTypes: true
757
- });
758
- imageFilesStats = imageFilesStats.filter((file) => file.isFile());
759
- const imageFiles = imageFilesStats.map((file) => file.path);
760
- const widthDir = `${imageDir}/${width}`;
761
- await BaseFileManager.createDirIfNotExists(widthDir);
762
- for (const imageFile of imageFiles) {
763
- const resizedImageExists = await BaseFileManager.pathExists(`${widthDir}/${imageFile}`);
764
- if (!resizedImageExists) {
765
- await this.resize({ filePath: `${imageDir}/${imageFile}`, width, height });
766
- }
767
- }
768
- }
769
- }
770
-
771
- const logger = debug('seedSdk:browser:helpers:FileManager');
772
- /**
773
- * Browser-safe path helpers for SDK virtual file paths.
774
- * We intentionally avoid Node/CJS path polyfills here to keep browser bundles ESM-safe.
775
- */
776
- const pathCompat = {
777
- dirname(filePath) {
778
- if (!filePath)
779
- return '.';
780
- const normalized = filePath.replace(/\\/g, '/');
781
- if (normalized === '/')
782
- return '/';
783
- const trimmed = normalized.endsWith('/') && normalized.length > 1
784
- ? normalized.slice(0, -1)
785
- : normalized;
786
- const lastSlash = trimmed.lastIndexOf('/');
787
- if (lastSlash === -1)
788
- return '.';
789
- if (lastSlash === 0)
790
- return '/';
791
- return trimmed.slice(0, lastSlash);
792
- },
793
- basename(filePath) {
794
- if (!filePath)
795
- return '';
796
- const normalized = filePath.replace(/\\/g, '/');
797
- if (normalized === '/')
798
- return '/';
799
- const trimmed = normalized.endsWith('/') && normalized.length > 1
800
- ? normalized.slice(0, -1)
801
- : normalized;
802
- const lastSlash = trimmed.lastIndexOf('/');
803
- return lastSlash === -1 ? trimmed : trimmed.slice(lastSlash + 1);
804
- },
805
- };
806
- /** OPFS / ZenFS can throw NotReadableError while a file is still settling after write. */
807
- function isTransientOpfsReadError(error) {
808
- if (error instanceof DOMException && error.name === 'NotReadableError') {
809
- return true;
810
- }
811
- const message = error instanceof Error ? error.message : String(error);
812
- // Chromium wording when getFile/read races a writer or stale handle
813
- if (message.includes('permission problems') && message.includes('reference')) {
814
- return true;
815
- }
816
- return false;
817
- }
818
- function sleep(ms) {
819
- return new Promise((resolve) => setTimeout(resolve, ms));
820
- }
821
- class FileManager extends BaseFileManager {
822
- static async getFs() {
823
- if (!this.zenfsCache) {
824
- this.zenfsCache = await import('@zenfs/core');
825
- }
826
- return this.zenfsCache;
827
- }
828
- static getFsSync() {
829
- if (!this.zenfsCache) {
830
- throw new Error('File system not initialized. Call getFs() or initializeFileSystem() first.');
831
- }
832
- return this.zenfsCache;
833
- }
834
- static async getContentUrlFromPath(path) {
835
- const fileExists = await this.pathExists(path);
836
- if (fileExists) {
837
- const file = await this.readFile(path);
838
- return URL.createObjectURL(file);
839
- }
840
- }
841
- static async initializeFileSystem(workingDir) {
842
- const zenfs = await this.getFs();
843
- const zenfsDomMod = await import('@zenfs/dom');
844
- const { WebAccess } = zenfsDomMod;
845
- const { configureSingle } = zenfs;
846
- const handle = await navigator.storage.getDirectory();
847
- // await configure({
848
- // mounts: {
849
- // '/': {
850
- // backend: WebAccess,
851
- // handle,
852
- // },
853
- // },
854
- // disableUpdateOnRead: true,
855
- // onlySyncOnClose: true,
856
- // })
857
- await configureSingle({
858
- backend: WebAccess,
859
- handle,
860
- });
861
- // Cache is already set in getFs(), so no need to set it again
862
- }
863
- static async downloadAllFiles({ transactionIds, arweaveHost, excludedTransactions, }) {
864
- const fileDownloader = new FileDownloader();
865
- await fileDownloader.downloadAll({ transactionIds, arweaveHost, excludedTransactions });
866
- }
867
- static async resizeImage({ filePath, width, height }) {
868
- const imageResizer = new ImageResizer();
869
- await imageResizer.resize({ filePath, width, height });
870
- }
871
- static async resizeAllImages({ width, height }) {
872
- const imageResizer = new ImageResizer();
873
- await imageResizer.resizeAll({ width, height });
874
- }
875
- static async listImageFiles() {
876
- return this.listFiles('images');
877
- }
878
- static async listFiles(dir) {
879
- const targetDir = BaseFileManager.getFilesPath(dir);
880
- const exists = await this.pathExists(targetDir);
881
- if (!exists) {
882
- return [];
883
- }
884
- const zenfs = await this.getFs();
885
- const entries = await zenfs.promises.readdir(targetDir, { withFileTypes: true });
886
- return entries.filter((entry) => entry.isFile()).map((entry) => entry.name);
887
- }
888
- static async pathExists(filePath) {
889
- try {
890
- const zenfs = await this.getFs();
891
- await zenfs.promises.access(filePath, zenfs.constants.F_OK);
892
- return true;
893
- }
894
- catch (error) {
895
- // ENOENT means the file doesn't exist, which is expected
896
- if (error?.code === 'ENOENT' || error?.errno === -2) {
897
- return false;
898
- }
899
- // For other errors, re-throw them
900
- throw error;
901
- }
902
- }
903
- static async createDirIfNotExists(filePath) {
904
- if (!(await this.pathExists(filePath))) {
905
- try {
906
- const zenfs = await this.getFs();
907
- await zenfs.promises.mkdir(filePath, { recursive: true });
908
- }
909
- catch (error) {
910
- // This is a no-op. We tried to create a directory that already exists.
911
- logger('Attempted to create a directory that already exists');
912
- }
913
- }
914
- }
915
- /**
916
- * Waits for a file to exist at the specified path.
917
- * @param {string} filePath - The path of the file to check.
918
- * @param {number} interval - The interval in milliseconds between checks (default: 500ms).
919
- * @param {number} timeout - The timeout in milliseconds to wait for the file to exist (default: 10s).
920
- * @returns {Promise<boolean>} - Resolves to true if the file exists within the timeout period, otherwise false.
921
- */
922
- static async waitForFile(filePath, interval = 1000, timeout = 60000) {
923
- // const fs = await this.getFs()
924
- // const fsNode = await import('node:fs')
925
- const pathExists = await this.pathExists(filePath);
926
- if (pathExists) {
927
- return true;
928
- }
929
- return new Promise((resolve, reject) => {
930
- const startTime = Date.now();
931
- let isBusy = false;
932
- const cancelableInterval = new CancelableInterval(async (stop) => {
933
- logger('waitForFile', filePath);
934
- if (isBusy) {
935
- return;
936
- }
937
- isBusy = true;
938
- // // TODO: Needs to read from OPFS
939
- // const exists = await BaseFileManager.pathExists(filePath)
940
- // if (exists) {
941
- // stop()
942
- // resolve(true)
943
- // }
944
- const pathExists = await this.pathExists(filePath);
945
- if (pathExists) {
946
- stop();
947
- resolve(true);
948
- }
949
- if (Date.now() - startTime >= timeout) {
950
- stop();
951
- reject(new Error('Timeout exceeded while waiting for file'));
952
- }
953
- isBusy = false;
954
- }, interval);
955
- cancelableInterval.start();
956
- // const _interval = setInterval(async () => {
957
- // logger('waitForFile', filePath)
958
- // if (isBusy) {
959
- // return
960
- // }
961
- // isBusy = true
962
- // // TODO: Needs to read from OPFS
963
- // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {
964
- // clearInterval(_interval)
965
- // resolve(true)
966
- // }
967
- // const pathExists = await this.pathExists(filePath)
968
- // if (pathExists) {
969
- // clearInterval(_interval)
970
- // resolve(true)
971
- // }
972
- // if (Date.now() - startTime >= timeout) {
973
- // clearInterval(_interval)
974
- // reject(new Error('Timeout exceeded while waiting for file'))
975
- // }
976
- // isBusy = false
977
- // }, interval)
978
- // retry(
979
- // {
980
- // times: Math.ceil(timeout / interval),
981
- // interval: interval,
982
- // },
983
- // (callback: Function) => {
984
- // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {
985
- // return callback(null, true) // File exists, finish with success
986
- // }
987
- // if (Date.now() - startTime >= timeout) {
988
- // return callback(new Error('Timeout exceeded while waiting for file'))
989
- // }
990
- // callback(new Error('File does not exist yet')) // Retry with this error
991
- // },
992
- // (err: Error, result: boolean) => {
993
- // if (err) {
994
- // return resolve(false) // Resolve as false if timeout or error occurs
995
- // }
996
- // resolve(result) // Resolve as true if file exists
997
- // },
998
- // )
999
- });
1000
- }
1001
- /**
1002
- * Waits for a file to exist and have content (non-zero size).
1003
- * This is important for browser/OPFS where writes may not be immediately readable.
1004
- * @param {string} filePath - The path of the file to check.
1005
- * @param {number} interval - The interval in milliseconds between checks (default: 100ms).
1006
- * @param {number} timeout - The timeout in milliseconds to wait (default: 5s).
1007
- * @returns {Promise<boolean>} - Resolves to true if the file exists with content within the timeout period.
1008
- */
1009
- static async waitForFileWithContent(filePath, interval = 100, timeout = 5000) {
1010
- // First wait for file to exist
1011
- await this.waitForFile(filePath, interval, timeout);
1012
- // Now wait for file to have content
1013
- return new Promise((resolve, reject) => {
1014
- const startTime = Date.now();
1015
- let isBusy = false;
1016
- const cancelableInterval = new CancelableInterval(async (stop) => {
1017
- logger('waitForFileWithContent', filePath);
1018
- if (isBusy) {
1019
- return;
1020
- }
1021
- isBusy = true;
1022
- try {
1023
- // Try to read the file to check if it has content
1024
- const file = await this.readFile(filePath);
1025
- if (file.size > 0) {
1026
- stop();
1027
- resolve(true);
1028
- return;
1029
- }
1030
- // File exists but is 0 bytes, continue waiting
1031
- }
1032
- catch (error) {
1033
- // If error is about file being 0 bytes, not readable, or I/O error, continue waiting
1034
- const errorMessage = error?.message || String(error);
1035
- if (errorMessage.includes('0 bytes') ||
1036
- errorMessage.includes('ENOENT') ||
1037
- errorMessage.includes('EIO') ||
1038
- errorMessage.includes('Input/output error') ||
1039
- isTransientOpfsReadError(error)) ;
1040
- else {
1041
- // Other errors should be thrown
1042
- stop();
1043
- reject(error);
1044
- return;
1045
- }
1046
- }
1047
- if (Date.now() - startTime >= timeout) {
1048
- stop();
1049
- reject(new Error(`Timeout exceeded while waiting for file ${filePath} to have content`));
1050
- return;
1051
- }
1052
- isBusy = false;
1053
- }, interval);
1054
- cancelableInterval.start();
1055
- });
1056
- }
1057
- static async saveFile(filePath, content) {
1058
- const zenfs = await this.getFs();
1059
- // Convert content to a format that zenfs.writeFile accepts
1060
- let writeContent;
1061
- if (typeof content === 'string') {
1062
- writeContent = content;
1063
- }
1064
- else if (content instanceof Blob) {
1065
- const arrayBuffer = await content.arrayBuffer();
1066
- writeContent = new Uint8Array(arrayBuffer);
1067
- }
1068
- else if (content instanceof ArrayBuffer) {
1069
- writeContent = new Uint8Array(content);
1070
- }
1071
- else {
1072
- throw new Error('Unsupported content type');
1073
- }
1074
- await zenfs.writeFile(filePath, writeContent);
1075
- await this.waitForFileWithContent(filePath, 100, 5000);
1076
- // try {
1077
- // // Get a handle to the OPFS root directory
1078
- // const root = await navigator.storage.getDirectory();
1079
- // // Split the file path into directory and file name
1080
- // const pathParts = filePath.split('/');
1081
- // const fileName = pathParts.pop();
1082
- // if (!fileName) throw new Error('Invalid file path');
1083
- // // Traverse directories and create them if they don't exist
1084
- // let currentDir = root;
1085
- // for (const part of pathParts) {
1086
- // if (part !== '') {
1087
- // currentDir = await currentDir.getDirectoryHandle(part, { create: true });
1088
- // }
1089
- // }
1090
- // // Get the file handle and create the file if it doesn't exist
1091
- // const fileHandle = await currentDir.getFileHandle(fileName, { create: true });
1092
- // // Create a writable stream and write the content
1093
- // const writable = await fileHandle.createWritable();
1094
- // if (typeof content === 'string' || content instanceof Uint8Array) {
1095
- // await writable.write(content);
1096
- // } else if (content instanceof Blob) {
1097
- // await writable.write(content);
1098
- // } else if (content instanceof ArrayBuffer) {
1099
- // await writable.write(new Blob([content]));
1100
- // } else {
1101
- // throw new Error('Unsupported content type');
1102
- // }
1103
- // await writable.close();
1104
- // logger(`File written successfully: ${filePath}`);
1105
- // } catch (error) {
1106
- // console.error(`Error writing to OPFS: ${error.message}`);
1107
- // }
1108
- }
1109
- static saveFileSync(filePath, content) {
1110
- // Note: This is a synchronous wrapper, but zenfs operations may still be async under the hood
1111
- // For true sync operations in browser, we'd need to use OPFS sync access handles
1112
- // For now, we'll use zenfs.writeFileSync which should be available
1113
- const zenfs = this.getFsSync();
1114
- // Convert content to a format that zenfs.writeFileSync accepts
1115
- let writeContent;
1116
- if (typeof content === 'string') {
1117
- writeContent = content;
1118
- }
1119
- else if (content instanceof Blob) {
1120
- // Blob cannot be converted synchronously - throw error
1121
- throw new Error('Blob content not supported in saveFileSync. Use saveFile() instead or convert to ArrayBuffer first.');
1122
- }
1123
- else if (content instanceof ArrayBuffer) {
1124
- writeContent = new Uint8Array(content);
1125
- }
1126
- else {
1127
- throw new Error('Unsupported content type');
1128
- }
1129
- zenfs.writeFileSync(filePath, writeContent);
1130
- }
1131
- static async readFile(filePath) {
1132
- const zenfs = await this.getFs();
1133
- const maxAttempts = 3;
1134
- const baseDelayMs = 50;
1135
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
1136
- try {
1137
- const data = await zenfs.promises.readFile(filePath);
1138
- return new File([new Uint8Array(data)], filePath);
1139
- }
1140
- catch (error) {
1141
- if (!isTransientOpfsReadError(error) || attempt === maxAttempts - 1) {
1142
- throw error;
1143
- }
1144
- await sleep(baseDelayMs * (attempt + 1));
1145
- }
1146
- }
1147
- throw new Error('readFile: exhausted retries');
1148
- // try {
1149
- // // Get a handle to the OPFS root directory
1150
- // const root = await navigator.storage.getDirectory();
1151
- // // Split the file path into directory and file name
1152
- // const pathParts = filePath.split('/');
1153
- // const fileName = pathParts.pop();
1154
- // if (!fileName) throw new Error('Invalid file path');
1155
- // // Traverse directories to reach the target file
1156
- // let currentDir = root;
1157
- // for (const part of pathParts) {
1158
- // if (part !== '') {
1159
- // currentDir = await currentDir.getDirectoryHandle(part, { create: false });
1160
- // }
1161
- // }
1162
- // // Get the file handle
1163
- // const fileHandle = await currentDir.getFileHandle(fileName, { create: false });
1164
- // // Get the file and read it as an ArrayBuffer
1165
- // return await fileHandle.getFile();
1166
- // } catch (error) {
1167
- // console.error(`Error reading from OPFS: ${error.message}`);
1168
- // throw error;
1169
- // }
1170
- }
1171
- static readFileSync(filePath) {
1172
- // Note: This is a synchronous wrapper, but zenfs operations may still be async under the hood
1173
- // For true sync operations in browser, we'd need to use OPFS sync access handles
1174
- // For now, we'll use zenfs.readFileSync which should be available
1175
- const zenfs = this.getFsSync();
1176
- const file = zenfs.readFileSync(filePath);
1177
- return new File([new Uint8Array(file)], filePath);
1178
- }
1179
- static async readFileAsBuffer(filePath) {
1180
- try {
1181
- // Get the file and read it as an ArrayBuffer
1182
- const file = await this.readFile(filePath);
1183
- const arrayBuffer = await file.arrayBuffer();
1184
- // Convert ArrayBuffer to Blob
1185
- return new Blob([arrayBuffer]);
1186
- }
1187
- catch (error) {
1188
- const errorMessage = error instanceof Error ? error.message : String(error);
1189
- console.error(`Error reading from OPFS: ${errorMessage}`);
1190
- throw error;
1191
- }
1192
- }
1193
- static async readFileAsString(filePath) {
1194
- const blob = await this.readFileAsBuffer(filePath);
1195
- return blob.text();
1196
- }
1197
- static getParentDirPath(filePath) {
1198
- return pathCompat.dirname(filePath);
1199
- }
1200
- static getFilenameFromPath(filePath) {
1201
- return pathCompat.basename(filePath);
1202
- }
1203
- static getPathModule() {
1204
- return pathCompat;
1205
- }
1206
- }
1207
- FileManager.zenfsCache = null;
1208
- class CancelableInterval {
1209
- constructor(task, interval) {
1210
- this.task = task;
1211
- this.interval = interval;
1212
- this.intervalId = null;
1213
- this.currentTaskAbortController = null;
1214
- }
1215
- start() {
1216
- this.intervalId = window.setInterval(async () => {
1217
- if (this.currentTaskAbortController) {
1218
- // Cancel the previous running task
1219
- this.currentTaskAbortController.abort();
1220
- }
1221
- // Create a new abort controller for the current task
1222
- this.currentTaskAbortController = new AbortController();
1223
- const signal = this.currentTaskAbortController.signal;
1224
- try {
1225
- await this.taskWithCancellation(signal);
1226
- }
1227
- catch (error) {
1228
- if (error instanceof DOMException && error.name === 'AbortError') {
1229
- logger('Previous task was canceled.');
1230
- }
1231
- else {
1232
- console.error('Task error:', error);
1233
- }
1234
- this.stop();
1235
- }
1236
- }, this.interval);
1237
- }
1238
- async taskWithCancellation(signal) {
1239
- await this.task(() => this.stop());
1240
- if (signal.aborted) {
1241
- throw new DOMException('Task was aborted', 'AbortError');
1242
- }
1243
- }
1244
- stop() {
1245
- if (this.intervalId !== null) {
1246
- clearInterval(this.intervalId);
1247
- this.intervalId = null;
1248
- }
1249
- if (this.currentTaskAbortController) {
1250
- this.currentTaskAbortController.abort();
1251
- }
1252
- }
1253
- }
1254
-
1255
- export { FileManager };
1256
- //# sourceMappingURL=FileManager-5GkHtxF7.js.map