@seedprotocol/sdk 0.7.3 → 0.7.4-next.784.g879c6a3

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 (127) hide show
  1. package/dist/{BasePathResolver-Cm4apKRb.js → BasePathResolver-DxdS0wJ0.js} +43 -8
  2. package/dist/BasePathResolver-DxdS0wJ0.js.map +1 -0
  3. package/dist/{ClientManager-i3nJASkg.js → ClientManager-De-vKHGe.js} +37 -38
  4. package/dist/ClientManager-De-vKHGe.js.map +1 -0
  5. package/dist/{Item-DBFchXpC.js → Item-cq9VcsAY.js} +365 -191
  6. package/dist/Item-cq9VcsAY.js.map +1 -0
  7. package/dist/{ModelProperty-BS49g01Y.js → ModelProperty-DuuoFXaC.js} +45 -37
  8. package/dist/ModelProperty-DuuoFXaC.js.map +1 -0
  9. package/dist/{Schema-CpMNEnUO.js → Schema-Dc5EA8Yb.js} +246 -68
  10. package/dist/Schema-Dc5EA8Yb.js.map +1 -0
  11. package/dist/{SchemaValidationService-DieV4KL-.js → SchemaValidationService-DViJ056F.js} +49 -36
  12. package/dist/SchemaValidationService-DViJ056F.js.map +1 -0
  13. package/dist/{backfillMetadataPropertyIds-DSoOoTnX.js → backfillMetadataPropertyIds-DacVthS5.js} +3 -3
  14. package/dist/{backfillMetadataPropertyIds-DSoOoTnX.js.map → backfillMetadataPropertyIds-DacVthS5.js.map} +1 -1
  15. package/dist/{configurePlatform-D0lQGAMQ.js → configurePlatform-DlZ23w7e.js} +2 -2
  16. package/dist/{configurePlatform-D0lQGAMQ.js.map → configurePlatform-DlZ23w7e.js.map} +1 -1
  17. package/dist/{detachRowsBeforeDelete-S0q-DJPT.js → detachRowsBeforeDelete-YRSZY6dO.js} +2 -2
  18. package/dist/{detachRowsBeforeDelete-S0q-DJPT.js.map → detachRowsBeforeDelete-YRSZY6dO.js.map} +1 -1
  19. package/dist/{eas-6pjU-OuX.js → eas-D_6ptL_F.js} +4 -4
  20. package/dist/{eas-6pjU-OuX.js.map → eas-D_6ptL_F.js.map} +1 -1
  21. package/dist/{index-8O3Uow-Y.js → errors-Cl8rbtKR.js} +192 -48
  22. package/dist/errors-Cl8rbtKR.js.map +1 -0
  23. package/dist/{getItem-CxBNZ-WL.js → getItem-BcmJcUZB.js} +5 -5
  24. package/dist/{getItem-CxBNZ-WL.js.map → getItem-BcmJcUZB.js.map} +1 -1
  25. package/dist/{getPublishPayload-CTCvRUoU.js → getPublishPayload-C278kK9P.js} +15 -15
  26. package/dist/{getPublishPayload-CTCvRUoU.js.map → getPublishPayload-C278kK9P.js.map} +1 -1
  27. package/dist/{getPublishUploads-SFHCbf_y.js → getPublishUploads-DJ1UPh7i.js} +9 -9
  28. package/dist/{getPublishUploads-SFHCbf_y.js.map → getPublishUploads-DJ1UPh7i.js.map} +1 -1
  29. package/dist/{index-Cvt5UBz4.js → index-CqnU-5i0.js} +9 -9
  30. package/dist/index-CqnU-5i0.js.map +1 -0
  31. package/dist/{index-AVFTVp1m.js → index-DAl9U4rn.js} +2 -2
  32. package/dist/index-DAl9U4rn.js.map +1 -0
  33. package/dist/{index.browser-DBhxRoe8.js → index.browser-J6QZ9smP.js} +10 -10
  34. package/dist/{index.browser-DBhxRoe8.js.map → index.browser-J6QZ9smP.js.map} +1 -1
  35. package/dist/{index.node-CJhlcNHM.js → index.node-C9VB9NlX.js} +9 -9
  36. package/dist/index.node-C9VB9NlX.js.map +1 -0
  37. package/dist/main.js +24 -24
  38. package/dist/{model-DGMe-TTm.js → model-oHA3YhOd.js} +5 -1
  39. package/dist/model-oHA3YhOd.js.map +1 -0
  40. package/dist/node.js +11 -11
  41. package/dist/node.js.map +1 -1
  42. package/dist/platform.browser.js +5 -5
  43. package/dist/platform.node.js +4 -4
  44. package/dist/{property-DwPD283A.js → property-Brgr5RdT.js} +11 -11
  45. package/dist/{property-DwPD283A.js.map → property-Brgr5RdT.js.map} +1 -1
  46. package/dist/propertyValidationRules-CDRitiiK.js +51 -0
  47. package/dist/propertyValidationRules-CDRitiiK.js.map +1 -0
  48. package/dist/{publishDraftGraph-BOn3_Occ.js → publishDraftGraph-C37ibxb5.js} +6 -6
  49. package/dist/{publishDraftGraph-BOn3_Occ.js.map → publishDraftGraph-C37ibxb5.js.map} +1 -1
  50. package/dist/{resetAmbiguousLegacyItemData-BkYmBeJc.js → resetAmbiguousLegacyItemData-CcLFRREE.js} +2 -2
  51. package/dist/{resetAmbiguousLegacyItemData-BkYmBeJc.js.map → resetAmbiguousLegacyItemData-CcLFRREE.js.map} +1 -1
  52. package/dist/{resolveModelForSyncedSeed-BL24nLa7.js → resolveModelForSyncedSeed-BTAeCOJE.js} +2 -2
  53. package/dist/{resolveModelForSyncedSeed-BL24nLa7.js.map → resolveModelForSyncedSeed-BTAeCOJE.js.map} +1 -1
  54. package/dist/src/Item/Item.d.ts +6 -2
  55. package/dist/src/Item/Item.d.ts.map +1 -1
  56. package/dist/src/Item/errors.d.ts +23 -0
  57. package/dist/src/Item/errors.d.ts.map +1 -0
  58. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  59. package/dist/src/ItemProperty/service/actors/hydrateFromDb.d.ts.map +1 -1
  60. package/dist/src/ItemProperty/service/actors/loadOrCreateProperty.d.ts.map +1 -1
  61. package/dist/src/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  62. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveFile.d.ts +19 -0
  63. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveFile.d.ts.map +1 -1
  64. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveImage.d.ts.map +1 -1
  65. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveItemStorage.d.ts.map +1 -1
  66. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  67. package/dist/src/Model/Model.d.ts +2 -0
  68. package/dist/src/Model/Model.d.ts.map +1 -1
  69. package/dist/src/Model/service/actors/createModelProperties.d.ts.map +1 -1
  70. package/dist/src/ModelProperty/ModelProperty.d.ts +2 -0
  71. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  72. package/dist/src/Schema/Schema.d.ts +11 -2
  73. package/dist/src/Schema/Schema.d.ts.map +1 -1
  74. package/dist/src/Schema/service/actors/checkExistingSchema.d.ts.map +1 -1
  75. package/dist/src/Schema/service/actors/loadOrCreateSchema.d.ts.map +1 -1
  76. package/dist/src/Schema/service/schemaMachine.d.ts.map +1 -1
  77. package/dist/src/Schema/service/validation/SchemaValidationService.d.ts +4 -1
  78. package/dist/src/Schema/service/validation/SchemaValidationService.d.ts.map +1 -1
  79. package/dist/src/db/Db/BaseDb.d.ts +5 -2
  80. package/dist/src/db/Db/BaseDb.d.ts.map +1 -1
  81. package/dist/src/db/write/updateItemPropertyValue.d.ts.map +1 -1
  82. package/dist/src/events/item/syncDbWithEas.d.ts.map +1 -1
  83. package/dist/src/helpers/db.d.ts.map +1 -1
  84. package/dist/src/helpers/entity/draftSaveErrors.d.ts +4 -0
  85. package/dist/src/helpers/entity/draftSaveErrors.d.ts.map +1 -0
  86. package/dist/src/helpers/entity/entityUnload.d.ts +2 -1
  87. package/dist/src/helpers/entity/entityUnload.d.ts.map +1 -1
  88. package/dist/src/helpers/entity/evictionEpoch.d.ts +27 -2
  89. package/dist/src/helpers/entity/evictionEpoch.d.ts.map +1 -1
  90. package/dist/src/helpers/isSqliteUniqueConstraintError.d.ts.map +1 -1
  91. package/dist/src/helpers/model.d.ts.map +1 -1
  92. package/dist/src/helpers/propertyValidationRules.d.ts +12 -0
  93. package/dist/src/helpers/propertyValidationRules.d.ts.map +1 -0
  94. package/dist/src/helpers/propertyWriteQueue.d.ts +15 -0
  95. package/dist/src/helpers/propertyWriteQueue.d.ts.map +1 -0
  96. package/dist/src/helpers/schema.d.ts.map +1 -1
  97. package/dist/src/helpers/storageFileName.d.ts +7 -0
  98. package/dist/src/helpers/storageFileName.d.ts.map +1 -0
  99. package/dist/src/index.d.ts +1 -0
  100. package/dist/src/index.d.ts.map +1 -1
  101. package/dist/src/node/db/Db.d.ts +1 -1
  102. package/dist/src/node/db/Db.d.ts.map +1 -1
  103. package/dist/src/node/index.d.ts +1 -0
  104. package/dist/src/node/index.d.ts.map +1 -1
  105. package/dist/src/types/index.d.ts +12 -0
  106. package/dist/src/types/index.d.ts.map +1 -1
  107. package/dist/{syncDbWithEas-Bv2Fe38J.js → syncDbWithEas-B-Ho0IOB.js} +50 -27
  108. package/dist/syncDbWithEas-B-Ho0IOB.js.map +1 -0
  109. package/dist/{tabEvents-9s2WCYw-.js → tabEvents-BTzckWrN.js} +4 -4
  110. package/dist/{tabEvents-9s2WCYw-.js.map → tabEvents-BTzckWrN.js.map} +1 -1
  111. package/dist/{tolerantWebAccess-iUu80pAP.js → tolerantWebAccess-DOm2Xv-f.js} +6 -6
  112. package/dist/{tolerantWebAccess-iUu80pAP.js.map → tolerantWebAccess-DOm2Xv-f.js.map} +1 -1
  113. package/dist/{updateSeedRevokedAt-zBfi931j.js → updateSeedRevokedAt-IHXnJI-i.js} +3 -3
  114. package/dist/{updateSeedRevokedAt-zBfi931j.js.map → updateSeedRevokedAt-IHXnJI-i.js.map} +1 -1
  115. package/package.json +5 -5
  116. package/dist/BasePathResolver-Cm4apKRb.js.map +0 -1
  117. package/dist/ClientManager-i3nJASkg.js.map +0 -1
  118. package/dist/Item-DBFchXpC.js.map +0 -1
  119. package/dist/ModelProperty-BS49g01Y.js.map +0 -1
  120. package/dist/Schema-CpMNEnUO.js.map +0 -1
  121. package/dist/SchemaValidationService-DieV4KL-.js.map +0 -1
  122. package/dist/index-8O3Uow-Y.js.map +0 -1
  123. package/dist/index-AVFTVp1m.js.map +0 -1
  124. package/dist/index-Cvt5UBz4.js.map +0 -1
  125. package/dist/index.node-CJhlcNHM.js.map +0 -1
  126. package/dist/model-DGMe-TTm.js.map +0 -1
  127. package/dist/syncDbWithEas-Bv2Fe38J.js.map +0 -1
@@ -1,12 +1,12 @@
1
1
  import { fromCallback, setup, assign, createActor } from 'xstate';
2
- import { g as getRefValueType, G as createModelsFromJson, p as listCompleteSchemaFiles, H as getLatestSchemaVersion, l as loadSchemaFromFile, J as jsonPropertiesToSchemaProperties, q as loadAllSchemasFromDb, k as getClient } from './ClientManager-i3nJASkg.js';
3
- import { aq as SEED_PROTOCOL_SCHEMA_NAME, E as BaseDb, z as schemas, aI as addSchemaToDb, i as isDataType, M as ModelPropertyDataTypes, $ as generateId, a2 as addModelsToDb, s as models, q as modelSchemas, u as properties, J as BaseFileManager, aK as loadModelsFromDbForSchema, aF as isInternalSchema } from './BasePathResolver-Cm4apKRb.js';
2
+ import { g as getRefValueType, G as createModelsFromJson, p as listCompleteSchemaFiles, H as getLatestSchemaVersion, l as loadSchemaFromFile, J as jsonPropertiesToSchemaProperties, q as loadAllSchemasFromDb, k as getClient } from './ClientManager-De-vKHGe.js';
3
+ import { aq as SEED_PROTOCOL_SCHEMA_NAME, E as BaseDb, z as schemas, aI as addSchemaToDb, i as isDataType, M as ModelPropertyDataTypes, $ as generateId, a2 as addModelsToDb, s as models, q as modelSchemas, u as properties, J as BaseFileManager, aK as loadModelsFromDbForSchema, aF as isInternalSchema } from './BasePathResolver-DxdS0wJ0.js';
4
4
  import { eq, desc, and } from 'drizzle-orm';
5
5
  import debug from 'debug';
6
- import { c as currentEvictionEpoch, w as writeProcessMachine, M as Model, C as ConflictError, d as setupEntityLiveQuery } from './index-8O3Uow-Y.js';
6
+ import { c as currentEvictionEpoch, w as writeProcessMachine, t as trackDraftSave, M as Model, g as getDraftSaveError, C as ConflictError, r as recordSchemaDestroy, f as finishSchemaDestroy, d as setupEntityLiveQuery } from './errors-Cl8rbtKR.js';
7
7
  import 'pluralize';
8
- import { SchemaValidationService } from './SchemaValidationService-DieV4KL-.js';
9
- import { D as DEFAULT_READY_TIMEOUT_MS, n as waitForEntityIdle, o as createReactiveProxy, q as findEntity, C as ClientManagerState, a0 as clearDestroySubscriptions, t as forceRemoveFromCaches, a1 as unloadEntity, u as runDestroyLifecycle } from './Item-DBFchXpC.js';
8
+ import { SchemaValidationService } from './SchemaValidationService-DViJ056F.js';
9
+ import { D as DEFAULT_READY_TIMEOUT_MS, n as waitForEntityIdle, o as createReactiveProxy, q as findEntity, C as ClientManagerState, a0 as clearDestroySubscriptions, t as forceRemoveFromCaches, a1 as unloadEntity, u as runDestroyLifecycle } from './Item-cq9VcsAY.js';
10
10
 
11
11
  const logger$d = debug('seedSdk:schema:actors:loadOrCreateSchema');
12
12
  /**
@@ -50,8 +50,8 @@ const createModelInstances$2 = async (modelIds, evictionEpoch) => {
50
50
  return;
51
51
  }
52
52
  try {
53
- const _mod_0 = await import('./index-8O3Uow-Y.js');
54
- const _ns_0 = _mod_0.f;
53
+ const _mod_0 = await import('./errors-Cl8rbtKR.js');
54
+ const _ns_0 = _mod_0.h;
55
55
  const modelMod = _ns_0;
56
56
  const { Model } = modelMod;
57
57
  // Create instances for all model IDs in parallel
@@ -167,7 +167,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
167
167
  // For Seed Protocol, always load from internal file, never create new
168
168
  logger$d(`Loading internal Seed Protocol schema from SDK`);
169
169
  try {
170
- const _mod_1 = await import('./ClientManager-i3nJASkg.js');
170
+ const _mod_1 = await import('./ClientManager-De-vKHGe.js');
171
171
  const _ns_1 = _mod_1.S;
172
172
  const internalSchema = _ns_1;
173
173
  const schemaFile = internalSchema.default;
@@ -662,7 +662,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
662
662
  // Ensure models are populated (fallback for seed-protocol if missing)
663
663
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
664
664
  try {
665
- const _mod_2 = await import('./ClientManager-i3nJASkg.js');
665
+ const _mod_2 = await import('./ClientManager-De-vKHGe.js');
666
666
  const _ns_2 = _mod_2.S;
667
667
  const internalSchema = _ns_2;
668
668
  const internalSchemaFile = internalSchema.default;
@@ -850,7 +850,9 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
850
850
  try {
851
851
  // Try to find file by schemaFileId in the complete schemas list
852
852
  const completeSchemas = await listCompleteSchemaFiles();
853
- const idBasedMatch = completeSchemas.find((s) => s.schemaFileId === dbSchema.schemaFileId);
853
+ // Match version too: the row is per schema name, so after a new version is imported
854
+ // under a new id it can carry the newer version with the older version's schemaFileId.
855
+ const idBasedMatch = completeSchemas.find((s) => s.schemaFileId === dbSchema.schemaFileId && s.version === dbSchema.version);
854
856
  if (idBasedMatch) {
855
857
  logger$d(`Found schema file by schemaFileId: ${idBasedMatch.filePath}`);
856
858
  const content = await BaseFileManager.readFileAsString(idBasedMatch.filePath);
@@ -891,7 +893,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
891
893
  // Ensure models are populated (fallback for seed-protocol if missing)
892
894
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
893
895
  try {
894
- const _mod_3 = await import('./ClientManager-i3nJASkg.js');
896
+ const _mod_3 = await import('./ClientManager-De-vKHGe.js');
895
897
  const _ns_3 = _mod_3.S;
896
898
  const internalSchema = _ns_3;
897
899
  const internalSchemaFile = internalSchema.default;
@@ -982,7 +984,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
982
984
  // Ensure models are populated (fallback for seed-protocol if missing)
983
985
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
984
986
  try {
985
- const _mod_4 = await import('./ClientManager-i3nJASkg.js');
987
+ const _mod_4 = await import('./ClientManager-De-vKHGe.js');
986
988
  const _ns_4 = _mod_4.S;
987
989
  const internalSchema = _ns_4;
988
990
  const internalSchemaFile = internalSchema.default;
@@ -1070,7 +1072,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
1070
1072
  // If schemaData is missing, try to load from internal schema file for seed-protocol
1071
1073
  if (!dbSchema.schemaData && schemaName === 'Seed Protocol') {
1072
1074
  try {
1073
- const _mod_5 = await import('./ClientManager-i3nJASkg.js');
1075
+ const _mod_5 = await import('./ClientManager-De-vKHGe.js');
1074
1076
  const _ns_5 = _mod_5.S;
1075
1077
  const internalSchema = _ns_5;
1076
1078
  const schemaFile = internalSchema.default;
@@ -1181,7 +1183,7 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
1181
1183
  // Ensure models are populated (fallback for seed-protocol if missing)
1182
1184
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
1183
1185
  try {
1184
- const _mod_6 = await import('./ClientManager-i3nJASkg.js');
1186
+ const _mod_6 = await import('./ClientManager-De-vKHGe.js');
1185
1187
  const _ns_6 = _mod_6.S;
1186
1188
  const internalSchema = _ns_6;
1187
1189
  const internalSchemaFile = internalSchema.default;
@@ -1508,8 +1510,8 @@ const createModelInstances$1 = async (modelIds, evictionEpoch) => {
1508
1510
  return;
1509
1511
  }
1510
1512
  try {
1511
- const _mod_7 = await import('./index-8O3Uow-Y.js');
1512
- const _ns_7 = _mod_7.f;
1513
+ const _mod_7 = await import('./errors-Cl8rbtKR.js');
1514
+ const _ns_7 = _mod_7.h;
1513
1515
  const mod = _ns_7;
1514
1516
  const Model = mod?.Model ?? mod?.default;
1515
1517
  if (!Model) {
@@ -1557,7 +1559,7 @@ const checkExistingSchema = fromCallback(({ sendBack, input: { context } }) => {
1557
1559
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
1558
1560
  // For Seed Protocol, check if it exists in database
1559
1561
  try {
1560
- const _mod_8 = await import('./ClientManager-i3nJASkg.js');
1562
+ const _mod_8 = await import('./ClientManager-De-vKHGe.js');
1561
1563
  const _ns_8 = _mod_8.S;
1562
1564
  const internalSchema = _ns_8;
1563
1565
  const schemaFile = internalSchema.default;
@@ -1724,7 +1726,9 @@ const checkExistingSchema = fromCallback(({ sendBack, input: { context } }) => {
1724
1726
  // Try to load from file
1725
1727
  try {
1726
1728
  const completeSchemas = await listCompleteSchemaFiles();
1727
- const idBasedMatch = completeSchemas.find((s) => s.schemaFileId === dbSchema.schemaFileId);
1729
+ // Match version too: the row is per schema name, so after a new version is imported
1730
+ // under a new id it can carry the newer version with the older version's schemaFileId.
1731
+ const idBasedMatch = completeSchemas.find((s) => s.schemaFileId === dbSchema.schemaFileId && s.version === dbSchema.version);
1728
1732
  if (idBasedMatch) {
1729
1733
  const content = await BaseFileManager.readFileAsString(idBasedMatch.filePath);
1730
1734
  schemaFile = JSON.parse(content);
@@ -1917,7 +1921,7 @@ const writeSchemaToDb = fromCallback(({ sendBack, input }) => {
1917
1921
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
1918
1922
  // For Seed Protocol, load from internal file
1919
1923
  logger$b(`Loading internal Seed Protocol schema from SDK`);
1920
- const _mod_9 = await import('./ClientManager-i3nJASkg.js');
1924
+ const _mod_9 = await import('./ClientManager-De-vKHGe.js');
1921
1925
  const _ns_9 = _mod_9.S;
1922
1926
  const internalSchema = _ns_9;
1923
1927
  finalSchema = internalSchema.default;
@@ -2388,8 +2392,8 @@ const createModelInstances = fromCallback(({ sendBack, input }) => {
2388
2392
  return;
2389
2393
  }
2390
2394
  try {
2391
- const _mod_10 = await import('./index-8O3Uow-Y.js');
2392
- const _ns_10 = _mod_10.f;
2395
+ const _mod_10 = await import('./errors-Cl8rbtKR.js');
2396
+ const _ns_10 = _mod_10.h;
2393
2397
  const modelMod = _ns_10;
2394
2398
  const { Model } = modelMod;
2395
2399
  // Create instances for all model IDs in parallel
@@ -2477,8 +2481,8 @@ const verifyModelInstancesInCache = fromCallback(({ sendBack, input }) => {
2477
2481
  }
2478
2482
  try {
2479
2483
  const result = await verifyWithRetry$2(async () => {
2480
- const _mod_11 = await import('./index-8O3Uow-Y.js');
2481
- const _ns_11 = _mod_11.f;
2484
+ const _mod_11 = await import('./errors-Cl8rbtKR.js');
2485
+ const _ns_11 = _mod_11.h;
2482
2486
  const modelMod = _ns_11;
2483
2487
  const { Model } = modelMod;
2484
2488
  // Check each model ID in the cache
@@ -2536,8 +2540,8 @@ const writePropertiesToDb = fromCallback(({ sendBack, input }) => {
2536
2540
  const _write = async () => {
2537
2541
  const { modelIds } = input;
2538
2542
  try {
2539
- const _mod_12 = await import('./BasePathResolver-Cm4apKRb.js');
2540
- const _ns_12 = _mod_12.aZ;
2543
+ const _mod_12 = await import('./BasePathResolver-DxdS0wJ0.js');
2544
+ const _ns_12 = _mod_12.a_;
2541
2545
  const modelSchemaMod = _ns_12;
2542
2546
  const { models: modelsTable, properties: propertiesTable } = modelSchemaMod;
2543
2547
  const drizzleMod = await import('drizzle-orm');
@@ -2726,10 +2730,10 @@ const createPropertyInstances = fromCallback(({ sendBack, input }) => {
2726
2730
  return;
2727
2731
  }
2728
2732
  try {
2729
- const modProp = await import('./ModelProperty-BS49g01Y.js');
2733
+ const modProp = await import('./ModelProperty-DuuoFXaC.js');
2730
2734
  const ModelProperty = modProp?.ModelProperty ?? modProp?.default;
2731
- const _mod_13 = await import('./index-8O3Uow-Y.js');
2732
- const _ns_13 = _mod_13.f;
2735
+ const _mod_13 = await import('./errors-Cl8rbtKR.js');
2736
+ const _ns_13 = _mod_13.h;
2733
2737
  const modModel = _ns_13;
2734
2738
  const Model = modModel?.Model ?? modModel?.default;
2735
2739
  if (!ModelProperty || !Model) {
@@ -2835,7 +2839,7 @@ const verifyPropertyInstancesInCache = fromCallback(({ sendBack, input }) => {
2835
2839
  }
2836
2840
  try {
2837
2841
  const result = await verifyWithRetry(async () => {
2838
- const mod = await import('./ModelProperty-BS49g01Y.js');
2842
+ const mod = await import('./ModelProperty-DuuoFXaC.js');
2839
2843
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
2840
2844
  if (!ModelProperty) {
2841
2845
  throw new Error('ModelProperty not available from dynamic import');
@@ -2992,6 +2996,13 @@ const schemaMachine = setup({
2992
2996
  if (event._dbVersion !== undefined) {
2993
2997
  newContext._dbVersion = event._dbVersion;
2994
2998
  }
2999
+ // saveNewVersion passes the schema it just wrote: the instance now is that version.
3000
+ const saved = event.savedSchema;
3001
+ if (saved) {
3002
+ newContext.version = saved.version;
3003
+ newContext.metadata = saved.metadata;
3004
+ newContext.migrations = saved.migrations;
3005
+ }
2995
3006
  return newContext;
2996
3007
  }),
2997
3008
  },
@@ -3065,6 +3076,13 @@ const schemaMachine = setup({
3065
3076
  _schemaRecord: ({ event }) => event.schemaRecord,
3066
3077
  id: ({ event }) => event.schema.id, // schemaFileId (string)
3067
3078
  _dbId: ({ event }) => event.schemaRecord?.id, // Database integer ID
3079
+ // A schema created in code has these only in the written record; without them
3080
+ // validation (and so saveNewVersion) failed with "Schema metadata is required".
3081
+ $schema: ({ context, event }) => context.$schema ?? event.schema.$schema,
3082
+ version: ({ context, event }) => context.version ?? event.schema.version,
3083
+ metadata: ({ context, event }) => context.metadata ?? event.schema.metadata,
3084
+ enums: ({ context, event }) => context.enums ?? event.schema.enums,
3085
+ migrations: ({ context, event }) => context.migrations ?? event.schema.migrations,
3068
3086
  }),
3069
3087
  },
3070
3088
  writeError: {
@@ -3538,6 +3556,95 @@ async function writeFullSchemaNewVersion(schemaName, schema) {
3538
3556
  logger$1(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
3539
3557
  return newFilePath;
3540
3558
  }
3559
+ /**
3560
+ * Get model name from modelId
3561
+ * @param modelId - The model ID to look up
3562
+ * @returns The model name, or undefined if not found
3563
+ */
3564
+ async function getModelNameFromId(modelId) {
3565
+ if (!modelId) {
3566
+ return undefined;
3567
+ }
3568
+ const db = BaseDb.getAppDb();
3569
+ if (!db) {
3570
+ throw new Error('Database not found');
3571
+ }
3572
+ const modelRecords = await db
3573
+ .select()
3574
+ .from(models)
3575
+ .where(eq(models.id, modelId))
3576
+ .limit(1);
3577
+ if (modelRecords.length === 0) {
3578
+ return undefined;
3579
+ }
3580
+ return modelRecords[0].name;
3581
+ }
3582
+ /**
3583
+ * Convert a TProperty/ModelPropertyMachineContext to SchemaPropertyUpdate format
3584
+ * This function converts the internal property representation to the schema file format
3585
+ * @param property - The TProperty instance to convert
3586
+ * @param modelName - The name of the model this property belongs to
3587
+ * @param propertyName - The name of the property
3588
+ * @returns A SchemaPropertyUpdate object ready to be passed to updateModelProperties
3589
+ */
3590
+ async function convertPropertyToSchemaUpdate(property, modelName, propertyName) {
3591
+ const updates = {};
3592
+ // Convert dataType to type
3593
+ if (property.dataType) {
3594
+ updates.type = property.dataType;
3595
+ }
3596
+ // Handle Relation type
3597
+ if (isDataType(property.dataType, ModelPropertyDataTypes.Relation)) {
3598
+ if (property.ref) {
3599
+ updates.model = property.ref;
3600
+ }
3601
+ else if (property.refModelId) {
3602
+ // If ref is not set but refModelId is, get the model name from the database
3603
+ const refModelName = await getModelNameFromId(property.refModelId);
3604
+ if (refModelName) {
3605
+ updates.model = refModelName;
3606
+ }
3607
+ }
3608
+ }
3609
+ // Handle List type
3610
+ if (isDataType(property.dataType, ModelPropertyDataTypes.List)) {
3611
+ if (property.refValueType) {
3612
+ updates.refValueType = property.refValueType;
3613
+ if (property.ref) {
3614
+ updates.ref = property.ref;
3615
+ }
3616
+ else if (property.refModelId) {
3617
+ // If ref is not set but refModelId is, get the model name from the database
3618
+ const refModelName = await getModelNameFromId(property.refModelId);
3619
+ if (refModelName) {
3620
+ updates.ref = refModelName;
3621
+ }
3622
+ }
3623
+ }
3624
+ }
3625
+ // Handle required (validation constraint)
3626
+ if (property.required !== undefined) {
3627
+ updates.required = property.required;
3628
+ }
3629
+ // Handle storage configuration (for Text properties with storage)
3630
+ if (property.storageType || property.localStorageDir || property.filenameSuffix) {
3631
+ const storageType = property.storageType || 'ItemStorage'; // Default to ItemStorage if not specified
3632
+ updates.storage = {
3633
+ type: storageType,
3634
+ };
3635
+ if (property.localStorageDir) {
3636
+ updates.storage.path = property.localStorageDir;
3637
+ }
3638
+ if (property.filenameSuffix) {
3639
+ updates.storage.extension = property.filenameSuffix;
3640
+ }
3641
+ }
3642
+ return {
3643
+ modelName,
3644
+ propertyName,
3645
+ updates,
3646
+ };
3647
+ }
3541
3648
  /**
3542
3649
  * Update model properties in a schema and create a new version
3543
3650
  * @param schemaName - The name of the schema to update
@@ -3750,8 +3857,8 @@ async function loadSchemaWithRenames(schemaFilePath, modelRenames) {
3750
3857
  updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
3751
3858
  };
3752
3859
  // Use dynamic import to break circular dependency
3753
- const _mod_14 = await import('./BasePathResolver-Cm4apKRb.js');
3754
- const _ns_14 = _mod_14.b2;
3860
+ const _mod_14 = await import('./BasePathResolver-DxdS0wJ0.js');
3861
+ const _ns_14 = _mod_14.b3;
3755
3862
  const dbMod = _ns_14;
3756
3863
  const { addSchemaToDb, addModelsToDb } = dbMod;
3757
3864
  // Add schema to database with schemaFileId
@@ -3870,8 +3977,8 @@ async function renameModelProperty(schemaName, modelName, oldPropertyName, newPr
3870
3977
  await BaseFileManager.waitForFileWithContent(newFilePath);
3871
3978
  logger$1(`Renamed property ${oldPropertyName} to ${newPropertyName} in schema ${schemaName} v${newVersion}`);
3872
3979
  // Migrate metadata rows so ItemProperty values follow the new name (prevents duplicate ItemProperties)
3873
- const _mod_15 = await import('./BasePathResolver-Cm4apKRb.js');
3874
- const _ns_15 = _mod_15.b2;
3980
+ const _mod_15 = await import('./BasePathResolver-DxdS0wJ0.js');
3981
+ const _ns_15 = _mod_15.b3;
3875
3982
  const { migrateMetadataForPropertyRename } = _ns_15;
3876
3983
  const migratedCount = await migrateMetadataForPropertyRename(modelName, oldPropertyName, newPropertyName, oldProperty.id, { schemaName });
3877
3984
  if (migratedCount > 0) {
@@ -4116,6 +4223,17 @@ async function deletePropertyFromModel(schemaName, modelName, propertyName, opti
4116
4223
  return newFilePath;
4117
4224
  }
4118
4225
 
4226
+ var updateSchema = /*#__PURE__*/Object.freeze({
4227
+ __proto__: null,
4228
+ convertPropertyToSchemaUpdate: convertPropertyToSchemaUpdate,
4229
+ deleteModelFromSchema: deleteModelFromSchema,
4230
+ deletePropertyFromModel: deletePropertyFromModel,
4231
+ getModelNameFromId: getModelNameFromId,
4232
+ renameModelProperty: renameModelProperty,
4233
+ updateModelProperties: updateModelProperties,
4234
+ writeFullSchemaNewVersion: writeFullSchemaNewVersion
4235
+ });
4236
+
4119
4237
  const logger = debug('seedSdk:schema:saveNewVersion');
4120
4238
  const saveDraftLogger = debug('seedSdk:schema:saveDraftToDb');
4121
4239
  // WeakMap to store non-serializable resources per Schema instance
@@ -4349,10 +4467,7 @@ class Schema {
4349
4467
  });
4350
4468
  // Save draft to database immediately so changes persist
4351
4469
  saveDraftLogger(`Name change detected, calling _saveDraftToDb (oldName: "${oldName}", newName: "${newName}")`);
4352
- instance._saveDraftToDb(oldName, newName).catch((error) => {
4353
- saveDraftLogger(`ERROR: Failed to save draft after name change: ${error instanceof Error ? error.message : String(error)}`);
4354
- logger(`Failed to save draft to database: ${error instanceof Error ? error.message : String(error)}`);
4355
- });
4470
+ trackDraftSave(instance._service, instance._saveDraftToDb(oldName, newName), `Schema "${newName}"`);
4356
4471
  }
4357
4472
  else {
4358
4473
  logger(`Schema name unchanged: "${oldName}"`);
@@ -4396,9 +4511,7 @@ class Schema {
4396
4511
  if (TRACKED_PROPERTIES.includes(prop)) {
4397
4512
  const trackedPropContext = newInstance._getSnapshotContext();
4398
4513
  const schemaName = trackedPropContext.metadata?.name || trackedPropContext.schemaName;
4399
- newInstance._saveDraftToDb(schemaName, schemaName).catch((error) => {
4400
- logger(`Failed to save draft to database: ${error instanceof Error ? error.message : String(error)}`);
4401
- });
4514
+ trackDraftSave(newInstance._service, newInstance._saveDraftToDb(schemaName, schemaName), `Schema "${schemaName}"`);
4402
4515
  }
4403
4516
  }
4404
4517
  },
@@ -4794,6 +4907,13 @@ class Schema {
4794
4907
  get validationErrors() {
4795
4908
  return this._getSnapshotContext()._validationErrors || [];
4796
4909
  }
4910
+ /**
4911
+ * The error from the last draft save that an assignment started (e.g. `schema.name = ...`),
4912
+ * such as a ConflictError; undefined once a later one succeeds.
4913
+ */
4914
+ get lastSaveError() {
4915
+ return getDraftSaveError(this._service);
4916
+ }
4797
4917
  get isValid() {
4798
4918
  const errors = this.validationErrors;
4799
4919
  return errors.length === 0;
@@ -4834,36 +4954,63 @@ class Schema {
4834
4954
  });
4835
4955
  }
4836
4956
  /**
4837
- * Build models object from Model instances (for persistence)
4838
- * Model instances are the source of truth for model data
4957
+ * Build the file-format `models` object from this schema's Model instances: every model
4958
+ * (those created at runtime too), each property as its file definition ({ id, type, model,
4959
+ * ref, refValueType, required, storage, validation, ... }).
4839
4960
  */
4840
- _buildModelsFromInstances() {
4961
+ async _buildModelsFromInstances() {
4841
4962
  const context = this._getSnapshotContext();
4963
+ const { convertPropertyToSchemaUpdate } = await Promise.resolve().then(function () { return updateSchema; });
4842
4964
  const models = {};
4843
- // Get model IDs from service context (reactive state)
4844
- const modelIds = context._liveQueryModelIds || [];
4845
- // Iterate through Model instances from static cache
4846
- for (const modelFileId of modelIds) {
4847
- const modelInstance = Model.getById(modelFileId);
4848
- if (!modelInstance)
4849
- continue;
4965
+ for (const modelInstance of this.models) {
4850
4966
  try {
4851
4967
  const modelName = modelInstance.modelName;
4852
- if (!modelName) {
4853
- logger(`Model instance with ID ${modelFileId} has no modelName, skipping`);
4968
+ if (!modelName)
4854
4969
  continue;
4970
+ const properties$1 = {};
4971
+ let propertyContexts = (modelInstance.properties ?? []).map((property) => property.getService().getSnapshot().context);
4972
+ // model.properties can still be empty for a model created at runtime (the browser fills
4973
+ // it from a live query): read the rows, preferring each row's cached instance.
4974
+ const modelDbId = modelInstance.getService().getSnapshot().context._dbId;
4975
+ const db = BaseDb.getAppDb();
4976
+ if (propertyContexts.length === 0 && modelDbId && db) {
4977
+ const { ModelProperty } = await import('./ModelProperty-DuuoFXaC.js');
4978
+ const rows = await db.select().from(properties).where(eq(properties.modelId, modelDbId));
4979
+ propertyContexts = rows.map((row) => {
4980
+ const cached = row.schemaFileId ? ModelProperty.getById(row.schemaFileId) : undefined;
4981
+ return cached
4982
+ ? cached.getService().getSnapshot().context
4983
+ : {
4984
+ ...row,
4985
+ id: row.schemaFileId ?? undefined,
4986
+ refModelId: row.refModelId ?? undefined,
4987
+ refValueType: row.refValueType ?? undefined,
4988
+ storageType: row.storageType ?? undefined,
4989
+ localStorageDir: row.localStorageDir ?? undefined,
4990
+ filenameSuffix: row.filenameSuffix ?? undefined,
4991
+ };
4992
+ });
4855
4993
  }
4856
- // Build model definition from Model instance context
4857
- // CRITICAL: Read properties from ModelProperty instances, not from Model's properties context
4858
- // ModelProperty instances are the source of truth for property data
4859
- const propertiesFromInstances = modelInstance._buildPropertiesFromInstances?.() || modelInstance.properties || {};
4994
+ for (const ctx of propertyContexts) {
4995
+ if (!ctx.name)
4996
+ continue;
4997
+ const { updates } = await convertPropertyToSchemaUpdate(ctx, modelName, ctx.name);
4998
+ properties$1[ctx.name] = {
4999
+ ...(ctx.id ? { id: ctx.id } : {}),
5000
+ ...updates,
5001
+ ...(ctx.validation ? { validation: ctx.validation } : {}),
5002
+ ...(ctx.htmlEmbeddedDataUriPolicy ? { htmlEmbeddedDataUriPolicy: ctx.htmlEmbeddedDataUriPolicy } : {}),
5003
+ };
5004
+ }
5005
+ // No property instances loaded for this model: keep the definitions the schema has.
5006
+ const fromContext = context.models?.[modelName]?.properties;
4860
5007
  models[modelName] = {
4861
- properties: propertiesFromInstances,
5008
+ ...(modelInstance.id ? { id: modelInstance.id } : {}),
5009
+ properties: Object.keys(properties$1).length > 0 || !fromContext ? properties$1 : fromContext,
4862
5010
  };
4863
- logger(`Built model "${modelName}" from Model instance (ID: ${modelFileId})`);
4864
5011
  }
4865
5012
  catch (error) {
4866
- logger(`Error building model from instance (ID: ${modelFileId}): ${error instanceof Error ? error.message : String(error)}`);
5013
+ logger(`Error building model from instance: ${error instanceof Error ? error.message : String(error)}`);
4867
5014
  }
4868
5015
  }
4869
5016
  logger(`Built ${Object.keys(models).length} models from Model instances`);
@@ -4904,7 +5051,7 @@ class Schema {
4904
5051
  // Build current schema state from context
4905
5052
  // CRITICAL: Read models from Model instances, not from Schema context
4906
5053
  // Model instances are the source of truth for model data
4907
- const modelsFromInstances = this._buildModelsFromInstances();
5054
+ const modelsFromInstances = await this._buildModelsFromInstances();
4908
5055
  const currentSchema = {
4909
5056
  id: context.id,
4910
5057
  $schema: context.$schema || 'https://seedprotocol.org/schemas/data-model/v1',
@@ -4977,9 +5124,10 @@ class Schema {
4977
5124
  type: 'clearDraft',
4978
5125
  _dbUpdatedAt: new Date(publishedSchema.metadata.updatedAt).getTime(),
4979
5126
  _dbVersion: publishedSchema.version,
5127
+ savedSchema: publishedSchema,
4980
5128
  });
4981
5129
  // Clear edited flags on all ModelProperty instances and in database
4982
- const modelPropertyMod = await import('./ModelProperty-BS49g01Y.js');
5130
+ const modelPropertyMod = await import('./ModelProperty-DuuoFXaC.js');
4983
5131
  const { ModelProperty } = modelPropertyMod;
4984
5132
  for (const propertyKey of context._editedProperties) {
4985
5133
  const [modelName, propertyName] = propertyKey.split(':');
@@ -5003,8 +5151,8 @@ class Schema {
5003
5151
  try {
5004
5152
  if (db && modelName && propertyName) {
5005
5153
  // Find this schema's model by name
5006
- const _mod_16 = await import('./BasePathResolver-Cm4apKRb.js');
5007
- const _ns_16 = _mod_16.b1;
5154
+ const _mod_16 = await import('./BasePathResolver-DxdS0wJ0.js');
5155
+ const _ns_16 = _mod_16.b2;
5008
5156
  const { resolveModelRecord } = _ns_16;
5009
5157
  const modelRecord = await resolveModelRecord(modelName, { schemaName: thisSchemaName }, db);
5010
5158
  const modelRecords = modelRecord ? [modelRecord] : [];
@@ -5309,7 +5457,7 @@ class Schema {
5309
5457
  const finalSchemaFileId = existingSchemaRecord?.schemaFileId || schemaFileId;
5310
5458
  // CRITICAL: Read models from Model instances, not from Schema context
5311
5459
  // Model instances are the source of truth for model data
5312
- const modelsFromInstances = this._buildModelsFromInstances();
5460
+ const modelsFromInstances = await this._buildModelsFromInstances();
5313
5461
  const currentSchema = {
5314
5462
  $schema: context.$schema || 'https://seedprotocol.org/schemas/data-model/v1',
5315
5463
  version: context.version || 1,
@@ -5610,14 +5758,28 @@ class Schema {
5610
5758
  Schema.instanceCacheByName,
5611
5759
  ],
5612
5760
  });
5761
+ // Until its rows are gone, nothing may re-create this schema's models. Its own actor stays live
5762
+ // till then, and its live query reacting to destroyStarted could read a model row the drained
5763
+ // write had just landed and re-create (and re-write) that model after the delete below.
5764
+ if (schemaName)
5765
+ recordSchemaDestroy(schemaName);
5766
+ try {
5767
+ await this._destroyRows(schemaFileId, schemaName, context.metadata?.name);
5768
+ }
5769
+ finally {
5770
+ if (schemaName)
5771
+ finishSchemaDestroy(schemaName);
5772
+ }
5773
+ }
5774
+ async _destroyRows(schemaFileId, schemaName, metadataName) {
5613
5775
  // The rows for this schema's models and properties are deleted below; evict their cached
5614
5776
  // instances too, or a re-import would get them back with dangling _dbIds.
5615
5777
  if (schemaName) {
5616
5778
  const evictedModelNames = Model.evictForSchema(schemaName);
5617
- const { ModelProperty } = await import('./ModelProperty-BS49g01Y.js');
5779
+ const { ModelProperty } = await import('./ModelProperty-DuuoFXaC.js');
5618
5780
  ModelProperty.evictForModels(evictedModelNames, schemaName);
5619
5781
  // Evicting stops new writes but not ones already running; let those land before deleting their rows
5620
- const _mod_17 = await import('./index-8O3Uow-Y.js');
5782
+ const _mod_17 = await import('./errors-Cl8rbtKR.js');
5621
5783
  const _ns_17 = _mod_17.e;
5622
5784
  const { waitForInFlightWrites } = _ns_17;
5623
5785
  await waitForInFlightWrites();
@@ -5650,7 +5812,7 @@ class Schema {
5650
5812
  .map((r) => r.modelId)
5651
5813
  .filter((id) => id != null)),
5652
5814
  ];
5653
- const { detachModelRows } = await import('./detachRowsBeforeDelete-S0q-DJPT.js');
5815
+ const { detachModelRows } = await import('./detachRowsBeforeDelete-YRSZY6dO.js');
5654
5816
  await detachModelRows(db, modelIds);
5655
5817
  await db.delete(modelSchemas).where(inArray(modelSchemas.schemaId, schemaIds));
5656
5818
  for (const modelId of modelIds) {
@@ -5660,6 +5822,22 @@ class Schema {
5660
5822
  await db.delete(models).where(eq(models.id, modelId));
5661
5823
  }
5662
5824
  await db.delete(schemas).where(eq(schemas.schemaFileId, schemaFileId));
5825
+ // Delete the SDK's own copies of this schema's files (all versions) in the working dir.
5826
+ // loadAllSchemasFromDb imports any schema file without a DB row, so leaving them brought
5827
+ // the destroyed schema back on the next Schema.all().
5828
+ // Match on name as well as id: versions imported from complete schema files can each
5829
+ // have their own id, and any version left behind would bring the schema back.
5830
+ const _mod_18 = await import('./ClientManager-De-vKHGe.js');
5831
+ const _ns_18 = _mod_18.K;
5832
+ const { listCompleteSchemaFiles } = _ns_18;
5833
+ const files = await listCompleteSchemaFiles().catch(() => []);
5834
+ const fs = await BaseFileManager.getFs();
5835
+ const names = new Set([schemaName, metadataName].filter(Boolean));
5836
+ for (const file of files) {
5837
+ if (file.schemaFileId === schemaFileId || names.has(file.name)) {
5838
+ await fs.promises.unlink(file.filePath).catch(() => { });
5839
+ }
5840
+ }
5663
5841
  },
5664
5842
  });
5665
5843
  }
@@ -5845,4 +6023,4 @@ var Schema$1 = /*#__PURE__*/Object.freeze({
5845
6023
  });
5846
6024
 
5847
6025
  export { Schema as S, deletePropertyFromModel as a, Schema$1 as b, deleteModelFromSchema as d, renameModelProperty as r, schemaMachine as s, updateModelProperties as u };
5848
- //# sourceMappingURL=Schema-CpMNEnUO.js.map
6026
+ //# sourceMappingURL=Schema-Dc5EA8Yb.js.map