@seedprotocol/sdk 0.7.9-next.1189.g5e63267 → 0.7.9

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 (581) hide show
  1. package/dist/BaseFileManager-BAlySv8w.js +650 -0
  2. package/dist/BaseFileManager-BAlySv8w.js.map +1 -0
  3. package/dist/{Item-CG5IhPtL.js → Item-Bf4kWKpH.js} +5576 -6649
  4. package/dist/Item-Bf4kWKpH.js.map +1 -0
  5. package/dist/{ModelProperty-DDD47KVm.js → ModelProperty-BlaEgb_U.js} +345 -709
  6. package/dist/ModelProperty-BlaEgb_U.js.map +1 -0
  7. package/dist/Schema-J_1f6p0c.js +1456 -0
  8. package/dist/Schema-J_1f6p0c.js.map +1 -0
  9. package/dist/{SchemaValidationService-CZzKNL04.js → SchemaValidationService-CnmKyzR-.js} +6 -9
  10. package/dist/{SchemaValidationService-CZzKNL04.js.map → SchemaValidationService-CnmKyzR-.js.map} +1 -1
  11. package/dist/{configurePlatform-Dukm2QwO.js → configurePlatform-CiOJ1R3q.js} +3 -12
  12. package/dist/configurePlatform-CiOJ1R3q.js.map +1 -0
  13. package/dist/db/drizzle/0026_add_content_hash_to_schemas.sql +1 -0
  14. package/dist/db/drizzle/0027_link_metadata_property_ids.sql +74 -0
  15. package/dist/db/drizzle/0028_add_definition_to_properties.sql +17 -0
  16. package/dist/db/drizzle/0029_dedupe_chain_uids_add_unique_indexes.sql +120 -0
  17. package/dist/db/drizzle/meta/0026_snapshot.json +1659 -0
  18. package/dist/db/drizzle/meta/0027_snapshot.json +1659 -0
  19. package/dist/db/drizzle/meta/0028_snapshot.json +1666 -0
  20. package/dist/db/drizzle/meta/0029_snapshot.json +1691 -0
  21. package/dist/db/drizzle/meta/_journal.json +29 -1
  22. package/dist/{detachRowsBeforeDelete-Di1enVUF.js → detachRowsBeforeDelete-sEaUwlOU.js} +2 -13
  23. package/dist/{detachRowsBeforeDelete-Di1enVUF.js.map → detachRowsBeforeDelete-sEaUwlOU.js.map} +1 -1
  24. package/dist/dist/{index-rOTW-2QZ.d.ts → BaseFileManager-BAlySv8w.d.ts} +1407 -2700
  25. package/dist/dist/BaseFileManager-BAlySv8w.d.ts.map +1 -0
  26. package/dist/dist/{configurePlatform-Dukm2QwO.d.ts → configurePlatform-CiOJ1R3q.d.ts} +1 -1
  27. package/dist/dist/configurePlatform-CiOJ1R3q.d.ts.map +1 -0
  28. package/dist/dist/{index-DxHpPNfn.d.ts → index-D0V-mjCV.d.ts} +39 -1
  29. package/dist/dist/{index-DxHpPNfn.d.ts.map → index-D0V-mjCV.d.ts.map} +1 -1
  30. package/dist/dist/{index.node-WsEJCOwC.d.ts → index.node-CYPemH-t.d.ts} +157 -5
  31. package/dist/dist/{index.node-WsEJCOwC.d.ts.map → index.node-CYPemH-t.d.ts.map} +1 -1
  32. package/dist/dist/platform.node.d.ts +2 -2
  33. package/dist/eas-wB_fQ8Tc.js +32 -0
  34. package/dist/eas-wB_fQ8Tc.js.map +1 -0
  35. package/dist/errors-DLSoqSHG.js +6550 -0
  36. package/dist/errors-DLSoqSHG.js.map +1 -0
  37. package/dist/getPublishPayload-BnIwpwz1.js +760 -0
  38. package/dist/getPublishPayload-BnIwpwz1.js.map +1 -0
  39. package/dist/getPublishPendingDiff-D6_-A5ns.js +125 -0
  40. package/dist/getPublishPendingDiff-D6_-A5ns.js.map +1 -0
  41. package/dist/getPublishUploads-sS6JfPgz.js +783 -0
  42. package/dist/getPublishUploads-sS6JfPgz.js.map +1 -0
  43. package/dist/{index-DQoyhp2c.js → index-BVBmz_cc.js} +11 -14
  44. package/dist/index-BVBmz_cc.js.map +1 -0
  45. package/dist/index-CYGWPoOx.js +27 -0
  46. package/dist/index-CYGWPoOx.js.map +1 -0
  47. package/dist/{index-DxHpPNfn.js → index-D0V-mjCV.js} +2 -2
  48. package/dist/index-D0V-mjCV.js.map +1 -0
  49. package/dist/index-DmTtj1nk.js +817 -0
  50. package/dist/index-DmTtj1nk.js.map +1 -0
  51. package/dist/{index.browser-QPWBkLJA.js → index.browser-CUmBVYen.js} +397 -356
  52. package/dist/index.browser-CUmBVYen.js.map +1 -0
  53. package/dist/{index.node-WsEJCOwC.js → index.node-CYPemH-t.js} +10 -10
  54. package/dist/index.node-CYPemH-t.js.map +1 -0
  55. package/dist/main.js +23 -1075
  56. package/dist/main.js.map +1 -1
  57. package/dist/modelPropertyRecordSchemas-C7UgA5TH.js +48 -0
  58. package/dist/modelPropertyRecordSchemas-C7UgA5TH.js.map +1 -0
  59. package/dist/node.js +14 -18
  60. package/dist/node.js.map +1 -1
  61. package/dist/platform.browser.js +8 -13
  62. package/dist/platform.browser.js.map +1 -1
  63. package/dist/platform.node.js +6 -16
  64. package/dist/platform.node.js.map +1 -1
  65. package/dist/property-BxUYznH0.js +87 -0
  66. package/dist/property-BxUYznH0.js.map +1 -0
  67. package/dist/publishGraph-EcB40Uii.js +311 -0
  68. package/dist/publishGraph-EcB40Uii.js.map +1 -0
  69. package/dist/readHtmlBodyForStorageSeed-D6KPtWoR.js +110 -0
  70. package/dist/readHtmlBodyForStorageSeed-D6KPtWoR.js.map +1 -0
  71. package/dist/seedSchema/ModelSchema.ts +4 -0
  72. package/dist/seedSchema/ModelSchemaSchema.ts +5 -2
  73. package/dist/seedSchema/PendingWriteSchema.ts +4 -1
  74. package/dist/seedSchema/SchemaSchema.ts +3 -0
  75. package/dist/seedSchema/SeedSchema.ts +8 -2
  76. package/dist/seedSchema/VersionSchema.ts +7 -2
  77. package/dist/seedSchema/attestedUid.ts +10 -0
  78. package/dist/src/Item/Item.d.ts +32 -30
  79. package/dist/src/Item/Item.d.ts.map +1 -1
  80. package/dist/src/Item/loadItem.d.ts +12 -0
  81. package/dist/src/Item/loadItem.d.ts.map +1 -0
  82. package/dist/src/Item/service/itemMachineSingle.d.ts +2 -13
  83. package/dist/src/Item/service/itemMachineSingle.d.ts.map +1 -1
  84. package/dist/src/ItemProperty/ItemProperty.d.ts +77 -46
  85. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  86. package/dist/src/ItemProperty/loadProperty.d.ts +11 -0
  87. package/dist/src/ItemProperty/loadProperty.d.ts.map +1 -0
  88. package/dist/src/ItemProperty/propertyWrite.d.ts +54 -0
  89. package/dist/src/ItemProperty/propertyWrite.d.ts.map +1 -0
  90. package/dist/src/ItemProperty/{service/actors/saveValueToDb/rowContext.d.ts → rowContext.d.ts} +1 -1
  91. package/dist/src/ItemProperty/rowContext.d.ts.map +1 -0
  92. package/dist/src/ItemProperty/service/actors/hydrateFromDb.d.ts +6 -0
  93. package/dist/src/ItemProperty/service/actors/hydrateFromDb.d.ts.map +1 -1
  94. package/dist/src/ItemProperty/service/actors/modelPropertyRecordSchemas.d.ts +5 -15
  95. package/dist/src/ItemProperty/service/actors/modelPropertyRecordSchemas.d.ts.map +1 -1
  96. package/dist/src/ItemProperty/service/propertyMachine.d.ts +4 -50
  97. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  98. package/dist/src/Model/Model.d.ts +26 -56
  99. package/dist/src/Model/Model.d.ts.map +1 -1
  100. package/dist/src/Model/createModelProperties.d.ts +10 -0
  101. package/dist/src/Model/createModelProperties.d.ts.map +1 -0
  102. package/dist/src/Model/loadModel.d.ts +13 -0
  103. package/dist/src/Model/loadModel.d.ts.map +1 -0
  104. package/dist/src/Model/service/actors/validateModel.d.ts.map +1 -1
  105. package/dist/src/Model/service/modelMachine.d.ts +5 -114
  106. package/dist/src/Model/service/modelMachine.d.ts.map +1 -1
  107. package/dist/src/ModelProperty/ModelProperty.d.ts +44 -37
  108. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  109. package/dist/src/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  110. package/dist/src/ModelProperty/service/actors/validateProperty.d.ts.map +1 -1
  111. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts +6 -77
  112. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  113. package/dist/src/Schema/Schema.d.ts +36 -37
  114. package/dist/src/Schema/Schema.d.ts.map +1 -1
  115. package/dist/src/Schema/loadOrCreateSchema.d.ts +21 -0
  116. package/dist/src/Schema/loadOrCreateSchema.d.ts.map +1 -0
  117. package/dist/src/Schema/service/schemaMachine.d.ts +7 -125
  118. package/dist/src/Schema/service/schemaMachine.d.ts.map +1 -1
  119. package/dist/src/browser/db/Db.d.ts.map +1 -1
  120. package/dist/src/browser/db/changeFeed.d.ts +2 -18
  121. package/dist/src/browser/db/changeFeed.d.ts.map +1 -1
  122. package/dist/src/browser/db/drizzleFiles.d.ts +6 -2
  123. package/dist/src/browser/db/drizzleFiles.d.ts.map +1 -1
  124. package/dist/src/browser/workers/filesDownload.d.ts.map +1 -1
  125. package/dist/src/browser/workers/imageResize.d.ts.map +1 -1
  126. package/dist/src/client/ClientManager.d.ts +90 -57
  127. package/dist/src/client/ClientManager.d.ts.map +1 -1
  128. package/dist/src/client/actors/addModelsToDb.d.ts +9 -7
  129. package/dist/src/client/actors/addModelsToDb.d.ts.map +1 -1
  130. package/dist/src/client/actors/dbInit.d.ts +3 -3
  131. package/dist/src/client/actors/dbInit.d.ts.map +1 -1
  132. package/dist/src/client/actors/fileSystemInit.d.ts +3 -3
  133. package/dist/src/client/actors/fileSystemInit.d.ts.map +1 -1
  134. package/dist/src/client/actors/platformClassesInit.d.ts +10 -5
  135. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  136. package/dist/src/client/actors/processSchemaFiles.d.ts +18 -3
  137. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  138. package/dist/src/client/actors/saveConfig.d.ts +6 -3
  139. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  140. package/dist/src/client/clientManagerMachine.d.ts +22 -20
  141. package/dist/src/client/clientManagerMachine.d.ts.map +1 -1
  142. package/dist/src/client/constants.d.ts +1 -9
  143. package/dist/src/client/constants.d.ts.map +1 -1
  144. package/dist/src/client/readiness.d.ts +26 -0
  145. package/dist/src/client/readiness.d.ts.map +1 -0
  146. package/dist/src/db/read/currentPropertyRow.d.ts +61 -0
  147. package/dist/src/db/read/currentPropertyRow.d.ts.map +1 -0
  148. package/dist/src/db/read/findSeedRow.d.ts +20 -0
  149. package/dist/src/db/read/findSeedRow.d.ts.map +1 -0
  150. package/dist/src/db/read/findSeedRowsByUid.d.ts +4 -1
  151. package/dist/src/db/read/findSeedRowsByUid.d.ts.map +1 -1
  152. package/dist/src/db/read/getAttesterForSeed.d.ts +1 -1
  153. package/dist/src/db/read/getAttesterForSeed.d.ts.map +1 -1
  154. package/dist/src/db/read/getItemData.d.ts.map +1 -1
  155. package/dist/src/db/read/getItemProperties.d.ts +5 -0
  156. package/dist/src/db/read/getItemProperties.d.ts.map +1 -1
  157. package/dist/src/db/read/getMetadataAttestationUidsForSeedUid.d.ts.map +1 -1
  158. package/dist/src/db/read/getModelSchemas.d.ts +0 -7
  159. package/dist/src/db/read/getModelSchemas.d.ts.map +1 -1
  160. package/dist/src/db/read/getModelsData.d.ts.map +1 -1
  161. package/dist/src/db/read/getPropertyClear.d.ts +5 -1
  162. package/dist/src/db/read/getPropertyClear.d.ts.map +1 -1
  163. package/dist/src/db/read/getPublishPayload.d.ts +35 -40
  164. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  165. package/dist/src/db/read/getPublishPendingDiff.d.ts +2 -2
  166. package/dist/src/db/read/getPublishPendingDiff.d.ts.map +1 -1
  167. package/dist/src/db/read/getPublishUploads.d.ts +59 -28
  168. package/dist/src/db/read/getPublishUploads.d.ts.map +1 -1
  169. package/dist/src/db/read/getSchemaUidForModel.d.ts.map +1 -1
  170. package/dist/src/db/read/getSeedPublishState.d.ts.map +1 -1
  171. package/dist/src/db/read/getSeedPublisher.d.ts.map +1 -1
  172. package/dist/src/db/read/getVersionsForSeedUid.d.ts.map +1 -1
  173. package/dist/src/db/read/isSeedRevoked.d.ts.map +1 -1
  174. package/dist/src/db/read/localModelSchemaLookups.d.ts +8 -0
  175. package/dist/src/db/read/localModelSchemaLookups.d.ts.map +1 -0
  176. package/dist/src/db/read/metadataProperty.d.ts +104 -0
  177. package/dist/src/db/read/metadataProperty.d.ts.map +1 -0
  178. package/dist/src/db/read/publishGraph.d.ts +148 -0
  179. package/dist/src/db/read/publishGraph.d.ts.map +1 -0
  180. package/dist/src/db/read/resolveModelRecord.d.ts +26 -2
  181. package/dist/src/db/read/resolveModelRecord.d.ts.map +1 -1
  182. package/dist/src/db/read/resolveRelatedSeedRef.d.ts +1 -7
  183. package/dist/src/db/read/resolveRelatedSeedRef.d.ts.map +1 -1
  184. package/dist/src/db/read/subqueries/metadataLatest.d.ts +3 -1
  185. package/dist/src/db/read/subqueries/metadataLatest.d.ts.map +1 -1
  186. package/dist/src/db/read/summarizePublishWork.d.ts +13 -5
  187. package/dist/src/db/read/summarizePublishWork.d.ts.map +1 -1
  188. package/dist/src/db/write/applyPropertyAttestationUidsFromPublish.d.ts +20 -21
  189. package/dist/src/db/write/applyPropertyAttestationUidsFromPublish.d.ts.map +1 -1
  190. package/dist/src/db/write/createMetadata.d.ts.map +1 -1
  191. package/dist/src/db/write/createNewItem.d.ts.map +1 -1
  192. package/dist/src/db/write/createSeeds.d.ts +5 -1
  193. package/dist/src/db/write/createSeeds.d.ts.map +1 -1
  194. package/dist/src/db/write/definitions.d.ts +127 -0
  195. package/dist/src/db/write/definitions.d.ts.map +1 -0
  196. package/dist/src/db/write/mergeChainRows.d.ts +22 -0
  197. package/dist/src/db/write/mergeChainRows.d.ts.map +1 -0
  198. package/dist/src/db/write/saveDefinition.d.ts +29 -0
  199. package/dist/src/db/write/saveDefinition.d.ts.map +1 -0
  200. package/dist/src/db/write/updateSeedUid.d.ts +4 -2
  201. package/dist/src/db/write/updateSeedUid.d.ts.map +1 -1
  202. package/dist/src/db/write/updateVersionUid.d.ts +12 -4
  203. package/dist/src/db/write/updateVersionUid.d.ts.map +1 -1
  204. package/dist/src/db/write/writeModelUids.d.ts +10 -0
  205. package/dist/src/db/write/writeModelUids.d.ts.map +1 -0
  206. package/dist/src/eas.d.ts +8 -6
  207. package/dist/src/eas.d.ts.map +1 -1
  208. package/dist/src/events/files/download.d.ts.map +1 -1
  209. package/dist/src/events/item/syncDbWithEas.d.ts.map +1 -1
  210. package/dist/src/helpers/arweaveContentTags.d.ts +1 -1
  211. package/dist/src/helpers/arweaveContentTags.d.ts.map +1 -1
  212. package/dist/src/helpers/compareMetadataRowsLatestFirst.d.ts +18 -3
  213. package/dist/src/helpers/compareMetadataRowsLatestFirst.d.ts.map +1 -1
  214. package/dist/src/helpers/constants.d.ts +5 -2
  215. package/dist/src/helpers/constants.d.ts.map +1 -1
  216. package/dist/src/helpers/dataUrl.d.ts +10 -0
  217. package/dist/src/helpers/dataUrl.d.ts.map +1 -0
  218. package/dist/src/helpers/db.d.ts +54 -105
  219. package/dist/src/helpers/db.d.ts.map +1 -1
  220. package/dist/src/helpers/ensureImageLocal.d.ts.map +1 -1
  221. package/dist/src/helpers/entity/contextUpdate.d.ts +20 -0
  222. package/dist/src/helpers/entity/contextUpdate.d.ts.map +1 -0
  223. package/dist/src/helpers/entity/draftSaveErrors.d.ts +5 -0
  224. package/dist/src/helpers/entity/draftSaveErrors.d.ts.map +1 -1
  225. package/dist/src/helpers/entity/entityCache.d.ts +65 -3
  226. package/dist/src/helpers/entity/entityCache.d.ts.map +1 -1
  227. package/dist/src/helpers/entity/entityCommon.d.ts +0 -22
  228. package/dist/src/helpers/entity/entityCommon.d.ts.map +1 -1
  229. package/dist/src/helpers/entity/entityLifecycle.d.ts +75 -0
  230. package/dist/src/helpers/entity/entityLifecycle.d.ts.map +1 -0
  231. package/dist/src/helpers/entity/entityLiveQuery.d.ts +1 -23
  232. package/dist/src/helpers/entity/entityLiveQuery.d.ts.map +1 -1
  233. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts +4 -9
  234. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts.map +1 -1
  235. package/dist/src/helpers/index.d.ts +2 -24
  236. package/dist/src/helpers/index.d.ts.map +1 -1
  237. package/dist/src/helpers/localImageBlobUrl.d.ts +7 -0
  238. package/dist/src/helpers/localImageBlobUrl.d.ts.map +1 -0
  239. package/dist/src/helpers/mediaRef.d.ts +3 -70
  240. package/dist/src/helpers/mediaRef.d.ts.map +1 -1
  241. package/dist/src/helpers/metadataPropertyNames.d.ts +34 -26
  242. package/dist/src/helpers/metadataPropertyNames.d.ts.map +1 -1
  243. package/dist/src/helpers/mimeTypes.d.ts +2 -1
  244. package/dist/src/helpers/mimeTypes.d.ts.map +1 -1
  245. package/dist/src/helpers/model.d.ts.map +1 -1
  246. package/dist/src/helpers/ownership.d.ts.map +1 -1
  247. package/dist/src/helpers/property.d.ts +21 -26
  248. package/dist/src/helpers/property.d.ts.map +1 -1
  249. package/dist/src/helpers/propertyDefinition.d.ts +59 -0
  250. package/dist/src/helpers/propertyDefinition.d.ts.map +1 -0
  251. package/dist/src/helpers/readHtmlBodyForStorageSeed.d.ts.map +1 -1
  252. package/dist/src/helpers/relationSeedRef.d.ts +0 -7
  253. package/dist/src/helpers/relationSeedRef.d.ts.map +1 -1
  254. package/dist/src/helpers/schema.d.ts +24 -38
  255. package/dist/src/helpers/schema.d.ts.map +1 -1
  256. package/dist/src/helpers/schemaApply.d.ts +135 -0
  257. package/dist/src/helpers/schemaApply.d.ts.map +1 -0
  258. package/dist/src/helpers/tabEvents.d.ts.map +1 -1
  259. package/dist/src/helpers/updateSchema.d.ts +2 -18
  260. package/dist/src/helpers/updateSchema.d.ts.map +1 -1
  261. package/dist/src/imports/index.d.ts +1 -1
  262. package/dist/src/imports/index.d.ts.map +1 -1
  263. package/dist/src/imports/json.d.ts +8 -78
  264. package/dist/src/imports/json.d.ts.map +1 -1
  265. package/dist/src/index.d.ts +13 -13
  266. package/dist/src/index.d.ts.map +1 -1
  267. package/dist/src/interfaces/IItem.d.ts +5 -0
  268. package/dist/src/interfaces/IItem.d.ts.map +1 -1
  269. package/dist/src/interfaces/IItemProperty.d.ts +9 -7
  270. package/dist/src/interfaces/IItemProperty.d.ts.map +1 -1
  271. package/dist/src/node/db/Db.d.ts.map +1 -1
  272. package/dist/src/node/index.d.ts +2 -1
  273. package/dist/src/node/index.d.ts.map +1 -1
  274. package/dist/src/outbox/conflicts.d.ts +2 -0
  275. package/dist/src/outbox/conflicts.d.ts.map +1 -1
  276. package/dist/src/outbox/itemAppliers.d.ts +63 -14
  277. package/dist/src/outbox/itemAppliers.d.ts.map +1 -1
  278. package/dist/src/outbox/outbox.d.ts +14 -3
  279. package/dist/src/outbox/outbox.d.ts.map +1 -1
  280. package/dist/src/outbox/pendingValues.d.ts +3 -1
  281. package/dist/src/outbox/pendingValues.d.ts.map +1 -1
  282. package/dist/src/outbox/storageValueRow.d.ts +7 -0
  283. package/dist/src/outbox/storageValueRow.d.ts.map +1 -0
  284. package/dist/src/platform/configurePlatform.d.ts.map +1 -1
  285. package/dist/src/platform/index.browser.d.ts.map +1 -1
  286. package/dist/src/platform/index.node.d.ts.map +1 -1
  287. package/dist/src/seedSchema/ModelSchema.d.ts +19 -0
  288. package/dist/src/seedSchema/ModelSchema.d.ts.map +1 -1
  289. package/dist/src/seedSchema/ModelSchemaSchema.d.ts.map +1 -1
  290. package/dist/src/seedSchema/PendingWriteSchema.d.ts.map +1 -1
  291. package/dist/src/seedSchema/SchemaSchema.d.ts +19 -0
  292. package/dist/src/seedSchema/SchemaSchema.d.ts.map +1 -1
  293. package/dist/src/seedSchema/SeedSchema.d.ts.map +1 -1
  294. package/dist/src/seedSchema/VersionSchema.d.ts.map +1 -1
  295. package/dist/src/seedSchema/attestedUid.d.ts +9 -0
  296. package/dist/src/seedSchema/attestedUid.d.ts.map +1 -0
  297. package/dist/src/storageValue/content.d.ts +45 -0
  298. package/dist/src/storageValue/content.d.ts.map +1 -0
  299. package/dist/src/storageValue/findFile.d.ts +7 -0
  300. package/dist/src/storageValue/findFile.d.ts.map +1 -0
  301. package/dist/src/storageValue/resolve.d.ts +71 -0
  302. package/dist/src/storageValue/resolve.d.ts.map +1 -0
  303. package/dist/src/storageValue/save.d.ts +24 -0
  304. package/dist/src/storageValue/save.d.ts.map +1 -0
  305. package/dist/src/storageValue/stage.d.ts +22 -0
  306. package/dist/src/storageValue/stage.d.ts.map +1 -0
  307. package/dist/src/types/db.d.ts +0 -14
  308. package/dist/src/types/db.d.ts.map +1 -1
  309. package/dist/src/types/index.d.ts +3 -3
  310. package/dist/src/types/index.d.ts.map +1 -1
  311. package/dist/src/types/machines.d.ts +1 -1
  312. package/dist/src/types/machines.d.ts.map +1 -1
  313. package/dist/src/types/property.d.ts +9 -24
  314. package/dist/src/types/property.d.ts.map +1 -1
  315. package/dist/src/types/publish.d.ts +1 -1
  316. package/dist/src/types/publish.d.ts.map +1 -1
  317. package/dist/{syncDbWithEas-BMHoou6X.js → syncDbWithEas-CA7PvBgu.js} +112 -162
  318. package/dist/syncDbWithEas-CA7PvBgu.js.map +1 -0
  319. package/dist/tabEvents-CaVmngqr.js +3804 -0
  320. package/dist/tabEvents-CaVmngqr.js.map +1 -0
  321. package/dist/{tolerantWebAccess-BHndShch.js → tolerantWebAccess-BJqViq08.js} +10 -15
  322. package/dist/{tolerantWebAccess-BHndShch.js.map → tolerantWebAccess-BJqViq08.js.map} +1 -1
  323. package/dist/{resolveModelForSyncedSeed-fIURvYRV.js → updateSeedRevokedAt-BL9Bg-G7.js} +30 -4
  324. package/dist/updateSeedRevokedAt-BL9Bg-G7.js.map +1 -0
  325. package/package.json +6 -6
  326. package/dist/ClientManager-DqL0q_eu.js +0 -5292
  327. package/dist/ClientManager-DqL0q_eu.js.map +0 -1
  328. package/dist/Item-CG5IhPtL.js.map +0 -1
  329. package/dist/ModelProperty-DDD47KVm.js.map +0 -1
  330. package/dist/Schema-BS8oR7QV.js +0 -4370
  331. package/dist/Schema-BS8oR7QV.js.map +0 -1
  332. package/dist/backfillMetadataPropertyIds-C7P7FL6F.js +0 -72
  333. package/dist/backfillMetadataPropertyIds-C7P7FL6F.js.map +0 -1
  334. package/dist/changeFeed-M8sGbOrW.js +0 -726
  335. package/dist/changeFeed-M8sGbOrW.js.map +0 -1
  336. package/dist/configurePlatform-Dukm2QwO.js.map +0 -1
  337. package/dist/dist/ClientManager-DqL0q_eu.d.ts +0 -952
  338. package/dist/dist/ClientManager-DqL0q_eu.d.ts.map +0 -1
  339. package/dist/dist/Item-CG5IhPtL.d.ts +0 -1115
  340. package/dist/dist/Item-CG5IhPtL.d.ts.map +0 -1
  341. package/dist/dist/ModelProperty-DDD47KVm.d.ts +0 -315
  342. package/dist/dist/ModelProperty-DDD47KVm.d.ts.map +0 -1
  343. package/dist/dist/Schema-BS8oR7QV.d.ts +0 -432
  344. package/dist/dist/Schema-BS8oR7QV.d.ts.map +0 -1
  345. package/dist/dist/SchemaValidationService-CZzKNL04.d.ts +0 -118
  346. package/dist/dist/SchemaValidationService-CZzKNL04.d.ts.map +0 -1
  347. package/dist/dist/backfillMetadataPropertyIds-C7P7FL6F.d.ts +0 -7
  348. package/dist/dist/backfillMetadataPropertyIds-C7P7FL6F.d.ts.map +0 -1
  349. package/dist/dist/changeFeed-M8sGbOrW.d.ts +0 -160
  350. package/dist/dist/changeFeed-M8sGbOrW.d.ts.map +0 -1
  351. package/dist/dist/configurePlatform-Dukm2QwO.d.ts.map +0 -1
  352. package/dist/dist/detachRowsBeforeDelete-Di1enVUF.d.ts +0 -13
  353. package/dist/dist/detachRowsBeforeDelete-Di1enVUF.d.ts.map +0 -1
  354. package/dist/dist/eas-B5VJolSj.d.ts +0 -12
  355. package/dist/dist/eas-B5VJolSj.d.ts.map +0 -1
  356. package/dist/dist/errors-C1qUEZ7A.d.ts +0 -25
  357. package/dist/dist/errors-C1qUEZ7A.d.ts.map +0 -1
  358. package/dist/dist/errors-CS3nDpUU.d.ts +0 -515
  359. package/dist/dist/errors-CS3nDpUU.d.ts.map +0 -1
  360. package/dist/dist/eventBus-7vxTCc3a.d.ts +0 -18
  361. package/dist/dist/eventBus-7vxTCc3a.d.ts.map +0 -1
  362. package/dist/dist/findSeedRowsByUid-CuQmK7An.d.ts +0 -13
  363. package/dist/dist/findSeedRowsByUid-CuQmK7An.d.ts.map +0 -1
  364. package/dist/dist/getItem-Uha3_H0t.d.ts +0 -6
  365. package/dist/dist/getItem-Uha3_H0t.d.ts.map +0 -1
  366. package/dist/dist/getPublishPayload-pbin4lk8.d.ts +0 -65
  367. package/dist/dist/getPublishPayload-pbin4lk8.d.ts.map +0 -1
  368. package/dist/dist/getPublishPendingDiff-ByIaPvCn.d.ts +0 -18
  369. package/dist/dist/getPublishPendingDiff-ByIaPvCn.d.ts.map +0 -1
  370. package/dist/dist/getPublishUploads-BBqiowVc.d.ts +0 -89
  371. package/dist/dist/getPublishUploads-BBqiowVc.d.ts.map +0 -1
  372. package/dist/dist/index-DQoyhp2c.d.ts +0 -6
  373. package/dist/dist/index-DQoyhp2c.d.ts.map +0 -1
  374. package/dist/dist/index-njjjo74v.d.ts +0 -14
  375. package/dist/dist/index-njjjo74v.d.ts.map +0 -1
  376. package/dist/dist/index-rOTW-2QZ.d.ts.map +0 -1
  377. package/dist/dist/index.browser-QPWBkLJA.d.ts +0 -9959
  378. package/dist/dist/index.browser-QPWBkLJA.d.ts.map +0 -1
  379. package/dist/dist/mimeTypes-C9r76DCH.d.ts +0 -30
  380. package/dist/dist/mimeTypes-C9r76DCH.d.ts.map +0 -1
  381. package/dist/dist/model-oHA3YhOd.d.ts +0 -6
  382. package/dist/dist/model-oHA3YhOd.d.ts.map +0 -1
  383. package/dist/dist/modelPropertyRecordSchemas-onFOG2x6.d.ts +0 -7
  384. package/dist/dist/modelPropertyRecordSchemas-onFOG2x6.d.ts.map +0 -1
  385. package/dist/dist/platform.browser.d.ts +0 -3
  386. package/dist/dist/platform.browser.d.ts.map +0 -1
  387. package/dist/dist/property-C85DCD7K.d.ts +0 -37
  388. package/dist/dist/property-C85DCD7K.d.ts.map +0 -1
  389. package/dist/dist/propertyValidationRules-CjUPOFeu.d.ts +0 -13
  390. package/dist/dist/propertyValidationRules-CjUPOFeu.d.ts.map +0 -1
  391. package/dist/dist/publishDraftGraph-DBWAN72w.d.ts +0 -93
  392. package/dist/dist/publishDraftGraph-DBWAN72w.d.ts.map +0 -1
  393. package/dist/dist/resolveModelForSyncedSeed-fIURvYRV.d.ts +0 -21
  394. package/dist/dist/resolveModelForSyncedSeed-fIURvYRV.d.ts.map +0 -1
  395. package/dist/dist/syncDbWithEas-BMHoou6X.d.ts +0 -13
  396. package/dist/dist/syncDbWithEas-BMHoou6X.d.ts.map +0 -1
  397. package/dist/dist/tolerantWebAccess-BHndShch.d.ts +0 -113
  398. package/dist/dist/tolerantWebAccess-BHndShch.d.ts.map +0 -1
  399. package/dist/dist/updateSeedRevokedAt-DpfG6ztE.d.ts +0 -11
  400. package/dist/dist/updateSeedRevokedAt-DpfG6ztE.d.ts.map +0 -1
  401. package/dist/eas-B5VJolSj.js +0 -67
  402. package/dist/eas-B5VJolSj.js.map +0 -1
  403. package/dist/errors-CS3nDpUU.js +0 -4006
  404. package/dist/errors-CS3nDpUU.js.map +0 -1
  405. package/dist/eventBus-7vxTCc3a.js +0 -64
  406. package/dist/eventBus-7vxTCc3a.js.map +0 -1
  407. package/dist/findSeedRowsByUid-CuQmK7An.js +0 -47
  408. package/dist/findSeedRowsByUid-CuQmK7An.js.map +0 -1
  409. package/dist/getItem-Uha3_H0t.js +0 -45
  410. package/dist/getItem-Uha3_H0t.js.map +0 -1
  411. package/dist/getPublishPayload-pbin4lk8.js +0 -1736
  412. package/dist/getPublishPayload-pbin4lk8.js.map +0 -1
  413. package/dist/getPublishPendingDiff-ByIaPvCn.js +0 -118
  414. package/dist/getPublishPendingDiff-ByIaPvCn.js.map +0 -1
  415. package/dist/getPublishUploads-BBqiowVc.js +0 -1080
  416. package/dist/getPublishUploads-BBqiowVc.js.map +0 -1
  417. package/dist/index-DQoyhp2c.js.map +0 -1
  418. package/dist/index-DxHpPNfn.js.map +0 -1
  419. package/dist/index-njjjo74v.js +0 -29
  420. package/dist/index-njjjo74v.js.map +0 -1
  421. package/dist/index-rOTW-2QZ.js +0 -4760
  422. package/dist/index-rOTW-2QZ.js.map +0 -1
  423. package/dist/index.browser-QPWBkLJA.js.map +0 -1
  424. package/dist/index.node-WsEJCOwC.js.map +0 -1
  425. package/dist/mimeTypes-C9r76DCH.js +0 -209
  426. package/dist/mimeTypes-C9r76DCH.js.map +0 -1
  427. package/dist/model-oHA3YhOd.js +0 -29
  428. package/dist/model-oHA3YhOd.js.map +0 -1
  429. package/dist/modelPropertyRecordSchemas-onFOG2x6.js +0 -94
  430. package/dist/modelPropertyRecordSchemas-onFOG2x6.js.map +0 -1
  431. package/dist/property-C85DCD7K.js +0 -289
  432. package/dist/property-C85DCD7K.js.map +0 -1
  433. package/dist/propertyValidationRules-CjUPOFeu.js +0 -73
  434. package/dist/propertyValidationRules-CjUPOFeu.js.map +0 -1
  435. package/dist/publishDraftGraph-DBWAN72w.js +0 -505
  436. package/dist/publishDraftGraph-DBWAN72w.js.map +0 -1
  437. package/dist/resolveModelForSyncedSeed-fIURvYRV.js.map +0 -1
  438. package/dist/src/Item/service/actors/loadOrCreateItem.d.ts +0 -5
  439. package/dist/src/Item/service/actors/loadOrCreateItem.d.ts.map +0 -1
  440. package/dist/src/Item/service/actors/waitForDb.d.ts +0 -4
  441. package/dist/src/Item/service/actors/waitForDb.d.ts.map +0 -1
  442. package/dist/src/ItemProperty/service/actors/loadOrCreateProperty.d.ts +0 -5
  443. package/dist/src/ItemProperty/service/actors/loadOrCreateProperty.d.ts.map +0 -1
  444. package/dist/src/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts +0 -5
  445. package/dist/src/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +0 -1
  446. package/dist/src/ItemProperty/service/actors/saveValueToDb/index.d.ts +0 -6
  447. package/dist/src/ItemProperty/service/actors/saveValueToDb/index.d.ts.map +0 -1
  448. package/dist/src/ItemProperty/service/actors/saveValueToDb/rowContext.d.ts.map +0 -1
  449. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveFile.d.ts +0 -24
  450. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveFile.d.ts.map +0 -1
  451. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveHtml.d.ts +0 -5
  452. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveHtml.d.ts.map +0 -1
  453. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveImage.d.ts +0 -5
  454. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveImage.d.ts.map +0 -1
  455. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveItemStorage.d.ts +0 -10
  456. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveItemStorage.d.ts.map +0 -1
  457. package/dist/src/ItemProperty/service/actors/saveValueToDb/storageValue.d.ts +0 -22
  458. package/dist/src/ItemProperty/service/actors/saveValueToDb/storageValue.d.ts.map +0 -1
  459. package/dist/src/ItemProperty/service/actors/waitForDb.d.ts +0 -4
  460. package/dist/src/ItemProperty/service/actors/waitForDb.d.ts.map +0 -1
  461. package/dist/src/Model/service/actors/createModelProperties.d.ts +0 -9
  462. package/dist/src/Model/service/actors/createModelProperties.d.ts.map +0 -1
  463. package/dist/src/Model/service/actors/loadOrCreateModel.d.ts +0 -5
  464. package/dist/src/Model/service/actors/loadOrCreateModel.d.ts.map +0 -1
  465. package/dist/src/Schema/service/actors/checkExistingSchema.d.ts +0 -5
  466. package/dist/src/Schema/service/actors/checkExistingSchema.d.ts.map +0 -1
  467. package/dist/src/Schema/service/actors/createModelInstances.d.ts +0 -11
  468. package/dist/src/Schema/service/actors/createModelInstances.d.ts.map +0 -1
  469. package/dist/src/Schema/service/actors/createPropertyInstances.d.ts +0 -12
  470. package/dist/src/Schema/service/actors/createPropertyInstances.d.ts.map +0 -1
  471. package/dist/src/Schema/service/actors/validateSchema.d.ts +0 -5
  472. package/dist/src/Schema/service/actors/validateSchema.d.ts.map +0 -1
  473. package/dist/src/Schema/service/actors/verifyModelInstancesInCache.d.ts +0 -6
  474. package/dist/src/Schema/service/actors/verifyModelInstancesInCache.d.ts.map +0 -1
  475. package/dist/src/Schema/service/actors/verifyModelsInDb.d.ts +0 -7
  476. package/dist/src/Schema/service/actors/verifyModelsInDb.d.ts.map +0 -1
  477. package/dist/src/Schema/service/actors/verifyPropertiesInDb.d.ts +0 -8
  478. package/dist/src/Schema/service/actors/verifyPropertiesInDb.d.ts.map +0 -1
  479. package/dist/src/Schema/service/actors/verifyPropertyInstancesInCache.d.ts +0 -6
  480. package/dist/src/Schema/service/actors/verifyPropertyInstancesInCache.d.ts.map +0 -1
  481. package/dist/src/Schema/service/actors/verifySchemaInDb.d.ts +0 -7
  482. package/dist/src/Schema/service/actors/verifySchemaInDb.d.ts.map +0 -1
  483. package/dist/src/Schema/service/actors/writeModelsToDb.d.ts +0 -9
  484. package/dist/src/Schema/service/actors/writeModelsToDb.d.ts.map +0 -1
  485. package/dist/src/Schema/service/actors/writePropertiesToDb.d.ts +0 -10
  486. package/dist/src/Schema/service/actors/writePropertiesToDb.d.ts.map +0 -1
  487. package/dist/src/Schema/service/actors/writeSchemaToDb.d.ts +0 -11
  488. package/dist/src/Schema/service/actors/writeSchemaToDb.d.ts.map +0 -1
  489. package/dist/src/browser/helpers/ArweaveClient.d.ts +0 -14
  490. package/dist/src/browser/helpers/ArweaveClient.d.ts.map +0 -1
  491. package/dist/src/browser/helpers/EasClient.d.ts +0 -10
  492. package/dist/src/browser/helpers/EasClient.d.ts.map +0 -1
  493. package/dist/src/browser/helpers/QueryClient.d.ts +0 -9
  494. package/dist/src/browser/helpers/QueryClient.d.ts.map +0 -1
  495. package/dist/src/client/actors/addModelsToStore.d.ts +0 -4
  496. package/dist/src/client/actors/addModelsToStore.d.ts.map +0 -1
  497. package/dist/src/db/backfillMetadataPropertyIds.d.ts +0 -7
  498. package/dist/src/db/backfillMetadataPropertyIds.d.ts.map +0 -1
  499. package/dist/src/db/read/getItem.d.ts +0 -3
  500. package/dist/src/db/read/getItem.d.ts.map +0 -1
  501. package/dist/src/db/read/getPropertyData.d.ts +0 -4
  502. package/dist/src/db/read/getPropertyData.d.ts.map +0 -1
  503. package/dist/src/db/read/getRelatedItemsForPublish.d.ts +0 -10
  504. package/dist/src/db/read/getRelatedItemsForPublish.d.ts.map +0 -1
  505. package/dist/src/db/read/getSeedData.d.ts +0 -12
  506. package/dist/src/db/read/getSeedData.d.ts.map +0 -1
  507. package/dist/src/db/read/itemLoads.d.ts +0 -20
  508. package/dist/src/db/read/itemLoads.d.ts.map +0 -1
  509. package/dist/src/db/read/publishDraftGraph.d.ts +0 -64
  510. package/dist/src/db/read/publishDraftGraph.d.ts.map +0 -1
  511. package/dist/src/db/write/linkModelToSchema.d.ts +0 -12
  512. package/dist/src/db/write/linkModelToSchema.d.ts.map +0 -1
  513. package/dist/src/helpers/ArweaveClient/BaseArweaveClient.d.ts +0 -2
  514. package/dist/src/helpers/ArweaveClient/BaseArweaveClient.d.ts.map +0 -1
  515. package/dist/src/helpers/ArweaveClient/arweaveL1UploadApi.d.ts +0 -2
  516. package/dist/src/helpers/ArweaveClient/arweaveL1UploadApi.d.ts.map +0 -1
  517. package/dist/src/helpers/ArweaveClient/selectReadGateway.d.ts +0 -2
  518. package/dist/src/helpers/ArweaveClient/selectReadGateway.d.ts.map +0 -1
  519. package/dist/src/helpers/ArweaveClient/uploadApiVerification.d.ts +0 -2
  520. package/dist/src/helpers/ArweaveClient/uploadApiVerification.d.ts.map +0 -1
  521. package/dist/src/helpers/EasClient/BaseEasClient.d.ts +0 -2
  522. package/dist/src/helpers/EasClient/BaseEasClient.d.ts.map +0 -1
  523. package/dist/src/helpers/QueryClient/BaseQueryClient.d.ts +0 -2
  524. package/dist/src/helpers/QueryClient/BaseQueryClient.d.ts.map +0 -1
  525. package/dist/src/helpers/easUid.d.ts +0 -2
  526. package/dist/src/helpers/easUid.d.ts.map +0 -1
  527. package/dist/src/helpers/entity/entityDestroy.d.ts +0 -49
  528. package/dist/src/helpers/entity/entityDestroy.d.ts.map +0 -1
  529. package/dist/src/helpers/entity/entityFind.d.ts +0 -52
  530. package/dist/src/helpers/entity/entityFind.d.ts.map +0 -1
  531. package/dist/src/helpers/entity/entityState.d.ts +0 -28
  532. package/dist/src/helpers/entity/entityState.d.ts.map +0 -1
  533. package/dist/src/helpers/entity/entityUnload.d.ts +0 -56
  534. package/dist/src/helpers/entity/entityUnload.d.ts.map +0 -1
  535. package/dist/src/helpers/entity/evictionEpoch.d.ts +0 -43
  536. package/dist/src/helpers/entity/evictionEpoch.d.ts.map +0 -1
  537. package/dist/src/helpers/entity/index.d.ts +0 -12
  538. package/dist/src/helpers/entity/index.d.ts.map +0 -1
  539. package/dist/src/helpers/gateway/gatewayState.d.ts +0 -2
  540. package/dist/src/helpers/gateway/gatewayState.d.ts.map +0 -1
  541. package/dist/src/helpers/gateway/resolveSeedGatewayEndpoints.d.ts +0 -2
  542. package/dist/src/helpers/gateway/resolveSeedGatewayEndpoints.d.ts.map +0 -1
  543. package/dist/src/helpers/gateway/seedGatewayConfig.d.ts +0 -2
  544. package/dist/src/helpers/gateway/seedGatewayConfig.d.ts.map +0 -1
  545. package/dist/src/helpers/getSchemaForItemProperty.d.ts +0 -15
  546. package/dist/src/helpers/getSchemaForItemProperty.d.ts.map +0 -1
  547. package/dist/src/helpers/getSegmentedItemProperties.d.ts +0 -10
  548. package/dist/src/helpers/getSegmentedItemProperties.d.ts.map +0 -1
  549. package/dist/src/helpers/isSqliteUniqueConstraintError.d.ts +0 -7
  550. package/dist/src/helpers/isSqliteUniqueConstraintError.d.ts.map +0 -1
  551. package/dist/src/helpers/propertyValidationRules.d.ts +0 -20
  552. package/dist/src/helpers/propertyValidationRules.d.ts.map +0 -1
  553. package/dist/src/helpers/propertyWriteTickets.d.ts +0 -11
  554. package/dist/src/helpers/propertyWriteTickets.d.ts.map +0 -1
  555. package/dist/src/helpers/reconcilePropertyDraftRows.d.ts +0 -10
  556. package/dist/src/helpers/reconcilePropertyDraftRows.d.ts.map +0 -1
  557. package/dist/src/helpers/waitForEntityIdle.d.ts +0 -21
  558. package/dist/src/helpers/waitForEntityIdle.d.ts.map +0 -1
  559. package/dist/src/interfaces/IQueryClient.d.ts +0 -15
  560. package/dist/src/interfaces/IQueryClient.d.ts.map +0 -1
  561. package/dist/src/node/helpers/ArweaveClient.d.ts +0 -5
  562. package/dist/src/node/helpers/ArweaveClient.d.ts.map +0 -1
  563. package/dist/src/node/helpers/EasClient.d.ts +0 -5
  564. package/dist/src/node/helpers/EasClient.d.ts.map +0 -1
  565. package/dist/src/node/helpers/QueryClient.d.ts +0 -5
  566. package/dist/src/node/helpers/QueryClient.d.ts.map +0 -1
  567. package/dist/src/services/write/actors/validateEntity.d.ts +0 -6
  568. package/dist/src/services/write/actors/validateEntity.d.ts.map +0 -1
  569. package/dist/src/services/write/actors/writeToDatabase.d.ts +0 -14
  570. package/dist/src/services/write/actors/writeToDatabase.d.ts.map +0 -1
  571. package/dist/src/services/write/writeProcessMachine.d.ts +0 -56
  572. package/dist/src/services/write/writeProcessMachine.d.ts.map +0 -1
  573. package/dist/src/stores/eas.d.ts +0 -2
  574. package/dist/src/stores/eas.d.ts.map +0 -1
  575. package/dist/src/types/arweave.d.ts +0 -57
  576. package/dist/src/types/arweave.d.ts.map +0 -1
  577. package/dist/src/types/gateway.d.ts +0 -2
  578. package/dist/src/types/gateway.d.ts.map +0 -1
  579. package/dist/syncDbWithEas-BMHoou6X.js.map +0 -1
  580. package/dist/updateSeedRevokedAt-DpfG6ztE.js +0 -31
  581. package/dist/updateSeedRevokedAt-DpfG6ztE.js.map +0 -1
@@ -1,28 +1,25 @@
1
- import { fromCallback, setup, assign, createActor } from 'xstate';
2
- import { w as writeProcessMachine, c as currentEvictionEpoch, M as Model, b as anyEvictionSince, s as schemaEvictedSince } from './errors-CS3nDpUU.js';
3
- import { L as BaseDb, p as models, E as properties, J as schemas, z as modelSchemas, ai as getModelIdByFileId, n as normalizeDataType, a5 as generateId, M as ModelPropertyDataTypes, Q as BaseFileManager, aj as getModelId, ak as setCachedPropertyRefresher } from './index-rOTW-2QZ.js';
1
+ import { fromCallback, setup, assign, createActor, waitFor } from 'xstate';
2
+ import { M as Model, F as saveDefinition } from './errors-DLSoqSHG.js';
3
+ import { r as resolveModelRecord, n as normalizeDataType, m as generateId, a2 as definitionOnlyFields, a3 as persistDefinitionFields, a4 as getPropertyDefinition, a5 as propertyDefinitionFromRow, M as ModelPropertyDataTypes, a6 as setCachedPropertyRefresher } from './tabEvents-CaVmngqr.js';
4
4
  import 'pluralize';
5
5
  import '@seedprotocol/eas';
6
- import { eq, and, inArray } from 'drizzle-orm';
7
- import { modelPropertiesToObject } from './model-oHA3YhOd.js';
8
- import { P as isActorStopped, Q as DEFAULT_READY_TIMEOUT_MS, F as waitForEntityIdle, R as createReactiveProxy, S as sameEntity, T as findEntity, U as forceRemoveFromCaches, V as runDestroyLifecycle } from './Item-CG5IhPtL.js';
6
+ import { B as BaseDb, d as models, l as properties, t as schemas, j as modelSchemas, w as BaseFileManager } from './BaseFileManager-BAlySv8w.js';
7
+ import { aj as isActorStopped, T as applyContextUpdate, U as isInternalUpdate, ak as differsFromOriginals, V as evictionLog, a7 as modelPropertiesToObject, Z as DEFAULT_READY_TIMEOUT_MS, _ as waitForEntityReady, $ as createReactiveProxy, al as onEntityTeardown, a0 as runEntityLoad, W as holdChild, a2 as entityStatus, a1 as evictEntities, a3 as releaseEntity, a4 as destroyEntity, a5 as EntityCache } from './Item-Bf4kWKpH.js';
9
8
  import debug from 'debug';
10
- import { S as Schema } from './Schema-BS8oR7QV.js';
11
- import './ClientManager-DqL0q_eu.js';
12
- import 'lodash-es';
13
- import './changeFeed-M8sGbOrW.js';
14
- import './eventBus-7vxTCc3a.js';
15
9
  import '@seedprotocol/arweave';
10
+ import { eq, and, inArray } from 'drizzle-orm';
11
+ import { S as Schema } from './Schema-J_1f6p0c.js';
12
+ import '@sinclair/typebox';
13
+ import 'lodash-es';
16
14
  import '@noble/hashes/sha3';
17
15
  import '@noble/hashes/utils';
18
16
  import '@seedprotocol/query';
19
- import '@sinclair/typebox';
20
17
  import 'drizzle-orm/sqlite-core';
21
18
  import 'nanoid';
22
19
  import 'nanoid-dictionary';
23
20
  import '@noble/hashes/sha256';
24
21
  import 'rxjs';
25
- import './SchemaValidationService-CZzKNL04.js';
22
+ import './SchemaValidationService-CnmKyzR-.js';
26
23
  import '@sinclair/typebox/value';
27
24
 
28
25
  const logger$3 = debug('seedSdk:modelProperty:actors:saveToSchema');
@@ -33,15 +30,15 @@ const logger$3 = debug('seedSdk:modelProperty:actors:saveToSchema');
33
30
  */
34
31
  async function getSchemaNameFromModel(modelName) {
35
32
  // Get the latest schema files and find which one contains this model
36
- const _mod_0 = await import('./ClientManager-DqL0q_eu.js');
37
- const _ns_0 = _mod_0.S;
33
+ const _mod_0 = await import('./errors-DLSoqSHG.js');
34
+ const _ns_0 = _mod_0.a5;
38
35
  const schemaHelpersMod = _ns_0;
39
36
  const { listLatestSchemaFiles } = schemaHelpersMod;
40
37
  const latestSchemas = await listLatestSchemaFiles();
41
38
  for (const schema of latestSchemas) {
42
39
  try {
43
- const _mod_1 = await import('./index-rOTW-2QZ.js');
44
- const _ns_1 = _mod_1.bb;
40
+ const _mod_1 = await import('./BaseFileManager-BAlySv8w.js');
41
+ const _ns_1 = _mod_1.A;
45
42
  const fileManagerMod = _ns_1;
46
43
  const { BaseFileManager } = fileManagerMod;
47
44
  const content = await BaseFileManager.readFileAsString(schema.filePath);
@@ -60,7 +57,7 @@ async function getSchemaNameFromModel(modelName) {
60
57
  const saveToSchema = fromCallback(({ sendBack, input: { context }, self }) => {
61
58
  const _saveToSchema = async () => {
62
59
  // Use dynamic import to break circular dependency
63
- const validationServiceMod = await import('./SchemaValidationService-CZzKNL04.js');
60
+ const validationServiceMod = await import('./SchemaValidationService-CnmKyzR-.js');
64
61
  const { SchemaValidationService } = validationServiceMod;
65
62
  const validationService = new SchemaValidationService();
66
63
  // Validate property structure before saving
@@ -79,23 +76,23 @@ const saveToSchema = fromCallback(({ sendBack, input: { context }, self }) => {
79
76
  throw new Error(`Model not found for modelId: ${context.modelId}`);
80
77
  }
81
78
  // Persist to database only - schema file is updated only when user calls Schema.saveNewVersion()
82
- const _mod_2 = await import('./index-rOTW-2QZ.js');
83
- const _ns_2 = _mod_2.bf;
79
+ const _mod_2 = await import('./tabEvents-CaVmngqr.js');
80
+ const _ns_2 = _mod_2.bh;
84
81
  const dbMod = _ns_2;
85
82
  const { savePropertyToDb } = dbMod;
86
83
  await savePropertyToDb(context);
87
84
  // Mark schema as draft so user knows to save
88
85
  const schemaName = context._schemaName ?? (await getSchemaNameFromModel(context.modelName));
89
86
  if (schemaName) {
90
- const _mod_3 = await import('./Schema-BS8oR7QV.js');
87
+ const _mod_3 = await import('./Schema-J_1f6p0c.js');
91
88
  const _ns_3 = _mod_3.a;
92
89
  const schemaMod = _ns_3;
93
90
  const { Schema } = schemaMod;
94
91
  // Stopped meanwhile (unloaded, or evicted with its schema): don't load the schema again
95
92
  if (isActorStopped(self))
96
93
  return;
97
- const schema = Schema.create(schemaName, { waitForReady: false, hold: false });
98
- schema.getService().send({
94
+ const schema = await Schema.find({ schemaName, waitForReady: false, hold: false });
95
+ schema?.getService().send({
99
96
  type: 'markAsDraft',
100
97
  propertyKey: `${context.modelName}:${context.name}`,
101
98
  });
@@ -125,22 +122,14 @@ const compareAndMarkDraft = fromCallback(({ sendBack, input: { context }, self }
125
122
  const schemaFileIdForResolve = fullContext._propertyFileId || (typeof fullContext.id === 'string' ? fullContext.id : undefined);
126
123
  if (schemaFileIdForResolve && (fullContext.modelName === undefined || fullContext.dataType === undefined)) {
127
124
  try {
128
- const _mod_4 = await import('./index-rOTW-2QZ.js');
129
- const _ns_4 = _mod_4.bf;
130
- const dbMod = _ns_4;
131
- const { getPropertyModelNameAndDataType, getModelNameByModelId } = dbMod;
132
- let fromDb;
133
- for (let attempt = 0; attempt < 6; attempt++) {
134
- fromDb = await getPropertyModelNameAndDataType(schemaFileIdForResolve);
135
- if (fromDb)
136
- break;
137
- if (attempt < 5)
138
- await new Promise((r) => setTimeout(r, 40));
139
- }
125
+ const _mod_4 = await import('./tabEvents-CaVmngqr.js');
126
+ const _ns_4 = _mod_4.be;
127
+ const { resolveModelRecord, resolvePropertyModelRecord } = _ns_4;
128
+ const fromDb = await resolvePropertyModelRecord(schemaFileIdForResolve);
140
129
  if (fromDb) {
141
130
  fullContext = {
142
131
  ...fullContext,
143
- modelName: fullContext.modelName ?? fromDb.modelName,
132
+ modelName: fullContext.modelName ?? fromDb.name,
144
133
  dataType: fullContext.dataType ?? fromDb.dataType,
145
134
  };
146
135
  }
@@ -149,7 +138,7 @@ const compareAndMarkDraft = fromCallback(({ sendBack, input: { context }, self }
149
138
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
150
139
  const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileIdForResolve);
151
140
  if (pendingModelId != null) {
152
- const modelName = await getModelNameByModelId(pendingModelId);
141
+ const modelName = (await resolveModelRecord(undefined, { modelId: pendingModelId }))?.name;
153
142
  if (modelName) {
154
143
  fullContext = { ...fullContext, modelName };
155
144
  }
@@ -172,8 +161,8 @@ const compareAndMarkDraft = fromCallback(({ sendBack, input: { context }, self }
172
161
  if (fullContext.modelName && fullContext.name && schemaFileId) {
173
162
  logger$2(`[compareAndMarkDraft] _originalValues not set, but saving to database anyway for property ${context.modelName}:${context.name} (schemaFileId: ${schemaFileId})`);
174
163
  try {
175
- const _mod_5 = await import('./index-rOTW-2QZ.js');
176
- const _ns_5 = _mod_5.bf;
164
+ const _mod_5 = await import('./tabEvents-CaVmngqr.js');
165
+ const _ns_5 = _mod_5.bh;
177
166
  const dbMod = _ns_5;
178
167
  const { savePropertyToDb } = dbMod;
179
168
  // Ensure _propertyFileId is set for savePropertyToDb to find the property
@@ -234,8 +223,8 @@ const compareAndMarkDraft = fromCallback(({ sendBack, input: { context }, self }
234
223
  logger$2(`Property ${fullContext.modelName}:${fullContext.name} has changes, marking as edited`);
235
224
  logger$2(`[compareAndMarkDraft] Context when saving: id=${fullContext.id}, _propertyFileId=${fullContext._propertyFileId}, name=${fullContext.name}, _originalValues.name=${fullContext._originalValues?.name}`);
236
225
  // Use dynamic import to break circular dependency
237
- const _mod_6 = await import('./index-rOTW-2QZ.js');
238
- const _ns_6 = _mod_6.bf;
226
+ const _mod_6 = await import('./tabEvents-CaVmngqr.js');
227
+ const _ns_6 = _mod_6.bh;
239
228
  const dbMod = _ns_6;
240
229
  const { savePropertyToDb } = dbMod;
241
230
  // Save to database (but not JSON file) - always save to DB when there are changes
@@ -250,16 +239,16 @@ const compareAndMarkDraft = fromCallback(({ sendBack, input: { context }, self }
250
239
  // Mark schema as draft if schema name is available
251
240
  if (fullContext._schemaName) {
252
241
  // Get the Schema instance and mark it as draft
253
- const _mod_7 = await import('./Schema-BS8oR7QV.js');
242
+ const _mod_7 = await import('./Schema-J_1f6p0c.js');
254
243
  const _ns_7 = _mod_7.a;
255
244
  const schemaMod = _ns_7;
256
245
  const { Schema } = schemaMod;
257
246
  // Stopped meanwhile (unloaded, or evicted with its schema): don't load the schema again
258
247
  if (isActorStopped(self))
259
248
  return;
260
- const schema = Schema.create(fullContext._schemaName, { waitForReady: false, hold: false });
249
+ const schema = await Schema.find({ schemaName: fullContext._schemaName, waitForReady: false, hold: false });
261
250
  // Send event to Schema machine to mark as draft
262
- schema.getService().send({
251
+ schema?.getService().send({
263
252
  type: 'markAsDraft',
264
253
  propertyKey: `${fullContext.modelName}:${fullContext.name}`,
265
254
  });
@@ -270,7 +259,7 @@ const compareAndMarkDraft = fromCallback(({ sendBack, input: { context }, self }
270
259
  logger$2(`Property ${fullContext.modelName}:${fullContext.name} has no changes`);
271
260
  // Clear isEdited flag in database
272
261
  try {
273
- const _mod_8 = await import('./index-DxHpPNfn.js');
262
+ const _mod_8 = await import('./index-D0V-mjCV.js');
274
263
  const _ns_8 = _mod_8.s;
275
264
  const seedSchemaMod = _ns_8;
276
265
  const { properties: propertiesTable } = seedSchemaMod;
@@ -279,7 +268,7 @@ const compareAndMarkDraft = fromCallback(({ sendBack, input: { context }, self }
279
268
  const db = BaseDb.getAppDb();
280
269
  if (db && fullContext.modelName && fullContext.name) {
281
270
  // Find this property's model (model names are only unique per schema)
282
- const _mod_9 = await import('./index-rOTW-2QZ.js');
271
+ const _mod_9 = await import('./tabEvents-CaVmngqr.js');
283
272
  const _ns_9 = _mod_9.be;
284
273
  const { resolveModelRecord } = _ns_9;
285
274
  const modelRecord = await resolveModelRecord(fullContext.modelName, {
@@ -336,53 +325,31 @@ const validateProperty = fromCallback(({ sendBack, input: { context }, self }) =
336
325
  };
337
326
  const schemaFileId = typeof context.id === 'string' ? context.id : undefined;
338
327
  if (schemaFileId && (fullContext.modelName === undefined || fullContext.dataType === undefined)) {
339
- // Brief wait so trackPendingWrite from ModelProperty.create() has time to run (it's in setTimeout(0))
340
- await new Promise((r) => setTimeout(r, 60));
341
328
  try {
342
- const _mod_10 = await import('./index-rOTW-2QZ.js');
343
- const _ns_10 = _mod_10.bf;
344
- const dbMod = _ns_10;
345
- const { getPropertyModelNameAndDataType, getModelNameByModelId } = dbMod;
329
+ const _mod_10 = await import('./tabEvents-CaVmngqr.js');
330
+ const _ns_10 = _mod_10.be;
331
+ const { resolveModelRecord, resolvePropertyModelRecord } = _ns_10;
346
332
  // Try pending write first (property row may not exist yet)
347
333
  if (fullContext.modelName === undefined && schemaFileId) {
348
334
  const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
349
335
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
350
336
  const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileId);
351
337
  if (pendingModelId != null) {
352
- const modelName = await getModelNameByModelId(pendingModelId);
338
+ const modelName = (await resolveModelRecord(undefined, { modelId: pendingModelId }))?.name;
353
339
  if (modelName) {
354
340
  fullContext = { ...fullContext, modelName };
355
341
  }
356
342
  }
357
343
  }
358
- // Then DB property lookup with retry (catches row after initial write)
359
- let fromDb;
360
- for (let attempt = 0; attempt < 6; attempt++) {
361
- fromDb = await getPropertyModelNameAndDataType(schemaFileId);
362
- if (fromDb)
363
- break;
364
- if (attempt < 5)
365
- await new Promise((r) => setTimeout(r, 40));
366
- }
344
+ // Then the property's row, once its write has run
345
+ const fromDb = await resolvePropertyModelRecord(schemaFileId);
367
346
  if (fromDb) {
368
347
  fullContext = {
369
348
  ...fullContext,
370
- modelName: fullContext.modelName ?? fromDb.modelName,
349
+ modelName: fullContext.modelName ?? fromDb.name,
371
350
  dataType: fullContext.dataType ?? fromDb.dataType,
372
351
  };
373
352
  }
374
- // If still no modelName, try pending write again (may have been set during retries)
375
- if (fullContext.modelName === undefined && schemaFileId) {
376
- const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
377
- const ModelProperty = mod?.ModelProperty ?? mod?.default;
378
- const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileId);
379
- if (pendingModelId != null) {
380
- const modelName = await getModelNameByModelId(pendingModelId);
381
- if (modelName) {
382
- fullContext = { ...fullContext, modelName };
383
- }
384
- }
385
- }
386
353
  }
387
354
  catch {
388
355
  // ignore
@@ -393,10 +360,10 @@ const validateProperty = fromCallback(({ sendBack, input: { context }, self }) =
393
360
  fullContext = { ...fullContext, dataType: (fullContext.dataType ?? context._originalValues?.dataType) || 'Text' };
394
361
  }
395
362
  // Use dynamic imports to break circular dependencies
396
- const validationServiceMod = await import('./SchemaValidationService-CZzKNL04.js');
363
+ const validationServiceMod = await import('./SchemaValidationService-CnmKyzR-.js');
397
364
  const { SchemaValidationService } = validationServiceMod;
398
365
  const validationService = new SchemaValidationService();
399
- const _mod_11 = await import('./Schema-BS8oR7QV.js');
366
+ const _mod_11 = await import('./Schema-J_1f6p0c.js');
400
367
  const _ns_11 = _mod_11.a;
401
368
  const schemaMod = _ns_11;
402
369
  const { Schema } = schemaMod;
@@ -412,7 +379,9 @@ const validateProperty = fromCallback(({ sendBack, input: { context }, self }) =
412
379
  return;
413
380
  if (fullContext._schemaName && fullContext.modelName) {
414
381
  try {
415
- const schema = Schema.create(fullContext._schemaName, { waitForReady: false, hold: false });
382
+ const schema = await Schema.find({ schemaName: fullContext._schemaName, waitForReady: false, hold: false });
383
+ if (!schema)
384
+ throw new Error(`No schema named "${fullContext._schemaName}"`);
416
385
  const schemaSnapshot = schema.getService().getSnapshot();
417
386
  const schemaStatus = schemaSnapshot.value;
418
387
  // Only validate against schema if it's loaded (in idle state)
@@ -494,7 +463,6 @@ const modelPropertyMachine = setup({
494
463
  saveToSchema,
495
464
  compareAndMarkDraft,
496
465
  validateProperty,
497
- writeProcessMachine,
498
466
  },
499
467
  guards: {
500
468
  isPropertyValid: ({ context }) => {
@@ -503,6 +471,29 @@ const modelPropertyMachine = setup({
503
471
  },
504
472
  },
505
473
  actions: {
474
+ applyUpdate: assign(({ context, event }) => {
475
+ const next = applyContextUpdate(context, event);
476
+ // TypeBox validation expects undefined, not null, for the optional ref fields
477
+ for (const field of ['refValueType', 'refModelId', 'ref', 'refModelName']) {
478
+ if (next[field] === null)
479
+ next[field] = undefined;
480
+ }
481
+ if (isInternalUpdate(event))
482
+ return next;
483
+ // Validation and the row write need these even when a just-created property is renamed
484
+ // before its creator's full context arrives
485
+ const originals = context._originalValues;
486
+ if (next.modelName === undefined && originals?.modelName !== undefined)
487
+ next.modelName = originals.modelName;
488
+ if (next.dataType === undefined && originals?.dataType !== undefined)
489
+ next.dataType = originals.dataType;
490
+ const edited = differsFromOriginals(originals, next, event);
491
+ return {
492
+ ...next,
493
+ ...(edited !== undefined && { _isEdited: edited }),
494
+ _validationErrors: undefined,
495
+ };
496
+ }),
506
497
  assignValidationErrors: assign(({ context, event }) => {
507
498
  if (event.type === 'validationError') {
508
499
  return {
@@ -521,66 +512,11 @@ const modelPropertyMachine = setup({
521
512
  return context;
522
513
  },
523
514
  on: {
524
- updateContext: {
525
- actions: assign(({ context, event }) => {
526
- const newContext = Object.assign({}, context);
527
- // Check if this is only updating internal fields
528
- const onlyInternalFields = Object.keys(event).every((key) => {
529
- return key === 'type' || key.startsWith('_');
530
- });
531
- // Update the context with new values
532
- for (let i = 0; i < Object.keys(event).length; i++) {
533
- const key = Object.keys(event)[i];
534
- if (key === 'type') {
535
- continue;
536
- }
537
- let value = event[key];
538
- // Convert null to undefined for optional fields (TypeBox validation expects undefined, not null)
539
- // This is especially important for refValueType, refModelId, etc.
540
- if (value === null && (key === 'refValueType' || key === 'refModelId' || key === 'ref' || key === 'refModelName')) {
541
- value = undefined;
542
- }
543
- newContext[key] = value;
544
- }
545
- // Preserve modelName and dataType from context or _originalValues so validation and savePropertyToDb
546
- // never run with missing required/needed fields (e.g. when a just-created property is renamed before
547
- // the full context is available from the creator).
548
- if (newContext.modelName === undefined && context._originalValues?.modelName !== undefined) {
549
- newContext.modelName = context._originalValues.modelName;
550
- }
551
- if (newContext.dataType === undefined && context._originalValues?.dataType !== undefined) {
552
- newContext.dataType = context._originalValues.dataType;
553
- }
554
- // Compare with original values and set _isEdited flag (only for non-internal updates)
555
- if (!onlyInternalFields && context._originalValues) {
556
- const hasChanges = Object.keys(event).some((key) => {
557
- if (key === 'type' || key.startsWith('_'))
558
- return false;
559
- return newContext[key] !== context._originalValues?.[key];
560
- });
561
- newContext._isEdited = hasChanges;
562
- }
563
- // Clear validation errors on context update (will be re-validated if needed)
564
- newContext._validationErrors = undefined;
565
- // Convert null to undefined for optional fields (TypeBox validation expects undefined, not null)
566
- // This is especially important for refValueType, refModelId, etc.
567
- const optionalFields = ['refValueType', 'refModelId', 'ref', 'refModelName'];
568
- for (const field of optionalFields) {
569
- if (newContext[field] === null) {
570
- newContext[field] = undefined;
571
- }
572
- }
573
- return newContext;
574
- }),
575
- // Only trigger validation and compareAndMarkDraft if we're updating non-internal fields
576
- guard: ({ event }) => {
577
- const shouldTransition = !Object.keys(event).every((key) => {
578
- return key === 'type' || key.startsWith('_');
579
- });
580
- return shouldTransition;
581
- },
582
- target: '.validating',
583
- },
515
+ updateContext: [
516
+ // A public change revalidates (then compareAndMarkDraft); an internal one is only applied
517
+ { guard: ({ event }) => !isInternalUpdate(event), actions: 'applyUpdate', target: '.validating' },
518
+ { actions: 'applyUpdate' },
519
+ ],
584
520
  validateProperty: {
585
521
  target: '.validating',
586
522
  },
@@ -646,34 +582,7 @@ const modelPropertyMachine = setup({
646
582
  validateProperty: {
647
583
  target: 'validating',
648
584
  },
649
- requestWrite: {
650
- actions: ({ context, event }) => {
651
- if (context.writeProcess) {
652
- context.writeProcess.send({
653
- type: 'startWrite',
654
- data: event.data,
655
- });
656
- }
657
- },
658
- },
659
585
  },
660
- entry: assign({
661
- writeProcess: ({ spawn, context }) => {
662
- // Spawn writeProcess if we have id (schemaFileId)
663
- // New properties will have id generated
664
- const entityId = context.id;
665
- if (!context.writeProcess && entityId) {
666
- return spawn(writeProcessMachine, {
667
- input: {
668
- entityType: 'modelProperty',
669
- entityId: String(entityId),
670
- entityData: context,
671
- },
672
- });
673
- }
674
- return context.writeProcess;
675
- },
676
- }),
677
586
  },
678
587
  validating: {
679
588
  on: {
@@ -718,72 +627,8 @@ const modelPropertyMachine = setup({
718
627
  on: {
719
628
  // Apply updateContext but do not re-invoke saveToSchema actor (avoids infinite loop).
720
629
  // Context is updated; in-flight save completes with original context.
721
- updateContext: [
722
- {
723
- guard: ({ context, event }) => {
724
- const onlyInternal = Object.keys(event).every((k) => k === 'type' || k.startsWith('_'));
725
- return !onlyInternal && event.name !== undefined && event.name !== context.name;
726
- },
727
- actions: assign(({ context, event }) => {
728
- const newContext = Object.assign({}, context);
729
- const onlyInternalFields = Object.keys(event).every((key) => key === 'type' || key.startsWith('_'));
730
- for (const key of Object.keys(event)) {
731
- if (key === 'type')
732
- continue;
733
- let value = event[key];
734
- if (value === null && ['refValueType', 'refModelId', 'ref', 'refModelName'].includes(key))
735
- value = undefined;
736
- newContext[key] = value;
737
- }
738
- if (newContext.modelName === undefined && context._originalValues?.modelName !== undefined) {
739
- newContext.modelName = context._originalValues.modelName;
740
- }
741
- if (newContext.dataType === undefined && context._originalValues?.dataType !== undefined) {
742
- newContext.dataType = context._originalValues.dataType;
743
- }
744
- if (!onlyInternalFields && context._originalValues) {
745
- const hasChanges = Object.keys(event).some((key) => {
746
- if (key === 'type' || key.startsWith('_'))
747
- return false;
748
- return newContext[key] !== context._originalValues?.[key];
749
- });
750
- newContext._isEdited = hasChanges;
751
- }
752
- newContext._validationErrors = undefined;
753
- return newContext;
754
- }),
755
- },
756
- {
757
- actions: assign(({ context, event }) => {
758
- const newContext = Object.assign({}, context);
759
- const onlyInternalFields = Object.keys(event).every((key) => key === 'type' || key.startsWith('_'));
760
- for (const key of Object.keys(event)) {
761
- if (key === 'type')
762
- continue;
763
- let value = event[key];
764
- if (value === null && ['refValueType', 'refModelId', 'ref', 'refModelName'].includes(key))
765
- value = undefined;
766
- newContext[key] = value;
767
- }
768
- if (newContext.modelName === undefined && context._originalValues?.modelName !== undefined) {
769
- newContext.modelName = context._originalValues.modelName;
770
- }
771
- if (newContext.dataType === undefined && context._originalValues?.dataType !== undefined) {
772
- newContext.dataType = context._originalValues.dataType;
773
- }
774
- if (!onlyInternalFields && context._originalValues) {
775
- const hasChanges = Object.keys(event).some((key) => {
776
- if (key === 'type' || key.startsWith('_'))
777
- return false;
778
- return newContext[key] !== context._originalValues?.[key];
779
- });
780
- newContext._isEdited = hasChanges;
781
- }
782
- newContext._validationErrors = undefined;
783
- return newContext;
784
- }),
785
- },
786
- ],
630
+ // Applied without re-invoking saveToSchema (that looped); the save in flight keeps its context
631
+ updateContext: { actions: 'applyUpdate' },
787
632
  // validationError: Uses root handler for assignment, but needs state-specific transition
788
633
  validationError: {
789
634
  target: 'idle',
@@ -843,6 +688,8 @@ const getModelPropertiesData = async (modelFileId) => {
843
688
  };
844
689
 
845
690
  const logger = debug('seedSdk:modelProperty:ModelProperty');
691
+ /** Property objects createById built from a row: their rules are already stored, nothing to persist. */
692
+ const definitionsReadFromRow = new WeakSet();
846
693
  // Define the property keys from TProperty
847
694
  const TPropertyKeys = [
848
695
  'id',
@@ -860,8 +707,8 @@ const TPropertyKeys = [
860
707
  ];
861
708
  class ModelProperty {
862
709
  constructor(property) {
863
- /** currentEvictionEpoch() at construction: lookups started for this instance don't outlive an eviction. */
864
- this._evictionEpoch = currentEvictionEpoch();
710
+ /** evictionLog.now() at construction: lookups started for this instance don't outlive an eviction. */
711
+ this._since = evictionLog.now();
865
712
  // id is now the schemaFileId (string), _dbId is the database integer ID
866
713
  // Preserve _propertyFileId if it exists in the property object (from getPropertySchema)
867
714
  // Convert null to undefined for optional fields (TypeBox validation expects undefined, not null)
@@ -878,7 +725,7 @@ class ModelProperty {
878
725
  });
879
726
  this._service.start();
880
727
  // Initialize original values from the input property
881
- this._initializeOriginalValues(property);
728
+ this._originalValuesLoaded = this._initializeOriginalValues(property);
882
729
  // Note: Property getters/setters are now handled by the Proxy in create()
883
730
  }
884
731
  /**
@@ -913,9 +760,15 @@ class ModelProperty {
913
760
  // Ignore errors - model might not exist yet
914
761
  });
915
762
  }
763
+ // Get schema name from model asynchronously (fire-and-forget)
764
+ if (property.modelName) {
765
+ this._setSchemaName(property).catch(() => {
766
+ // If we can't get schema name, that's okay - it will be set later if needed
767
+ });
768
+ }
916
769
  // Get schema file values to use as "original" values
917
770
  // This allows us to detect if the property was edited (DB value differs from schema file)
918
- this._getSchemaFileValues(property).then((schemaFileValues) => {
771
+ return this._getSchemaFileValues(property).then((schemaFileValues) => {
919
772
  // Use schema file values as original (not the current property values)
920
773
  // This way, if current values differ from schema file, _isEdited will be true
921
774
  const originalValues = schemaFileValues || {};
@@ -969,9 +822,8 @@ class ModelProperty {
969
822
  // For runtime-created properties, set isEdited = true initially
970
823
  isEdited = true;
971
824
  }
972
- // Initialize with original values, including isEdited flag
973
- // Load isEdited from database if property exists in DB (async, fire-and-forget)
974
- this._loadIsEditedFromDb(property, isEdited).then((isEditedFromDb) => {
825
+ // Initialize with original values, including isEdited flag (from the row when there is one)
826
+ return this._loadIsEditedFromDb(property, isEdited).then((isEditedFromDb) => {
975
827
  this._sendIfRunning({
976
828
  type: 'initializeOriginalValues',
977
829
  originalValues,
@@ -1001,12 +853,6 @@ class ModelProperty {
1001
853
  schemaName: undefined,
1002
854
  });
1003
855
  });
1004
- // Get schema name from model asynchronously (fire-and-forget)
1005
- if (property.modelName) {
1006
- this._setSchemaName(property).catch(() => {
1007
- // If we can't get schema name, that's okay - it will be set later if needed
1008
- });
1009
- }
1010
856
  }
1011
857
  /**
1012
858
  * Load isEdited flag from database if property exists in DB
@@ -1024,7 +870,7 @@ class ModelProperty {
1024
870
  return fallbackIsEdited;
1025
871
  }
1026
872
  // Find this property's model (by modelId when known; model names are only unique per schema)
1027
- const _mod_12 = await import('./index-rOTW-2QZ.js');
873
+ const _mod_12 = await import('./tabEvents-CaVmngqr.js');
1028
874
  const _ns_12 = _mod_12.be;
1029
875
  const { resolveModelRecord } = _ns_12;
1030
876
  const modelRecord = await resolveModelRecord(property.modelName, this._ownerModelScope(property), db);
@@ -1062,7 +908,7 @@ class ModelProperty {
1062
908
  return undefined;
1063
909
  }
1064
910
  // Resolve the ref within the owning model's schema
1065
- const _mod_13 = await import('./index-rOTW-2QZ.js');
911
+ const _mod_13 = await import('./tabEvents-CaVmngqr.js');
1066
912
  const _ns_13 = _mod_13.be;
1067
913
  const { resolveRefModelRecord } = _ns_13;
1068
914
  const refModelRecord = await resolveRefModelRecord(refModelName, property ? this._ownerModelScope(property) : { schemaName: this._getSnapshotContext()._schemaName }, db);
@@ -1108,7 +954,7 @@ class ModelProperty {
1108
954
  }
1109
955
  }
1110
956
  if (!model && modelId) {
1111
- const _mod_14 = await import('./index-rOTW-2QZ.js');
957
+ const _mod_14 = await import('./tabEvents-CaVmngqr.js');
1112
958
  const _ns_14 = _mod_14.be;
1113
959
  const { resolveModelRecord } = _ns_14;
1114
960
  const modelFileId = (await resolveModelRecord(property.modelName, { modelId }))?.schemaFileId;
@@ -1120,10 +966,10 @@ class ModelProperty {
1120
966
  return undefined;
1121
967
  if (!model) {
1122
968
  try {
1123
- // The epoch from when this instance was built: an eviction of the model's schema since
1124
- // then (this instance may already be stopped) must not re-create the model.
969
+ // An eviction of the model's schema since this instance was built (it may already be
970
+ // stopped) must not re-create the model.
1125
971
  model = await Model.getByNameAsync(property.modelName, undefined, {
1126
- evictionEpoch: this._evictionEpoch,
972
+ since: this._since,
1127
973
  hold: false,
1128
974
  });
1129
975
  }
@@ -1244,7 +1090,9 @@ class ModelProperty {
1244
1090
  if (modelId == null)
1245
1091
  return undefined;
1246
1092
  // Resolve modelFileId (string) to database ID (number) if needed - modelSchemas.modelId expects number
1247
- const modelIdNum = typeof modelId === 'string' ? await getModelIdByFileId(modelId) : modelId;
1093
+ const modelIdNum = typeof modelId === 'string' ? (await resolveModelRecord(undefined, { modelFileId: modelId }, db))?.id : modelId;
1094
+ if (modelIdNum == null)
1095
+ return undefined;
1248
1096
  const modelSchemaRecords = await db
1249
1097
  .select({ schemaName: schemas.name })
1250
1098
  .from(modelSchemas)
@@ -1274,6 +1122,9 @@ class ModelProperty {
1274
1122
  const waitForReady = options?.waitForReady !== false;
1275
1123
  const readyTimeout = options?.readyTimeout ?? DEFAULT_READY_TIMEOUT_MS;
1276
1124
  const schemaName = options?.schemaName;
1125
+ const hold = options?.hold !== false;
1126
+ // An id the caller passed (not one generated below): the cache may have that property
1127
+ const givenId = typeof property.id === 'string' ? property.id : (property._propertyFileId ?? undefined);
1277
1128
  // Handle 'type' field from JSON schema format - convert to 'dataType'
1278
1129
  // Normalize to PascalCase so lowercase values from JSON (e.g. 'text') work
1279
1130
  const propertyWithId = { ...property };
@@ -1308,37 +1159,19 @@ class ModelProperty {
1308
1159
  propertyWithId.id = generateId();
1309
1160
  logger(`ModelProperty.create: Generated new id (schemaFileId) "${propertyWithId.id}" for property "${property.name}"`);
1310
1161
  }
1311
- // Create cache key from modelName and name, or use id
1312
- let cacheKey = propertyWithId.modelName && propertyWithId.name
1313
- ? `${propertyWithId.modelName}:${propertyWithId.name}`
1314
- : propertyWithId.id
1315
- ? `id:${propertyWithId.id}`
1316
- : propertyWithId.name || 'unnamed';
1317
- // Model names are only unique per schema: a cached "Post:title" may be another schema's
1318
- // property. If the ids say it's a different property, key this one by its own id instead.
1319
- // (Not by file id: the same property is often created first with a generated id, then its real one.)
1162
+ // By id, else by `modelName:name`. Model names are only unique per schema: a property cached
1163
+ // under that name may be another schema's. (Not only by id: the same property is often created
1164
+ // first with a generated id, then with its real one.)
1165
+ const nameKey = propertyWithId.modelName && propertyWithId.name ? `${propertyWithId.modelName}:${propertyWithId.name}` : undefined;
1320
1166
  const isOtherProperty = (cachedContext) => (typeof propertyWithId.modelId === 'number' &&
1321
1167
  typeof cachedContext.modelId === 'number' &&
1322
1168
  cachedContext.modelId !== propertyWithId.modelId) ||
1323
1169
  (!!schemaName && !!cachedContext._schemaName && cachedContext._schemaName !== schemaName);
1324
- const cachedByName = this.instanceCache.get(cacheKey);
1325
- if (cachedByName && propertyWithId.id && isOtherProperty(cachedByName.instance._getSnapshotContext())) {
1326
- // Reuse this property's own id-keyed entry if it already has one.
1327
- cacheKey = `id:${propertyWithId.id}`;
1328
- for (const [key, { instance }] of this.instanceCache.entries()) {
1329
- if (!key.startsWith('id:'))
1330
- continue;
1331
- const ctx = instance._getSnapshotContext();
1332
- if (ctx.modelName === propertyWithId.modelName && ctx.name === propertyWithId.name && !isOtherProperty(ctx)) {
1333
- cacheKey = key;
1334
- break;
1335
- }
1336
- }
1337
- }
1338
- // Check if instance exists in cache
1339
- if (this.instanceCache.has(cacheKey)) {
1340
- const cachedEntry = this.instanceCache.get(cacheKey);
1341
- const { instance, refCount } = cachedEntry;
1170
+ const cachedByName = this.cache.peek(nameKey);
1171
+ const nameTakenByOther = !!cachedByName && isOtherProperty(cachedByName._getSnapshotContext());
1172
+ const cached = this.cache.peek(givenId) ?? (nameTakenByOther ? undefined : cachedByName);
1173
+ if (cached) {
1174
+ const instance = cached;
1342
1175
  const cachedContext = instance._getSnapshotContext();
1343
1176
  // Update cached instance if new property data has fields that the cached instance doesn't have
1344
1177
  // This handles cases where the property was created without ref initially, but now we have ref from schema
@@ -1352,30 +1185,32 @@ class ModelProperty {
1352
1185
  if (propertyWithId.refModelId && !cachedContext.refModelId) {
1353
1186
  needsUpdate.refModelId = propertyWithId.refModelId;
1354
1187
  }
1355
- // Rules defined in code exist only on the instance: an instance cached from the DB row first
1356
- // (which has no column for them) must still take them.
1188
+ // Rules defined in code: an instance cached from a row that doesn't have them takes them,
1189
+ // and so does the row's definition.
1357
1190
  if (propertyWithId.validation && !cachedContext.validation) {
1358
1191
  needsUpdate.validation = propertyWithId.validation;
1359
1192
  }
1360
1193
  if (propertyWithId.htmlEmbeddedDataUriPolicy && !cachedContext.htmlEmbeddedDataUriPolicy) {
1361
1194
  needsUpdate.htmlEmbeddedDataUriPolicy = propertyWithId.htmlEmbeddedDataUriPolicy;
1362
1195
  }
1196
+ const codeDefined = definitionOnlyFields(propertyWithId);
1197
+ if (Object.keys(codeDefined).length > 0 && typeof propertyWithId.id === 'string') {
1198
+ void persistDefinitionFields({ schemaFileId: propertyWithId.id }, codeDefined).catch((error) => logger(`Could not store the definition of property "${property.name}": ${error}`));
1199
+ }
1363
1200
  if (Object.keys(needsUpdate).length > 0) {
1364
1201
  instance._service.send({
1365
1202
  type: 'updateContext',
1366
1203
  ...needsUpdate,
1367
1204
  });
1368
1205
  }
1369
- this.instanceCache.set(cacheKey, {
1370
- ...cachedEntry,
1371
- refCount: refCount + 1,
1372
- });
1206
+ if (hold)
1207
+ this.cache.holdInstance(instance);
1373
1208
  if (!waitForReady)
1374
1209
  return instance;
1375
- return waitForEntityIdle(instance, { timeout: readyTimeout }).then(() => instance);
1210
+ return waitForEntityReady(instance, { timeout: readyTimeout }).then(() => instance);
1376
1211
  }
1377
1212
  const newInstance = new this(propertyWithId);
1378
- // Set schema name before async operations so getModelId can resolve the correct model
1213
+ // Set schema name before async operations so the model lookup is scoped to the right schema
1379
1214
  if (schemaName) {
1380
1215
  newInstance._service.send({
1381
1216
  type: 'setSchemaName',
@@ -1401,13 +1236,20 @@ class ModelProperty {
1401
1236
  });
1402
1237
  },
1403
1238
  });
1404
- this.instanceCache.set(cacheKey, {
1405
- instance: proxiedInstance,
1406
- refCount: 1,
1239
+ this.cache.add(proxiedInstance, [propertyWithId.id, nameTakenByOther ? undefined : nameKey], { hold });
1240
+ // A property is often created with a generated id and gets its real one later: key it by that too
1241
+ let keyedId = propertyWithId.id;
1242
+ const idWatch = newInstance._service.subscribe((snapshot) => {
1243
+ const id = snapshot.context.id;
1244
+ if (!id || id === keyedId)
1245
+ return;
1246
+ if (keyedId)
1247
+ this.cache.removeKey(proxiedInstance, keyedId);
1248
+ keyedId = id;
1249
+ this.cache.addKey(proxiedInstance, id);
1407
1250
  });
1408
- this.indexCachedInstance(cacheKey, proxiedInstance);
1409
- // Trigger write process if property has modelId (or modelName) and id (schemaFileId)
1410
- // Wait for service to be ready (idle state) and have writeProcess spawned
1251
+ onEntityTeardown(proxiedInstance, () => idWatch.unsubscribe());
1252
+ // A property with a model (modelId or modelName) and an id (schemaFileId) writes its row
1411
1253
  const propertyFileId = propertyWithId.id; // id is now the schemaFileId (string)
1412
1254
  const hasModelId = propertyWithId.modelId || propertyWithId.modelName;
1413
1255
  // A _dbId means the data was loaded from an existing row (createById, getPropertySchema), so
@@ -1416,212 +1258,111 @@ class ModelProperty {
1416
1258
  // Settles when the row write finishes; create() waits for it when waitForReady is on, so a
1417
1259
  // failed write rejects create() instead of resolving with nothing in the DB.
1418
1260
  let writeDone = Promise.resolve();
1261
+ const codeDefined = definitionOnlyFields(propertyWithId);
1262
+ if (isPersisted && Object.keys(codeDefined).length > 0 && !definitionsReadFromRow.has(property)) {
1263
+ // The row exists (a schema file's, or an earlier run's); rules defined in code go into its
1264
+ // definition now rather than at the next saveNewVersion.
1265
+ writeDone = persistDefinitionFields({ id: propertyWithId._dbId }, codeDefined).catch((error) => logger(`Could not store the definition of property "${property.name}": ${error}`));
1266
+ }
1419
1267
  if (hasModelId && propertyFileId && !isPersisted) {
1420
- let resolveWrite;
1421
- let rejectWrite;
1422
- writeDone = new Promise((resolve, reject) => {
1423
- resolveWrite = resolve;
1424
- rejectWrite = reject;
1425
- });
1426
- // Wait for writeProcess to be spawned (it's spawned in idle state entry action)
1427
- // Retry a few times if writeProcess isn't available yet
1428
- let retries = 0;
1429
- const maxRetries = 10;
1430
- const checkAndSend = async () => {
1431
- const service = proxiedInstance.getService();
1432
- const snapshot = service.getSnapshot();
1433
- // Unloaded or evicted (e.g. Schema.destroy) before the write started: nothing to write to
1434
- if (isActorStopped(service)) {
1435
- resolveWrite();
1436
- return;
1437
- }
1438
- if (snapshot.value === 'idle' && snapshot.context.writeProcess) {
1439
- const writeProcess = snapshot.context.writeProcess;
1440
- // Resolve dbModelId - convert from string (modelFileId) to number (database ID) if needed
1441
- let resolvedModelId = undefined;
1442
- if (propertyWithId.modelId) {
1443
- if (typeof propertyWithId.modelId === 'number') {
1444
- resolvedModelId = propertyWithId.modelId;
1445
- }
1446
- else if (typeof propertyWithId.modelId === 'string') {
1447
- // modelId is a string (modelFileId), need to convert to database ID
1448
- try {
1449
- resolvedModelId = await getModelIdByFileId(propertyWithId.modelId);
1450
- logger(`Converted modelFileId "${propertyWithId.modelId}" to database modelId: ${resolvedModelId}`);
1451
- }
1452
- catch (error) {
1453
- logger(`Failed to convert modelFileId "${propertyWithId.modelId}" to database ID: ${error}`);
1454
- console.error(`[ModelProperty.create] Failed to convert modelFileId: ${error}`);
1455
- }
1456
- }
1457
- }
1458
- // If we still don't have a modelId, try to resolve it from modelName
1459
- if (!resolvedModelId && propertyWithId.modelName) {
1460
- try {
1461
- // Get schemaName from context if available
1462
- const schemaName = snapshot.context._schemaName;
1463
- resolvedModelId = await getModelId(propertyWithId.modelName, schemaName);
1464
- logger(`Resolved modelId for model "${propertyWithId.modelName}": ${resolvedModelId}`);
1465
- }
1466
- catch (error) {
1467
- logger(`Failed to resolve modelId for model "${propertyWithId.modelName}": ${error}`);
1468
- console.error(`[ModelProperty.create] Failed to resolve modelId: ${error}`);
1469
- }
1470
- }
1471
- if (!resolvedModelId) {
1472
- logger(`ERROR: Cannot write property "${property.name}" - no modelId available`);
1473
- console.error(`[ModelProperty.create] ERROR: Cannot write property "${property.name}" - no modelId available. modelId: ${propertyWithId.modelId}, modelName: ${propertyWithId.modelName}`);
1474
- // Don't clear pending write here - it might resolve later
1475
- rejectWrite(new Error(`Cannot write property "${property.name}": model ${propertyWithId.modelName ?? propertyWithId.modelId} has no database row`));
1476
- return;
1477
- }
1478
- // Resolving the modelId awaited the DB; the instance may have been stopped meanwhile
1479
- if (isActorStopped(service)) {
1480
- resolveWrite();
1481
- return;
1482
- }
1483
- // Track pending write now that we have the resolved modelId
1484
- this.trackPendingWrite(propertyFileId, resolvedModelId);
1485
- logger(`Triggering write process for property "${property.name}" (modelId: ${resolvedModelId}, propertyFileId: ${propertyFileId})`);
1486
- // Check current write state
1487
- const currentWriteState = writeProcess.getSnapshot();
1488
- if (currentWriteState.value === 'success') {
1489
- // Write already succeeded
1490
- void this.completePendingWrite(propertyFileId, resolvedModelId);
1491
- resolveWrite();
1492
- }
1493
- else {
1494
- // Set up subscription to catch future state changes
1495
- const writeSubscription = writeProcess.subscribe((writeSnapshot) => {
1496
- if (writeSnapshot.value === 'success') {
1497
- writeSubscription.unsubscribe();
1498
- logger(`[writeProcess subscription] Write succeeded for property "${property.name}" (propertyFileId: ${propertyFileId})`);
1499
- void this.completePendingWrite(propertyFileId, resolvedModelId);
1500
- resolveWrite();
1501
- }
1502
- else if (writeSnapshot.value === 'error') {
1503
- writeSubscription.unsubscribe();
1504
- const errorContext = writeSnapshot.context;
1505
- logger(`Write process failed for property "${property.name}" (propertyFileId: ${propertyFileId}): ${errorContext.error?.message || 'Unknown error'}`);
1506
- logger(`Write process error details:`, errorContext.error);
1507
- // Mark pending write as error
1508
- this.clearPendingWrite(propertyFileId, 'error');
1509
- rejectWrite(new Error(`Failed to write property "${property.name}": ${errorContext.error?.message || 'Unknown error'}`));
1510
- }
1511
- });
1512
- }
1513
- const propertyData = {
1514
- modelId: resolvedModelId,
1515
- name: property.name,
1516
- dataType: property.dataType,
1517
- refModelId: property.refModelId,
1518
- refValueType: property.refValueType,
1519
- required: property.required,
1520
- storageType: property.storageType,
1521
- localStorageDir: property.localStorageDir,
1522
- filenameSuffix: property.filenameSuffix,
1523
- };
1524
- service.send({
1525
- type: 'requestWrite',
1526
- data: propertyData,
1527
- });
1528
- }
1529
- else if (retries < maxRetries) {
1530
- retries++;
1531
- setTimeout(checkAndSend, 50); // Retry after 50ms
1532
- }
1533
- else {
1534
- logger(`ERROR: writeProcess not available after ${maxRetries} retries for property "${property.name}" (propertyFileId: ${propertyFileId})`);
1535
- console.error(`[ModelProperty.create] ERROR: writeProcess not available after ${maxRetries} retries for property "${property.name}" (propertyFileId: ${propertyFileId})`);
1536
- // Mark as error if we couldn't even start the write process
1537
- this.clearPendingWrite(propertyFileId, 'error');
1538
- rejectWrite(new Error(`Failed to write property "${property.name}": its write process never started`));
1539
- }
1540
- };
1541
- // Start checking after a short delay to allow state machine to initialize
1542
- setTimeout(checkAndSend, 0);
1268
+ writeDone = this.persistNewProperty(proxiedInstance, propertyWithId, propertyFileId);
1543
1269
  }
1544
- if (!waitForReady) {
1545
- // Nobody awaits the write; failures are already logged above.
1546
- writeDone.catch(() => { });
1270
+ // Ready once its row is written (when it had none) and its original values are known
1271
+ void runEntityLoad(proxiedInstance, async () => {
1272
+ await Promise.all([writeDone, newInstance._originalValuesLoaded.catch(() => { })]);
1273
+ });
1274
+ if (!waitForReady)
1547
1275
  return proxiedInstance;
1548
- }
1549
- let timer;
1550
- const writeWithin = Promise.race([
1551
- writeDone,
1552
- new Promise((_, reject) => {
1553
- timer = setTimeout(() => reject(new Error(`Property "${property.name}" was not written within ${readyTimeout}ms`)), readyTimeout);
1554
- }),
1555
- ]).finally(() => clearTimeout(timer));
1556
- return Promise.all([waitForEntityIdle(proxiedInstance, { timeout: readyTimeout }), writeWithin]).then(() => proxiedInstance);
1276
+ return waitForEntityReady(proxiedInstance, { timeout: readyTimeout }).then(() => proxiedInstance);
1557
1277
  }
1558
- /** Whether an idIndex entry still points at a cached instance with that id. */
1559
- static isIndexEntryCurrent(propertyFileId, entry) {
1560
- const cached = this.instanceCache.get(entry.cacheKey)?.instance;
1561
- if (!cached || !sameEntity(cached, entry.instance))
1562
- return false;
1278
+ /**
1279
+ * Writes the row of a property ModelProperty.create made, under the model row its modelId (row id
1280
+ * or file id) or modelName names. Resolves without writing once the instance is stopped; rejects
1281
+ * when the model has no row or the write fails.
1282
+ */
1283
+ static async persistNewProperty(instance, property, propertyFileId) {
1284
+ const service = instance.getService();
1285
+ const findModelId = async () => {
1286
+ if (typeof property.modelId === 'number')
1287
+ return property.modelId;
1288
+ if (typeof property.modelId === 'string') {
1289
+ const row = await resolveModelRecord(undefined, { modelFileId: property.modelId });
1290
+ if (row?.id)
1291
+ return row.id;
1292
+ }
1293
+ if (!property.modelName)
1294
+ return undefined;
1295
+ // With a schema name only that schema's model counts (no name-only fallback)
1296
+ const row = await resolveModelRecord(property.modelName, {
1297
+ modelFileId: property.modelName,
1298
+ schemaName: service.getSnapshot().context._schemaName,
1299
+ strict: true,
1300
+ });
1301
+ return row?.id;
1302
+ };
1303
+ const modelId = await findModelId().catch((error) => {
1304
+ logger(`Could not resolve the model of property "${property.name}": ${error}`);
1305
+ return undefined;
1306
+ });
1307
+ if (!modelId) {
1308
+ throw new Error(`Cannot write property "${property.name}": model ${property.modelName ?? property.modelId} has no database row`);
1309
+ }
1310
+ // Unloaded or evicted (e.g. Schema.destroy) before the write started: nothing to write to
1311
+ if (isActorStopped(service))
1312
+ return;
1313
+ this.trackPendingWrite(propertyFileId, modelId);
1563
1314
  try {
1564
- return entry.instance._getSnapshotContext().id === propertyFileId;
1315
+ await saveDefinition({
1316
+ type: 'property',
1317
+ propertyFileId,
1318
+ data: () => {
1319
+ // A rename made since create is written, not the name create got
1320
+ const context = service.getSnapshot().context;
1321
+ return {
1322
+ modelId,
1323
+ name: context.name ?? property.name,
1324
+ dataType: context.dataType ?? property.dataType,
1325
+ refModelId: context.refModelId ?? property.refModelId,
1326
+ refModelName: context.refModelName ?? property.refModelName,
1327
+ refValueType: context.refValueType ?? property.refValueType,
1328
+ required: context.required ?? property.required,
1329
+ storageType: context.storageType ?? property.storageType,
1330
+ localStorageDir: context.localStorageDir ?? property.localStorageDir,
1331
+ filenameSuffix: context.filenameSuffix ?? property.filenameSuffix,
1332
+ // Stored in the row's definition column with the rest
1333
+ ...definitionOnlyFields(property),
1334
+ };
1335
+ },
1336
+ });
1565
1337
  }
1566
- catch {
1567
- return false;
1338
+ catch (error) {
1339
+ this.clearPendingWrite(propertyFileId, 'error');
1340
+ throw new Error(`Failed to write property "${property.name}": ${error instanceof Error ? error.message : String(error)}`);
1568
1341
  }
1569
- }
1570
- /** Add a newly cached instance to idIndex, and keep its entry current when its id changes. */
1571
- static indexCachedInstance(cacheKey, instance) {
1572
- const index = (id) => {
1573
- if (!id)
1574
- return;
1575
- const existing = this.idIndex.get(id);
1576
- // Keep the instance cached first, as the old scan in insertion order returned
1577
- if (existing && !sameEntity(existing.instance, instance) && this.isIndexEntryCurrent(id, existing))
1578
- return;
1579
- this.idIndex.set(id, { cacheKey, instance });
1580
- };
1581
- let indexedId = instance._getSnapshotContext().id;
1582
- index(indexedId);
1583
- instance._service.subscribe((snapshot) => {
1584
- const id = snapshot.context.id;
1585
- if (id === indexedId)
1586
- return;
1587
- indexedId = id;
1588
- index(id);
1589
- });
1342
+ void this.completePendingWrite(propertyFileId, modelId);
1590
1343
  }
1591
1344
  /**
1592
- * Turns the caller's hold from the create call just made into model ownership: the instance stays
1593
- * cached and running for its model, and app holders' unload calls don't stop it.
1345
+ * Make the property's model hold it: the instance stays cached and running for its model, and app
1346
+ * holders' unload calls don't stop it. Teardown of the model releases it. Without a cached model
1347
+ * (it was unloaded meanwhile) nothing holds it.
1594
1348
  * @internal Used by the model's property loading.
1595
1349
  */
1596
- static adoptForModel(instance) {
1597
- for (const [key, entry] of this.instanceCache) {
1598
- if (entry.instance._service !== instance._service)
1599
- continue;
1600
- this.instanceCache.set(key, { ...entry, refCount: Math.max(0, entry.refCount - 1), modelOwned: true });
1601
- }
1350
+ static holdForModel(instance, model) {
1351
+ const context = instance._getSnapshotContext();
1352
+ const owner = model ??
1353
+ Model.cache.instances((candidate) => {
1354
+ const modelContext = candidate.getService().getSnapshot().context;
1355
+ if (typeof context.modelId === 'number')
1356
+ return modelContext._dbId === context.modelId;
1357
+ return (modelContext.modelName === context.modelName &&
1358
+ (!context._schemaName || modelContext.schemaName === context._schemaName));
1359
+ })[0];
1360
+ if (owner)
1361
+ holdChild(owner, instance, this.cache);
1602
1362
  }
1603
- /**
1604
- * Get ModelProperty instance by propertyFileId from static cache
1605
- */
1363
+ /** The cached ModelProperty with this propertyFileId, without taking a hold. */
1606
1364
  static getById(propertyFileId) {
1607
- if (!propertyFileId)
1608
- return undefined;
1609
- const indexed = this.idIndex.get(propertyFileId);
1610
- if (!indexed)
1611
- return undefined;
1612
- if (this.isIndexEntryCurrent(propertyFileId, indexed))
1613
- return indexed.instance;
1614
- // The indexed instance left the cache or changed id; another cached instance may still have it.
1615
- // Cache key might be "modelName:propertyName" or "id:propertyId"
1616
- this.idIndex.delete(propertyFileId);
1617
- for (const [cacheKey, { instance }] of this.instanceCache.entries()) {
1618
- // id is now the schemaFileId (string)
1619
- if (instance._getSnapshotContext().id === propertyFileId) {
1620
- this.idIndex.set(propertyFileId, { cacheKey, instance });
1621
- return instance;
1622
- }
1623
- }
1624
- return undefined;
1365
+ return this.cache.peek(propertyFileId);
1625
1366
  }
1626
1367
  /**
1627
1368
  * Create or get ModelProperty instance by propertyFileId
@@ -1631,9 +1372,10 @@ class ModelProperty {
1631
1372
  if (!propertyFileId) {
1632
1373
  return undefined;
1633
1374
  }
1634
- // First, check if we have an instance cached
1375
+ // Cached (an app may have created it before its model's load got here): its model holds it too
1635
1376
  const cachedInstance = this.getById(propertyFileId);
1636
1377
  if (cachedInstance) {
1378
+ this.holdForModel(cachedInstance);
1637
1379
  return cachedInstance;
1638
1380
  }
1639
1381
  // Query database to get property data from ID
@@ -1641,7 +1383,7 @@ class ModelProperty {
1641
1383
  if (!db) {
1642
1384
  return undefined;
1643
1385
  }
1644
- const evictionEpoch = options?.evictionEpoch ?? currentEvictionEpoch();
1386
+ const since = options?.since ?? evictionLog.now();
1645
1387
  const propertyRecords = await db
1646
1388
  .select()
1647
1389
  .from(properties)
@@ -1661,53 +1403,37 @@ class ModelProperty {
1661
1403
  return undefined;
1662
1404
  }
1663
1405
  const modelName = modelRecords[0].name;
1664
- // Build property data
1665
- // id is now the schemaFileId (string), _dbId is the database integer ID
1406
+ // id is the schemaFileId (string), _dbId the row id
1407
+ const definition = await getPropertyDefinition(propertyRecord.id, db);
1408
+ if (!definition)
1409
+ return undefined;
1666
1410
  const propertyData = {
1667
- id: propertyFileId, // schemaFileId (string) - public ID
1668
- _dbId: propertyRecord.id ?? undefined, // Database integer ID - internal only
1669
- name: propertyRecord.name,
1670
- dataType: propertyRecord.dataType,
1671
- modelId: propertyRecord.modelId,
1411
+ ...definition,
1412
+ id: propertyFileId,
1672
1413
  modelName,
1673
- refModelId: propertyRecord.refModelId || undefined,
1674
- refValueType: propertyRecord.refValueType ? propertyRecord.refValueType : undefined,
1675
- required: propertyRecord.required ?? false,
1676
- storageType: propertyRecord.storageType ?? undefined,
1677
- localStorageDir: propertyRecord.localStorageDir ?? undefined,
1678
- filenameSuffix: propertyRecord.filenameSuffix ?? undefined,
1414
+ required: definition.required ?? false,
1679
1415
  };
1416
+ definitionsReadFromRow.add(propertyData);
1680
1417
  // Load isEdited from database
1681
1418
  const isEditedFromDb = propertyRecord.isEdited ?? false;
1682
- // Get ref model name if applicable
1683
- if (propertyRecord.refModelId) {
1684
- const refModelRecords = await db
1685
- .select({ name: models.name })
1686
- .from(models)
1687
- .where(eq(models.id, propertyRecord.refModelId))
1688
- .limit(1);
1689
- if (refModelRecords.length > 0) {
1690
- propertyData.refModelName = refModelRecords[0].name;
1691
- propertyData.ref = refModelRecords[0].name;
1692
- }
1693
- }
1694
1419
  // Its model's schema was evicted while we read the rows (e.g. a model's property lookup in flight
1695
1420
  // during Schema.destroy or test cleanup): don't bring the property back.
1696
- if (anyEvictionSince(evictionEpoch)) {
1697
- const schemaRows = await db
1698
- .select({ name: schemas.name })
1421
+ if (evictionLog.now() !== since) {
1422
+ const owners = await db
1423
+ .select({ schemaName: schemas.name, modelFileId: models.schemaFileId })
1699
1424
  .from(modelSchemas)
1700
1425
  .innerJoin(schemas, eq(schemas.id, modelSchemas.schemaId))
1426
+ .innerJoin(models, eq(models.id, modelSchemas.modelId))
1701
1427
  .where(eq(modelSchemas.modelId, propertyRecord.modelId));
1702
- if (schemaRows.length === 0 ||
1703
- schemaRows.some((row) => schemaEvictedSince(row.name, evictionEpoch))) {
1428
+ if (owners.length === 0 ||
1429
+ owners.some((row) => evictionLog.evictedSince([`schema:${row.schemaName}`, `model:${row.modelFileId}`], since))) {
1704
1430
  return undefined;
1705
1431
  }
1706
1432
  }
1707
1433
  // Create ModelProperty instance (sync for createById so we can send updateContext)
1708
- const instance = this.create(propertyData, { waitForReady: false });
1709
- // Loaded for its model (Model's property list, the model machine), not held by a caller.
1710
- this.adoptForModel(instance);
1434
+ const instance = this.create(propertyData, { waitForReady: false, hold: false });
1435
+ // Loaded for its model (Model's property list), not held by a caller
1436
+ this.holdForModel(instance);
1711
1437
  // Set isEdited from database after creation
1712
1438
  if (isEditedFromDb) {
1713
1439
  instance._service.send({
@@ -1732,37 +1458,29 @@ class ModelProperty {
1732
1458
  if (!db)
1733
1459
  return;
1734
1460
  const rows = await db
1735
- .select({
1736
- schemaFileId: properties.schemaFileId,
1737
- name: properties.name,
1738
- dataType: properties.dataType,
1739
- refModelId: properties.refModelId,
1740
- refModelName: models.name,
1741
- refValueType: properties.refValueType,
1742
- required: properties.required,
1743
- storageType: properties.storageType,
1744
- localStorageDir: properties.localStorageDir,
1745
- filenameSuffix: properties.filenameSuffix,
1746
- })
1461
+ .select({ property: properties, refModelName: models.name })
1747
1462
  .from(properties)
1748
1463
  .leftJoin(models, eq(models.id, properties.refModelId))
1749
1464
  .where(inArray(properties.schemaFileId, [...ids]));
1750
1465
  for (const row of rows) {
1751
- const propertyFileId = row.schemaFileId;
1752
- if (!propertyFileId || !row.name)
1466
+ const propertyFileId = row.property.schemaFileId;
1467
+ if (!propertyFileId || !row.property.name)
1753
1468
  continue;
1754
- const dataType = row.dataType;
1469
+ const definition = propertyDefinitionFromRow(row.property, row.refModelName);
1470
+ const dataType = definition.dataType;
1755
1471
  const rowValues = {
1756
- name: row.name,
1472
+ name: definition.name,
1757
1473
  dataType,
1758
- refValueType: row.refValueType ?? undefined,
1759
- required: row.required ?? false,
1760
- storageType: row.storageType ?? undefined,
1761
- localStorageDir: row.localStorageDir ?? undefined,
1762
- filenameSuffix: row.filenameSuffix ?? undefined,
1474
+ refValueType: definition.refValueType,
1475
+ required: definition.required ?? false,
1476
+ storageType: definition.storageType,
1477
+ localStorageDir: definition.localStorageDir,
1478
+ filenameSuffix: definition.filenameSuffix,
1479
+ // Only when the row has them: rules code just set may not be stored yet
1480
+ ...definitionOnlyFields(definition),
1763
1481
  };
1764
- if (row.refModelId) {
1765
- rowValues.refModelId = row.refModelId;
1482
+ if (definition.refModelId) {
1483
+ rowValues.refModelId = definition.refModelId;
1766
1484
  if (row.refModelName) {
1767
1485
  rowValues.ref = row.refModelName;
1768
1486
  rowValues.refModelName = row.refModelName;
@@ -1775,24 +1493,23 @@ class ModelProperty {
1775
1493
  rowValues.ref = undefined;
1776
1494
  rowValues.refModelName = undefined;
1777
1495
  }
1778
- for (const [cacheKey, entry] of [...this.instanceCache.entries()]) {
1779
- const { instance } = entry;
1496
+ for (const instance of this.cache.instances()) {
1780
1497
  if (isActorStopped(instance._service))
1781
1498
  continue;
1782
1499
  const context = instance._getSnapshotContext();
1783
1500
  if (context.id !== propertyFileId || context._isEdited)
1784
1501
  continue;
1785
- const changed = Object.fromEntries(Object.entries(rowValues).filter(([key, value]) => context[key] !== value));
1502
+ const changed = Object.fromEntries(Object.entries(rowValues).filter(([key, value]) => typeof value === 'object' && value !== null
1503
+ ? JSON.stringify(context[key]) !== JSON.stringify(value)
1504
+ : context[key] !== value));
1786
1505
  if (Object.keys(changed).length === 0)
1787
1506
  continue;
1788
1507
  instance._service.send({ type: 'syncedFromStorage', values: changed });
1789
- const newCacheKey = changed.name && context.modelName ? `${context.modelName}:${changed.name}` : undefined;
1790
- if (newCacheKey && cacheKey === `${context.modelName}:${context.name}` && !this.instanceCache.has(newCacheKey)) {
1791
- this.instanceCache.delete(cacheKey);
1792
- this.instanceCache.set(newCacheKey, entry);
1793
- const indexed = this.idIndex.get(propertyFileId)?.instance;
1794
- if (indexed && sameEntity(indexed, instance)) {
1795
- this.idIndex.set(propertyFileId, { cacheKey: newCacheKey, instance });
1508
+ // Renamed: creating the property by its new name finds it
1509
+ if (changed.name && context.modelName) {
1510
+ const ownNameKey = this.cache.keysOf(instance).includes(`${context.modelName}:${context.name}`);
1511
+ if (ownNameKey && !this.cache.peek(`${context.modelName}:${changed.name}`)) {
1512
+ this.cache.setKeys(instance, [propertyFileId, `${context.modelName}:${changed.name}`]);
1796
1513
  }
1797
1514
  }
1798
1515
  }
@@ -1808,13 +1525,10 @@ class ModelProperty {
1808
1525
  if (!propertyFileId) {
1809
1526
  return undefined;
1810
1527
  }
1811
- return await findEntity({
1812
- getById: (id) => ModelProperty.getById(id),
1813
- createById: (id) => ModelProperty.createById(id),
1814
- }, { id: propertyFileId }, {
1815
- waitForReady,
1816
- readyTimeout,
1817
- });
1528
+ const property = ModelProperty.getById(propertyFileId) ?? (await ModelProperty.createById(propertyFileId));
1529
+ if (property && waitForReady)
1530
+ await waitForEntityReady(property, { timeout: readyTimeout });
1531
+ return property;
1818
1532
  }
1819
1533
  /**
1820
1534
  * Get all ModelProperty instances for a model.
@@ -1836,9 +1550,7 @@ class ModelProperty {
1836
1550
  }
1837
1551
  }
1838
1552
  if (waitForReady && instances.length > 0) {
1839
- await Promise.all(instances.map((p) => waitForEntityIdle(p, {
1840
- timeout: readyTimeout,
1841
- })));
1553
+ await Promise.all(instances.map((property) => waitForEntityReady(property, { timeout: readyTimeout })));
1842
1554
  }
1843
1555
  return instances;
1844
1556
  }
@@ -1917,8 +1629,13 @@ class ModelProperty {
1917
1629
  }
1918
1630
  return `${workingDir}/${this.localStorageDir}/${this.name}${this.filenameSuffix || ''}`;
1919
1631
  }
1632
+ /** Resolves once `status` is `ready`; rejects when the load failed or `timeout` ms pass. */
1633
+ waitForReady(options) {
1634
+ return waitForEntityReady(this, options);
1635
+ }
1636
+ /** `loading` until its row is written (when it had none) and its original values are known. */
1920
1637
  get status() {
1921
- return this._getSnapshot().value;
1638
+ return entityStatus(this);
1922
1639
  }
1923
1640
  get isEdited() {
1924
1641
  const context = this._getSnapshotContext();
@@ -1947,35 +1664,11 @@ class ModelProperty {
1947
1664
  * @returns Validation result
1948
1665
  */
1949
1666
  async validate() {
1950
- return new Promise((resolve) => {
1951
- let resolved = false;
1952
- const subscription = this._service.subscribe((snapshot) => {
1953
- const state = snapshot.value;
1954
- // Wait for validation to complete (idle state after validating)
1955
- if (state === 'idle' && !resolved) {
1956
- resolved = true;
1957
- subscription.unsubscribe();
1958
- const errors = snapshot.context._validationErrors || [];
1959
- resolve({
1960
- isValid: errors.length === 0,
1961
- errors,
1962
- });
1963
- }
1964
- });
1965
- this._service.send({ type: 'validateProperty' });
1966
- // Timeout fallback
1967
- setTimeout(() => {
1968
- if (!resolved) {
1969
- resolved = true;
1970
- subscription.unsubscribe();
1971
- const errors = this._getSnapshotContext()._validationErrors || [];
1972
- resolve({
1973
- isValid: errors.length === 0,
1974
- errors,
1975
- });
1976
- }
1977
- }, 5000);
1978
- });
1667
+ this._service.send({ type: 'validateProperty' });
1668
+ // Settles back in idle; after 5 s, the errors so far
1669
+ await waitFor(this._service, (snapshot) => snapshot.value === 'idle', { timeout: 5000 }).catch(() => { });
1670
+ const errors = this._getSnapshotContext()._validationErrors || [];
1671
+ return { isValid: errors.length === 0, errors };
1979
1672
  }
1980
1673
  save() {
1981
1674
  const snapshot = this._service.getSnapshot();
@@ -2014,139 +1707,82 @@ class ModelProperty {
2014
1707
  if (modelNames.length === 0)
2015
1708
  return;
2016
1709
  const names = new Set(modelNames);
2017
- for (const [cacheKey, { instance }] of this.instanceCache.entries()) {
2018
- let context;
2019
- try {
2020
- context = instance._getSnapshotContext();
2021
- }
2022
- catch {
2023
- continue;
2024
- }
1710
+ evictEntities(this.cache, (property) => {
1711
+ const context = property._getSnapshotContext();
2025
1712
  if (!context.modelName || !names.has(context.modelName))
2026
- continue;
2027
- if (schemaName && context._schemaName && context._schemaName !== schemaName)
2028
- continue;
2029
- this.instanceCache.delete(cacheKey);
2030
- try {
2031
- instance._service.stop();
2032
- }
2033
- catch {
2034
- // Service might already be stopped
1713
+ return false;
1714
+ return !schemaName || !context._schemaName || context._schemaName === schemaName;
1715
+ });
1716
+ }
1717
+ /**
1718
+ * Force-evict one model's cached properties (Model.destroy): by its row id when the property has
1719
+ * one, else by model and schema name.
1720
+ */
1721
+ static evictForModel(model) {
1722
+ evictEntities(this.cache, (property) => {
1723
+ const context = property._getSnapshotContext();
1724
+ if (typeof context.modelId === 'number' && typeof model.modelId === 'number') {
1725
+ return context.modelId === model.modelId;
2035
1726
  }
2036
- }
1727
+ if (!model.modelName || context.modelName !== model.modelName)
1728
+ return false;
1729
+ return !model.schemaName || !context._schemaName || context._schemaName === model.schemaName;
1730
+ });
2037
1731
  }
2038
1732
  /**
2039
1733
  * Releases this caller's hold. The instance is shared: it keeps running while other callers hold
2040
- * it, or while its model owns it (a model's properties are stopped when the model is evicted).
2041
- * An instance nobody else holds is stopped and leaves the cache.
1734
+ * it, or while its model holds it. An instance nobody else holds is stopped and leaves the cache.
2042
1735
  */
2043
1736
  unload() {
2044
- const entries = [...ModelProperty.instanceCache.entries()].filter(([, entry]) => entry.instance._service === this._service);
2045
- if (entries.length > 0) {
2046
- const [, first] = entries[0];
2047
- const refCount = Math.max(0, first.refCount - 1);
2048
- if (refCount > 0 || first.modelOwned) {
2049
- for (const [key, entry] of entries)
2050
- ModelProperty.instanceCache.set(key, { ...entry, refCount });
2051
- return;
2052
- }
2053
- for (const [key] of entries)
2054
- ModelProperty.instanceCache.delete(key);
2055
- }
2056
- try {
2057
- this._service.stop();
2058
- }
2059
- catch {
2060
- // Service might already be stopped
2061
- }
1737
+ releaseEntity(this, ModelProperty.cache);
2062
1738
  }
2063
1739
  /**
2064
- * Destroy the model property: remove from caches, delete from database, update Schema context, stop service.
1740
+ * Destroy the model property: delete its row, remove it from its Schema's context, and stop it
1741
+ * whoever holds it.
2065
1742
  */
2066
1743
  async destroy() {
2067
1744
  const context = this._getSnapshotContext();
2068
- // Stored under "modelName:name", or "id:<id>" when another schema's same-name property holds that key
2069
- const cacheKeys = [...ModelProperty.instanceCache.entries()]
2070
- .filter(([, entry]) => {
2071
- try {
2072
- return entry.instance._getSnapshotContext().id === context.id;
1745
+ await destroyEntity(this, ModelProperty.cache, async () => {
1746
+ const db = BaseDb.getAppDb();
1747
+ const modelName = context.modelName;
1748
+ const propertyName = context.name;
1749
+ const propertyFileId = context.id ?? context._propertyFileId;
1750
+ if (db && propertyFileId) {
1751
+ const [row] = await db
1752
+ .select({ id: properties.id })
1753
+ .from(properties)
1754
+ .where(eq(properties.schemaFileId, propertyFileId))
1755
+ .limit(1);
1756
+ if (row) {
1757
+ const { detachPropertyRows } = await import('./detachRowsBeforeDelete-sEaUwlOU.js');
1758
+ await detachPropertyRows(db, [row.id]);
1759
+ await db.delete(properties).where(eq(properties.id, row.id));
1760
+ }
2073
1761
  }
2074
- catch {
2075
- return false;
1762
+ if (!modelName || !propertyName)
1763
+ return;
1764
+ // Resolve schema name from DB when _schemaName is missing (e.g. destroy ran before _setSchemaName finished)
1765
+ const schemaName = context._schemaName ?? (db ? await this._resolveSchemaNameForDestroy(db, context) : undefined);
1766
+ if (!schemaName)
1767
+ return;
1768
+ const schema = await Schema.find({ schemaName, waitForReady: false, hold: false });
1769
+ const schemaContext = schema?.getService().getSnapshot().context;
1770
+ if (schema && schemaContext?.models?.[modelName]?.properties?.[propertyName]) {
1771
+ const updatedModels = { ...schemaContext.models };
1772
+ const updatedProperties = { ...updatedModels[modelName].properties };
1773
+ delete updatedProperties[propertyName];
1774
+ updatedModels[modelName] = { ...updatedModels[modelName], properties: updatedProperties };
1775
+ schema.getService().send({ type: 'updateContext', models: updatedModels });
1776
+ schema.getService().send({ type: 'markAsDraft', propertyKey: `property:${modelName}:${propertyName}` });
2076
1777
  }
2077
- })
2078
- .map(([key]) => key);
2079
- if (cacheKeys.length === 0 && context.modelName && context.name) {
2080
- cacheKeys.push(`${context.modelName}:${context.name}`);
2081
- }
2082
- if (cacheKeys.length === 0)
2083
- return;
2084
- forceRemoveFromCaches(this, {
2085
- getCacheKeys: () => cacheKeys,
2086
- caches: [ModelProperty.instanceCache],
2087
- });
2088
- await runDestroyLifecycle(this, {
2089
- getService: (instance) => instance._service,
2090
- doDestroy: async () => {
2091
- const db = BaseDb.getAppDb();
2092
- let schemaName = context._schemaName;
2093
- const modelName = context.modelName;
2094
- const propertyName = context.name;
2095
- if (!modelName || !propertyName)
2096
- return;
2097
- // Resolve schema name from DB when _schemaName is missing (e.g. destroy ran before _setSchemaName finished)
2098
- if (!schemaName && db) {
2099
- schemaName = await this._resolveSchemaNameForDestroy(db, context);
2100
- }
2101
- if (db && schemaName) {
2102
- const propertyRecords = await db
2103
- .select({ propertyId: properties.id })
2104
- .from(properties)
2105
- .innerJoin(models, eq(properties.modelId, models.id))
2106
- .innerJoin(modelSchemas, eq(models.id, modelSchemas.modelId))
2107
- .innerJoin(schemas, eq(modelSchemas.schemaId, schemas.id))
2108
- .where(and(eq(schemas.name, schemaName), eq(models.name, modelName), eq(properties.name, propertyName)))
2109
- .limit(1);
2110
- if (propertyRecords.length > 0 && propertyRecords[0].propertyId != null) {
2111
- const { detachPropertyRows } = await import('./detachRowsBeforeDelete-Di1enVUF.js');
2112
- await detachPropertyRows(db, [propertyRecords[0].propertyId]);
2113
- await db
2114
- .delete(properties)
2115
- .where(eq(properties.id, propertyRecords[0].propertyId));
2116
- }
2117
- }
2118
- if (schemaName) {
2119
- const schema = Schema.create(schemaName, { waitForReady: false, hold: false });
2120
- const snapshot = schema.getService().getSnapshot();
2121
- const schemaContext = snapshot.context;
2122
- if (schemaContext.models?.[modelName]?.properties?.[propertyName]) {
2123
- const updatedModels = { ...schemaContext.models };
2124
- const updatedProperties = { ...updatedModels[modelName].properties };
2125
- delete updatedProperties[propertyName];
2126
- updatedModels[modelName] = { ...updatedModels[modelName], properties: updatedProperties };
2127
- schema.getService().send({ type: 'updateContext', models: updatedModels });
2128
- schema.getService().send({ type: 'markAsDraft', propertyKey: `property:${modelName}:${propertyName}` });
2129
- }
2130
- }
2131
- },
2132
1778
  });
2133
1779
  }
2134
1780
  }
2135
1781
  /**
2136
- * `refCount` counts app holders (ModelProperty.create callers that haven't unloaded). `modelOwned`
2137
- * marks an instance its model created or loaded: the model keeps it until the model is evicted,
2138
- * so it isn't stopped when the app's holders unload it.
2139
- */
2140
- ModelProperty.instanceCache = new Map();
2141
- /**
2142
- * propertyFileId -> where the instance with that id is cached, so getById doesn't scan the cache
2143
- * (a model's properties are looked up one by one, which made loading one model O(n²)).
2144
- * Every cached instance's current id has an entry: it's added when the instance is cached and
2145
- * again whenever its context id changes (a property is often created with a generated id and
2146
- * then gets its real one). Entries aren't removed when an instance leaves the cache or changes
2147
- * id; getById checks an entry before using it.
1782
+ * Cached under its id (schemaFileId) and `modelName:name` (ADR 0014). Its model holds it (see
1783
+ * holdForModel), so app holders' unloads don't stop a model's property.
2148
1784
  */
2149
- ModelProperty.idIndex = new Map();
1785
+ ModelProperty.cache = new EntityCache();
2150
1786
  // Pending writes tracking
2151
1787
  ModelProperty.pendingWrites = new Map();
2152
1788
  setCachedPropertyRefresher((propertyFileIds) => ModelProperty.refreshFromDb(propertyFileIds));
@@ -2157,4 +1793,4 @@ var ModelProperty$1 = /*#__PURE__*/Object.freeze({
2157
1793
  });
2158
1794
 
2159
1795
  export { ModelProperty };
2160
- //# sourceMappingURL=ModelProperty-DDD47KVm.js.map
1796
+ //# sourceMappingURL=ModelProperty-BlaEgb_U.js.map