@seedprotocol/sdk 0.6.10 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (382) hide show
  1. package/dist/{BasePathResolver-B6CKqoKw.js → BasePathResolver-ndE8XTpw.js} +36 -2
  2. package/dist/BasePathResolver-ndE8XTpw.js.map +1 -0
  3. package/dist/ClientManager-DLleL_2e.js +4763 -0
  4. package/dist/ClientManager-DLleL_2e.js.map +1 -0
  5. package/dist/{ClientManager-ChcmUL47.js → Item-zBFWQDU9.js} +1119 -5893
  6. package/dist/Item-zBFWQDU9.js.map +1 -0
  7. package/dist/{ModelProperty-D79uV42p.js → ModelProperty-lth9L37R.js} +289 -101
  8. package/dist/ModelProperty-lth9L37R.js.map +1 -0
  9. package/dist/{Schema-a8uO-hIZ.js → Schema-DOhlrQ-N.js} +94 -864
  10. package/dist/Schema-DOhlrQ-N.js.map +1 -0
  11. package/dist/{SchemaValidationService-Y49vqast.js → SchemaValidationService-DDKr5piy.js} +26 -18
  12. package/dist/SchemaValidationService-DDKr5piy.js.map +1 -0
  13. package/dist/{backfillMetadataPropertyIds-CBsf7LnU.js → backfillMetadataPropertyIds-fG3ujaSh.js} +11 -6
  14. package/dist/backfillMetadataPropertyIds-fG3ujaSh.js.map +1 -0
  15. package/dist/cjs/{ModelProperty-D9FGaGuE.js → ModelProperty-BEsIHAjk.js} +260 -81
  16. package/dist/cjs/ModelProperty-BEsIHAjk.js.map +1 -0
  17. package/dist/cjs/{Schema-BiJIPLEL.js → Schema-qEp5mH1N.js} +66 -847
  18. package/dist/cjs/Schema-qEp5mH1N.js.map +1 -0
  19. package/dist/cjs/{SchemaValidationService-DtYs_CNY.js → SchemaValidationService-CWEnZmOH.js} +18 -11
  20. package/dist/cjs/SchemaValidationService-CWEnZmOH.js.map +1 -0
  21. package/dist/cjs/{backfillMetadataPropertyIds-2XaN3b9S.js → backfillMetadataPropertyIds-tw8JGMT0.js} +8 -3
  22. package/dist/cjs/backfillMetadataPropertyIds-tw8JGMT0.js.map +1 -0
  23. package/dist/cjs/{eas-CMNppmGE.js → eas-CLiV2Hmn.js} +4 -4
  24. package/dist/cjs/{eas-CMNppmGE.js.map → eas-CLiV2Hmn.js.map} +1 -1
  25. package/dist/cjs/{getItem-B6jEINjW.js → getItem-DSRtx_68.js} +2 -2
  26. package/dist/cjs/{getItem-B6jEINjW.js.map → getItem-DSRtx_68.js.map} +1 -1
  27. package/dist/cjs/getLatestVersionRow-DVizNNoI.js +59 -0
  28. package/dist/cjs/getLatestVersionRow-DVizNNoI.js.map +1 -0
  29. package/dist/cjs/{getPublishPayload-D5DhLGvN.js → getPublishPayload-D5-dYtNq.js} +249 -60
  30. package/dist/cjs/getPublishPayload-D5-dYtNq.js.map +1 -0
  31. package/dist/cjs/{getPublishUploads-DMhCCKYF.js → getPublishUploads-B5Lq6q-_.js} +20 -13
  32. package/dist/cjs/getPublishUploads-B5Lq6q-_.js.map +1 -0
  33. package/dist/cjs/{getSegmentedItemProperties-CU8rtBAo.js → getSegmentedItemProperties-giHO7R3d.js} +10 -11
  34. package/dist/cjs/getSegmentedItemProperties-giHO7R3d.js.map +1 -0
  35. package/dist/cjs/{index-DPp9rdRL.js → index-B3UDbm1C.js} +3 -3
  36. package/dist/cjs/index-B3UDbm1C.js.map +1 -0
  37. package/dist/cjs/{index-CSNtEnbF.js → index-C66AfYDG.js} +2510 -1694
  38. package/dist/cjs/index-C66AfYDG.js.map +1 -0
  39. package/dist/cjs/{property-DlKiAWt4.js → property-BVJIP7SX.js} +40 -35
  40. package/dist/cjs/property-BVJIP7SX.js.map +1 -0
  41. package/dist/cjs/resetAmbiguousLegacyItemData-BaZqUui9.js +116 -0
  42. package/dist/cjs/resetAmbiguousLegacyItemData-BaZqUui9.js.map +1 -0
  43. package/dist/cjs/resolveModelForSyncedSeed-CC6dQctx.js +49 -0
  44. package/dist/cjs/resolveModelForSyncedSeed-CC6dQctx.js.map +1 -0
  45. package/dist/cjs/syncDbWithEas-Dk96sAG-.js +873 -0
  46. package/dist/cjs/syncDbWithEas-Dk96sAG-.js.map +1 -0
  47. package/dist/{configurePlatform-CE0Vew17.js → configurePlatform-BMoPG9vY.js} +4 -4
  48. package/dist/{configurePlatform-CE0Vew17.js.map → configurePlatform-BMoPG9vY.js.map} +1 -1
  49. package/dist/db/drizzle/0015_add_model_file_id_to_seeds.sql +11 -0
  50. package/dist/db/drizzle/0016_add_revoked_at_to_metadata.sql +1 -0
  51. package/dist/db/drizzle/0017_add_revoked_at_to_versions.sql +1 -0
  52. package/dist/db/drizzle/0018_add_storage_settings_to_properties.sql +53 -0
  53. package/dist/db/drizzle/0019_add_derived_from_uid_to_metadata.sql +35 -0
  54. package/dist/db/drizzle/meta/0011_snapshot.json +1182 -0
  55. package/dist/db/drizzle/meta/0012_snapshot.json +1244 -0
  56. package/dist/db/drizzle/meta/0013_snapshot.json +63 -1
  57. package/dist/db/drizzle/meta/0014_snapshot.json +62 -0
  58. package/dist/db/drizzle/meta/0015_snapshot.json +1338 -0
  59. package/dist/db/drizzle/meta/0016_snapshot.json +1345 -0
  60. package/dist/db/drizzle/meta/0017_snapshot.json +1352 -0
  61. package/dist/db/drizzle/meta/0018_snapshot.json +1373 -0
  62. package/dist/db/drizzle/meta/0019_snapshot.json +1380 -0
  63. package/dist/db/drizzle/meta/_journal.json +35 -0
  64. package/dist/{db-WbrzEf7c.js → db-BJZN0a0a.js} +546 -106
  65. package/dist/db-BJZN0a0a.js.map +1 -0
  66. package/dist/{eas-CfYCu4IX.js → eas-B0hsMLqt.js} +7 -7
  67. package/dist/eas-B0hsMLqt.js.map +1 -0
  68. package/dist/errors-CrBxGWah.js +17 -0
  69. package/dist/errors-CrBxGWah.js.map +1 -0
  70. package/dist/{getItem-Br-bGNFO.js → getItem-DEh4WfHG.js} +8 -10
  71. package/dist/{getItem-Br-bGNFO.js.map → getItem-DEh4WfHG.js.map} +1 -1
  72. package/dist/getLatestVersionRow-Brrl1AnW.js +46 -0
  73. package/dist/getLatestVersionRow-Brrl1AnW.js.map +1 -0
  74. package/dist/{getPublishPayload-BIrTVUxb.js → getPublishPayload-H032DHC7.js} +263 -75
  75. package/dist/getPublishPayload-H032DHC7.js.map +1 -0
  76. package/dist/{getPublishUploads-C6cDeZdz.js → getPublishUploads-CR66RlGJ.js} +25 -17
  77. package/dist/{getPublishUploads-C6cDeZdz.js.map → getPublishUploads-CR66RlGJ.js.map} +1 -1
  78. package/dist/{getSegmentedItemProperties-BmKE71vU.js → getSegmentedItemProperties-C2EJ2G0N.js} +13 -14
  79. package/dist/getSegmentedItemProperties-C2EJ2G0N.js.map +1 -0
  80. package/dist/{index-ClSv5pTA.js → index-6bJuv5Tt.js} +12 -11
  81. package/dist/index-6bJuv5Tt.js.map +1 -0
  82. package/dist/{index-Djd3667v.js → index-B0LgJblD.js} +2 -2
  83. package/dist/index-B0LgJblD.js.map +1 -0
  84. package/dist/{index-HRHkbVQd.js → index-DtfjeuxC.js} +417 -174
  85. package/dist/index-DtfjeuxC.js.map +1 -0
  86. package/dist/index.browser-CNrqhvEA.js +4139 -0
  87. package/dist/index.browser-CNrqhvEA.js.map +1 -0
  88. package/dist/{index.node-DBtQkEfz.js → index.node-DrHiTuOr.js} +9 -4
  89. package/dist/index.node-DrHiTuOr.js.map +1 -0
  90. package/dist/main.cjs +1 -1
  91. package/dist/main.js +771 -521
  92. package/dist/main.js.map +1 -1
  93. package/dist/node.js +19 -15
  94. package/dist/node.js.map +1 -1
  95. package/dist/platform.browser.js +18 -3719
  96. package/dist/platform.browser.js.map +1 -1
  97. package/dist/platform.node.js +3 -3
  98. package/dist/{property-CQjuZ4JW.js → property-D2Nnsmm1.js} +53 -48
  99. package/dist/property-D2Nnsmm1.js.map +1 -0
  100. package/dist/resetAmbiguousLegacyItemData-BqbHNUYk.js +88 -0
  101. package/dist/resetAmbiguousLegacyItemData-BqbHNUYk.js.map +1 -0
  102. package/dist/resolveModelForSyncedSeed-DQK6JfXS.js +46 -0
  103. package/dist/resolveModelForSyncedSeed-DQK6JfXS.js.map +1 -0
  104. package/dist/seedSchema/MetadataSchema.ts +9 -0
  105. package/dist/seedSchema/ModelSchema.ts +5 -0
  106. package/dist/seedSchema/SeedSchema.ts +3 -0
  107. package/dist/seedSchema/VersionSchema.ts +5 -0
  108. package/dist/src/Item/Item.d.ts +10 -0
  109. package/dist/src/Item/Item.d.ts.map +1 -1
  110. package/dist/src/Item/service/actors/loadOrCreateItem.d.ts.map +1 -1
  111. package/dist/src/Item/service/actors/waitForDb.d.ts.map +1 -1
  112. package/dist/src/Item/service/itemMachineSingle.d.ts +3 -29
  113. package/dist/src/Item/service/itemMachineSingle.d.ts.map +1 -1
  114. package/dist/src/ItemProperty/ItemProperty.d.ts +3 -4
  115. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  116. package/dist/src/ItemProperty/service/actors/hydrateFromDb.d.ts.map +1 -1
  117. package/dist/src/ItemProperty/service/actors/loadOrCreateProperty.d.ts.map +1 -1
  118. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveFile.d.ts.map +1 -1
  119. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveHtml.d.ts.map +1 -1
  120. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveImage.d.ts.map +1 -1
  121. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveItemStorage.d.ts.map +1 -1
  122. package/dist/src/ItemProperty/service/propertyMachine.d.ts +4 -9
  123. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  124. package/dist/src/Model/Model.d.ts +37 -0
  125. package/dist/src/Model/Model.d.ts.map +1 -1
  126. package/dist/src/Model/errors.d.ts +10 -0
  127. package/dist/src/Model/errors.d.ts.map +1 -0
  128. package/dist/src/Model/service/actors/createModelProperties.d.ts.map +1 -1
  129. package/dist/src/Model/service/actors/loadOrCreateModel.d.ts.map +1 -1
  130. package/dist/src/Model/service/modelMachine.d.ts +0 -8
  131. package/dist/src/Model/service/modelMachine.d.ts.map +1 -1
  132. package/dist/src/ModelProperty/ModelProperty.d.ts +33 -1
  133. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  134. package/dist/src/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  135. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts +2 -9
  136. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  137. package/dist/src/Schema/Schema.d.ts +1 -2
  138. package/dist/src/Schema/Schema.d.ts.map +1 -1
  139. package/dist/src/Schema/service/schemaMachine.d.ts +1 -217
  140. package/dist/src/Schema/service/schemaMachine.d.ts.map +1 -1
  141. package/dist/src/Schema/service/validation/SchemaValidationService.d.ts.map +1 -1
  142. package/dist/src/browser/db/Db.d.ts +3 -0
  143. package/dist/src/browser/db/Db.d.ts.map +1 -1
  144. package/dist/src/browser/db/drizzleFiles.d.ts +7 -2
  145. package/dist/src/browser/db/drizzleFiles.d.ts.map +1 -1
  146. package/dist/src/browser/db/embeddedMigrations.d.ts +11 -2
  147. package/dist/src/browser/db/embeddedMigrations.d.ts.map +1 -1
  148. package/dist/src/browser/db/sqliteBusyRetry.d.ts +14 -0
  149. package/dist/src/browser/db/sqliteBusyRetry.d.ts.map +1 -0
  150. package/dist/src/browser/helpers/FileManager.d.ts +1 -0
  151. package/dist/src/browser/helpers/FileManager.d.ts.map +1 -1
  152. package/dist/src/browser/helpers/QueryClient.d.ts +1 -0
  153. package/dist/src/browser/helpers/QueryClient.d.ts.map +1 -1
  154. package/dist/src/browser/helpers/opfsErrors.d.ts +2 -0
  155. package/dist/src/browser/helpers/opfsErrors.d.ts.map +1 -0
  156. package/dist/src/browser/helpers/tolerantWebAccess.d.ts +47 -0
  157. package/dist/src/browser/helpers/tolerantWebAccess.d.ts.map +1 -0
  158. package/dist/src/browser/workers/FileDownloader.d.ts.map +1 -1
  159. package/dist/src/browser/workers/ImageResizer.d.ts.map +1 -1
  160. package/dist/src/browser/workers/filesDownload.d.ts.map +1 -1
  161. package/dist/src/browser/workers/imageResize.d.ts.map +1 -1
  162. package/dist/src/client/ClientManager.d.ts.map +1 -1
  163. package/dist/src/client/actors/addModelsToDb.d.ts +14 -0
  164. package/dist/src/client/actors/addModelsToDb.d.ts.map +1 -1
  165. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  166. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  167. package/dist/src/client/actors/saveConfig.d.ts +11 -0
  168. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  169. package/dist/src/client/constants.d.ts +0 -8
  170. package/dist/src/client/constants.d.ts.map +1 -1
  171. package/dist/src/db/backfillMetadataPropertyIds.d.ts.map +1 -1
  172. package/dist/src/db/configs/{dev.schema.config.d.ts → migrations.config.d.ts} +1 -1
  173. package/dist/src/db/configs/migrations.config.d.ts.map +1 -0
  174. package/dist/src/db/read/batchLatestPublishedVersionBySeedLocalIds.d.ts +1 -1
  175. package/dist/src/db/read/batchLatestPublishedVersionBySeedLocalIds.d.ts.map +1 -1
  176. package/dist/src/db/read/getItemData.d.ts.map +1 -1
  177. package/dist/src/db/read/getItemProperties.d.ts.map +1 -1
  178. package/dist/src/db/read/getItems.d.ts +7 -2
  179. package/dist/src/db/read/getItems.d.ts.map +1 -1
  180. package/dist/src/db/read/getLatestPublishedVersionRow.d.ts +2 -1
  181. package/dist/src/db/read/getLatestPublishedVersionRow.d.ts.map +1 -1
  182. package/dist/src/db/read/getLatestVersionRow.d.ts +13 -0
  183. package/dist/src/db/read/getLatestVersionRow.d.ts.map +1 -0
  184. package/dist/src/db/read/getModelSchemas.d.ts.map +1 -1
  185. package/dist/src/db/read/getPropertyData.d.ts.map +1 -1
  186. package/dist/src/db/read/getPublishPayload.d.ts +9 -11
  187. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  188. package/dist/src/db/read/getPublishPendingDiff.d.ts +2 -1
  189. package/dist/src/db/read/getPublishPendingDiff.d.ts.map +1 -1
  190. package/dist/src/db/read/getPublishUploads.d.ts.map +1 -1
  191. package/dist/src/db/read/getSchemaUidForModel.d.ts.map +1 -1
  192. package/dist/src/db/read/getSeedPublishState.d.ts +8 -2
  193. package/dist/src/db/read/getSeedPublishState.d.ts.map +1 -1
  194. package/dist/src/db/read/isSeedRevoked.d.ts +7 -0
  195. package/dist/src/db/read/isSeedRevoked.d.ts.map +1 -0
  196. package/dist/src/db/read/publishErrors.d.ts +37 -0
  197. package/dist/src/db/read/publishErrors.d.ts.map +1 -0
  198. package/dist/src/db/read/resolveModelForSyncedSeed.d.ts +39 -0
  199. package/dist/src/db/read/resolveModelForSyncedSeed.d.ts.map +1 -0
  200. package/dist/src/db/read/resolveModelRecord.d.ts +69 -0
  201. package/dist/src/db/read/resolveModelRecord.d.ts.map +1 -0
  202. package/dist/src/db/read/resolveRelatedSeedRef.d.ts +34 -0
  203. package/dist/src/db/read/resolveRelatedSeedRef.d.ts.map +1 -0
  204. package/dist/src/db/read/subqueries/liveVersion.d.ts +12 -0
  205. package/dist/src/db/read/subqueries/liveVersion.d.ts.map +1 -0
  206. package/dist/src/db/read/subqueries/metadataLatest.d.ts +4 -0
  207. package/dist/src/db/read/subqueries/metadataLatest.d.ts.map +1 -1
  208. package/dist/src/db/read/subqueries/versionData.d.ts +7 -2
  209. package/dist/src/db/read/subqueries/versionData.d.ts.map +1 -1
  210. package/dist/src/db/read/summarizePublishWork.d.ts +10 -2
  211. package/dist/src/db/read/summarizePublishWork.d.ts.map +1 -1
  212. package/dist/src/db/resetAmbiguousLegacyItemData.d.ts +17 -0
  213. package/dist/src/db/resetAmbiguousLegacyItemData.d.ts.map +1 -0
  214. package/dist/src/db/sqlParamBatches.d.ts +27 -0
  215. package/dist/src/db/sqlParamBatches.d.ts.map +1 -0
  216. package/dist/src/db/write/addExcludedTransactions.d.ts +7 -0
  217. package/dist/src/db/write/addExcludedTransactions.d.ts.map +1 -0
  218. package/dist/src/db/write/applyPropertyAttestationUidsFromPublish.d.ts +6 -0
  219. package/dist/src/db/write/applyPropertyAttestationUidsFromPublish.d.ts.map +1 -1
  220. package/dist/src/db/write/createMetadata.d.ts +2 -0
  221. package/dist/src/db/write/createMetadata.d.ts.map +1 -1
  222. package/dist/src/db/write/createNewItem.d.ts +3 -1
  223. package/dist/src/db/write/createNewItem.d.ts.map +1 -1
  224. package/dist/src/db/write/createSeed.d.ts +2 -1
  225. package/dist/src/db/write/createSeed.d.ts.map +1 -1
  226. package/dist/src/db/write/createSeeds.d.ts +1 -1
  227. package/dist/src/db/write/createSeeds.d.ts.map +1 -1
  228. package/dist/src/db/write/linkModelToSchema.d.ts +12 -0
  229. package/dist/src/db/write/linkModelToSchema.d.ts.map +1 -0
  230. package/dist/src/db/write/updateItemPropertyValue.d.ts.map +1 -1
  231. package/dist/src/db/write/updateMetadata.d.ts.map +1 -1
  232. package/dist/src/db/write/updateSeedRevokedAt.d.ts +11 -1
  233. package/dist/src/db/write/updateSeedRevokedAt.d.ts.map +1 -1
  234. package/dist/src/db/write/updateSeedUid.d.ts.map +1 -1
  235. package/dist/src/db/write/updateVersionUid.d.ts +2 -1
  236. package/dist/src/db/write/updateVersionUid.d.ts.map +1 -1
  237. package/dist/src/events/files/download.d.ts.map +1 -1
  238. package/dist/src/events/item/easSyncManager.d.ts +2 -0
  239. package/dist/src/events/item/easSyncManager.d.ts.map +1 -1
  240. package/dist/src/events/item/index.d.ts.map +1 -1
  241. package/dist/src/events/item/syncDbWithEas.d.ts +16 -0
  242. package/dist/src/events/item/syncDbWithEas.d.ts.map +1 -1
  243. package/dist/src/helpers/FileManager/BaseFileManager.d.ts +1 -0
  244. package/dist/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  245. package/dist/src/helpers/FileManager/IFileManager.d.ts +5 -0
  246. package/dist/src/helpers/FileManager/IFileManager.d.ts.map +1 -1
  247. package/dist/src/helpers/FileManager/errors.d.ts +10 -0
  248. package/dist/src/helpers/FileManager/errors.d.ts.map +1 -0
  249. package/dist/src/helpers/compareMetadataRowsLatestFirst.d.ts +21 -3
  250. package/dist/src/helpers/compareMetadataRowsLatestFirst.d.ts.map +1 -1
  251. package/dist/src/helpers/constants.d.ts +9 -0
  252. package/dist/src/helpers/constants.d.ts.map +1 -1
  253. package/dist/src/helpers/crypto.d.ts +5 -0
  254. package/dist/src/helpers/crypto.d.ts.map +1 -1
  255. package/dist/src/helpers/db.d.ts +25 -5
  256. package/dist/src/helpers/db.d.ts.map +1 -1
  257. package/dist/src/helpers/easPropertyCanonical.d.ts +1 -1
  258. package/dist/src/helpers/easPropertyCanonical.d.ts.map +1 -1
  259. package/dist/src/helpers/entity/entityCommon.d.ts +10 -0
  260. package/dist/src/helpers/entity/entityCommon.d.ts.map +1 -1
  261. package/dist/src/helpers/entity/entityDestroy.d.ts +1 -1
  262. package/dist/src/helpers/entity/entityDestroy.d.ts.map +1 -1
  263. package/dist/src/helpers/entity/entityLiveQuery.d.ts +5 -0
  264. package/dist/src/helpers/entity/entityLiveQuery.d.ts.map +1 -1
  265. package/dist/src/helpers/file/fetchAll/actors.d.ts.map +1 -1
  266. package/dist/src/helpers/getSegmentedItemProperties.d.ts.map +1 -1
  267. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts +6 -0
  268. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts.map +1 -1
  269. package/dist/src/helpers/isPublishedMetadataRow.d.ts +10 -0
  270. package/dist/src/helpers/isPublishedMetadataRow.d.ts.map +1 -0
  271. package/dist/src/helpers/ownership.d.ts.map +1 -1
  272. package/dist/src/helpers/property.d.ts +6 -1
  273. package/dist/src/helpers/property.d.ts.map +1 -1
  274. package/dist/src/helpers/schema.d.ts +14 -4
  275. package/dist/src/helpers/schema.d.ts.map +1 -1
  276. package/dist/src/helpers/tabCoordinator.d.ts +45 -0
  277. package/dist/src/helpers/tabCoordinator.d.ts.map +1 -0
  278. package/dist/src/helpers/tabEvents.d.ts +27 -0
  279. package/dist/src/helpers/tabEvents.d.ts.map +1 -0
  280. package/dist/src/helpers/tabLocks.d.ts +28 -0
  281. package/dist/src/helpers/tabLocks.d.ts.map +1 -0
  282. package/dist/src/helpers/updateSchema.d.ts.map +1 -1
  283. package/dist/src/imports/json.d.ts.map +1 -1
  284. package/dist/src/imports/markdown.d.ts.map +1 -1
  285. package/dist/src/index.d.ts +11 -2
  286. package/dist/src/index.d.ts.map +1 -1
  287. package/dist/src/node/db/Db.d.ts.map +1 -1
  288. package/dist/src/node/helpers/FileManager.d.ts +2 -0
  289. package/dist/src/node/helpers/FileManager.d.ts.map +1 -1
  290. package/dist/src/query/createLocalQueryDataSource.d.ts +4 -0
  291. package/dist/src/query/createLocalQueryDataSource.d.ts.map +1 -1
  292. package/dist/src/seedSchema/MetadataSchema.d.ts +36 -0
  293. package/dist/src/seedSchema/MetadataSchema.d.ts.map +1 -1
  294. package/dist/src/seedSchema/ModelSchema.d.ts +57 -0
  295. package/dist/src/seedSchema/ModelSchema.d.ts.map +1 -1
  296. package/dist/src/seedSchema/SeedSchema.d.ts +19 -0
  297. package/dist/src/seedSchema/SeedSchema.d.ts.map +1 -1
  298. package/dist/src/seedSchema/VersionSchema.d.ts +17 -0
  299. package/dist/src/seedSchema/VersionSchema.d.ts.map +1 -1
  300. package/dist/src/services/write/actors/writeToDatabase.d.ts +5 -0
  301. package/dist/src/services/write/actors/writeToDatabase.d.ts.map +1 -1
  302. package/dist/src/services/write/writeProcessMachine.d.ts.map +1 -1
  303. package/dist/src/stores/eas.d.ts +1 -1
  304. package/dist/src/stores/eas.d.ts.map +1 -1
  305. package/dist/src/types/index.d.ts +7 -0
  306. package/dist/src/types/index.d.ts.map +1 -1
  307. package/dist/src/types/item.d.ts +12 -3
  308. package/dist/src/types/item.d.ts.map +1 -1
  309. package/dist/src/types/property.d.ts +3 -2
  310. package/dist/src/types/property.d.ts.map +1 -1
  311. package/dist/syncDbWithEas-LRKr_NZF.js +855 -0
  312. package/dist/syncDbWithEas-LRKr_NZF.js.map +1 -0
  313. package/dist/{index-280bL-n4.js → tabEvents-DYI2GU7i.js} +231 -68
  314. package/dist/tabEvents-DYI2GU7i.js.map +1 -0
  315. package/dist/tolerantWebAccess-CzOBz5M6.js +160 -0
  316. package/dist/tolerantWebAccess-CzOBz5M6.js.map +1 -0
  317. package/dist/updateSeedRevokedAt-B58ORbY3.js +32 -0
  318. package/dist/updateSeedRevokedAt-B58ORbY3.js.map +1 -0
  319. package/package.json +5 -5
  320. package/dist/BasePathResolver-B6CKqoKw.js.map +0 -1
  321. package/dist/ClientManager-ChcmUL47.js.map +0 -1
  322. package/dist/ModelProperty-D79uV42p.js.map +0 -1
  323. package/dist/Schema-a8uO-hIZ.js.map +0 -1
  324. package/dist/SchemaValidationService-Y49vqast.js.map +0 -1
  325. package/dist/backfillMetadataPropertyIds-CBsf7LnU.js.map +0 -1
  326. package/dist/cjs/ModelProperty-D9FGaGuE.js.map +0 -1
  327. package/dist/cjs/Schema-BiJIPLEL.js.map +0 -1
  328. package/dist/cjs/SchemaValidationService-DtYs_CNY.js.map +0 -1
  329. package/dist/cjs/backfillMetadataPropertyIds-2XaN3b9S.js.map +0 -1
  330. package/dist/cjs/getPublishPayload-D5DhLGvN.js.map +0 -1
  331. package/dist/cjs/getPublishUploads-DMhCCKYF.js.map +0 -1
  332. package/dist/cjs/getSegmentedItemProperties-CU8rtBAo.js.map +0 -1
  333. package/dist/cjs/index-CSNtEnbF.js.map +0 -1
  334. package/dist/cjs/index-DPp9rdRL.js.map +0 -1
  335. package/dist/cjs/property-DlKiAWt4.js.map +0 -1
  336. package/dist/cjs/syncDbWithEas-C6n34o_Q.js +0 -606
  337. package/dist/cjs/syncDbWithEas-C6n34o_Q.js.map +0 -1
  338. package/dist/db-WbrzEf7c.js.map +0 -1
  339. package/dist/eas-CfYCu4IX.js.map +0 -1
  340. package/dist/getPublishPayload-BIrTVUxb.js.map +0 -1
  341. package/dist/getSegmentedItemProperties-BmKE71vU.js.map +0 -1
  342. package/dist/index-280bL-n4.js.map +0 -1
  343. package/dist/index-ClSv5pTA.js.map +0 -1
  344. package/dist/index-Djd3667v.js.map +0 -1
  345. package/dist/index-HRHkbVQd.js.map +0 -1
  346. package/dist/index.node-DBtQkEfz.js.map +0 -1
  347. package/dist/property-CQjuZ4JW.js.map +0 -1
  348. package/dist/src/Item/service/actors/fetchDataFromEas.d.ts +0 -4
  349. package/dist/src/Item/service/actors/fetchDataFromEas.d.ts.map +0 -1
  350. package/dist/src/Item/service/actors/hydrateExistingItem.d.ts +0 -4
  351. package/dist/src/Item/service/actors/hydrateExistingItem.d.ts.map +0 -1
  352. package/dist/src/Item/service/actors/hydrateNewItem.d.ts +0 -4
  353. package/dist/src/Item/service/actors/hydrateNewItem.d.ts.map +0 -1
  354. package/dist/src/Item/service/actors/initialize.d.ts +0 -4
  355. package/dist/src/Item/service/actors/initialize.d.ts.map +0 -1
  356. package/dist/src/Item/service/actors/reload.d.ts +0 -5
  357. package/dist/src/Item/service/actors/reload.d.ts.map +0 -1
  358. package/dist/src/Item/service/actors/saveDataToDb.d.ts +0 -4
  359. package/dist/src/Item/service/actors/saveDataToDb.d.ts.map +0 -1
  360. package/dist/src/ItemProperty/service/actors/resolveRemoteStorage.d.ts +0 -5
  361. package/dist/src/ItemProperty/service/actors/resolveRemoteStorage.d.ts.map +0 -1
  362. package/dist/src/Schema/service/addModelsMachine.d.ts +0 -123
  363. package/dist/src/Schema/service/addModelsMachine.d.ts.map +0 -1
  364. package/dist/src/db/configs/dev.schema.config.d.ts.map +0 -1
  365. package/dist/src/helpers/file/download/actors.d.ts +0 -17
  366. package/dist/src/helpers/file/download/actors.d.ts.map +0 -1
  367. package/dist/src/helpers/file/download/index.d.ts +0 -70
  368. package/dist/src/helpers/file/download/index.d.ts.map +0 -1
  369. package/dist/src/services/publish/actors/createPublishAttempt.d.ts +0 -4
  370. package/dist/src/services/publish/actors/createPublishAttempt.d.ts.map +0 -1
  371. package/dist/src/services/publish/actors/preparePublishRequestData.d.ts +0 -4
  372. package/dist/src/services/publish/actors/preparePublishRequestData.d.ts.map +0 -1
  373. package/dist/src/services/publish/actors/upload.d.ts +0 -4
  374. package/dist/src/services/publish/actors/upload.d.ts.map +0 -1
  375. package/dist/src/services/publish/actors/validateItemData.d.ts +0 -4
  376. package/dist/src/services/publish/actors/validateItemData.d.ts.map +0 -1
  377. package/dist/src/services/publish/publishMachine.d.ts +0 -32
  378. package/dist/src/services/publish/publishMachine.d.ts.map +0 -1
  379. package/dist/syncDbWithEas-CuARXfyN.js +0 -598
  380. package/dist/syncDbWithEas-CuARXfyN.js.map +0 -1
  381. package/dist/updateSeedRevokedAt-CBcLfHWs.js +0 -22
  382. package/dist/updateSeedRevokedAt-CBcLfHWs.js.map +0 -1
@@ -1,11 +1,12 @@
1
1
  import { fromCallback, fromPromise, setup, assign, createActor } from 'xstate';
2
- import { a as BaseDb, m as models, p as properties, J as isInternalSchema, i as modelSchemas, s as schemas } from './BasePathResolver-B6CKqoKw.js';
3
- import { eq, or } from 'drizzle-orm';
4
- import './index-280bL-n4.js';
2
+ import { B as BaseDb, m as models, p as properties, K as isInternalSchema, i as modelSchemas, s as schemas } from './BasePathResolver-ndE8XTpw.js';
3
+ import { eq, and, isNull, or } from 'drizzle-orm';
4
+ import './tabEvents-DYI2GU7i.js';
5
5
  import debug from 'debug';
6
6
  import { generateId } from './generateId-BopUwD8F.js';
7
- import { y as writeModelToDb, z as writePropertyToDb, A as addSchemaToDb, C as renameModelInDb, d as TProperty } from './db-WbrzEf7c.js';
8
- import { n as waitForEntityIdle, af as getInvariantSafePropertyDescriptor, q as findEntity, H as getClient, y as ClientManagerState, I as Item, ag as unloadEntity, ah as clearDestroySubscriptions, u as forceRemoveFromCaches, v as runDestroyLifecycle } from './ClientManager-ChcmUL47.js';
7
+ import { G as writeModelToDb, K as writePropertyToDb, O as addSchemaToDb, A as AmbiguousModelError, Q as renameModelInDb, d as TProperty } from './db-BJZN0a0a.js';
8
+ import { j as waitForEntityIdle, T as getInvariantSafePropertyDescriptor, m as findEntity, C as ClientManagerState, I as Item, U as clearDestroySubscriptions, n as forceRemoveFromCaches, V as unloadEntity, o as runDestroyLifecycle } from './Item-zBFWQDU9.js';
9
+ import { h as getClient } from './ClientManager-DLleL_2e.js';
9
10
  import { modelPropertiesToObject } from './model-DGMe-TTm.js';
10
11
  import { toSnakeCase } from 'drizzle-orm/casing';
11
12
  import { Type } from '@sinclair/typebox';
@@ -21,7 +22,7 @@ const createPropertyInstances = async (propertyFileIds) => {
21
22
  return;
22
23
  }
23
24
  try {
24
- const mod = await import('./ModelProperty-D79uV42p.js');
25
+ const mod = await import('./ModelProperty-lth9L37R.js');
25
26
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
26
27
  if (!ModelProperty) {
27
28
  logger$7('createPropertyInstances: ModelProperty not available from dynamic import');
@@ -85,11 +86,40 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
85
86
  // But if we have a schemaFileId and the model found by name has a different schemaFileId,
86
87
  // don't use it - we're creating a new model from a schema file with a specific ID
87
88
  if (!modelRecord) {
88
- const dbModels = await db
89
- .select()
89
+ // Model names are only unique per schema: prefer this schema's row, and otherwise only
90
+ // consider same-name rows that no schema claims yet (never another schema's model).
91
+ const _mod_0 = await import('./BasePathResolver-ndE8XTpw.js');
92
+ const _ns_0 = _mod_0.R;
93
+ const { modelSchemas } = _ns_0;
94
+ const _mod_1 = await import('./BasePathResolver-ndE8XTpw.js');
95
+ const _ns_1 = _mod_1.Q;
96
+ const { schemas: schemasTable } = _ns_1;
97
+ let dbModels = await db
98
+ .select({
99
+ id: models.id,
100
+ name: models.name,
101
+ schemaFileId: models.schemaFileId,
102
+ isEdited: models.isEdited,
103
+ })
90
104
  .from(models)
91
- .where(eq(models.name, modelName))
105
+ .innerJoin(modelSchemas, eq(models.id, modelSchemas.modelId))
106
+ .innerJoin(schemasTable, eq(modelSchemas.schemaId, schemasTable.id))
107
+ .where(and(eq(models.name, modelName), eq(schemasTable.name, schemaName)))
92
108
  .limit(1);
109
+ if (dbModels.length === 0) {
110
+ dbModels = await db
111
+ .select({
112
+ id: models.id,
113
+ name: models.name,
114
+ schemaFileId: models.schemaFileId,
115
+ isEdited: models.isEdited,
116
+ })
117
+ .from(models)
118
+ .leftJoin(modelSchemas, eq(models.id, modelSchemas.modelId))
119
+ // Stubs only: an unlinked row with a schemaFileId is a deleted schema's leftover, not ours
120
+ .where(and(eq(models.name, modelName), isNull(modelSchemas.id), isNull(models.schemaFileId)))
121
+ .limit(1);
122
+ }
93
123
  if (dbModels.length > 0) {
94
124
  const foundModel = dbModels[0];
95
125
  const dbSchemaFileId = foundModel.schemaFileId;
@@ -98,7 +128,9 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
98
128
  // This handles the case where Model.create was called with a generated ID, but the model
99
129
  // already exists in the database with a different ID. By updating the current instance's
100
130
  // schemaFileId to match the database, both will point to the same cached instance.
101
- if (dbSchemaFileId) {
131
+ // Skip for schema models (_idFromSchema): their id is authoritative, and a same-name row
132
+ // with a different id belongs to another schema (e.g. two schemas that each define "Post").
133
+ if (dbSchemaFileId && !(_idFromSchema && schemaFileId && schemaFileId !== dbSchemaFileId)) {
102
134
  try {
103
135
  const modelMod = await Promise.resolve().then(function () { return Model$1; });
104
136
  const { Model } = modelMod;
@@ -205,9 +237,9 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
205
237
  // Step 2: Fallback to Schema context (only if database doesn't have the model)
206
238
  // This handles the case where model exists in schema file but not yet in database
207
239
  try {
208
- const _mod_0 = await import('./Schema-a8uO-hIZ.js');
209
- const _ns_0 = _mod_0.b;
210
- const schemaMod = _ns_0;
240
+ const _mod_2 = await import('./Schema-DOhlrQ-N.js');
241
+ const _ns_2 = _mod_2.b;
242
+ const schemaMod = _ns_2;
211
243
  const { Schema } = schemaMod;
212
244
  const schema = Schema.create(schemaName, { waitForReady: false });
213
245
  const schemaSnapshot = schema.getService().getSnapshot();
@@ -353,13 +385,13 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
353
385
  }
354
386
  // Also check database for models (in case they're persisted but not in Schema context)
355
387
  if (db) {
356
- const _mod_1 = await import('./BasePathResolver-B6CKqoKw.js');
357
- const _ns_1 = _mod_1.Q;
358
- const modelSchemaSchemaMod = _ns_1;
388
+ const _mod_3 = await import('./BasePathResolver-ndE8XTpw.js');
389
+ const _ns_3 = _mod_3.R;
390
+ const modelSchemaSchemaMod = _ns_3;
359
391
  const { modelSchemas } = modelSchemaSchemaMod;
360
- const _mod_2 = await import('./BasePathResolver-B6CKqoKw.js');
361
- const _ns_2 = _mod_2.O;
362
- const schemaSchemaMod = _ns_2;
392
+ const _mod_4 = await import('./BasePathResolver-ndE8XTpw.js');
393
+ const _ns_4 = _mod_4.Q;
394
+ const schemaSchemaMod = _ns_4;
363
395
  const { schemas: schemasTable } = schemaSchemaMod;
364
396
  // Query all models for this schema to check for duplicates (case-insensitive)
365
397
  logger$7(`Checking database for duplicate model names in schema "${schemaName}"`);
@@ -453,9 +485,9 @@ const loadOrCreateModel = fromCallback(({ sendBack, input: { context } }) => {
453
485
  }
454
486
  // Mark schema as draft when a new model is created so saveNewVersion() can persist it
455
487
  try {
456
- const _mod_3 = await import('./Schema-a8uO-hIZ.js');
457
- const _ns_3 = _mod_3.b;
458
- const schemaMod = _ns_3;
488
+ const _mod_5 = await import('./Schema-DOhlrQ-N.js');
489
+ const _ns_5 = _mod_5.b;
490
+ const schemaMod = _ns_5;
459
491
  const { Schema } = schemaMod;
460
492
  const schema = Schema.create(schemaName, { waitForReady: false });
461
493
  schema.getService().send({ type: 'markAsDraft', propertyKey: 'schema:models' });
@@ -499,12 +531,12 @@ const validateModel = fromCallback(({ sendBack, input: { context } }) => {
499
531
  const _validateModel = async () => {
500
532
  try {
501
533
  // Use dynamic imports to break circular dependencies
502
- const validationServiceMod = await import('./SchemaValidationService-Y49vqast.js');
534
+ const validationServiceMod = await import('./SchemaValidationService-DDKr5piy.js');
503
535
  const { SchemaValidationService } = validationServiceMod;
504
536
  const validationService = new SchemaValidationService();
505
- const _mod_4 = await import('./Schema-a8uO-hIZ.js');
506
- const _ns_4 = _mod_4.b;
507
- const schemaMod = _ns_4;
537
+ const _mod_6 = await import('./Schema-DOhlrQ-N.js');
538
+ const _ns_6 = _mod_6.b;
539
+ const schemaMod = _ns_6;
508
540
  const { Schema } = schemaMod;
509
541
  // Validate model structure
510
542
  const structureResult = validationService.validateModelStructure(context);
@@ -604,7 +636,7 @@ const logger$5 = debug('seedSdk:model:actors:createModelProperties');
604
636
  const createModelProperties = fromCallback(({ sendBack, input }) => {
605
637
  const _createProperties = async () => {
606
638
  const { context, propertyDefinitions } = input;
607
- const { id, _dbId, modelName } = context;
639
+ const { id, _dbId, modelName, schemaName } = context;
608
640
  if (!id || !_dbId || !modelName) {
609
641
  throw new Error('Model ID, file ID, and name are required to create properties');
610
642
  }
@@ -614,7 +646,7 @@ const createModelProperties = fromCallback(({ sendBack, input }) => {
614
646
  return;
615
647
  }
616
648
  logger$5(`Creating ${Object.keys(propertyDefinitions).length} properties for model "${modelName}" (id: ${_dbId})`);
617
- const mod = await import('./ModelProperty-D79uV42p.js');
649
+ const mod = await import('./ModelProperty-lth9L37R.js');
618
650
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
619
651
  if (!ModelProperty) {
620
652
  logger$5('ModelProperty not available from dynamic import');
@@ -622,13 +654,25 @@ const createModelProperties = fromCallback(({ sendBack, input }) => {
622
654
  return;
623
655
  }
624
656
  const drizzleMod = await import('drizzle-orm');
625
- const { eq } = drizzleMod;
657
+ const { and, eq } = drizzleMod;
626
658
  const db = BaseDb.getAppDb();
627
659
  for (const [propName, propData] of Object.entries(propertyDefinitions)) {
628
- // Use provided ID or generate a random one
660
+ // The model's own write (writeModelToDb) normally stored this property already, under
661
+ // propData.id or an id it generated. Reuse that row so the instance gets the same id
662
+ // and doesn't write the property a second time.
663
+ const propertyRecord = db
664
+ ? (await db
665
+ .select()
666
+ .from(properties)
667
+ .where(propData.id
668
+ ? eq(properties.schemaFileId, propData.id)
669
+ : and(eq(properties.modelId, _dbId), eq(properties.name, propName)))
670
+ .limit(1))[0]
671
+ : undefined;
672
+ // Otherwise use provided ID or generate a random one
629
673
  // IDs should be generated in the import process before creating properties
630
674
  const { generateId } = await import('./generateId-BopUwD8F.js');
631
- const propertyFileId = propData.id || generateId();
675
+ const propertyFileId = propData.id || propertyRecord?.schemaFileId || generateId();
632
676
  logger$5(`Creating property "${propName}" with fileId "${propertyFileId}"`);
633
677
  // Query database to get refModelId if the property has ref/refModelName
634
678
  // The property should already be in DB from addModelsToDb
@@ -637,24 +681,18 @@ const createModelProperties = fromCallback(({ sendBack, input }) => {
637
681
  try {
638
682
  const refModelName = propData.refModelName || propData.ref;
639
683
  // First try to get refModelId from the property record in the database
640
- const propertyRecords = await db
641
- .select()
642
- .from(properties)
643
- .where(eq(properties.schemaFileId, propertyFileId))
644
- .limit(1);
645
- if (propertyRecords.length > 0 && propertyRecords[0].refModelId) {
646
- refModelId = propertyRecords[0].refModelId;
684
+ if (propertyRecord?.refModelId) {
685
+ refModelId = propertyRecord.refModelId;
647
686
  logger$5(`Found refModelId ${refModelId} from database for property "${propName}"`);
648
687
  }
649
688
  else if (refModelName) {
650
- // Fallback: query models table directly by name
651
- const refModelRecords = await db
652
- .select()
653
- .from(models)
654
- .where(eq(models.name, refModelName))
655
- .limit(1);
656
- if (refModelRecords.length > 0 && refModelRecords[0].id) {
657
- refModelId = refModelRecords[0].id;
689
+ // Fallback: resolve the ref by name within this model's schema
690
+ const _mod_7 = await import('./db-BJZN0a0a.js');
691
+ const _ns_7 = _mod_7.Y;
692
+ const { resolveModelRecord } = _ns_7;
693
+ const refModelRecord = await resolveModelRecord(refModelName, { schemaName }, db);
694
+ if (refModelRecord?.id) {
695
+ refModelId = refModelRecord.id;
658
696
  logger$5(`Resolved refModelId ${refModelId} from model name "${refModelName}" for property "${propName}"`);
659
697
  }
660
698
  }
@@ -678,12 +716,14 @@ const createModelProperties = fromCallback(({ sendBack, input }) => {
678
716
  refModelName: propData.refModelName,
679
717
  refModelId,
680
718
  refValueType: propData.refValueType,
681
- storageType: propData.storageType,
682
- localStorageDir: propData.localStorageDir,
683
- filenameSuffix: propData.filenameSuffix,
719
+ // Definitions built from DB rows may lack storage settings; the row has them.
720
+ storageType: propData.storageType ?? propertyRecord?.storageType ?? undefined,
721
+ localStorageDir: propData.localStorageDir ?? propertyRecord?.localStorageDir ?? undefined,
722
+ filenameSuffix: propData.filenameSuffix ?? propertyRecord?.filenameSuffix ?? undefined,
684
723
  required: propData.required,
685
724
  _propertyFileId: propertyFileId, // Store schemaFileId for getById() lookups
686
- }); // Use 'as any' because _propertyFileId is not in TProperty type
725
+ _dbId: propertyRecord?.schemaFileId === propertyFileId ? propertyRecord.id : undefined, // Already persisted: skip the write
726
+ }, { schemaName }); // Use 'as any' because _propertyFileId is not in TProperty type
687
727
  }
688
728
  logger$5(`Successfully created all properties for model "${modelName}"`);
689
729
  sendBack({ type: 'createModelPropertiesSuccess' });
@@ -717,7 +757,7 @@ const validateEntity = fromPromise(async ({ input }) => {
717
757
  const structureMsg = `[validateEntity] Validating model structure`;
718
758
  logger$4(structureMsg);
719
759
  // Use existing Model validation
720
- const validationServiceMod = await import('./SchemaValidationService-Y49vqast.js');
760
+ const validationServiceMod = await import('./SchemaValidationService-DDKr5piy.js');
721
761
  const { SchemaValidationService } = validationServiceMod;
722
762
  const validationService = new SchemaValidationService();
723
763
  // Validate model structure
@@ -735,9 +775,9 @@ const validateEntity = fromPromise(async ({ input }) => {
735
775
  if (entityInput.entityData.schemaName) {
736
776
  try {
737
777
  logger$4(`[validateEntity] Validating model against schema "${entityInput.entityData.schemaName}"`);
738
- const _mod_5 = await import('./Schema-a8uO-hIZ.js');
739
- const _ns_5 = _mod_5.b;
740
- const schemaMod = _ns_5;
778
+ const _mod_8 = await import('./Schema-DOhlrQ-N.js');
779
+ const _ns_8 = _mod_8.b;
780
+ const schemaMod = _ns_8;
741
781
  const { Schema } = schemaMod;
742
782
  const schema = Schema.create(entityInput.entityData.schemaName, {
743
783
  waitForReady: false,
@@ -773,7 +813,7 @@ const validateEntity = fromPromise(async ({ input }) => {
773
813
  }
774
814
  else if (entityInput.entityType === 'modelProperty') {
775
815
  // Use existing ModelProperty validation
776
- const validationServiceMod = await import('./SchemaValidationService-Y49vqast.js');
816
+ const validationServiceMod = await import('./SchemaValidationService-DDKr5piy.js');
777
817
  const { SchemaValidationService } = validationServiceMod;
778
818
  const validationService = new SchemaValidationService();
779
819
  // Validate property structure
@@ -788,9 +828,9 @@ const validateEntity = fromPromise(async ({ input }) => {
788
828
  // If schema name and model name provided, validate against schema
789
829
  if (entityInput.entityData._schemaName && entityInput.entityData.modelName) {
790
830
  try {
791
- const _mod_6 = await import('./Schema-a8uO-hIZ.js');
792
- const _ns_6 = _mod_6.b;
793
- const schemaMod = _ns_6;
831
+ const _mod_9 = await import('./Schema-DOhlrQ-N.js');
832
+ const _ns_9 = _mod_9.b;
833
+ const schemaMod = _ns_9;
794
834
  const { Schema } = schemaMod;
795
835
  const schema = Schema.create(entityInput.entityData._schemaName, {
796
836
  waitForReady: false,
@@ -819,7 +859,7 @@ const validateEntity = fromPromise(async ({ input }) => {
819
859
  }
820
860
  else if (entityInput.entityType === 'schema') {
821
861
  // Schema validation - use existing validation
822
- const validationServiceMod = await import('./SchemaValidationService-Y49vqast.js');
862
+ const validationServiceMod = await import('./SchemaValidationService-DDKr5piy.js');
823
863
  const { SchemaValidationService } = validationServiceMod;
824
864
  const validationService = new SchemaValidationService();
825
865
  const schemaResult = validationService.validateSchema(entityInput.entityData);
@@ -849,6 +889,22 @@ const validateEntity = fromPromise(async ({ input }) => {
849
889
  });
850
890
 
851
891
  const logger$3 = debug('seedSdk:write:writeToDatabase');
892
+ // Writes that have started. Stopping a write process's actor can't cancel one, so code that deletes rows
893
+ // under live instances (Schema.destroy, test cleanup) waits for these after evicting the instances.
894
+ const inFlightWrites = new Set();
895
+ /**
896
+ * Resolves once every database write started so far has finished (or after timeoutMs). Evict/stop the
897
+ * instances first so no new writes start while waiting.
898
+ */
899
+ const waitForInFlightWrites = async (timeoutMs = 5000) => {
900
+ const deadline = Date.now() + timeoutMs;
901
+ while (inFlightWrites.size > 0 && Date.now() < deadline) {
902
+ await Promise.race([
903
+ Promise.allSettled([...inFlightWrites]),
904
+ new Promise((resolve) => setTimeout(resolve, deadline - Date.now())),
905
+ ]);
906
+ }
907
+ };
852
908
  const writeToDatabase = fromCallback(({ sendBack, input }) => {
853
909
  const _write = async () => {
854
910
  try {
@@ -892,7 +948,7 @@ const writeToDatabase = fromCallback(({ sendBack, input }) => {
892
948
  // initial write completes is not overwritten by the stale requestWrite payload.
893
949
  let dataToWrite = input.entityData;
894
950
  try {
895
- const mod = await import('./ModelProperty-D79uV42p.js');
951
+ const mod = await import('./ModelProperty-lth9L37R.js');
896
952
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
897
953
  if (ModelProperty && typeof ModelProperty.getById === 'function') {
898
954
  const instance = ModelProperty.getById(input.entityId);
@@ -909,6 +965,7 @@ const writeToDatabase = fromCallback(({ sendBack, input }) => {
909
965
  storageType: ctx.storageType ?? input.entityData.storageType,
910
966
  localStorageDir: ctx.localStorageDir ?? input.entityData.localStorageDir,
911
967
  filenameSuffix: ctx.filenameSuffix ?? input.entityData.filenameSuffix,
968
+ required: ctx.required ?? input.entityData.required,
912
969
  };
913
970
  }
914
971
  }
@@ -941,18 +998,26 @@ const writeToDatabase = fromCallback(({ sendBack, input }) => {
941
998
  });
942
999
  }
943
1000
  };
944
- _write().catch((error) => {
1001
+ const write = _write().catch((error) => {
945
1002
  logger$3('Error in writeToDatabase promise:', error);
946
1003
  sendBack({
947
1004
  type: 'writeError',
948
1005
  error: error instanceof Error ? error : new Error(String(error)),
949
1006
  });
950
1007
  });
1008
+ inFlightWrites.add(write);
1009
+ write.finally(() => inFlightWrites.delete(write));
951
1010
  return () => {
952
1011
  // Cleanup function (optional)
953
1012
  };
954
1013
  });
955
1014
 
1015
+ var writeToDatabase$1 = /*#__PURE__*/Object.freeze({
1016
+ __proto__: null,
1017
+ waitForInFlightWrites: waitForInFlightWrites,
1018
+ writeToDatabase: writeToDatabase
1019
+ });
1020
+
956
1021
  const logger$2 = debug('seedSdk:write:writeProcessMachine');
957
1022
  const writeProcessMachine = setup({
958
1023
  types: {
@@ -1131,7 +1196,10 @@ const writeProcessMachine = setup({
1131
1196
  retryCount: ({ context }) => context.retryCount + 1,
1132
1197
  }),
1133
1198
  ({ context, event }) => {
1134
- logger$2(`[writing] Write error for ${context.entityType} "${context.entityId}":`, event.error);
1199
+ const errorMsg = `[writing] Write error for ${context.entityType} "${context.entityId}": ${event.error}`;
1200
+ logger$2(errorMsg);
1201
+ // Nothing else reports a failed persist to the caller, so always log to console
1202
+ console.error(errorMsg, event.error);
1135
1203
  },
1136
1204
  ],
1137
1205
  },
@@ -1189,9 +1257,6 @@ const modelMachine = setup({
1189
1257
  isModelValid: ({ context }) => {
1190
1258
  return !context._validationErrors || context._validationErrors.length === 0;
1191
1259
  },
1192
- hasValidationErrors: ({ context }) => {
1193
- return !!context._validationErrors && context._validationErrors.length > 0;
1194
- },
1195
1260
  },
1196
1261
  actions: {
1197
1262
  assignValidationErrors: assign(({ context, event }) => {
@@ -1272,7 +1337,7 @@ const modelMachine = setup({
1272
1337
  // Create ModelProperty instances for any new property IDs
1273
1338
  if (Array.isArray(newPropertyIds) && newPropertyIds.length > 0) {
1274
1339
  // Import and create instances asynchronously (fire-and-forget)
1275
- import('./ModelProperty-D79uV42p.js').then(({ ModelProperty }) => {
1340
+ import('./ModelProperty-lth9L37R.js').then(({ ModelProperty }) => {
1276
1341
  const createPromises = newPropertyIds.map(async (propertyFileId) => {
1277
1342
  try {
1278
1343
  const property = await ModelProperty.createById(propertyFileId);
@@ -1349,22 +1414,15 @@ const modelMachine = setup({
1349
1414
  })),
1350
1415
  },
1351
1416
  destroyStarted: {
1352
- actions: assign({ _destroyInProgress: true, _destroyError: null }),
1353
- },
1354
- destroyDone: {
1355
- actions: assign({ _destroyInProgress: false }),
1417
+ actions: assign({ _destroyError: null }),
1356
1418
  },
1357
1419
  destroyError: {
1358
1420
  actions: assign(({ event }) => ({
1359
- _destroyInProgress: false,
1360
1421
  _destroyError: event.error instanceof Error
1361
1422
  ? { message: event.error.message, name: event.error.name }
1362
1423
  : { message: String(event.error) },
1363
1424
  })),
1364
1425
  },
1365
- clearDestroyError: {
1366
- actions: assign({ _destroyError: null }),
1367
- },
1368
1426
  },
1369
1427
  states: {
1370
1428
  loading: {
@@ -1497,10 +1555,9 @@ const modelMachine = setup({
1497
1555
  },
1498
1556
  ],
1499
1557
  },
1500
- always: {
1501
- guard: 'hasValidationErrors',
1502
- target: 'validating',
1503
- },
1558
+ // No `always: hasValidationErrors -> validating` here: validation is re-run when the context changes
1559
+ // (updateContext) or on request (validateModel). Re-entering while errors exist would loop forever on a
1560
+ // model that is still invalid.
1504
1561
  },
1505
1562
  validating: {
1506
1563
  on: {
@@ -1550,6 +1607,8 @@ const modelMachine = setup({
1550
1607
  // Trigger property refresh after properties are created
1551
1608
  // This ensures _liveQueryPropertyIds is updated in Node.js where liveQuery isn't available
1552
1609
  setTimeout(() => {
1610
+ if (self.getSnapshot().status === 'stopped')
1611
+ return;
1553
1612
  self.send({ type: 'refreshProperties' });
1554
1613
  }, 100); // Small delay to ensure properties are written to DB
1555
1614
  },
@@ -1579,6 +1638,22 @@ class ConflictError extends Error {
1579
1638
  }
1580
1639
  }
1581
1640
 
1641
+ /**
1642
+ * Common getters and utilities for entity classes
1643
+ * These work with any entity that has a getService() method returning an XState actor
1644
+ */
1645
+ /**
1646
+ * Get the current state value from an entity's service
1647
+ */
1648
+ /**
1649
+ * Whether an actor has been stopped (unload, destroy, or Schema eviction). Async work started by an
1650
+ * entity (DB lookups, retry timers) must check this before sending, since a stopped actor ignores
1651
+ * events and XState warns about every one of them.
1652
+ */
1653
+ function isActorStopped(actor) {
1654
+ return actor.getSnapshot().status === 'stopped';
1655
+ }
1656
+
1582
1657
  /**
1583
1658
  * Set up liveQuery subscription for an entity
1584
1659
  * This enables cross-instance synchronization (e.g., changes in other tabs/windows)
@@ -1608,7 +1683,9 @@ function setupEntityLiveQuery(instance, config) {
1608
1683
  if (config.createChildInstances) {
1609
1684
  await config.createChildInstances(initialIds);
1610
1685
  }
1611
- // Update context with initial IDs
1686
+ // Update context with initial IDs (the queries above can outlive the instance)
1687
+ if (isActorStopped(instance.getService()))
1688
+ return;
1612
1689
  config.updateContext(instance, initialIds);
1613
1690
  }
1614
1691
  }
@@ -1638,6 +1715,8 @@ function setupEntityLiveQuery(instance, config) {
1638
1715
  await config.createChildInstances(ids);
1639
1716
  }
1640
1717
  // Update context with new IDs
1718
+ if (isActorStopped(instance.getService()))
1719
+ return;
1641
1720
  config.updateContext(instance, ids);
1642
1721
  },
1643
1722
  error: (error) => {
@@ -1656,9 +1735,31 @@ function setupEntityLiveQuery(instance, config) {
1656
1735
  setupState.subscriptionSetUp = false; // Reset on error so we can retry
1657
1736
  }
1658
1737
  };
1659
- // Set up liveQuery subscription as soon as we have entity ID
1660
- const setupSubscription = instance.getService().subscribe(async (snapshot) => {
1661
- // Check if entity is ready
1738
+ // The entity's DB row can be written after the entity goes idle (e.g. a schema import writes its
1739
+ // models' rows after the Model instances loaded from the schema file). Nothing changes the
1740
+ // entity's snapshot then, so an idle entity's id is also retried on a timer until found or the
1741
+ // actor stops. Only while idle and not writing (canRetryEntityId): a busy entity's own snapshots
1742
+ // drive the lookup, and finding its row mid-write handed a Model its _dbId before its write (and
1743
+ // its properties' rows) had finished.
1744
+ let retryIndex = 0;
1745
+ let retryTimer;
1746
+ const scheduleRetry = () => {
1747
+ if (retryTimer !== undefined || retryIndex >= ENTITY_ID_RETRY_DELAYS_MS.length)
1748
+ return;
1749
+ retryTimer = setTimeout(() => {
1750
+ retryTimer = undefined;
1751
+ // Busy: its next snapshot retries
1752
+ if (instance.getService().getSnapshot().value !== 'idle')
1753
+ return;
1754
+ if (config.canRetryEntityId && !config.canRetryEntityId(instance))
1755
+ return;
1756
+ retryIndex++;
1757
+ void trySetup();
1758
+ }, ENTITY_ID_RETRY_DELAYS_MS[retryIndex]);
1759
+ };
1760
+ const trySetup = async () => {
1761
+ if (setupState.subscriptionSetUp || isActorStopped(instance.getService()))
1762
+ return;
1662
1763
  if (config.isReady && !config.isReady(instance)) {
1663
1764
  if (config.waitForReady) {
1664
1765
  await config.waitForReady(instance);
@@ -1667,35 +1768,42 @@ function setupEntityLiveQuery(instance, config) {
1667
1768
  return; // Not ready yet, will retry on next snapshot
1668
1769
  }
1669
1770
  }
1670
- // Get entity ID
1671
- const entityId = await config.getEntityId(instance);
1771
+ let entityId;
1772
+ try {
1773
+ entityId = await config.getEntityId(instance);
1774
+ }
1775
+ catch (error) {
1776
+ logger(`Error getting entity ID: ${error}`);
1777
+ }
1672
1778
  if (!entityId) {
1673
- return; // Need entity ID to proceed
1779
+ scheduleRetry();
1780
+ return;
1674
1781
  }
1675
1782
  // Once we have entity ID, set up the liveQuery subscription (only once)
1676
1783
  if (!setupState.subscriptionSetUp) {
1677
1784
  await setupLiveQuery(entityId);
1678
- if (setupState.subscriptionSetUp) {
1679
- setupSubscription.unsubscribe();
1680
- }
1681
1785
  }
1682
- });
1683
- // Also check current state immediately in case entity ID is already available
1684
- instance.getService().getSnapshot();
1685
- if (config.isReady && !config.isReady(instance)) {
1686
- // Not ready yet, will be handled by subscription
1687
- return;
1688
- }
1689
- config.getEntityId(instance).then((entityId) => {
1690
- if (entityId && !setupState.subscriptionSetUp) {
1691
- setupLiveQuery(entityId).catch((error) => {
1692
- logger(`Error in immediate setup: ${error}`);
1693
- });
1786
+ if (setupState.subscriptionSetUp) {
1787
+ setupSubscription.unsubscribe();
1788
+ if (retryTimer !== undefined)
1789
+ clearTimeout(retryTimer);
1694
1790
  }
1695
- }).catch((error) => {
1696
- logger(`Error getting entity ID: ${error}`);
1791
+ };
1792
+ // Set up liveQuery subscription as soon as we have entity ID
1793
+ const setupSubscription = instance.getService().subscribe({
1794
+ next: () => {
1795
+ void trySetup();
1796
+ },
1797
+ complete: () => {
1798
+ if (retryTimer !== undefined)
1799
+ clearTimeout(retryTimer);
1800
+ },
1697
1801
  });
1802
+ // Also check current state immediately in case entity ID is already available
1803
+ void trySetup();
1698
1804
  }
1805
+ /** Backoff for retrying an entity's id when its DB row isn't there yet (~60s in total). */
1806
+ const ENTITY_ID_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600, ...Array(28).fill(2000)];
1699
1807
 
1700
1808
  /**
1701
1809
  * Returns model rows (id, name, schemaFileId, isEdited) for building Model instances.
@@ -1743,7 +1851,7 @@ const saveDraftLogger = debug('seedSdk:model:saveDraftToDb');
1743
1851
  // Lazy import cache for ModelProperty to avoid circular dependency
1744
1852
  // Eagerly start loading to minimize delay on first access
1745
1853
  let ModelPropertyClass = null;
1746
- const modelPropertyImportPromise = import('./ModelProperty-D79uV42p.js')
1854
+ const modelPropertyImportPromise = import('./ModelProperty-lth9L37R.js')
1747
1855
  .then(module => {
1748
1856
  ModelPropertyClass = module.ModelProperty;
1749
1857
  return ModelPropertyClass;
@@ -1758,17 +1866,10 @@ function getModelProperty() {
1758
1866
  // and the getter will return empty array, which matches the original behavior
1759
1867
  return ModelPropertyClass;
1760
1868
  }
1761
- // Lazy import cache for Schema to avoid circular dependency
1762
- let SchemaClass = null;
1763
- const schemaImportPromise = (async () => { const _mod_7 = await import('./Schema-a8uO-hIZ.js'); return _mod_7.b; })()
1764
- .then(module => {
1765
- SchemaClass = module.Schema;
1766
- return SchemaClass;
1767
- })
1768
- .catch(() => {
1769
- // If import fails, SchemaClass remains null
1770
- return null;
1771
- });
1869
+ // Lazy import for Schema to avoid circular dependency
1870
+ const schemaImportPromise = (async () => { const _mod_12 = await import('./Schema-DOhlrQ-N.js'); return _mod_12.b; })()
1871
+ .then(module => module.Schema)
1872
+ .catch(() => null);
1772
1873
  // WeakMap to store mutable state per Model instance
1773
1874
  // This avoids issues with read-only properties when instances are frozen by Immer
1774
1875
  const modelInstanceState = new WeakMap();
@@ -1830,6 +1931,14 @@ class Model {
1830
1931
  });
1831
1932
  // Note: Property getters/setters are now handled by the Proxy in create()
1832
1933
  }
1934
+ /**
1935
+ * True when a name-cached instance belongs to a different model than the requested modelFileId.
1936
+ * A schema re-imported under the same name can give its models new ids while the previous
1937
+ * instances are still cached by name; Model.create must not hand those back for the new id.
1938
+ */
1939
+ static isOtherModelId(cachedId, requestedId) {
1940
+ return !!requestedId && !!cachedId && cachedId !== requestedId;
1941
+ }
1833
1942
  /**
1834
1943
  * Find a unique model name by checking for duplicates (case-insensitive) in the cache
1835
1944
  * If duplicates are found, appends an incrementing number to make it unique
@@ -1888,36 +1997,6 @@ class Model {
1888
1997
  }
1889
1998
  }
1890
1999
  }
1891
- // Also check schema context models (case-insensitive)
1892
- // This ensures runtime-created models are renamed if they conflict with schema-defined models
1893
- try {
1894
- // Use lazy-loaded Schema class to avoid circular dependency
1895
- if (SchemaClass) {
1896
- const schema = SchemaClass.create(schemaName);
1897
- const schemaContext = schema.getService().getSnapshot().context;
1898
- if (schemaContext.models) {
1899
- for (const schemaModelName of Object.keys(schemaContext.models)) {
1900
- const lowerSchemaModelName = schemaModelName.toLowerCase();
1901
- // If it matches the base name (case-insensitive), check if it has a number suffix
1902
- if (lowerSchemaModelName === lowerModelName) {
1903
- existingNumbers.add(0); // Base name exists in schema
1904
- }
1905
- else if (lowerSchemaModelName.startsWith(lowerModelName + ' ')) {
1906
- // Check if it's the base name followed by a space and a number
1907
- const suffix = lowerSchemaModelName.slice(lowerModelName.length + 1);
1908
- const number = parseInt(suffix, 10);
1909
- if (!isNaN(number) && suffix === number.toString()) {
1910
- existingNumbers.add(number);
1911
- }
1912
- }
1913
- }
1914
- }
1915
- }
1916
- }
1917
- catch (error) {
1918
- // If schema check fails, continue with cache-only check
1919
- // This is a best-effort check and shouldn't block model creation
1920
- }
1921
2000
  // If no duplicates found (no base name match and no numbered variants), return original name
1922
2001
  if (existingNumbers.size === 0) {
1923
2002
  return modelName;
@@ -1997,7 +2076,7 @@ class Model {
1997
2076
  if (this.instanceCache.has(legacyKey)) {
1998
2077
  const { instance, refCount } = this.instanceCache.get(legacyKey);
1999
2078
  const ctx = instance._getSnapshotContext();
2000
- if (!ctx._idFromSchema) {
2079
+ if (!ctx._idFromSchema && !this.isOtherModelId(ctx.id, id)) {
2001
2080
  this.instanceCache.set(legacyKey, {
2002
2081
  instance,
2003
2082
  refCount: refCount + 1,
@@ -2033,7 +2112,8 @@ class Model {
2033
2112
  : `${schemaName}:__pending__${resolvedId}`;
2034
2113
  // Step 6: Check legacy cache with unique name (backward compatibility during migration)
2035
2114
  // This is a fallback in case an instance was cached with a unique name
2036
- if (this.instanceCache.has(nameKey)) {
2115
+ if (this.instanceCache.has(nameKey) &&
2116
+ !this.isOtherModelId(this.instanceCache.get(nameKey).instance._getSnapshotContext().id, id)) {
2037
2117
  const { instance, refCount } = this.instanceCache.get(nameKey);
2038
2118
  this.instanceCache.set(nameKey, {
2039
2119
  instance,
@@ -2415,6 +2495,9 @@ class Model {
2415
2495
  let retries = 0;
2416
2496
  const maxRetries = 10;
2417
2497
  const checkAndSend = async () => {
2498
+ // Unloaded or evicted (e.g. Schema.destroy) before the write started: nothing to write to
2499
+ if (isActorStopped(proxiedInstance._service))
2500
+ return;
2418
2501
  const currentSnapshot = proxiedInstance._service.getSnapshot();
2419
2502
  if (currentSnapshot.context.writeProcess) {
2420
2503
  logger(`Triggering write process for model "${finalSnapshot.context.modelName}" (schemaId: ${schemaId})`);
@@ -2540,14 +2623,45 @@ class Model {
2540
2623
  }
2541
2624
  return this.getById(id);
2542
2625
  }
2543
- // If schemaName not provided, try to find in cache by searching all name keys
2626
+ // If schemaName not provided, search all name keys. Model names are only unique per schema, so
2627
+ // this throws AmbiguousModelError when cached models from several schemas share the name.
2628
+ // Callers that know the schema or model id should use Model.resolve() instead.
2629
+ return this._getUniqueCachedModel(modelName, (cachedModelName) => cachedModelName === modelName);
2630
+ }
2631
+ /** The one cached Model whose name matches, or AmbiguousModelError if models from several schemas do. */
2632
+ static _getUniqueCachedModel(label, matches) {
2633
+ const matchesById = new Map(); // modelFileId -> schemaName
2544
2634
  for (const [nameKey, id] of this.instanceCacheByName.entries()) {
2545
- const [, cachedModelName] = nameKey.split(':');
2546
- if (cachedModelName === modelName) {
2547
- return this.getById(id);
2635
+ const separator = nameKey.lastIndexOf(':');
2636
+ const cachedModelName = nameKey.slice(separator + 1);
2637
+ if (id && cachedModelName && matches(cachedModelName) && this.instanceCacheById.has(id)) {
2638
+ matchesById.set(id, nameKey.slice(0, separator));
2548
2639
  }
2549
2640
  }
2550
- return undefined;
2641
+ if (matchesById.size > 1) {
2642
+ throw new AmbiguousModelError(label, [...matchesById.values()]);
2643
+ }
2644
+ const [matchId] = matchesById.keys();
2645
+ return matchId ? this.getById(matchId) : undefined;
2646
+ }
2647
+ /**
2648
+ * Resolve a cached Model from the most specific scope available: modelFileId (Model.id), then
2649
+ * schemaName + modelName, then modelName alone.
2650
+ */
2651
+ static resolve(modelName, scope = {}) {
2652
+ if (scope.modelFileId) {
2653
+ const byId = this.getById(scope.modelFileId);
2654
+ if (byId)
2655
+ return byId;
2656
+ }
2657
+ if (!modelName)
2658
+ return undefined;
2659
+ if (scope.schemaName) {
2660
+ const bySchema = this.getByName(modelName, scope.schemaName);
2661
+ if (bySchema)
2662
+ return bySchema;
2663
+ }
2664
+ return this.getByName(modelName);
2551
2665
  }
2552
2666
  /**
2553
2667
  * Find Model by modelType (snake_case from DB/metadata).
@@ -2556,14 +2670,7 @@ class Model {
2556
2670
  static findByModelType(modelType) {
2557
2671
  if (!modelType)
2558
2672
  return undefined;
2559
- for (const [nameKey, id] of this.instanceCacheByName.entries()) {
2560
- const parts = nameKey.split(':', 2);
2561
- const cachedModelName = parts[1];
2562
- if (cachedModelName && toSnakeCase(cachedModelName) === modelType) {
2563
- return this.getById(id);
2564
- }
2565
- }
2566
- return undefined;
2673
+ return this._getUniqueCachedModel(modelType, (cachedModelName) => toSnakeCase(cachedModelName) === modelType);
2567
2674
  }
2568
2675
  /**
2569
2676
  * Get all Model instances for a schema from cache only (synchronous).
@@ -2595,6 +2702,50 @@ class Model {
2595
2702
  }
2596
2703
  return instances;
2597
2704
  }
2705
+ /**
2706
+ * Async Model.resolve(): exact cache hit by modelFileId or schemaName+modelName, else the DB row for
2707
+ * that scope (instantiating the Model), and only then the name-only fallback.
2708
+ */
2709
+ static async resolveAsync(modelName, scope = {}) {
2710
+ if (scope.modelFileId) {
2711
+ const byId = this.getById(scope.modelFileId);
2712
+ if (byId)
2713
+ return byId;
2714
+ }
2715
+ if (modelName && scope.schemaName) {
2716
+ const bySchema = this.getByName(modelName, scope.schemaName);
2717
+ if (bySchema)
2718
+ return bySchema;
2719
+ }
2720
+ if (scope.modelFileId || scope.schemaName) {
2721
+ const db = BaseDb.getAppDb();
2722
+ if (db) {
2723
+ try {
2724
+ const rows = await db
2725
+ .select({
2726
+ modelFileId: models.schemaFileId,
2727
+ modelName: models.name,
2728
+ schemaName: schemas.name,
2729
+ })
2730
+ .from(models)
2731
+ .innerJoin(modelSchemas, eq(models.id, modelSchemas.modelId))
2732
+ .innerJoin(schemas, eq(modelSchemas.schemaId, schemas.id))
2733
+ .where(scope.modelFileId
2734
+ ? eq(models.schemaFileId, scope.modelFileId)
2735
+ : and(eq(models.name, modelName ?? ''), eq(schemas.name, scope.schemaName)))
2736
+ .limit(1);
2737
+ const record = rows[0];
2738
+ if (record?.modelName && record.schemaName && record.modelFileId) {
2739
+ return this.create(record.modelName, record.schemaName, { id: record.modelFileId });
2740
+ }
2741
+ }
2742
+ catch (error) {
2743
+ logger(`Model.resolveAsync: scoped lookup failed for "${modelName}": ${error instanceof Error ? error.message : String(error)}`);
2744
+ }
2745
+ }
2746
+ }
2747
+ return modelName ? this.getByNameAsync(modelName) : undefined;
2748
+ }
2598
2749
  /**
2599
2750
  * Get Model instance by name, querying database if not in cache
2600
2751
  * This is an async version that can query the database when schemaName is not provided
@@ -2616,7 +2767,14 @@ class Model {
2616
2767
  return undefined;
2617
2768
  }
2618
2769
  try {
2619
- // Query model by name
2770
+ // Query model by name (throws AmbiguousModelError when several schemas define it)
2771
+ const _mod_10 = await import('./db-BJZN0a0a.js');
2772
+ const _ns_10 = _mod_10.Y;
2773
+ const { resolveModelRecord } = _ns_10;
2774
+ const resolved = await resolveModelRecord(modelName, {}, db);
2775
+ if (!resolved?.schemaFileId) {
2776
+ return undefined;
2777
+ }
2620
2778
  const modelRecords = await db
2621
2779
  .select({
2622
2780
  modelFileId: models.schemaFileId,
@@ -2626,7 +2784,7 @@ class Model {
2626
2784
  .from(models)
2627
2785
  .innerJoin(modelSchemas, eq(models.id, modelSchemas.modelId))
2628
2786
  .innerJoin(schemas, eq(modelSchemas.schemaId, schemas.id))
2629
- .where(eq(models.name, modelName))
2787
+ .where(eq(models.id, resolved.id))
2630
2788
  .limit(1);
2631
2789
  if (modelRecords.length === 0) {
2632
2790
  return undefined;
@@ -2641,6 +2799,8 @@ class Model {
2641
2799
  });
2642
2800
  }
2643
2801
  catch (error) {
2802
+ if (error instanceof AmbiguousModelError)
2803
+ throw error;
2644
2804
  logger(`Model.getByNameAsync: Error looking up model by name "${modelName}": ${error instanceof Error ? error.message : String(error)}`);
2645
2805
  return undefined;
2646
2806
  }
@@ -2846,9 +3006,10 @@ class Model {
2846
3006
  const instances = [];
2847
3007
  const seen = new Set();
2848
3008
  for (const row of rows) {
2849
- if (row.schemaFileId) {
3009
+ // A model can appear more than once (e.g. duplicate model_schemas links); return it once.
3010
+ if (row.schemaFileId && !seen.has(row.schemaFileId)) {
2850
3011
  const instance = await this.createById(row.schemaFileId);
2851
- if (instance) {
3012
+ if (instance && !seen.has(instance.id ?? row.schemaFileId)) {
2852
3013
  instances.push(instance);
2853
3014
  seen.add(instance.id ?? row.schemaFileId);
2854
3015
  }
@@ -3206,6 +3367,50 @@ class Model {
3206
3367
  }, 10000);
3207
3368
  });
3208
3369
  }
3370
+ /**
3371
+ * Force-evict every cached Model belonging to a schema, ignoring refCounts, and stop their services.
3372
+ * Used by Schema.destroy(): once the DB rows are gone, cached instances would keep a dangling _dbId
3373
+ * and be handed back by Model.create/Model.all after the schema is re-imported.
3374
+ * @returns names of the evicted models (so callers can evict their ModelProperty instances)
3375
+ */
3376
+ static evictForSchema(schemaName) {
3377
+ const instances = new Set();
3378
+ for (const { instance } of this.instanceCacheById.values())
3379
+ instances.add(instance);
3380
+ for (const { instance } of this.instanceCache.values())
3381
+ instances.add(instance);
3382
+ const evictedNames = [];
3383
+ for (const instance of instances) {
3384
+ let context;
3385
+ try {
3386
+ context = instance._getSnapshotContext();
3387
+ }
3388
+ catch {
3389
+ continue;
3390
+ }
3391
+ if (context.schemaName !== schemaName)
3392
+ continue;
3393
+ const nameKey = `${context.schemaName}:${context.modelName}`;
3394
+ clearDestroySubscriptions(instance, { instanceState: modelInstanceState });
3395
+ forceRemoveFromCaches(instance, {
3396
+ getCacheKeys: () => (context.id ? [context.id, nameKey] : [nameKey]),
3397
+ caches: [
3398
+ Model.instanceCacheById,
3399
+ Model.instanceCacheByName,
3400
+ Model.instanceCache,
3401
+ ],
3402
+ });
3403
+ try {
3404
+ instance._service.stop();
3405
+ }
3406
+ catch {
3407
+ // Service might already be stopped
3408
+ }
3409
+ if (context.modelName)
3410
+ evictedNames.push(context.modelName);
3411
+ }
3412
+ return evictedNames;
3413
+ }
3209
3414
  /**
3210
3415
  * Unload the model instance and clean up resources
3211
3416
  */
@@ -3320,16 +3525,18 @@ class Model {
3320
3525
  if (!db) {
3321
3526
  return undefined;
3322
3527
  }
3323
- const modelRecords = await db
3324
- .select()
3325
- .from(models)
3326
- .where(eq(models.name, modelName))
3327
- .limit(1);
3328
- if (modelRecords.length === 0 || !modelRecords[0].id) {
3528
+ // Model names are only unique per schema: find this model's row by its id (schemaFileId).
3529
+ const _mod_11 = await import('./db-BJZN0a0a.js');
3530
+ const _ns_11 = _mod_11.Y;
3531
+ const { resolveModelRecord } = _ns_11;
3532
+ const modelRecord = await resolveModelRecord(modelName, { modelFileId: context.id, schemaName: context.schemaName }, db);
3533
+ if (!modelRecord?.id) {
3329
3534
  return undefined;
3330
3535
  }
3331
- dbId = modelRecords[0].id;
3332
- // Update context with _dbId
3536
+ dbId = modelRecord.id;
3537
+ // Update context with _dbId (unless the model was stopped while the lookup ran)
3538
+ if (isActorStopped(model._service))
3539
+ return undefined;
3333
3540
  model._service.send({
3334
3541
  type: 'updateContext',
3335
3542
  _dbId: dbId,
@@ -3389,6 +3596,12 @@ class Model {
3389
3596
  schemaFileId: row.schemaFileId,
3390
3597
  }));
3391
3598
  },
3599
+ // The model writes from its writeProcess child while itself idle; wait for that write to end.
3600
+ canRetryEntityId: (model) => {
3601
+ const writeProcess = model._getSnapshotContext().writeProcess;
3602
+ const writeState = writeProcess?.getSnapshot().value;
3603
+ return writeState !== 'validating' && writeState !== 'writing';
3604
+ },
3392
3605
  instanceState: modelInstanceState,
3393
3606
  loggerName: 'seedSdk:model:liveQuery',
3394
3607
  });
@@ -3412,6 +3625,9 @@ class Model {
3412
3625
  .select({ schemaFileId: properties.schemaFileId })
3413
3626
  .from(properties)
3414
3627
  .where(eq(properties.modelId, dbId)); // Use _dbId (database integer ID)
3628
+ // Stopped while querying: don't re-cache ModelProperty instances for an evicted/unloaded model
3629
+ if (isActorStopped(this._service))
3630
+ return;
3415
3631
  const propertyIds = propertyRows
3416
3632
  .map((row) => row.schemaFileId)
3417
3633
  .filter((id) => id !== null && id !== undefined);
@@ -3446,7 +3662,10 @@ class Model {
3446
3662
  logger(`[Model._refreshPropertiesFromDb] Error importing ModelProperty or creating instances: ${error}`);
3447
3663
  }
3448
3664
  }
3449
- // Update context with refreshed property IDs AFTER creating instances
3665
+ // Update context with refreshed property IDs AFTER creating instances (the awaits above can
3666
+ // outlive the instance)
3667
+ if (isActorStopped(this._service))
3668
+ return;
3450
3669
  this._service.send({
3451
3670
  type: 'updateContext',
3452
3671
  _liveQueryPropertyIds: propertyIds,
@@ -3463,6 +3682,30 @@ class Model {
3463
3682
  async refreshProperties() {
3464
3683
  await this._refreshPropertiesFromDb();
3465
3684
  }
3685
+ /**
3686
+ * Refresh the property ids of every cached Model whose DB row is `dbId`. Called when a property
3687
+ * write for that model finishes: until then `properties` includes it as a pending write, and in Node
3688
+ * (no reactive liveQuery) nothing else adds it to `_liveQueryPropertyIds`.
3689
+ */
3690
+ static async refreshPropertiesForDbId(dbId) {
3691
+ const instances = new Set();
3692
+ for (const { instance } of this.instanceCacheById.values())
3693
+ instances.add(instance);
3694
+ for (const { instance } of this.instanceCache.values())
3695
+ instances.add(instance);
3696
+ for (const instance of instances) {
3697
+ let context;
3698
+ try {
3699
+ context = instance._getSnapshotContext();
3700
+ }
3701
+ catch {
3702
+ continue;
3703
+ }
3704
+ if (context._dbId !== dbId)
3705
+ continue;
3706
+ await instance._refreshPropertiesFromDb();
3707
+ }
3708
+ }
3466
3709
  }
3467
3710
  // Primary cache: ID-based (never changes on rename)
3468
3711
  Model.instanceCacheById = new Map();
@@ -3488,5 +3731,5 @@ var Model$1 = /*#__PURE__*/Object.freeze({
3488
3731
  const TModelValues = Type.Record(Type.String(), Type.Any());
3489
3732
  const TModelSchema = Type.Record(Type.String(), TProperty);
3490
3733
 
3491
- export { ConflictError as C, Model as M, TModelSchema as T, TModelValues as a, Model$1 as b, setupEntityLiveQuery as s, writeProcessMachine as w };
3492
- //# sourceMappingURL=index-HRHkbVQd.js.map
3734
+ export { ConflictError as C, Model as M, TModelSchema as T, TModelValues as a, writeToDatabase$1 as b, Model$1 as c, isActorStopped as i, setupEntityLiveQuery as s, writeProcessMachine as w };
3735
+ //# sourceMappingURL=index-DtfjeuxC.js.map