@seedprotocol/sdk 0.7.3-next.613.g79a8dfd → 0.7.3

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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPublishUploads-SFHCbf_y.js","sources":["../../src/helpers/mapWithConcurrency.ts","../../src/helpers/compositeUpload.ts","../../src/db/read/getPublishUploads.ts"],"sourcesContent":["/**\n * `Promise.all(items.map(fn))` with at most `limit` calls in flight. Results keep the input order.\n * Rejects with the first error (by time); after that no new calls start, though calls already in\n * flight run to completion.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n const workerCount = Math.max(1, Math.min(Math.floor(limit) || 1, items.length))\n let next = 0\n let failed = false\n\n const worker = async (): Promise<void> => {\n while (!failed && next < items.length) {\n const index = next++\n try {\n results[index] = await fn(items[index]!, index)\n } catch (error) {\n failed = true\n throw error\n }\n }\n }\n\n await Promise.all(Array.from({ length: workerCount }, worker))\n return results\n}\n","/**\n * Composite uploads: several ItemStorage files of one item in a single Arweave transaction.\n *\n * Producer: `getPublishUploads.ts` (`processUploadPropertyData`), for an item with a\n * `storageTransactionId` property and ItemStorage properties (e.g. a Post's `html` and `json`).\n * Consumer: the download worker (`browser/workers/filesDownload.ts`), which keeps its own copy of\n * {@link decodeCompositeUpload} because it runs from a string; a test keeps the two in step.\n *\n * Format (unchanged for text children, so composites already on Arweave still read):\n *\n * ===FILE_SEPARATOR===<name>===FILE_SEPARATOR===<utf-8 text> (repeated per child)\n *\n * A child that is not valid UTF-8 text (or whose text contains the separator) is written as\n * base64 under the name `<name>;base64`. Composites written before this suffix existed converted\n * every child to text, which corrupted binary children; those bytes cannot be recovered.\n */\nexport const COMPOSITE_SEPARATOR = '===FILE_SEPARATOR==='\nexport const COMPOSITE_BASE64_SUFFIX = ';base64'\n\nexport type CompositeChild = { name: string; bytes: Uint8Array }\n\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n let binary = ''\n const chunk = 0x8000\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk))\n }\n return btoa(binary)\n}\n\nconst base64ToBytes = (base64: string): Uint8Array | undefined => {\n try {\n const binary = atob(base64.replace(/\\s/g, ''))\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)\n return out\n } catch {\n return undefined\n }\n}\n\n/** The child's text when it can travel as text: valid UTF-8, no NUL bytes, no separator. */\nconst childAsText = (bytes: Uint8Array): string | undefined => {\n if (bytes.includes(0)) return undefined\n let text: string\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n } catch {\n return undefined\n }\n return text.includes(COMPOSITE_SEPARATOR) ? undefined : text\n}\n\nexport const encodeCompositeUpload = (children: CompositeChild[]): Uint8Array => {\n let composite = ''\n for (const { name, bytes } of children) {\n const text = childAsText(bytes)\n composite +=\n text !== undefined\n ? `${COMPOSITE_SEPARATOR}${name}${COMPOSITE_SEPARATOR}${text}`\n : `${COMPOSITE_SEPARATOR}${name}${COMPOSITE_BASE64_SUFFIX}${COMPOSITE_SEPARATOR}${bytesToBase64(bytes)}`\n }\n return new TextEncoder().encode(composite)\n}\n\nconst SEPARATOR_BYTES = new TextEncoder().encode(COMPOSITE_SEPARATOR)\n\n/** True when `bytes` start with the composite separator (checked on bytes, before any text heuristics). */\nexport const isCompositeUpload = (bytes: Uint8Array): boolean =>\n bytes.length >= SEPARATOR_BYTES.length && SEPARATOR_BYTES.every((b, i) => bytes[i] === b)\n\n/** Children of a composite, or `undefined` when `bytes` are not a well-formed composite. */\nexport const decodeCompositeUpload = (bytes: Uint8Array): CompositeChild[] | undefined => {\n if (!isCompositeUpload(bytes)) return undefined\n const parts = new TextDecoder('utf-8').decode(bytes).split(COMPOSITE_SEPARATOR).slice(1)\n if (parts.length % 2 !== 0) return undefined\n const encoder = new TextEncoder()\n const children: CompositeChild[] = []\n for (let i = 0; i < parts.length; i += 2) {\n const rawName = parts[i]!\n const content = parts[i + 1]!\n if (rawName.endsWith(COMPOSITE_BASE64_SUFFIX)) {\n const decoded = base64ToBytes(content)\n if (!decoded) return undefined\n children.push({ name: rawName.slice(0, -COMPOSITE_BASE64_SUFFIX.length), bytes: decoded })\n } else {\n children.push({ name: rawName, bytes: encoder.encode(content) })\n }\n }\n return children\n}\n","import { BaseFileManager } from '@/helpers'\nimport {\n getStorageDirForDataType,\n getItemStorageLocalFileName,\n getItemStorageSubdir,\n} from '@/helpers/storageDir'\nimport {\n isPublishedSeedRef,\n normalizeRelationPropertyValue,\n resolveSeedIdsFromRefString,\n} from '@/helpers/relationSeedRef'\nimport { BaseArweaveClient } from '@/helpers/ArweaveClient/BaseArweaveClient'\nimport { getSegmentedItemProperties } from '@/helpers/getSegmentedItemProperties'\nimport debug from 'debug'\nimport { IItem, IItemProperty } from '@/interfaces'\nimport { buildArweaveContentTags, getContentSha256 } from '@/helpers/arweaveContentTags'\nimport { Item } from '@/Item/Item'\nimport type { ArweaveTransaction, TransactionTag } from '@/types/arweave'\nimport type { PublishUpload, PublishUploadData } from '@/types/publish'\nimport { BaseDb } from '@/db/Db/BaseDb'\nimport { htmlEmbeddedImageCoPublish } from '@/seedSchema/HtmlEmbeddedImageCoPublishSchema'\nimport { and, eq } from 'drizzle-orm'\nimport { metadata, type MetadataType } from '@/seedSchema'\nimport { compareMetadataRowsLatestFirst } from '@/helpers/compareMetadataRowsLatestFirst'\nimport { ModelPropertyDataTypes, isDataType } from '@/helpers/property'\nimport { getPublishDraftGraph } from '@/db/read/publishDraftGraph'\nimport { resolveUploadMimeType } from '@/helpers/mimeTypes'\nimport { mapWithConcurrency } from '@/helpers/mapWithConcurrency'\nimport { encodeCompositeUpload, type CompositeChild } from '@/helpers/compositeUpload'\nimport {\n convertVerbatimItemStorageRow,\n isVerbatimItemStorageDraftRow,\n} from '@/db/write/convertVerbatimItemStorageRow'\n\nconst logger = debug('seedSdk:item:getPublishUploads')\n\n/** L1 transactions {@link getPublishUploads} creates at once (each asks the gateway for price and anchor). */\nexport const CREATE_TRANSACTION_CONCURRENCY = 4\n\n/** Optional tags merged into each Arweave tx after Content-SHA-256 / Content-Type. */\nexport type GetPublishUploadsOptions = {\n arweaveUploadTags?: TransactionTag[]\n /**\n * Html storage seed local ids to skip (phase 1 of two-phase embedded-image publish).\n */\n deferHtmlStorageSeedLocalIds?: string[]\n /**\n * When set, only Html storage seeds in this list are included (phase 2). Non-Html storage uploads are omitted.\n */\n onlyHtmlStorageSeedLocalIds?: string[]\n /** When true, do not recurse into relation properties (phase 2 must not re-upload related items). */\n skipRelationRecursion?: boolean\n}\n\nconst toUint8Array = async (data: Buffer | Blob): Promise<Uint8Array> => {\n if (typeof Blob !== 'undefined' && data instanceof Blob) {\n return new Uint8Array(await data.arrayBuffer())\n }\n return new Uint8Array(data as Buffer)\n}\n\n/** A local file's bytes plus its MIME type: the Blob's own type, else the name's extension, else a sniff of the bytes. */\nconst readUploadFile = async (\n filePath: string,\n fileName: string = filePath,\n): Promise<{ bytes: Uint8Array; contentType: string | undefined }> => {\n const data = await BaseFileManager.readFileAsBuffer(filePath)\n const bytes = await toUint8Array(data)\n const sourceType = typeof Blob !== 'undefined' && data instanceof Blob ? data.type : undefined\n return { bytes, contentType: resolveUploadMimeType({ sourceType, fileName, bytes }) }\n}\n\nexport const prepareArweaveTransaction = async (\n data: string | Uint8Array,\n contentHash: string | undefined,\n contentType?: string,\n additionalTags?: TransactionTag[],\n): Promise<ArweaveTransaction> => {\n const tags = buildArweaveContentTags(contentHash, contentType, additionalTags)\n\n const tx = await BaseArweaveClient.createTransaction(data, {\n tags: tags.length ? tags : undefined,\n })\n\n return tx\n}\n\ntype UploadTarget = Pick<\n PublishUploadData,\n 'itemPropertyName' | 'itemPropertyLocalId' | 'seedLocalId' | 'versionLocalId'\n>\n\n/**\n * The one place an upload's bytes become a {@link PublishUploadData}: everything after this\n * (Content-SHA-256, tags, the L1 transaction or the bundler DataItem, signing) works from what it\n * returns. A future private-publish option that encrypts content belongs here, before the hash and\n * tags are computed, so both publish paths pick it up.\n */\nconst buildPublishUploadData = (\n data: Uint8Array,\n contentType: string | undefined,\n target: UploadTarget,\n options: GetPublishUploadsOptions | undefined,\n): PublishUploadData => {\n const contentHash = getContentSha256(data)\n return {\n data,\n contentHash,\n contentType,\n tags: buildArweaveContentTags(contentHash, contentType, options?.arweaveUploadTags),\n ...target,\n }\n}\n\n\n\nconst DATA_URI_IMAGE = /^data:(image\\/[a-zA-Z0-9.+-]+);base64,([\\s\\S]*)$/i\n\nfunction decodeDataUriImage(dataUri: string): { mimeType: string; bytes: Uint8Array } | null {\n const m = DATA_URI_IMAGE.exec((dataUri ?? '').trim())\n if (!m) return null\n try {\n const mimeType = m[1]!.toLowerCase().trim()\n const base64 = m[2]!.replace(/\\s/g, '')\n const binary = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))\n return { mimeType, bytes: binary }\n } catch {\n return null\n }\n}\n\nconst getStorageSeedUploadData = async (\n itemStorageSeedProperties: IItemProperty<any>[],\n options?: GetPublishUploadsOptions,\n): Promise<PublishUploadData[]> => {\n const uploads: PublishUploadData[] = []\n\n for (const itemProperty of itemStorageSeedProperties) {\n const snapshot = itemProperty.getService().getSnapshot()\n const context = 'context' in snapshot ? snapshot.context : null\n if (!context) {\n continue\n }\n const propertyValue = (context as any).propertyValue\n const refResolvedValue = (context as any).refResolvedValue\n if (!refResolvedValue) {\n continue\n }\n\n // propertyValue is the storage seed's seedLocalId; use it for the upload so processRelationOrImageProperty can match\n const { seedLocalId } = resolveSeedIdsFromRefString(\n normalizeRelationPropertyValue(propertyValue) ?? '',\n )\n if (!seedLocalId) {\n continue\n }\n\n const dataType =\n itemProperty.propertyDef?.refValueType ??\n itemProperty.propertyDef?.dataType ??\n 'Image'\n\n if (isDataType(dataType, ModelPropertyDataTypes.Html)) {\n if (options?.deferHtmlStorageSeedLocalIds?.includes(seedLocalId)) {\n continue\n }\n if (\n options?.onlyHtmlStorageSeedLocalIds?.length &&\n !options.onlyHtmlStorageSeedLocalIds.includes(seedLocalId)\n ) {\n continue\n }\n } else if (options?.onlyHtmlStorageSeedLocalIds?.length) {\n continue\n }\n\n const baseDir = getStorageDirForDataType(dataType)\n const filePath = `${baseDir}/${refResolvedValue}`\n\n const exists = await BaseFileManager.pathExists(filePath)\n if (!exists) {\n continue\n }\n\n const { bytes: fileContents, contentType } = await readUploadFile(filePath, refResolvedValue)\n\n uploads.push(\n buildPublishUploadData(\n fileContents,\n contentType,\n {\n itemPropertyName: itemProperty.propertyName,\n itemPropertyLocalId: itemProperty.localId,\n seedLocalId,\n versionLocalId: itemProperty.versionLocalId!,\n },\n options,\n ),\n )\n }\n\n return uploads\n}\n\nasync function appendCoPublishedImageUploadData(\n item: IItem<any>,\n uploads: PublishUploadData[],\n options?: GetPublishUploadsOptions,\n): Promise<PublishUploadData[]> {\n const appDb = BaseDb.getAppDb()\n if (!appDb || options?.onlyHtmlStorageSeedLocalIds?.length) return uploads\n\n const rows = await appDb\n .select()\n .from(htmlEmbeddedImageCoPublish)\n .where(eq(htmlEmbeddedImageCoPublish.parentSeedLocalId, item.seedLocalId))\n\n const seen = new Set(uploads.map((u) => u.seedLocalId))\n\n for (const row of rows) {\n if (seen.has(row.imageSeedLocalId)) continue\n const imageItem = await Item.find({ seedLocalId: row.imageSeedLocalId, modelName: 'Image' })\n if (!imageItem) continue\n const st =\n imageItem.internalProperties['storageTransactionId'] ??\n imageItem.allProperties['storageTransactionId']\n const stSnap = st?.getService().getSnapshot()\n const stCtx = stSnap && 'context' in stSnap ? stSnap.context : undefined\n const stValue = typeof (stCtx as { propertyValue?: unknown } | undefined)?.propertyValue === 'string'\n ? ((stCtx as { propertyValue?: string }).propertyValue ?? '')\n : ''\n const decoded = decodeDataUriImage(stValue)\n\n const more: PublishUploadData[] = []\n if (decoded && st && st.localId && st.versionLocalId) {\n more.push(\n buildPublishUploadData(\n decoded.bytes,\n decoded.mimeType,\n {\n itemPropertyName: st.propertyName,\n itemPropertyLocalId: st.localId,\n seedLocalId: imageItem.seedLocalId,\n versionLocalId: st.versionLocalId,\n },\n options,\n ),\n )\n }\n for (const u of more) {\n if (!seen.has(u.seedLocalId)) {\n uploads.push(u)\n seen.add(u.seedLocalId)\n }\n }\n }\n return uploads\n}\n\nexport type UploadProperty = {\n itemProperty: IItemProperty<any>\n childProperties: IItemProperty<any>[]\n}\ntype ChildUploadData = {\n propertyName: string\n localStoragePath: string\n}\n\nconst isUsablePath = (filePath: string | void | null | undefined): filePath is string =>\n !!filePath && !filePath.endsWith('undefined') && !filePath.endsWith('null')\n\n/** The newest metadata row of an ItemStorage property, read from the DB (not the live query). */\nconst getLatestItemStorageRow = async (\n childProperty: IItemProperty<any>,\n): Promise<MetadataType | undefined> => {\n const appDb = BaseDb.getAppDb()\n const seedLocalId = childProperty.seedLocalId\n const propertyName = childProperty.storagePropertyName || childProperty.propertyName\n if (!appDb || !seedLocalId || !propertyName) return undefined\n const where = [eq(metadata.seedLocalId, seedLocalId), eq(metadata.propertyName, propertyName)]\n if (childProperty.versionLocalId) where.push(eq(metadata.versionLocalId, childProperty.versionLocalId))\n const rows: MetadataType[] = await appDb.select().from(metadata).where(and(...where))\n return [...rows].sort(compareMetadataRowsLatestFirst)[0]\n}\n\n/**\n * Write a legacy ItemStorage draft row's verbatim content to `<seedUid or seedLocalId><extension>`\n * and record it on the row (refResolvedValue, localStorageDir) and in the property context. The\n * row's propertyValue is cleared once the file is written, so the row has the same shape as one a\n * save makes and a later edit of the file never leaves stale text behind it.\n */\nconst migrateVerbatimItemStorageRow = async (\n childProperty: IItemProperty<any>,\n row: MetadataType,\n): Promise<string | undefined> => {\n const seedId = row.seedUid || childProperty.seedUid || row.seedLocalId || childProperty.seedLocalId\n if (!seedId || !row.localId) return undefined\n const propertyDef = childProperty.propertyDef\n const converted = await convertVerbatimItemStorageRow(row.localId, {\n seedId,\n localStorageDir: propertyDef?.localStorageDir || row.localStorageDir,\n filenameSuffix: propertyDef?.filenameSuffix,\n })\n if (!converted) return undefined\n const { fileName, filePath, localStorageDir, content } = converted\n // The content is still the value: keep it as renderValue (the property may show it from propertyValue).\n childProperty.getService().send({\n type: 'updateContext',\n refResolvedValue: fileName,\n localStorageDir,\n renderValue: content,\n })\n logger(`resolveItemStorageChildFile: wrote verbatim ${childProperty.propertyName} content to ${filePath}`)\n return filePath\n}\n\n/**\n * Local file of one ItemStorage child of a composite upload. Tries, in order: the property's\n * localStoragePath (context set by save / hydration / the live query), its newest metadata row's\n * refResolvedValue + localStorageDir, then (for a local draft whose propertyValue is the content\n * itself, as rows made before Item.create saved ItemStorage values) that content written to its\n * file, then (for a local draft, or no row) the name\n * saveItemStorage gives a new file (`<seedUid or seedLocalId><extension>` in the model's storage\n * directory). A published or derived row is never swapped for a local file of another name: that\n * file would be older content.\n *\n * `missingLocalEdit` lists the paths tried when nothing exists although the newest row is a saved\n * local edit (no attestation uid, not derived from one, refResolvedValue set by saveItemStorage):\n * that edit's file should be there. A published or derived row without a file (e.g. content not\n * downloaded, or a property the composite never had) is skipped as before.\n */\nexport const resolveItemStorageChildFile = async (\n childProperty: IItemProperty<any>,\n): Promise<{ filePath?: string; missingLocalEdit?: string[] }> => {\n const tried: string[] = []\n const tryPath = async (filePath: string | void | null | undefined): Promise<string | undefined> => {\n if (!isUsablePath(filePath) || tried.includes(filePath)) return undefined\n tried.push(filePath)\n return (await BaseFileManager.pathExists(filePath)) ? filePath : undefined\n }\n\n const fromContext = await tryPath(childProperty.localStoragePath)\n if (fromContext) return { filePath: fromContext }\n\n const row = await getLatestItemStorageRow(childProperty).catch((error) => {\n logger('resolveItemStorageChildFile: metadata lookup failed', error)\n return undefined\n })\n const propertyDef = childProperty.propertyDef\n const dir = getItemStorageSubdir(propertyDef?.localStorageDir || row?.localStorageDir)\n\n if (row?.refResolvedValue) {\n const fromRow = await tryPath(BaseFileManager.getFilesPath(dir, row.refResolvedValue))\n if (fromRow) return { filePath: fromRow }\n }\n\n const isLocalDraft = !!row && !row.uid && row.derivedFromUid == null\n\n // A local draft holding the content itself (no file reference): what Item.create / createNewItem\n // stored for ItemStorage values before they went through the save pipeline. Write it to the file a\n // save would have, point the row and the property at it, and upload that.\n if (row && isVerbatimItemStorageDraftRow(row)) {\n const migrated = await migrateVerbatimItemStorageRow(childProperty, row).catch((error) => {\n logger('resolveItemStorageChildFile: writing verbatim ItemStorage content failed', error)\n return undefined\n })\n if (migrated) return { filePath: migrated }\n }\n\n const suffix = propertyDef?.filenameSuffix\n const seedIds = !row || isLocalDraft\n ? [row?.seedUid, childProperty.seedUid, row?.seedLocalId, childProperty.seedLocalId]\n : []\n for (const seedId of seedIds) {\n if (!seedId) continue\n const derived = await tryPath(\n BaseFileManager.getFilesPath(dir, getItemStorageLocalFileName(seedId, suffix)),\n )\n if (derived) return { filePath: derived }\n }\n\n // saveItemStorage sets refResolvedValue on the draft row once the file is written. A draft row\n // without one is the empty row createNewItem makes for every model property: nothing to upload.\n return isLocalDraft && !!row?.refResolvedValue ? { missingLocalEdit: tried } : {}\n}\n\n/**\n * True if publish would include at least one Arweave upload (local file / storage seed present).\n * Does not create Arweave transactions or hit the network — use for routing (e.g. skip EAS-only)\n * when {@link getPublishUploads} would fail early (e.g. gateway unreachable during tx creation).\n */\nasync function storageSeedHasUploadCandidates(\n itemStorageSeedProperties: IItemProperty<any>[],\n): Promise<boolean> {\n for (const itemProperty of itemStorageSeedProperties) {\n const snapshot = itemProperty.getService().getSnapshot()\n const context = 'context' in snapshot ? snapshot.context : null\n if (!context) {\n continue\n }\n const propertyValue = (context as any).propertyValue\n const refResolvedValue = (context as any).refResolvedValue\n if (!refResolvedValue) {\n continue\n }\n\n const { seedLocalId } = resolveSeedIdsFromRefString(\n normalizeRelationPropertyValue(propertyValue) ?? '',\n )\n if (!seedLocalId) {\n continue\n }\n\n const dataType =\n itemProperty.propertyDef?.refValueType ??\n itemProperty.propertyDef?.dataType ??\n 'Image'\n const baseDir = getStorageDirForDataType(dataType)\n const filePath = `${baseDir}/${refResolvedValue}`\n\n if (await BaseFileManager.pathExists(filePath)) {\n return true\n }\n }\n\n return false\n}\n\nasync function uploadPropertyWouldUpload(\n uploadProperty: UploadProperty,\n relatedItemProperty?: IItemProperty<any>,\n): Promise<boolean> {\n\n for (const childProperty of uploadProperty.childProperties) {\n // Not strict: a local edit whose file is missing still means \"would upload\", so the publish\n // goes ahead and fails loudly in processUploadPropertyData instead of skipping the upload.\n const resolved = await resolveItemStorageChildFile(childProperty)\n if (resolved.filePath || resolved.missingLocalEdit) {\n return true\n }\n }\n\n if (relatedItemProperty && relatedItemProperty.localStoragePath) {\n const filePath = relatedItemProperty.localStoragePath\n\n if (!filePath || filePath.endsWith('undefined')) {\n return false\n }\n\n return await BaseFileManager.pathExists(filePath)\n }\n\n return false\n}\n\nasync function itemOwnUploadCandidates(\n item: IItem<any>,\n relatedItemProperty: IItemProperty<any> | undefined,\n recurseStorageRelations: boolean,\n): Promise<boolean> {\n const { itemUploadProperties, itemRelationProperties, itemImageProperties } =\n await getSegmentedItemProperties(item)\n\n for (const uploadProperty of itemUploadProperties) {\n if (await uploadPropertyWouldUpload(uploadProperty, relatedItemProperty)) {\n return true\n }\n }\n\n if (await storageSeedHasUploadCandidates(itemImageProperties)) {\n return true\n }\n\n if (!recurseStorageRelations) return false\n const storageProperties = new Set(itemImageProperties)\n for (const relationProperty of itemRelationProperties) {\n if (!storageProperties.has(relationProperty)) continue\n const snapshot = relationProperty.getService().getSnapshot()\n const context = 'context' in snapshot ? snapshot.context : null\n if (!context) {\n continue\n }\n const propertyValue = (context as any).propertyValue\n\n if (!propertyValue || relationProperty.uid) {\n continue\n }\n\n const { seedLocalId, seedUid } = resolveSeedIdsFromRefString(\n normalizeRelationPropertyValue(propertyValue) ?? '',\n )\n if (!seedLocalId && !seedUid) {\n throw new Error(\n `Invalid relation value for ${relationProperty.propertyName}: expected local seed id or 0x uid`,\n )\n }\n\n const relatedItem = await Item.find({\n seedLocalId,\n seedUid,\n })\n\n if (!relatedItem) {\n // Related seed referenced by attested uid with no local copy: already published, nothing to upload.\n if (isPublishedSeedRef(propertyValue)) continue\n throw new Error(\n `No relatedItem found for ${relationProperty.propertyName}`,\n )\n }\n\n if (await itemOwnUploadCandidates(relatedItem, relationProperty, false)) {\n return true\n }\n }\n\n return false\n}\n\n/** Same walk as getPublishUploads: the item and the draft items its publish carries along. */\nexport async function itemHasPublishUploadCandidates(\n item: IItem<any>,\n relatedItemProperty?: IItemProperty<any>,\n): Promise<boolean> {\n if (await itemOwnUploadCandidates(item, relatedItemProperty, true)) return true\n const { drafts } = await getPublishDraftGraph(item, { strict: true })\n for (const { item: draft, via, viaList } of drafts) {\n if (await itemOwnUploadCandidates(draft, viaList ? undefined : via, true)) return true\n }\n return false\n}\n\nconst processUploadPropertyData = async (\n uploadProperty: UploadProperty,\n uploads: PublishUploadData[],\n relatedItemProperty?: IItemProperty<any>,\n options?: GetPublishUploadsOptions,\n): Promise<PublishUploadData[]> => {\n const itemProperty = uploadProperty.itemProperty\n\n const childUploads: ChildUploadData[] = []\n\n for (const childProperty of uploadProperty.childProperties) {\n const { filePath, missingLocalEdit } = await resolveItemStorageChildFile(childProperty)\n\n if (!filePath) {\n if (missingLocalEdit) {\n // Uploading without it would publish a composite that silently lacks this edit.\n throw new Error(\n `Cannot publish ${itemProperty.seedLocalId}: the local file for ${childProperty.propertyName} ` +\n `was not found (looked in ${missingLocalEdit.join(', ')})`,\n )\n }\n continue\n }\n\n childUploads.push({\n propertyName: childProperty.propertyName,\n localStoragePath: filePath,\n })\n }\n\n let fileContents\n let fileContentType: string | undefined\n\n if (!childUploads || childUploads.length === 0) {\n if (relatedItemProperty && relatedItemProperty.localStoragePath) {\n const filePath = relatedItemProperty.localStoragePath\n\n if (!filePath || filePath.endsWith('undefined')) {\n return uploads\n }\n\n const exists = await BaseFileManager.pathExists(filePath)\n if (!exists) {\n return uploads\n }\n\n try {\n const read = await readUploadFile(filePath)\n fileContents = read.bytes\n fileContentType = read.contentType\n } catch (e) {\n const fs = await BaseFileManager.getFs()\n fileContents = await toUint8Array(fs.readFileSync(filePath))\n fileContentType = resolveUploadMimeType({ fileName: filePath, bytes: fileContents })\n }\n }\n if (!fileContents) {\n return uploads\n }\n }\n\n if (childUploads.length > 0) {\n // Composite of the item's ItemStorage files; see helpers/compositeUpload.ts for the format.\n // Children are read as bytes: a binary child is base64-framed instead of decoded as text.\n const children: CompositeChild[] = []\n const fs = await BaseFileManager.getFs()\n for (const childUpload of childUploads) {\n let childUploadContents: Uint8Array | string\n try {\n childUploadContents = await fs.promises.readFile(childUpload.localStoragePath)\n } catch (e) {\n childUploadContents = fs.readFileSync(childUpload.localStoragePath)\n }\n children.push({\n name: childUpload.propertyName,\n bytes:\n typeof childUploadContents === 'string'\n ? new TextEncoder().encode(childUploadContents)\n : new Uint8Array(childUploadContents),\n })\n }\n fileContents = encodeCompositeUpload(children)\n }\n\n if (!fileContents) {\n throw new Error(`No file contents found for ${itemProperty.propertyName}`)\n }\n\n const uint8Array = new Uint8Array(fileContents)\n\n let contentType: string | undefined\n if (childUploads.length === 0 && relatedItemProperty?.localStoragePath) {\n contentType = fileContentType\n } else if (childUploads.length > 0) {\n contentType = 'application/octet-stream'\n }\n\n let itemPropertyLocalId = relatedItemProperty\n ? relatedItemProperty.localId\n : itemProperty.localId\n let itemPropertyName = relatedItemProperty\n ? relatedItemProperty.propertyName\n : itemProperty.propertyName\n\n uploads.push(\n buildPublishUploadData(\n uint8Array,\n contentType,\n {\n itemPropertyName,\n itemPropertyLocalId,\n seedLocalId: itemProperty.seedLocalId!,\n versionLocalId: itemProperty.versionLocalId!,\n },\n options,\n ),\n )\n\n return uploads\n}\n\n/** No seed uid yet: a related item in this state is published together with the item. */\nconst isDraftItem = (item: IItem<any>): boolean =>\n !item.seedUid || item.seedUid === '0x' + '0'.repeat(64)\n\n/** One item's own uploads: its files, storage seeds, Html-embedded images, and the items its storage relations point at. */\nconst getItemOwnPublishUploadData = async (\n item: IItem<any>,\n uploads: PublishUploadData[],\n relatedItemProperty: IItemProperty<any> | undefined,\n options: GetPublishUploadsOptions | undefined,\n): Promise<PublishUploadData[]> => {\n const { itemUploadProperties, itemRelationProperties, itemImageProperties } =\n await getSegmentedItemProperties(item)\n\n // Phase 2 of an embedded-image publish: only the deferred Html storage seeds, of this item and of\n // the related items published with it (whose Html can embed images too).\n const onlyDeferredHtml = !!options?.onlyHtmlStorageSeedLocalIds?.length\n if (onlyDeferredHtml) {\n const storageSeedUploads = await getStorageSeedUploadData(itemImageProperties, options)\n uploads.push(...storageSeedUploads)\n } else {\n for (const uploadProperty of itemUploadProperties) {\n uploads = await processUploadPropertyData(\n uploadProperty,\n uploads,\n relatedItemProperty,\n options,\n )\n }\n\n const storageSeedUploads = await getStorageSeedUploadData(itemImageProperties, options)\n uploads.push(...storageSeedUploads)\n\n // Images embedded in this item's Html: the published item's, and a related draft's published with it.\n if (!relatedItemProperty || isDraftItem(item)) {\n uploads = await appendCoPublishedImageUploadData(item, uploads, options)\n }\n }\n\n if (options?.skipRelationRecursion) {\n return uploads\n }\n\n // Relations to Image/File/Html/Json items: their file, read through the relation property.\n const storageProperties = new Set(itemImageProperties)\n for (const relationProperty of itemRelationProperties) {\n if (!storageProperties.has(relationProperty)) continue\n const snapshot = relationProperty.getService().getSnapshot()\n const context = 'context' in snapshot ? snapshot.context : null\n if (!context) {\n continue\n }\n const propertyValue = (context as any).propertyValue\n\n if (!propertyValue || relationProperty.uid) {\n continue\n }\n\n const { seedLocalId, seedUid } = resolveSeedIdsFromRefString(\n normalizeRelationPropertyValue(propertyValue) ?? '',\n )\n if (!seedLocalId && !seedUid) {\n throw new Error(\n `Invalid relation value for ${relationProperty.propertyName}: expected local seed id or 0x uid`,\n )\n }\n\n const relatedItem = await Item.find({\n seedLocalId,\n seedUid,\n })\n\n if (!relatedItem) {\n // Related seed referenced by attested uid with no local copy: already published, nothing to upload.\n if (isPublishedSeedRef(propertyValue)) continue\n throw new Error(\n `No relatedItem found for ${relationProperty.propertyName}`,\n )\n }\n\n uploads = await getItemOwnPublishUploadData(relatedItem, uploads, relationProperty, {\n ...options,\n skipRelationRecursion: true,\n })\n }\n\n return uploads\n}\n\n/**\n * Upload data for a publish of `item`: its own, and that of every draft item the publish carries\n * along (reachable through relation and list properties, see publishDraftGraph.ts). Raw bytes plus\n * Content-SHA-256 / Content-Type / configured tags; no Arweave transaction is created, so this\n * does not touch the network. The bundler path in `@seedprotocol/publish` signs these as\n * DataItems; {@link getPublishUploads} turns them into L1 transactions.\n */\nexport const getPublishUploadData = async (\n item: IItem<any>,\n uploads: PublishUploadData[] = [],\n relatedItemProperty?: IItemProperty<any>,\n options?: GetPublishUploadsOptions,\n): Promise<PublishUploadData[]> => {\n uploads = await getItemOwnPublishUploadData(item, uploads, relatedItemProperty, options)\n\n if (options?.skipRelationRecursion) {\n return uploads\n }\n\n const { drafts } = await getPublishDraftGraph(item, { strict: true })\n for (const { item: draft, via, viaList } of drafts) {\n uploads = await getItemOwnPublishUploadData(draft, uploads, viaList ? undefined : via, options)\n }\n\n return uploads\n}\n\n/**\n * Arweave L1 transactions for a publish of `item`: {@link getPublishUploadData}, each made into an\n * unsigned transaction carrying the same tags.\n */\nexport const getPublishUploads = async (\n item: IItem<any>,\n uploads: PublishUpload[] = [],\n relatedItemProperty?: IItemProperty<any>,\n options?: GetPublishUploadsOptions,\n): Promise<PublishUpload[]> => {\n const uploadData = await getPublishUploadData(item, [], relatedItemProperty, options)\n // Each createTransaction fetches the price / anchor from the gateway: run a few at once.\n const created = await mapWithConcurrency(uploadData, CREATE_TRANSACTION_CONCURRENCY, async (upload) => ({\n itemPropertyName: upload.itemPropertyName,\n itemPropertyLocalId: upload.itemPropertyLocalId,\n seedLocalId: upload.seedLocalId,\n versionLocalId: upload.versionLocalId,\n transactionToSign: await BaseArweaveClient.createTransaction(upload.data, {\n tags: upload.tags.length ? upload.tags : undefined,\n }),\n }))\n uploads.push(...created)\n return uploads\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;AAIG;AACI,eAAe,kBAAkB,CACtC,KAAmB,EACnB,KAAa,EACb,EAA0C,EAAA;IAE1C,MAAM,OAAO,GAAG,IAAI,KAAK,CAAI,KAAK,CAAC,MAAM,CAAC;IAC1C,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC/E,IAAI,IAAI,GAAG,CAAC;IACZ,IAAI,MAAM,GAAG,KAAK;AAElB,IAAA,MAAM,MAAM,GAAG,YAA0B;QACvC,OAAO,CAAC,MAAM,IAAI,IAAI,GAAG,KAAK,CAAC,MAAM,EAAE;AACrC,YAAA,MAAM,KAAK,GAAG,IAAI,EAAE;AACpB,YAAA,IAAI;AACF,gBAAA,OAAO,CAAC,KAAK,CAAC,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,KAAK,CAAE,EAAE,KAAK,CAAC;YACjD;YAAE,OAAO,KAAK,EAAE;gBACd,MAAM,GAAG,IAAI;AACb,gBAAA,MAAM,KAAK;YACb;QACF;AACF,IAAA,CAAC;AAED,IAAA,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,MAAM,CAAC,CAAC;AAC9D,IAAA,OAAO,OAAO;AAChB;;AC7BA;;;;;;;;;;;;;;;AAeG;AACI,MAAM,mBAAmB,GAAG,sBAAsB;AAClD,MAAM,uBAAuB,GAAG,SAAS;AAIhD,MAAM,aAAa,GAAG,CAAC,KAAiB,KAAY;IAClD,IAAI,MAAM,GAAG,E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,SAAS,GAAG,GAAG,EAAE,OAAO,CAAC;IACjG;AAEA,IAAA,OAAO,OAAO;AAChB;AAEA;;;AAGG;AACI,MAAM,iBAAiB,GAAG,OAC/B,IAAgB,EAChB,OAAA,GAA2B,EAAE,EAC7B,mBAAwC,EACxC,OAAkC,KACN;AAC5B,IAAA,MAAM,UAAU,GAAG,MAAM,oBAAoB,CAAC,IAAI,EAAE,EAAE,EAAE,mBAAmB,EAAE,OAAO,CAAC;;AAErF,IAAA,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,UAAU,EAAE,8BAA8B,EAAE,OAAO,MAAM,MAAM;QACtG,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;QACzC,mBAAmB,EAAE,MAAM,CAAC,mBAAmB;QAC/C,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,iBAAiB,EAAE,MAAM,iBAAiB,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,EAAE;AACxE,YAAA,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,GAAG,SAAS;SACnD,CAAC;AACH,KAAA,CAAC,CAAC;AACH,IAAA,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC;AACxB,IAAA,OAAO,OAAO;AAChB;;"}
@@ -1,11 +1,9 @@
1
1
  import { fromCallback, fromPromise, setup, assign, createActor } from 'xstate';
2
- import { a as BaseDb, j as models, p as properties, K as isInternalSchema, g as modelSchemas, s as schemas } from './BasePathResolver-BdxCSIzn.js';
2
+ import { E as BaseDb, s as models, u as properties, $ as generateId, aF as isInternalSchema, aG as writeModelToDb, aH as writePropertyToDb, aI as addSchemaToDb, q as modelSchemas, z as schemas, F as AmbiguousModelError, aJ as renameModelInDb, a as TProperty } from './BasePathResolver-Cm4apKRb.js';
3
3
  import { eq, and, isNull, or } from 'drizzle-orm';
4
- import { b as generateId } from './tabEvents-BZJMY5uK.js';
5
4
  import debug from 'debug';
6
- import { G as writeModelToDb, K as writePropertyToDb, O as addSchemaToDb, A as AmbiguousModelError, Q as renameModelInDb, d as TProperty } from './db-CQt-gcAl.js';
7
- import { j as waitForEntityIdle, S as getInvariantSafePropertyDescriptor, m as findEntity, C as ClientManagerState, I as Item, T as clearDestroySubscriptions, n as forceRemoveFromCaches, U as unloadEntity, o as runDestroyLifecycle } from './Item-D4FigtYS.js';
8
- import { h as getClient } from './ClientManager-DDA9956Y.js';
5
+ import { n as waitForEntityIdle, D as DEFAULT_READY_TIMEOUT_MS, $ as getInvariantSafePropertyDescriptor, q as findEntity, C as ClientManagerState, I as Item, a0 as clearDestroySubscriptions, t as forceRemoveFromCaches, a1 as unloadEntity, u as runDestroyLifecycle } from './Item-DBFchXpC.js';
6
+ import { k as getClient } from './ClientManager-i3nJASkg.js';
9
7
  import { modelPropertiesToObject } from './model-DGMe-TTm.js';
10
8
  import { toSnakeCase } from 'drizzle-orm/casing';
11
9
  import { Type } from '@sinclair/typebox';
@@ -37,7 +35,7 @@ const createPropertyInstances = async (propertyFileIds) => {
37
35
  return;
38
36
  }
39
37
  try {
40
- const mod = await import('./ModelProperty-BDt6AU2h.js');
38
+ const mod = await import('./ModelProperty-BS49g01Y.js');
41
39
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
42
40
  if (!ModelProperty) {
43
41
  logger$7('createPropertyInstances: ModelProperty not available from dynamic import');
@@ -103,11 +101,11 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context }, self })
103
101
  if (!modelRecord) {
104
102
  // Model names are only unique per schema: prefer this schema's row, and otherwise only
105
103
  // consider same-name rows that no schema claims yet (never another schema's model).
106
- const _mod_0 = await import('./BasePathResolver-BdxCSIzn.js');
107
- const _ns_0 = _mod_0.R;
104
+ const _mod_0 = await import('./BasePathResolver-Cm4apKRb.js');
105
+ const _ns_0 = _mod_0.b0;
108
106
  const { modelSchemas } = _ns_0;
109
- const _mod_1 = await import('./BasePathResolver-BdxCSIzn.js');
110
- const _ns_1 = _mod_1.Q;
107
+ const _mod_1 = await import('./BasePathResolver-Cm4apKRb.js');
108
+ const _ns_1 = _mod_1.a$;
111
109
  const { schemas: schemasTable } = _ns_1;
112
110
  let dbModels = await db
113
111
  .select({
@@ -254,7 +252,7 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context }, self })
254
252
  // Step 2: Fallback to Schema context (only if database doesn't have the model)
255
253
  // This handles the case where model exists in schema file but not yet in database
256
254
  try {
257
- const _mod_2 = await import('./Schema-B8xqLWkL.js');
255
+ const _mod_2 = await import('./Schema-CpMNEnUO.js');
258
256
  const _ns_2 = _mod_2.b;
259
257
  const schemaMod = _ns_2;
260
258
  const { Schema } = schemaMod;
@@ -405,12 +403,12 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context }, self })
405
403
  }
406
404
  // Also check database for models (in case they're persisted but not in Schema context)
407
405
  if (db) {
408
- const _mod_3 = await import('./BasePathResolver-BdxCSIzn.js');
409
- const _ns_3 = _mod_3.R;
406
+ const _mod_3 = await import('./BasePathResolver-Cm4apKRb.js');
407
+ const _ns_3 = _mod_3.b0;
410
408
  const modelSchemaSchemaMod = _ns_3;
411
409
  const { modelSchemas } = modelSchemaSchemaMod;
412
- const _mod_4 = await import('./BasePathResolver-BdxCSIzn.js');
413
- const _ns_4 = _mod_4.Q;
410
+ const _mod_4 = await import('./BasePathResolver-Cm4apKRb.js');
411
+ const _ns_4 = _mod_4.a$;
414
412
  const schemaSchemaMod = _ns_4;
415
413
  const { schemas: schemasTable } = schemaSchemaMod;
416
414
  // Query all models for this schema to check for duplicates (case-insensitive)
@@ -505,7 +503,7 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context }, self })
505
503
  }
506
504
  // Mark schema as draft when a new model is created so saveNewVersion() can persist it
507
505
  try {
508
- const _mod_5 = await import('./Schema-B8xqLWkL.js');
506
+ const _mod_5 = await import('./Schema-CpMNEnUO.js');
509
507
  const _ns_5 = _mod_5.b;
510
508
  const schemaMod = _ns_5;
511
509
  const { Schema } = schemaMod;
@@ -553,10 +551,10 @@ const validateModel = fromCallback(({ sendBack, input: { context }, self }) => {
553
551
  const _validateModel = async () => {
554
552
  try {
555
553
  // Use dynamic imports to break circular dependencies
556
- const validationServiceMod = await import('./SchemaValidationService-BPxkfDLU.js');
554
+ const validationServiceMod = await import('./SchemaValidationService-DieV4KL-.js');
557
555
  const { SchemaValidationService } = validationServiceMod;
558
556
  const validationService = new SchemaValidationService();
559
- const _mod_6 = await import('./Schema-B8xqLWkL.js');
557
+ const _mod_6 = await import('./Schema-CpMNEnUO.js');
560
558
  const _ns_6 = _mod_6.b;
561
559
  const schemaMod = _ns_6;
562
560
  const { Schema } = schemaMod;
@@ -675,7 +673,7 @@ const createModelProperties = fromCallback(({ sendBack, input, self }) => {
675
673
  return;
676
674
  }
677
675
  logger$5(`Creating ${Object.keys(propertyDefinitions).length} properties for model "${modelName}" (id: ${_dbId})`);
678
- const mod = await import('./ModelProperty-BDt6AU2h.js');
676
+ const mod = await import('./ModelProperty-BS49g01Y.js');
679
677
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
680
678
  if (!ModelProperty) {
681
679
  logger$5('ModelProperty not available from dynamic import');
@@ -700,8 +698,8 @@ const createModelProperties = fromCallback(({ sendBack, input, self }) => {
700
698
  : undefined;
701
699
  // Otherwise use provided ID or generate a random one
702
700
  // IDs should be generated in the import process before creating properties
703
- const _mod_7 = await import('./tabEvents-BZJMY5uK.js');
704
- const _ns_7 = _mod_7.P;
701
+ const _mod_7 = await import('./BasePathResolver-Cm4apKRb.js');
702
+ const _ns_7 = _mod_7.b4;
705
703
  const { generateId } = _ns_7;
706
704
  const propertyFileId = propData.id || propertyRecord?.schemaFileId || generateId();
707
705
  logger$5(`Creating property "${propName}" with fileId "${propertyFileId}"`);
@@ -718,8 +716,8 @@ const createModelProperties = fromCallback(({ sendBack, input, self }) => {
718
716
  }
719
717
  else if (refModelName) {
720
718
  // Fallback: resolve the ref by name within this model's schema
721
- const _mod_8 = await import('./db-CQt-gcAl.js');
722
- const _ns_8 = _mod_8.Y;
719
+ const _mod_8 = await import('./BasePathResolver-Cm4apKRb.js');
720
+ const _ns_8 = _mod_8.b1;
723
721
  const { resolveModelRecord } = _ns_8;
724
722
  const refModelRecord = await resolveModelRecord(refModelName, { schemaName }, db);
725
723
  if (refModelRecord?.id) {
@@ -819,7 +817,7 @@ const validateEntity = fromPromise(async ({ input }) => {
819
817
  const evictionEpoch = currentEvictionEpoch();
820
818
  /** The schema to validate against; throws (validation then skips the schema check) once it was evicted. */
821
819
  const schemaForValidation = async (schemaName) => {
822
- const _mod_9 = await import('./Schema-B8xqLWkL.js');
820
+ const _mod_9 = await import('./Schema-CpMNEnUO.js');
823
821
  const _ns_9 = _mod_9.b;
824
822
  const { Schema } = _ns_9;
825
823
  if (schemaEvictedSince(schemaName, evictionEpoch)) {
@@ -837,7 +835,7 @@ const validateEntity = fromPromise(async ({ input }) => {
837
835
  const structureMsg = `[validateEntity] Validating model structure`;
838
836
  logger$4(structureMsg);
839
837
  // Use existing Model validation
840
- const validationServiceMod = await import('./SchemaValidationService-BPxkfDLU.js');
838
+ const validationServiceMod = await import('./SchemaValidationService-DieV4KL-.js');
841
839
  const { SchemaValidationService } = validationServiceMod;
842
840
  const validationService = new SchemaValidationService();
843
841
  // Validate model structure
@@ -887,7 +885,7 @@ const validateEntity = fromPromise(async ({ input }) => {
887
885
  }
888
886
  else if (entityInput.entityType === 'modelProperty') {
889
887
  // Use existing ModelProperty validation
890
- const validationServiceMod = await import('./SchemaValidationService-BPxkfDLU.js');
888
+ const validationServiceMod = await import('./SchemaValidationService-DieV4KL-.js');
891
889
  const { SchemaValidationService } = validationServiceMod;
892
890
  const validationService = new SchemaValidationService();
893
891
  // Validate property structure
@@ -927,7 +925,7 @@ const validateEntity = fromPromise(async ({ input }) => {
927
925
  }
928
926
  else if (entityInput.entityType === 'schema') {
929
927
  // Schema validation - use existing validation
930
- const validationServiceMod = await import('./SchemaValidationService-BPxkfDLU.js');
928
+ const validationServiceMod = await import('./SchemaValidationService-DieV4KL-.js');
931
929
  const { SchemaValidationService } = validationServiceMod;
932
930
  const validationService = new SchemaValidationService();
933
931
  const schemaResult = validationService.validateSchema(entityInput.entityData);
@@ -1016,7 +1014,7 @@ const writeToDatabase = fromCallback(({ sendBack, input }) => {
1016
1014
  // initial write completes is not overwritten by the stale requestWrite payload.
1017
1015
  let dataToWrite = input.entityData;
1018
1016
  try {
1019
- const mod = await import('./ModelProperty-BDt6AU2h.js');
1017
+ const mod = await import('./ModelProperty-BS49g01Y.js');
1020
1018
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
1021
1019
  if (ModelProperty && typeof ModelProperty.getById === 'function') {
1022
1020
  const instance = ModelProperty.getById(input.entityId);
@@ -1410,7 +1408,7 @@ const modelMachine = setup({
1410
1408
  // Create ModelProperty instances for any new property IDs
1411
1409
  if (Array.isArray(newPropertyIds) && newPropertyIds.length > 0) {
1412
1410
  // Import and create instances asynchronously (fire-and-forget)
1413
- import('./ModelProperty-BDt6AU2h.js').then(({ ModelProperty }) => {
1411
+ import('./ModelProperty-BS49g01Y.js').then(({ ModelProperty }) => {
1414
1412
  if (self.getSnapshot().status === 'stopped')
1415
1413
  return;
1416
1414
  const createPromises = newPropertyIds.map(async (propertyFileId) => {
@@ -1915,7 +1913,7 @@ const saveDraftLogger = debug('seedSdk:model:saveDraftToDb');
1915
1913
  // Lazy import cache for ModelProperty to avoid circular dependency
1916
1914
  // Eagerly start loading to minimize delay on first access
1917
1915
  let ModelPropertyClass = null;
1918
- const modelPropertyImportPromise = import('./ModelProperty-BDt6AU2h.js')
1916
+ const modelPropertyImportPromise = import('./ModelProperty-BS49g01Y.js')
1919
1917
  .then(module => {
1920
1918
  ModelPropertyClass = module.ModelProperty;
1921
1919
  return ModelPropertyClass;
@@ -1930,13 +1928,13 @@ function getModelProperty() {
1930
1928
  // and the getter will return empty array, which matches the original behavior
1931
1929
  return ModelPropertyClass;
1932
1930
  }
1933
- // Lazy import for Schema to avoid circular dependency
1934
- const schemaImportPromise = (async () => { const _mod_12 = await import('./Schema-B8xqLWkL.js'); return _mod_12.b; })()
1935
- .then(module => module.Schema)
1936
- .catch(() => null);
1937
1931
  // WeakMap to store mutable state per Model instance
1938
1932
  // This avoids issues with read-only properties when instances are frozen by Immer
1939
1933
  const modelInstanceState = new WeakMap();
1934
+ // Settles once the properties passed to Model.create exist, or rejects when they can't be created.
1935
+ // The model reaches idle before its write, so idle alone doesn't mean they exist yet. Keyed by the
1936
+ // actor because callers hold the proxy, not the instance.
1937
+ const pendingPropertyCreation = new WeakMap();
1940
1938
  // Define tracked properties for the Proxy
1941
1939
  // These properties will be read from/written to the actor context
1942
1940
  const TRACKED_PROPERTIES = [
@@ -1995,6 +1993,34 @@ class Model {
1995
1993
  });
1996
1994
  // Note: Property getters/setters are now handled by the Proxy in create()
1997
1995
  }
1996
+ /**
1997
+ * Resolves once the model is idle and any properties passed to Model.create exist.
1998
+ * Rejects if it errors, times out, or its properties can't be created.
1999
+ */
2000
+ static async waitUntilReady(instance, timeout) {
2001
+ const startedAt = Date.now();
2002
+ await waitForEntityIdle(instance, { timeout });
2003
+ const propertyCreation = pendingPropertyCreation.get(instance.getService());
2004
+ if (!propertyCreation)
2005
+ return instance;
2006
+ const remaining = Math.max(0, timeout - (Date.now() - startedAt));
2007
+ let timer;
2008
+ try {
2009
+ await Promise.race([
2010
+ propertyCreation,
2011
+ new Promise((_, reject) => {
2012
+ timer = setTimeout(() => {
2013
+ const modelName = instance.getService().getSnapshot().context.modelName;
2014
+ reject(new Error(`Model "${modelName}" did not finish creating its properties within ${timeout}ms`));
2015
+ }, remaining);
2016
+ }),
2017
+ ]);
2018
+ }
2019
+ finally {
2020
+ clearTimeout(timer);
2021
+ }
2022
+ return instance;
2023
+ }
1998
2024
  /**
1999
2025
  * True when a name-cached instance belongs to a different model than the requested modelFileId.
2000
2026
  * A schema re-imported under the same name can give its models new ids while the previous
@@ -2080,7 +2106,7 @@ class Model {
2080
2106
  throw new Error('Model name is required');
2081
2107
  }
2082
2108
  const waitForReady = options?.waitForReady !== false;
2083
- const readyTimeout = options?.readyTimeout ?? 5000;
2109
+ const readyTimeout = options?.readyTimeout ?? DEFAULT_READY_TIMEOUT_MS;
2084
2110
  // Extract schema name and instance
2085
2111
  let schemaName;
2086
2112
  let schemaInstance; // Using any to avoid circular dependency with Schema
@@ -2107,7 +2133,7 @@ class Model {
2107
2133
  logger(`Model.create: Found instance in ID cache for "${modelName}" (ID: ${id})`);
2108
2134
  if (!waitForReady)
2109
2135
  return instance;
2110
- return waitForEntityIdle(instance, { timeout: readyTimeout }).then(() => instance);
2136
+ return this.waitUntilReady(instance, readyTimeout);
2111
2137
  }
2112
2138
  // Step 2: Check for duplicate names and generate unique name if needed (before checking cache)
2113
2139
  // This allows us to create new models with renamed versions when duplicates exist
@@ -2153,7 +2179,7 @@ class Model {
2153
2179
  }
2154
2180
  if (!waitForReady)
2155
2181
  return instance;
2156
- return waitForEntityIdle(instance, { timeout: readyTimeout }).then(() => instance);
2182
+ return this.waitUntilReady(instance, readyTimeout);
2157
2183
  }
2158
2184
  }
2159
2185
  }
@@ -2193,7 +2219,7 @@ class Model {
2193
2219
  }
2194
2220
  if (!waitForReady)
2195
2221
  return instance;
2196
- return waitForEntityIdle(instance, { timeout: readyTimeout }).then(() => instance);
2222
+ return this.waitUntilReady(instance, readyTimeout);
2197
2223
  }
2198
2224
  // Step 7: Create new instance with id in initial context
2199
2225
  // This ensures loadOrCreateModel sees the ID immediately
@@ -2207,6 +2233,32 @@ class Model {
2207
2233
  if (options?.properties) {
2208
2234
  logger(`[Model.create] Created instance with _pendingPropertyDefinitions in initial context (${Object.keys(options.properties).length} properties) for model "${uniqueModelName}"`);
2209
2235
  }
2236
+ // Called by the write trigger below when the properties will never be created
2237
+ let failPropertyCreation = () => { };
2238
+ if (options?.properties && Object.keys(options.properties).length > 0) {
2239
+ const service = newInstance.getService();
2240
+ const propertyCreation = new Promise((resolve, reject) => {
2241
+ const subscription = service.subscribe({
2242
+ next: (snapshot) => {
2243
+ if (snapshot.value === 'idle' && !snapshot.context._pendingPropertyDefinitions) {
2244
+ subscription.unsubscribe();
2245
+ resolve();
2246
+ }
2247
+ else if (snapshot.value === 'error') {
2248
+ failPropertyCreation('the model is in an error state');
2249
+ }
2250
+ },
2251
+ complete: () => failPropertyCreation('the model was unloaded'),
2252
+ });
2253
+ failPropertyCreation = (reason) => {
2254
+ subscription.unsubscribe();
2255
+ reject(new Error(`Model "${service.getSnapshot().context.modelName}" could not create its properties: ${reason}`));
2256
+ };
2257
+ });
2258
+ // Only waitUntilReady reports this; without waitForReady nobody awaits it
2259
+ propertyCreation.catch(() => { });
2260
+ pendingPropertyCreation.set(service, propertyCreation);
2261
+ }
2210
2262
  // Step 7: Set initial model data if provided
2211
2263
  // Note: description is not supported - JSON files can have it but we ignore it at runtime
2212
2264
  if (options) {
@@ -2430,8 +2482,10 @@ class Model {
2430
2482
  }, 10000);
2431
2483
  });
2432
2484
  // Unloaded or evicted (e.g. Schema.destroy) while it loaded: a stopped model never writes
2433
- if (isActorStopped(proxiedInstance._service))
2485
+ if (isActorStopped(proxiedInstance._service)) {
2486
+ failPropertyCreation('the model was unloaded');
2434
2487
  return;
2488
+ }
2435
2489
  // Only write if validation passed (model is in idle state, not error)
2436
2490
  const finalSnapshot = proxiedInstance._service.getSnapshot();
2437
2491
  if (finalSnapshot.value === 'idle' && (!finalSnapshot.context._validationErrors || finalSnapshot.context._validationErrors.length === 0)) {
@@ -2526,6 +2580,7 @@ class Model {
2526
2580
  _dbId: schemaInstance ? schemaInstance._getSnapshotContext()._dbId : 'N/A',
2527
2581
  schemaName: schemaName || 'N/A',
2528
2582
  });
2583
+ failPropertyCreation(`its schema "${schemaName}" was not found in the database`);
2529
2584
  }
2530
2585
  else if (finalSnapshot.context.id) {
2531
2586
  // Verify schema exists in database before proceeding (additional safety check)
@@ -2563,8 +2618,10 @@ class Model {
2563
2618
  const maxRetries = 10;
2564
2619
  const checkAndSend = async () => {
2565
2620
  // Unloaded or evicted (e.g. Schema.destroy) before the write started: nothing to write to
2566
- if (isActorStopped(proxiedInstance._service))
2621
+ if (isActorStopped(proxiedInstance._service)) {
2622
+ failPropertyCreation('the model was unloaded');
2567
2623
  return;
2624
+ }
2568
2625
  const currentSnapshot = proxiedInstance._service.getSnapshot();
2569
2626
  if (currentSnapshot.context.writeProcess) {
2570
2627
  // Track pending write (only once it really starts: a stopped model leaves none behind)
@@ -2619,6 +2676,7 @@ class Model {
2619
2676
  logger(`Write process failed for model "${finalSnapshot.context.modelName}": ${errorContext.error?.message || 'Unknown error'}`);
2620
2677
  logger(`Write process error details:`, errorContext.error);
2621
2678
  logger(`Validation errors:`, errorContext.validationErrors);
2679
+ failPropertyCreation(`writing the model failed: ${errorContext.error?.message || 'Unknown error'}`);
2622
2680
  }
2623
2681
  });
2624
2682
  }
@@ -2639,6 +2697,7 @@ class Model {
2639
2697
  }
2640
2698
  else {
2641
2699
  logger(`ERROR: writeProcess not available after ${maxRetries} retries for model "${finalSnapshot.context.modelName}"`);
2700
+ failPropertyCreation('its write process never started');
2642
2701
  }
2643
2702
  };
2644
2703
  // Start checking immediately, but also allow time for entry action to complete
@@ -2646,20 +2705,23 @@ class Model {
2646
2705
  }
2647
2706
  else {
2648
2707
  logger(`Cannot trigger write process: missing schemaId (${schemaId}) or id (${finalSnapshot.context.id})`);
2708
+ failPropertyCreation('it has no id');
2649
2709
  }
2650
2710
  }
2651
2711
  else {
2652
2712
  logger(`Model validation failed or model in error state, skipping write process`);
2713
+ failPropertyCreation('the model failed validation');
2653
2714
  }
2654
2715
  }
2655
2716
  catch (error) {
2656
2717
  logger(`Failed to trigger write process: ${error instanceof Error ? error.message : String(error)}`);
2718
+ failPropertyCreation(error instanceof Error ? error.message : String(error));
2657
2719
  }
2658
2720
  });
2659
2721
  }
2660
2722
  if (!waitForReady)
2661
2723
  return proxiedInstance;
2662
- return waitForEntityIdle(proxiedInstance, { timeout: readyTimeout }).then(() => proxiedInstance);
2724
+ return this.waitUntilReady(proxiedInstance, readyTimeout);
2663
2725
  }
2664
2726
  /**
2665
2727
  * Get Model instance by modelFileId (O(1) lookup)
@@ -2842,8 +2904,8 @@ class Model {
2842
2904
  const evictionEpoch = options?.evictionEpoch ?? currentEvictionEpoch();
2843
2905
  try {
2844
2906
  // Query model by name (throws AmbiguousModelError when several schemas define it)
2845
- const _mod_10 = await import('./db-CQt-gcAl.js');
2846
- const _ns_10 = _mod_10.Y;
2907
+ const _mod_10 = await import('./BasePathResolver-Cm4apKRb.js');
2908
+ const _ns_10 = _mod_10.b1;
2847
2909
  const { resolveModelRecord } = _ns_10;
2848
2910
  const resolved = await resolveModelRecord(modelName, {}, db);
2849
2911
  if (!resolved?.schemaFileId) {
@@ -2954,7 +3016,7 @@ class Model {
2954
3016
  * @param options - Find options including lookup parameters and wait configuration
2955
3017
  * @returns Model instance if found, undefined otherwise
2956
3018
  */
2957
- static async find({ modelFileId, modelName, schemaName, waitForReady = true, readyTimeout = 5000, }) {
3019
+ static async find({ modelFileId, modelName, schemaName, waitForReady = true, readyTimeout = DEFAULT_READY_TIMEOUT_MS, }) {
2958
3020
  return await findEntity({
2959
3021
  getById: (id) => Model.getById(id),
2960
3022
  createById: (id) => Model.createById(id),
@@ -3043,10 +3105,11 @@ class Model {
3043
3105
  /**
3044
3106
  * Get all Model instances, optionally filtered by schema.
3045
3107
  * When DB is available, loads from DB via getModelsData; otherwise returns from cache.
3046
- * Supports waitForReady to wait for each model to reach idle state before returning.
3108
+ * With waitForReady, waits for each model to be ready (idle, with any properties from Model.create
3109
+ * created) and leaves out models that error or time out.
3047
3110
  */
3048
3111
  static async all(schemaName, options) {
3049
- const { waitForReady = false, readyTimeout = 5000 } = options ?? {};
3112
+ const { waitForReady = false, readyTimeout = DEFAULT_READY_TIMEOUT_MS } = options ?? {};
3050
3113
  const appDb = BaseDb.getAppDb();
3051
3114
  if (!appDb) {
3052
3115
  const instances = [];
@@ -3130,11 +3193,13 @@ class Model {
3130
3193
  }
3131
3194
  }
3132
3195
  if (waitForReady && instances.length > 0) {
3133
- await Promise.all(instances.map((m) => waitForEntityIdle(m, {
3134
- timeout: readyTimeout,
3135
- throwOnError: false,
3196
+ // Leave out models that errored or didn't get ready in time. Don't re-read their state afterwards:
3197
+ // a ready model can already be validating again, and it still belongs in the result.
3198
+ const ready = await Promise.all(instances.map((m) => this.waitUntilReady(m, readyTimeout).then(() => true, (error) => {
3199
+ logger(`Model.all: leaving out a model that isn't ready: ${error instanceof Error ? error.message : String(error)}`);
3200
+ return false;
3136
3201
  })));
3137
- return instances.filter((m) => m._getSnapshot?.().value === 'idle');
3202
+ return instances.filter((_, i) => ready[i]);
3138
3203
  }
3139
3204
  return instances;
3140
3205
  }
@@ -3573,6 +3638,8 @@ class Model {
3573
3638
  .limit(1);
3574
3639
  if (modelRecords.length > 0) {
3575
3640
  const modelId = modelRecords[0].id;
3641
+ const { detachModelRows } = await import('./detachRowsBeforeDelete-S0q-DJPT.js');
3642
+ await detachModelRows(db, [typeof modelId === 'string' ? parseInt(modelId, 10) : modelId]);
3576
3643
  await db.delete(modelSchemas).where(eq(modelSchemas.modelId, modelId));
3577
3644
  await db
3578
3645
  .delete(properties)
@@ -3581,9 +3648,10 @@ class Model {
3581
3648
  }
3582
3649
  }
3583
3650
  if (schemaName && modelName) {
3584
- const Schema = await schemaImportPromise;
3585
- if (!Schema)
3586
- throw new Error('Schema not loaded');
3651
+ // Imported here, not at module load: Model and Schema import each other.
3652
+ const _mod_11 = await import('./Schema-CpMNEnUO.js');
3653
+ const _ns_11 = _mod_11.b;
3654
+ const { Schema } = _ns_11;
3587
3655
  const schema = Schema.create(schemaName, { waitForReady: false });
3588
3656
  const schemaContext = schema.getService().getSnapshot().context;
3589
3657
  if (schemaContext.models?.[modelName]) {
@@ -3618,9 +3686,9 @@ class Model {
3618
3686
  return undefined;
3619
3687
  }
3620
3688
  // Model names are only unique per schema: find this model's row by its id (schemaFileId).
3621
- const _mod_11 = await import('./db-CQt-gcAl.js');
3622
- const _ns_11 = _mod_11.Y;
3623
- const { resolveModelRecord } = _ns_11;
3689
+ const _mod_12 = await import('./BasePathResolver-Cm4apKRb.js');
3690
+ const _ns_12 = _mod_12.b1;
3691
+ const { resolveModelRecord } = _ns_12;
3624
3692
  const modelRecord = await resolveModelRecord(modelName, { modelFileId: context.id, schemaName: context.schemaName }, db);
3625
3693
  if (!modelRecord?.id) {
3626
3694
  return undefined;
@@ -3824,4 +3892,4 @@ const TModelValues = Type.Record(Type.String(), Type.Any());
3824
3892
  const TModelSchema = Type.Record(Type.String(), TProperty);
3825
3893
 
3826
3894
  export { ConflictError as C, Model as M, TModelSchema as T, TModelValues as a, anyEvictionSince as b, currentEvictionEpoch as c, setupEntityLiveQuery as d, writeToDatabase$1 as e, Model$1 as f, isActorStopped as i, schemaEvictedSince as s, writeProcessMachine as w };
3827
- //# sourceMappingURL=index-Xl1_4Lmb.js.map
3895
+ //# sourceMappingURL=index-8O3Uow-Y.js.map