@seedprotocol/sdk 0.4.5 → 0.4.7

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 (168) hide show
  1. package/dist/{ArweaveClient-WcG8CZAE.js → ArweaveClient-BdQaTOZ4.js} +3 -3
  2. package/dist/{ArweaveClient-WcG8CZAE.js.map → ArweaveClient-BdQaTOZ4.js.map} +1 -1
  3. package/dist/{ArweaveClient-CgWK-JgT.js → ArweaveClient-nrTU_rhU.js} +3 -3
  4. package/dist/{ArweaveClient-CgWK-JgT.js.map → ArweaveClient-nrTU_rhU.js.map} +1 -1
  5. package/dist/{Db-DjofXdeU.js → Db-CWKaeNQH.js} +7 -104
  6. package/dist/Db-CWKaeNQH.js.map +1 -0
  7. package/dist/{Db-DjFdIdR9.js → Db-Cq4q88X_.js} +21 -5
  8. package/dist/Db-Cq4q88X_.js.map +1 -0
  9. package/dist/{EasClient-Aojewp6P.js → EasClient-Du9_TULE.js} +2 -2
  10. package/dist/{EasClient-BVFXp2O6.js.map → EasClient-Du9_TULE.js.map} +1 -1
  11. package/dist/{EasClient-BVFXp2O6.js → EasClient-ZCIE6UQq.js} +2 -2
  12. package/dist/{EasClient-Aojewp6P.js.map → EasClient-ZCIE6UQq.js.map} +1 -1
  13. package/dist/{FileManager-C9zr4AJe.js → FileManager-Cub9icdd.js} +4 -3
  14. package/dist/FileManager-Cub9icdd.js.map +1 -0
  15. package/dist/{FileManager-CxGJLw5C.js → FileManager-HSFEess-.js} +2 -2
  16. package/dist/{FileManager-CxGJLw5C.js.map → FileManager-HSFEess-.js.map} +1 -1
  17. package/dist/Item/Item.d.ts +2 -0
  18. package/dist/Item/Item.d.ts.map +1 -1
  19. package/dist/Item/service/actors/fetchDataFromEas.d.ts.map +1 -1
  20. package/dist/Item/service/actors/loadOrCreateItem.d.ts.map +1 -1
  21. package/dist/Item/service/actors/runPublish.d.ts.map +1 -1
  22. package/dist/Item/service/itemMachineSingle.d.ts.map +1 -1
  23. package/dist/ItemProperty/ItemProperty.d.ts.map +1 -1
  24. package/dist/ItemProperty/service/actors/hydrateFromDb.d.ts.map +1 -1
  25. package/dist/ItemProperty/service/actors/loadOrCreateProperty.d.ts.map +1 -1
  26. package/dist/ItemProperty/service/actors/resolveRelatedValue.d.ts.map +1 -1
  27. package/dist/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  28. package/dist/ItemProperty/service/actors/saveValueToDb/saveRelation.d.ts.map +1 -1
  29. package/dist/Model/Model.d.ts +5 -0
  30. package/dist/Model/Model.d.ts.map +1 -1
  31. package/dist/Model/service/actors/createModelProperties.d.ts.map +1 -1
  32. package/dist/Model/service/actors/loadOrCreateModel.d.ts.map +1 -1
  33. package/dist/Model/service/actors/validateModel.d.ts.map +1 -1
  34. package/dist/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  35. package/dist/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  36. package/dist/ModelProperty/service/actors/validateProperty.d.ts.map +1 -1
  37. package/dist/{ModelProperty-CGdkocQ8.js → ModelProperty-D4zaeIOT.js} +52 -18
  38. package/dist/ModelProperty-D4zaeIOT.js.map +1 -0
  39. package/dist/{PathResolver-z_WX47_o.js → PathResolver-DVLBs_qi.js} +2 -2
  40. package/dist/{PathResolver-z_WX47_o.js.map → PathResolver-DVLBs_qi.js.map} +1 -1
  41. package/dist/{PathResolver-CX6GHoTS.js → PathResolver-T1yEDECb.js} +2 -2
  42. package/dist/{PathResolver-CX6GHoTS.js.map → PathResolver-T1yEDECb.js.map} +1 -1
  43. package/dist/{QueryClient-Cb1iJO-x.js → QueryClient-DcKDQuwz.js} +2 -2
  44. package/dist/{QueryClient-Cb1iJO-x.js.map → QueryClient-DcKDQuwz.js.map} +1 -1
  45. package/dist/{QueryClient-ByKPdRmE.js → QueryClient-Vs9KN5kS.js} +2 -2
  46. package/dist/{QueryClient-ByKPdRmE.js.map → QueryClient-Vs9KN5kS.js.map} +1 -1
  47. package/dist/Schema/Schema.d.ts.map +1 -1
  48. package/dist/Schema/service/actors/createModelInstances.d.ts.map +1 -1
  49. package/dist/Schema/service/actors/loadOrCreateSchema.d.ts.map +1 -1
  50. package/dist/Schema/service/actors/verifyModelInstancesInCache.d.ts.map +1 -1
  51. package/dist/Schema/service/actors/writePropertiesToDb.d.ts.map +1 -1
  52. package/dist/Schema/service/addModelsMachine.d.ts.map +1 -1
  53. package/dist/{Schema-D1eqDHyt.js → Schema-SbwqmoMM.js} +63 -24
  54. package/dist/Schema-SbwqmoMM.js.map +1 -0
  55. package/dist/{SchemaValidationService-DyttFaV_.js → SchemaValidationService-DHGIw4Nx.js} +2 -2
  56. package/dist/{SchemaValidationService-DyttFaV_.js.map → SchemaValidationService-DHGIw4Nx.js.map} +1 -1
  57. package/dist/browser/db/drizzleFiles.d.ts +3 -2
  58. package/dist/browser/db/drizzleFiles.d.ts.map +1 -1
  59. package/dist/browser/helpers/FileManager.d.ts.map +1 -1
  60. package/dist/browser/react/item.d.ts +2 -0
  61. package/dist/browser/react/item.d.ts.map +1 -1
  62. package/dist/browser/react/itemProperty.d.ts.map +1 -1
  63. package/dist/cjs/{ModelProperty-BeJvgKMw.js → ModelProperty-DpjD0o0E.js} +32 -18
  64. package/dist/cjs/ModelProperty-DpjD0o0E.js.map +1 -0
  65. package/dist/cjs/{Schema-CVs9J6eP.js → Schema-DkSBMBwz.js} +33 -24
  66. package/dist/cjs/Schema-DkSBMBwz.js.map +1 -0
  67. package/dist/cjs/{SchemaValidationService-CDKcVRFQ.js → SchemaValidationService-O3FCMROl.js} +2 -2
  68. package/dist/cjs/{SchemaValidationService-CDKcVRFQ.js.map → SchemaValidationService-O3FCMROl.js.map} +1 -1
  69. package/dist/cjs/{getItem-B5RYPvrG.js → getItem-BeAVMk54.js} +2 -2
  70. package/dist/cjs/{getItem-B5RYPvrG.js.map → getItem-BeAVMk54.js.map} +1 -1
  71. package/dist/cjs/{getPublishPayload-BD1qRob1.js → getPublishPayload-CoLriAMV.js} +7 -5
  72. package/dist/cjs/getPublishPayload-CoLriAMV.js.map +1 -0
  73. package/dist/cjs/{getPublishUploads-CnC9aYxs.js → getPublishUploads-DDsT9zZ6.js} +3 -3
  74. package/dist/cjs/{getPublishUploads-CnC9aYxs.js.map → getPublishUploads-DDsT9zZ6.js.map} +1 -1
  75. package/dist/cjs/{getSegmentedItemProperties-B_njnntx.js → getSegmentedItemProperties-DGR0utR5.js} +2 -2
  76. package/dist/cjs/{getSegmentedItemProperties-B_njnntx.js.map → getSegmentedItemProperties-DGR0utR5.js.map} +1 -1
  77. package/dist/cjs/{index-BeKPbbk0.js → index-B95Ng80C.js} +629 -241
  78. package/dist/cjs/index-B95Ng80C.js.map +1 -0
  79. package/dist/cjs/{index-Dnywap_P.js → index-CvcOtzbi.js} +2 -2
  80. package/dist/cjs/index-CvcOtzbi.js.map +1 -0
  81. package/dist/cjs/ownership-Dm5ER1nI.js +103 -0
  82. package/dist/cjs/ownership-Dm5ER1nI.js.map +1 -0
  83. package/dist/client/ClientManager.d.ts +54 -43
  84. package/dist/client/ClientManager.d.ts.map +1 -1
  85. package/dist/client/actors/platformClassesInit.d.ts.map +1 -1
  86. package/dist/client/actors/saveConfig.d.ts.map +1 -1
  87. package/dist/client/clientManagerMachine.d.ts.map +1 -1
  88. package/dist/db/drizzle/drizzle/0004_add_publisher_to_seeds.sql +1 -0
  89. package/dist/db/drizzle/drizzle/meta/0004_snapshot.json +857 -0
  90. package/dist/db/drizzle/drizzle/meta/_journal.json +7 -0
  91. package/dist/db/read/getItemData.d.ts.map +1 -1
  92. package/dist/db/read/getItems.d.ts +2 -0
  93. package/dist/db/read/getItems.d.ts.map +1 -1
  94. package/dist/db/read/getModelSchemas.d.ts.map +1 -1
  95. package/dist/db/read/getPublishPayload.d.ts.map +1 -1
  96. package/dist/db/write/createNewItem.d.ts.map +1 -1
  97. package/dist/eas.d.ts.map +1 -1
  98. package/dist/events/files/download.d.ts.map +1 -1
  99. package/dist/events/item/syncDbWithEas.d.ts.map +1 -1
  100. package/dist/{getItem-BB5HBCbK.js → getItem-CqrJt-Ee.js} +2 -2
  101. package/dist/{getItem-BB5HBCbK.js.map → getItem-CqrJt-Ee.js.map} +1 -1
  102. package/dist/{getPublishPayload-uLm0AqN_.js → getPublishPayload-BRgULCf3.js} +7 -5
  103. package/dist/getPublishPayload-BRgULCf3.js.map +1 -0
  104. package/dist/{getPublishUploads-Dc-HqhO8.js → getPublishUploads-B0WArDfp.js} +3 -3
  105. package/dist/{getPublishUploads-Dc-HqhO8.js.map → getPublishUploads-B0WArDfp.js.map} +1 -1
  106. package/dist/{getSegmentedItemProperties-BrIqFNfD.js → getSegmentedItemProperties-DZL9Ymd4.js} +2 -2
  107. package/dist/{getSegmentedItemProperties-BrIqFNfD.js.map → getSegmentedItemProperties-DZL9Ymd4.js.map} +1 -1
  108. package/dist/helpers/addresses.d.ts +12 -0
  109. package/dist/helpers/addresses.d.ts.map +1 -0
  110. package/dist/helpers/db.d.ts +11 -0
  111. package/dist/helpers/db.d.ts.map +1 -1
  112. package/dist/helpers/ownership.d.ts +16 -0
  113. package/dist/helpers/ownership.d.ts.map +1 -0
  114. package/dist/helpers/property.d.ts.map +1 -1
  115. package/dist/helpers/updateSchema.d.ts.map +1 -1
  116. package/dist/imports/json.d.ts.map +1 -1
  117. package/dist/{index-2FcQHgKp.js → index-BIPPEMVY.js} +2 -2
  118. package/dist/index-BIPPEMVY.js.map +1 -0
  119. package/dist/{index-LEY0Og1p.js → index-BnF3MRZ8.js} +3 -3
  120. package/dist/index-BnF3MRZ8.js.map +1 -0
  121. package/dist/{index-DPll6EAp.js → index-zsq08F5p.js} +644 -154
  122. package/dist/index-zsq08F5p.js.map +1 -0
  123. package/dist/main.cjs +1 -1
  124. package/dist/main.js +20 -14
  125. package/dist/main.js.map +1 -1
  126. package/dist/node/db/Db.d.ts.map +1 -1
  127. package/dist/node.js +10 -10
  128. package/dist/ownership-CSsweVap.js +85 -0
  129. package/dist/ownership-CSsweVap.js.map +1 -0
  130. package/dist/{property-B15X7jLX.js → property-Cqh_o0zx.js} +10 -4
  131. package/dist/property-Cqh_o0zx.js.map +1 -0
  132. package/dist/{queries-BPDSpiEX.js → queries-DSBgjcJJ.js} +2 -2
  133. package/dist/{queries-BPDSpiEX.js.map → queries-DSBgjcJJ.js.map} +1 -1
  134. package/dist/seedSchema/ModelSchemaSchema.d.ts +1 -1
  135. package/dist/seedSchema/ModelSchemaSchema.ts +4 -4
  136. package/dist/seedSchema/ModelUidSchema.ts +1 -1
  137. package/dist/seedSchema/PropertyUidSchema.ts +1 -1
  138. package/dist/seedSchema/SeedSchema.d.ts +19 -0
  139. package/dist/seedSchema/SeedSchema.d.ts.map +1 -1
  140. package/dist/seedSchema/SeedSchema.ts +1 -0
  141. package/dist/seedSchema/index.d.ts +10 -10
  142. package/dist/seedSchema/index.d.ts.map +1 -1
  143. package/dist/seedSchema/index.ts +10 -10
  144. package/dist/services/publish/actors/preparePublishRequestData.d.ts.map +1 -1
  145. package/dist/services/publish/actors/upload.d.ts.map +1 -1
  146. package/dist/services/write/actors/validateEntity.d.ts.map +1 -1
  147. package/dist/types/index.d.ts +11 -1
  148. package/dist/types/index.d.ts.map +1 -1
  149. package/dist/types/item.d.ts +1 -0
  150. package/dist/types/item.d.ts.map +1 -1
  151. package/dist/types/machines.d.ts +2 -0
  152. package/dist/types/machines.d.ts.map +1 -1
  153. package/package.json +4 -11
  154. package/dist/Db-DjFdIdR9.js.map +0 -1
  155. package/dist/Db-DjofXdeU.js.map +0 -1
  156. package/dist/FileManager-C9zr4AJe.js.map +0 -1
  157. package/dist/ModelProperty-CGdkocQ8.js.map +0 -1
  158. package/dist/Schema-D1eqDHyt.js.map +0 -1
  159. package/dist/cjs/ModelProperty-BeJvgKMw.js.map +0 -1
  160. package/dist/cjs/Schema-CVs9J6eP.js.map +0 -1
  161. package/dist/cjs/getPublishPayload-BD1qRob1.js.map +0 -1
  162. package/dist/cjs/index-BeKPbbk0.js.map +0 -1
  163. package/dist/cjs/index-Dnywap_P.js.map +0 -1
  164. package/dist/getPublishPayload-uLm0AqN_.js.map +0 -1
  165. package/dist/index-2FcQHgKp.js.map +0 -1
  166. package/dist/index-DPll6EAp.js.map +0 -1
  167. package/dist/index-LEY0Og1p.js.map +0 -1
  168. package/dist/property-B15X7jLX.js.map +0 -1
@@ -464,6 +464,30 @@ const generateId = () => {
464
464
  const toSnakeCase = (str) => {
465
465
  return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
466
466
  };
467
+ const identifyString = (str) => {
468
+ try {
469
+ JSON.parse(str);
470
+ return 'json';
471
+ }
472
+ catch (e) {
473
+ // Not JSON
474
+ }
475
+ if (!str) {
476
+ return;
477
+ }
478
+ if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
479
+ return 'html';
480
+ }
481
+ // Simple markdown checks (very naive)
482
+ if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
483
+ return 'markdown';
484
+ }
485
+ if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
486
+ return 'base64';
487
+ }
488
+ // Default to plain text if unsure
489
+ return 'text';
490
+ };
467
491
  const getMimeType = (base64) => {
468
492
  if (!base64) {
469
493
  return null;
@@ -541,6 +565,21 @@ const convertTxIdToImage = async (txId) => {
541
565
  const imageBlob = new Blob([uint]);
542
566
  return URL.createObjectURL(imageBlob);
543
567
  };
568
+ /**
569
+ * Constructs an Arweave URL for a storage transaction ID
570
+ * @param storageTransactionId - The Arweave transaction ID
571
+ * @returns The full URL to access the transaction data on Arweave (e.g., https://arweave.net/raw/{transactionId})
572
+ * @deprecated Use BaseArweaveClient.getRawUrl() instead for better consistency and testability
573
+ */
574
+ const getArweaveUrlForTransaction = (storageTransactionId) => {
575
+ return BaseArweaveClient.getRawUrl(storageTransactionId);
576
+ };
577
+ const getExecutionTime = async (task, args) => {
578
+ const start = Date.now();
579
+ await task(...args);
580
+ return Date.now() - start;
581
+ };
582
+ const capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);
544
583
  const parseEasRelationPropertyName = (easPropertyName) => {
545
584
  // Split the input string on the first underscore
546
585
  const [singularProperty, modelName, idSegment] = easPropertyName.split('_');
@@ -556,6 +595,25 @@ const parseEasRelationPropertyName = (easPropertyName) => {
556
595
  isList, // True if the property is a list (e.g., 'ids' is present)
557
596
  };
558
597
  };
598
+ const isBinary = (arrayBuffer) => {
599
+ const view = new Uint8Array(arrayBuffer);
600
+ let nonTextCount = 0;
601
+ const threshold = 0.2; // Adjust as needed (e.g., 20% non-text implies binary)
602
+ for (let i = 0; i < view.length; i++) {
603
+ const byte = view[i];
604
+ // ASCII printable characters (32-126) and common whitespace (9, 10, 13)
605
+ if ((byte >= 32 && byte <= 126) || // Printable ASCII
606
+ byte === 9 || byte === 10 || byte === 13 // Tab, LF, CR
607
+ ) {
608
+ continue;
609
+ }
610
+ nonTextCount++;
611
+ if (nonTextCount / view.length > threshold) {
612
+ return true; // More than threshold are non-text bytes
613
+ }
614
+ }
615
+ return false; // Fewer than threshold are non-text bytes
616
+ };
559
617
 
560
618
  var index = /*#__PURE__*/Object.freeze({
561
619
  __proto__: null,
@@ -563,11 +621,16 @@ var index = /*#__PURE__*/Object.freeze({
563
621
  BaseEasClient: BaseEasClient,
564
622
  BaseFileManager: BaseFileManager,
565
623
  BaseQueryClient: BaseQueryClient,
624
+ capitalizeFirstLetter: capitalizeFirstLetter,
566
625
  convertTxIdToImage: convertTxIdToImage,
567
626
  generateId: generateId,
627
+ getArweaveUrlForTransaction: getArweaveUrlForTransaction,
568
628
  getCorrectId: getCorrectId,
569
629
  getDataTypeFromString: getDataTypeFromString,
630
+ getExecutionTime: getExecutionTime,
570
631
  getMimeType: getMimeType,
632
+ identifyString: identifyString,
633
+ isBinary: isBinary,
571
634
  parseEasRelationPropertyName: parseEasRelationPropertyName,
572
635
  toSnakeCase: toSnakeCase,
573
636
  waitForEntityIdle: waitForEntityIdle
@@ -584,7 +647,7 @@ const createPropertyInstances = async (propertyFileIds) => {
584
647
  return;
585
648
  }
586
649
  try {
587
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); });
650
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-DpjD0o0E.js'); });
588
651
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
589
652
  if (!ModelProperty) {
590
653
  logger$x('createPropertyInstances: ModelProperty not available from dynamic import');
@@ -667,7 +730,8 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
667
730
  // schemaFileId to match the database, both will point to the same cached instance.
668
731
  if (dbSchemaFileId) {
669
732
  try {
670
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
733
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
734
+ const { Model } = modelMod;
671
735
  // Access instanceCacheById via type assertion since it's protected
672
736
  const cacheById = Model.instanceCacheById;
673
737
  if (cacheById.has(dbSchemaFileId)) {
@@ -772,7 +836,8 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
772
836
  // Step 2: Fallback to Schema context (only if database doesn't have the model)
773
837
  // This handles the case where model exists in schema file but not yet in database
774
838
  try {
775
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; });
839
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DkSBMBwz.js'); }).then(function (n) { return n.Schema$1; });
840
+ const { Schema } = schemaMod;
776
841
  const schema = Schema.create(schemaName, { waitForReady: false });
777
842
  const schemaSnapshot = schema.getService().getSnapshot();
778
843
  // Wait for schema to load if it's still loading
@@ -843,7 +908,8 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
843
908
  let finalModelName = modelName;
844
909
  if (db) {
845
910
  // Check if this is an internal schema (Seed Protocol)
846
- const { isInternalSchema } = await Promise.resolve().then(function () { return constants; });
911
+ const constantsMod = await Promise.resolve().then(function () { return constants; });
912
+ const { isInternalSchema } = constantsMod;
847
913
  const isInternal = isInternalSchema(schemaName);
848
914
  // Only skip duplicate check if:
849
915
  // 1. We found a model record to use (modelRecord is set), OR
@@ -858,7 +924,8 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
858
924
  const existingNumbers = new Set(existingNumbersFromSchemaContext ?? []);
859
925
  // First, check Model cache for models (includes models from imported schemas that may not be in DB yet)
860
926
  try {
861
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
927
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
928
+ const { Model } = modelMod;
862
929
  // Check name-based cache for this schema
863
930
  // Skip the current model (context.id): Model.create() adds the new instance to the cache
864
931
  // before this callback runs, so we must not count it as a duplicate.
@@ -917,8 +984,10 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
917
984
  }
918
985
  // Also check database for models (in case they're persisted but not in Schema context)
919
986
  if (db) {
920
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
921
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
987
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
988
+ const { modelSchemas } = modelSchemaSchemaMod;
989
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
990
+ const { schemas: schemasTable } = schemaSchemaMod;
922
991
  // Query all models for this schema to check for duplicates (case-insensitive)
923
992
  logger$x(`Checking database for duplicate model names in schema "${schemaName}"`);
924
993
  const allModelsForSchema = await db
@@ -991,7 +1060,8 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
991
1060
  }
992
1061
  // Runtime creates use a placeholder cache key in Model.create; move it to the final name. Skip when schema model (_idFromSchema).
993
1062
  if (!_idFromSchema) {
994
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
1063
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
1064
+ const { Model } = modelMod;
995
1065
  Model.updateNameIndex('__pending__' + schemaFileId, finalModelName, schemaName, schemaFileId);
996
1066
  }
997
1067
  // If model name was changed, store it in a temporary internal field so loadOrCreateModelSuccess can apply it
@@ -1010,7 +1080,8 @@ const loadOrCreateModel = xstate.fromCallback(({ sendBack, input: { context } })
1010
1080
  }
1011
1081
  // Mark schema as draft when a new model is created so saveNewVersion() can persist it
1012
1082
  try {
1013
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; });
1083
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DkSBMBwz.js'); }).then(function (n) { return n.Schema$1; });
1084
+ const { Schema } = schemaMod;
1014
1085
  const schema = Schema.create(schemaName, { waitForReady: false });
1015
1086
  schema.getService().send({ type: 'markAsDraft', propertyKey: 'schema:models' });
1016
1087
  }
@@ -1053,9 +1124,11 @@ const validateModel = xstate.fromCallback(({ sendBack, input: { context } }) =>
1053
1124
  const _validateModel = async () => {
1054
1125
  try {
1055
1126
  // Use dynamic imports to break circular dependencies
1056
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CDKcVRFQ.js'); });
1127
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-O3FCMROl.js'); });
1128
+ const { SchemaValidationService } = validationServiceMod;
1057
1129
  const validationService = new SchemaValidationService();
1058
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; });
1130
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DkSBMBwz.js'); }).then(function (n) { return n.Schema$1; });
1131
+ const { Schema } = schemaMod;
1059
1132
  // Validate model structure
1060
1133
  const structureResult = validationService.validateModelStructure(context);
1061
1134
  if (!structureResult.isValid) {
@@ -1166,19 +1239,21 @@ const createModelProperties = xstate.fromCallback(({ sendBack, input }) => {
1166
1239
  return;
1167
1240
  }
1168
1241
  logger$v(`Creating ${Object.keys(propertyDefinitions).length} properties for model "${modelName}" (id: ${_dbId})`);
1169
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); });
1242
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-DpjD0o0E.js'); });
1170
1243
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
1171
1244
  if (!ModelProperty) {
1172
1245
  logger$v('ModelProperty not available from dynamic import');
1173
1246
  sendBack({ type: 'createModelPropertiesError', error: new Error('ModelProperty not available') });
1174
1247
  return;
1175
1248
  }
1176
- const { eq } = await import('drizzle-orm');
1249
+ const drizzleMod = await import('drizzle-orm');
1250
+ const { eq } = drizzleMod;
1177
1251
  const db = BaseDb.getAppDb();
1178
1252
  for (const [propName, propData] of Object.entries(propertyDefinitions)) {
1179
1253
  // Use provided ID or generate a random one
1180
1254
  // IDs should be generated in the import process before creating properties
1181
- const { generateId } = await Promise.resolve().then(function () { return index; });
1255
+ const helpersMod = await Promise.resolve().then(function () { return index; });
1256
+ const { generateId } = helpersMod;
1182
1257
  const propertyFileId = propData.id || generateId();
1183
1258
  logger$v(`Creating property "${propName}" with fileId "${propertyFileId}"`);
1184
1259
  // Query database to get refModelId if the property has ref/refModelName
@@ -1269,7 +1344,8 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
1269
1344
  logger$u(structureMsg);
1270
1345
  console.log(structureMsg); // Always log to console
1271
1346
  // Use existing Model validation
1272
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CDKcVRFQ.js'); });
1347
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-O3FCMROl.js'); });
1348
+ const { SchemaValidationService } = validationServiceMod;
1273
1349
  const validationService = new SchemaValidationService();
1274
1350
  // Validate model structure
1275
1351
  const structureResult = validationService.validateModelStructure(entityInput.entityData);
@@ -1287,7 +1363,8 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
1287
1363
  if (entityInput.entityData.schemaName) {
1288
1364
  try {
1289
1365
  logger$u(`[validateEntity] Validating model against schema "${entityInput.entityData.schemaName}"`);
1290
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; });
1366
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DkSBMBwz.js'); }).then(function (n) { return n.Schema$1; });
1367
+ const { Schema } = schemaMod;
1291
1368
  const schema = Schema.create(entityInput.entityData.schemaName, {
1292
1369
  waitForReady: false,
1293
1370
  });
@@ -1322,7 +1399,8 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
1322
1399
  }
1323
1400
  else if (entityInput.entityType === 'modelProperty') {
1324
1401
  // Use existing ModelProperty validation
1325
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CDKcVRFQ.js'); });
1402
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-O3FCMROl.js'); });
1403
+ const { SchemaValidationService } = validationServiceMod;
1326
1404
  const validationService = new SchemaValidationService();
1327
1405
  // Validate property structure
1328
1406
  const structureResult = validationService.validatePropertyStructure(entityInput.entityData);
@@ -1336,7 +1414,8 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
1336
1414
  // If schema name and model name provided, validate against schema
1337
1415
  if (entityInput.entityData._schemaName && entityInput.entityData.modelName) {
1338
1416
  try {
1339
- const { Schema } = await Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; });
1417
+ const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DkSBMBwz.js'); }).then(function (n) { return n.Schema$1; });
1418
+ const { Schema } = schemaMod;
1340
1419
  const schema = Schema.create(entityInput.entityData._schemaName, {
1341
1420
  waitForReady: false,
1342
1421
  });
@@ -1364,7 +1443,8 @@ const validateEntity = xstate.fromPromise(async ({ input }) => {
1364
1443
  }
1365
1444
  else if (entityInput.entityType === 'schema') {
1366
1445
  // Schema validation - use existing validation
1367
- const { SchemaValidationService } = await Promise.resolve().then(function () { return require('./SchemaValidationService-CDKcVRFQ.js'); });
1446
+ const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-O3FCMROl.js'); });
1447
+ const { SchemaValidationService } = validationServiceMod;
1368
1448
  const validationService = new SchemaValidationService();
1369
1449
  const schemaResult = validationService.validateSchema(entityInput.entityData);
1370
1450
  if (!schemaResult.isValid) {
@@ -1400,6 +1480,7 @@ const seeds = sqliteCore.sqliteTable('seeds', {
1400
1480
  uid: sqliteCore.text('uid'),
1401
1481
  schemaUid: sqliteCore.text('schema_uid'),
1402
1482
  type: sqliteCore.text('type'),
1483
+ publisher: sqliteCore.text('publisher'),
1403
1484
  attestationRaw: sqliteCore.text('attestation_raw'),
1404
1485
  attestationCreatedAt: sqliteCore.int('attestation_created_at'),
1405
1486
  createdAt: sqliteCore.int('created_at'),
@@ -1542,6 +1623,42 @@ const escapeSqliteString = (value) => {
1542
1623
  }
1543
1624
  return value.replace(/'/g, "''");
1544
1625
  };
1626
+ const getObjectForRow = (row) => {
1627
+ const obj = {};
1628
+ row.columnNames.forEach((colName, index) => {
1629
+ const value = row.row[index];
1630
+ if (typeof value !== 'string') {
1631
+ obj[colName] = row.row[index];
1632
+ return;
1633
+ }
1634
+ // Try to parse the value as JSON
1635
+ try {
1636
+ obj[colName] = JSON.parse(value);
1637
+ }
1638
+ catch (e) {
1639
+ // If it fails, just set the value as a string
1640
+ obj[colName] = value;
1641
+ }
1642
+ });
1643
+ return obj;
1644
+ };
1645
+ const getSqlResultObject = (queryResult) => {
1646
+ if (!queryResult || !queryResult.rows || queryResult.rows.length === 0) {
1647
+ return;
1648
+ }
1649
+ let obj;
1650
+ if (queryResult.rows.length === 1) {
1651
+ obj = getObjectForRow(queryResult.rows[0]);
1652
+ }
1653
+ if (queryResult.rows.length > 1) {
1654
+ obj = queryResult.rows.reduce((acc, row) => {
1655
+ const rowObj = getObjectForRow(row);
1656
+ acc.push(rowObj);
1657
+ return acc;
1658
+ }, []);
1659
+ }
1660
+ return obj;
1661
+ };
1545
1662
  const createOrUpdate = async (db, table, values) => {
1546
1663
  const valueFilters = [];
1547
1664
  const propertiesToExcludeFromDb = ['ref'];
@@ -1877,7 +1994,7 @@ async function checkIfPropertyIsEdited(modelName, propertyName, schemaFileValue)
1877
1994
  const cacheKey = `${modelName}:${propertyName}`;
1878
1995
  // First, check the in-memory cache (for current session edits)
1879
1996
  // Robust dynamic import for consumer re-bundling (named or default export)
1880
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); });
1997
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-DpjD0o0E.js'); });
1881
1998
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
1882
1999
  if (!ModelProperty) {
1883
2000
  logger$t('ModelProperty not available from dynamic import');
@@ -2120,7 +2237,8 @@ const addModelsToDb$1 = async (models, schema, modelRenames, schemaFileData) =>
2120
2237
  schema = pendingProperties;
2121
2238
  }
2122
2239
  else {
2123
- const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
2240
+ const modelHelpersMod = await Promise.resolve().then(function () { return model; });
2241
+ const { modelPropertiesToObject } = modelHelpersMod;
2124
2242
  const modelProperties = modelClass.properties || [];
2125
2243
  schema = modelPropertiesToObject(modelProperties);
2126
2244
  }
@@ -2140,7 +2258,8 @@ const addModelsToDb$1 = async (models, schema, modelRenames, schemaFileData) =>
2140
2258
  // If no propertyFileId from map, generate a random ID
2141
2259
  // IDs should be generated in the import process before calling addModelsToDb
2142
2260
  if (!propertyFileId) {
2143
- const { generateId } = await Promise.resolve().then(function () { return index; });
2261
+ const helpersIndexMod = await Promise.resolve().then(function () { return index; });
2262
+ const { generateId } = helpersIndexMod;
2144
2263
  propertyFileId = generateId();
2145
2264
  logger$t(`Generated propertyFileId "${propertyFileId}" for property "${modelName}:${propertyName}" (not found in propertyFileIds map)`);
2146
2265
  }
@@ -2555,13 +2674,49 @@ const savePropertyToDb = async (property) => {
2555
2674
  logger$t(`Created property ${property.modelName}:${property.name} in database`);
2556
2675
  }
2557
2676
  };
2558
- const getAddressesFromDb = async () => {
2677
+ function parseAddressConfig(value) {
2678
+ if (!value)
2679
+ return null;
2680
+ try {
2681
+ const parsed = JSON.parse(value);
2682
+ if (Array.isArray(parsed)) {
2683
+ return { owned: parsed, watched: [] };
2684
+ }
2685
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.owned)) {
2686
+ return {
2687
+ owned: parsed.owned,
2688
+ watched: Array.isArray(parsed.watched) ? parsed.watched : [],
2689
+ };
2690
+ }
2691
+ return null;
2692
+ }
2693
+ catch {
2694
+ return null;
2695
+ }
2696
+ }
2697
+ const getOwnedAddressesFromDb = async () => {
2698
+ const config = await getAddressConfigFromDb();
2699
+ return config?.owned ?? [];
2700
+ };
2701
+ const getWatchedAddressesFromDb = async () => {
2702
+ const config = await getAddressConfigFromDb();
2703
+ return config?.watched ?? [];
2704
+ };
2705
+ /**
2706
+ * Returns owned + watched addresses. Use for EAS sync and file download.
2707
+ */
2708
+ const getAllAddressesFromDb = async () => {
2709
+ const config = await getAddressConfigFromDb();
2710
+ if (!config)
2711
+ return [];
2712
+ return [...config.owned, ...config.watched];
2713
+ };
2714
+ async function getAddressConfigFromDb() {
2559
2715
  const appDb = BaseDb.getAppDb();
2560
2716
  if (!appDb) {
2561
2717
  return new Promise((resolve) => {
2562
2718
  setTimeout(async () => {
2563
- const addresses = await getAddressesFromDb();
2564
- resolve(addresses);
2719
+ resolve(await getAddressConfigFromDb());
2565
2720
  }, 500);
2566
2721
  });
2567
2722
  }
@@ -2571,14 +2726,25 @@ const getAddressesFromDb = async () => {
2571
2726
  .where(drizzleOrm.eq(appState.key, 'addresses'))
2572
2727
  .limit(1);
2573
2728
  if (!appStatesRecords || appStatesRecords.length === 0) {
2574
- throw new Error('No appStatesRecords for addresses found');
2729
+ return null;
2575
2730
  }
2576
- const addressRecord = appStatesRecords[0];
2577
- const addressArrayString = addressRecord.value;
2578
- if (!addressArrayString) {
2731
+ const addressArrayString = appStatesRecords[0].value;
2732
+ return parseAddressConfig(addressArrayString);
2733
+ }
2734
+ const getAddressesFromDb = async () => {
2735
+ const config = await getAddressConfigFromDb();
2736
+ if (!config || config.owned.length === 0) {
2579
2737
  throw new Error('No addresses found');
2580
2738
  }
2581
- return JSON.parse(addressArrayString);
2739
+ return config.owned;
2740
+ };
2741
+ /**
2742
+ * Like getAddressesFromDb but returns [] instead of throwing when no addresses are configured.
2743
+ * Returns owned addresses. Use getAllAddressesFromDb for sync (owned + watched).
2744
+ */
2745
+ const getAddressesFromDbOptional = async () => {
2746
+ const config = await getAddressConfigFromDb();
2747
+ return config?.owned ?? [];
2582
2748
  };
2583
2749
  /**
2584
2750
  * Write model to database and create model_schemas join entry
@@ -2685,7 +2851,8 @@ async function writeModelToDb(modelFileId, data) {
2685
2851
  throw new Error(`Model with id ${modelId} does not exist in database. Cannot create join record.`);
2686
2852
  }
2687
2853
  // Verify schemaId exists and get name/fileId for invalidation broadcast
2688
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
2854
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
2855
+ const { schemas: schemasTable } = schemaSchemaMod;
2689
2856
  const schemaCheck = await db
2690
2857
  .select({
2691
2858
  id: schemasTable.id,
@@ -2751,7 +2918,8 @@ async function writeModelToDb(modelFileId, data) {
2751
2918
  else {
2752
2919
  // Generate random propertyFileId
2753
2920
  // IDs should be generated in the import process before calling writeModelToDb
2754
- const { generateId } = await Promise.resolve().then(function () { return index; });
2921
+ const helpersIndexMod = await Promise.resolve().then(function () { return index; });
2922
+ const { generateId } = helpersIndexMod;
2755
2923
  propertyFileId = generateId();
2756
2924
  logger$t(`Generated propertyFileId "${propertyFileId}" for property "${data.modelName}:${propName}"`);
2757
2925
  }
@@ -2877,6 +3045,68 @@ async function writePropertyToDb(propertyFileId, data, isEdited = false) {
2877
3045
  }
2878
3046
  }
2879
3047
  }
3048
+ /**
3049
+ * Get schema database ID from schema name or schemaFileId
3050
+ * @param schemaNameOrFileId - Schema name (string) or schemaFileId (string)
3051
+ * @returns Schema database ID
3052
+ * @throws Error if schema not found
3053
+ */
3054
+ async function getSchemaId(schemaNameOrFileId) {
3055
+ const db = BaseDb.getAppDb();
3056
+ if (!db) {
3057
+ throw new Error('Database not available');
3058
+ }
3059
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
3060
+ const { schemas: schemasTable } = schemaSchemaMod;
3061
+ const drizzleMod = await import('drizzle-orm');
3062
+ const { eq, desc } = drizzleMod;
3063
+ // Try to find by schemaFileId first (more reliable)
3064
+ let records = await db
3065
+ .select()
3066
+ .from(schemasTable)
3067
+ .where(eq(schemasTable.schemaFileId, schemaNameOrFileId))
3068
+ .orderBy(desc(schemasTable.version))
3069
+ .limit(1);
3070
+ // If not found by schemaFileId, try by name
3071
+ if (records.length === 0) {
3072
+ records = await db
3073
+ .select()
3074
+ .from(schemasTable)
3075
+ .where(eq(schemasTable.name, schemaNameOrFileId))
3076
+ .orderBy(desc(schemasTable.version))
3077
+ .limit(1);
3078
+ }
3079
+ if (records.length === 0) {
3080
+ throw new Error(`Schema "${schemaNameOrFileId}" not found in database`);
3081
+ }
3082
+ return records[0].id;
3083
+ }
3084
+ /**
3085
+ * Get schema database ID from schemaFileId
3086
+ * @param schemaFileId - The schema file ID
3087
+ * @returns Schema database ID
3088
+ * @throws Error if schema not found
3089
+ */
3090
+ async function getSchemaIdByFileId(schemaFileId) {
3091
+ const db = BaseDb.getAppDb();
3092
+ if (!db) {
3093
+ throw new Error('Database not available');
3094
+ }
3095
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
3096
+ const { schemas: schemasTable } = schemaSchemaMod;
3097
+ const drizzleMod = await import('drizzle-orm');
3098
+ const { eq, desc } = drizzleMod;
3099
+ const records = await db
3100
+ .select()
3101
+ .from(schemasTable)
3102
+ .where(eq(schemasTable.schemaFileId, schemaFileId))
3103
+ .orderBy(desc(schemasTable.version))
3104
+ .limit(1);
3105
+ if (records.length === 0) {
3106
+ throw new Error(`Schema with file ID "${schemaFileId}" not found in database`);
3107
+ }
3108
+ return records[0].id;
3109
+ }
2880
3110
  /**
2881
3111
  * Get model database ID from model name or modelFileId
2882
3112
  * @param modelNameOrFileId - Model name (string) or modelFileId (string)
@@ -2889,8 +3119,10 @@ async function getModelId(modelNameOrFileId, schemaNameOrId) {
2889
3119
  if (!db) {
2890
3120
  throw new Error('Database not available');
2891
3121
  }
2892
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
2893
- const { eq, and, or } = await import('drizzle-orm');
3122
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
3123
+ const { models: modelsTable } = modelSchemaMod;
3124
+ const drizzleMod = await import('drizzle-orm');
3125
+ const { eq, and, or } = drizzleMod;
2894
3126
  // Try to find by modelFileId first (more reliable)
2895
3127
  let records = await db
2896
3128
  .select()
@@ -2902,8 +3134,10 @@ async function getModelId(modelNameOrFileId, schemaNameOrId) {
2902
3134
  [eq(modelsTable.name, modelNameOrFileId)];
2903
3135
  // If schema is provided, narrow the search
2904
3136
  if (schemaNameOrId !== undefined) {
2905
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
2906
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
3137
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
3138
+ const { modelSchemas } = modelSchemaSchemaMod;
3139
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
3140
+ const { schemas: schemasTable } = schemaSchemaMod;
2907
3141
  if (typeof schemaNameOrId === 'number') {
2908
3142
  // schemaNameOrId is schemaId
2909
3143
  records = await db
@@ -2950,8 +3184,10 @@ async function getModelIdByFileId(modelFileId) {
2950
3184
  if (!db) {
2951
3185
  throw new Error('Database not available');
2952
3186
  }
2953
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
2954
- const { eq } = await import('drizzle-orm');
3187
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
3188
+ const { models: modelsTable } = modelSchemaMod;
3189
+ const drizzleMod = await import('drizzle-orm');
3190
+ const { eq } = drizzleMod;
2955
3191
  const records = await db
2956
3192
  .select()
2957
3193
  .from(modelsTable)
@@ -2970,10 +3206,18 @@ var db = /*#__PURE__*/Object.freeze({
2970
3206
  createOrUpdate: createOrUpdate,
2971
3207
  escapeSqliteString: escapeSqliteString,
2972
3208
  getAddressesFromDb: getAddressesFromDb,
3209
+ getAddressesFromDbOptional: getAddressesFromDbOptional,
3210
+ getAllAddressesFromDb: getAllAddressesFromDb,
2973
3211
  getModelId: getModelId,
2974
3212
  getModelIdByFileId: getModelIdByFileId,
2975
3213
  getModelNameByModelId: getModelNameByModelId,
3214
+ getObjectForRow: getObjectForRow,
3215
+ getOwnedAddressesFromDb: getOwnedAddressesFromDb,
2976
3216
  getPropertyModelNameAndDataType: getPropertyModelNameAndDataType,
3217
+ getSchemaId: getSchemaId,
3218
+ getSchemaIdByFileId: getSchemaIdByFileId,
3219
+ getSqlResultObject: getSqlResultObject,
3220
+ getWatchedAddressesFromDb: getWatchedAddressesFromDb,
2977
3221
  loadModelsFromDbForSchema: loadModelsFromDbForSchema,
2978
3222
  renameModelInDb: renameModelInDb,
2979
3223
  savePropertyToDb: savePropertyToDb,
@@ -3027,7 +3271,7 @@ const writeToDatabase = xstate.fromCallback(({ sendBack, input }) => {
3027
3271
  // initial write completes is not overwritten by the stale requestWrite payload.
3028
3272
  let dataToWrite = input.entityData;
3029
3273
  try {
3030
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); });
3274
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-DpjD0o0E.js'); });
3031
3275
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
3032
3276
  if (ModelProperty && typeof ModelProperty.getById === 'function') {
3033
3277
  const instance = ModelProperty.getById(input.entityId);
@@ -3418,7 +3662,7 @@ const modelMachine = xstate.setup({
3418
3662
  // Create ModelProperty instances for any new property IDs
3419
3663
  if (Array.isArray(newPropertyIds) && newPropertyIds.length > 0) {
3420
3664
  // Import and create instances asynchronously (fire-and-forget)
3421
- Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); }).then(({ ModelProperty }) => {
3665
+ Promise.resolve().then(function () { return require('./ModelProperty-DpjD0o0E.js'); }).then(({ ModelProperty }) => {
3422
3666
  const createPromises = newPropertyIds.map(async (propertyFileId) => {
3423
3667
  try {
3424
3668
  const property = await ModelProperty.createById(propertyFileId);
@@ -4264,7 +4508,8 @@ const fetchDataFromEas = xstate.fromCallback(({ sendBack, input: { context } })
4264
4508
  }
4265
4509
  else if (modelName) {
4266
4510
  // Dynamic import to break circular dependency
4267
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
4511
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
4512
+ const { Model } = modelMod;
4268
4513
  const model = Model.getByName(modelName);
4269
4514
  modelSchema = model?.properties ? modelPropertiesToObject(model.properties) : undefined;
4270
4515
  }
@@ -4383,33 +4628,56 @@ var versionData = /*#__PURE__*/Object.freeze({
4383
4628
 
4384
4629
  const logger$p = debug('seedSdk:item:actors:loadOrCreateItem');
4385
4630
  /**
4386
- * Create ItemProperty instances for all metadata records to ensure they're cached
4631
+ * Create ItemProperty instances for all metadata records to ensure they're cached.
4632
+ * Passes propertyRecordSchema from Model when available (Fix 3: enables value persistence for runtime-created models).
4387
4633
  * @param metadataRows - Array of metadata records to create ItemProperty instances for
4388
4634
  * @param seedLocalId - Seed local ID
4389
4635
  * @param seedUid - Seed UID
4636
+ * @param modelName - Model name for resolving propertyRecordSchema from Model
4390
4637
  * @returns Map of propertyName -> ItemProperty instance
4391
4638
  */
4392
- const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid) => {
4639
+ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid, modelName) => {
4393
4640
  const propertyInstances = new Map();
4394
4641
  if (metadataRows.length === 0) {
4395
4642
  return propertyInstances;
4396
4643
  }
4397
4644
  try {
4398
- const { ItemProperty } = await Promise.resolve().then(function () { return ItemProperty$1; });
4399
- // Create instances for all metadata records in parallel
4645
+ const itemPropertyMod = await Promise.resolve().then(function () { return ItemProperty$1; });
4646
+ const { ItemProperty } = itemPropertyMod;
4647
+ const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
4648
+ const { Model } = await Promise.resolve().then(function () { return Model$1; });
4649
+ // Resolve Model and build property schemas for propertyRecordSchema (Fix 3)
4650
+ let propertySchemas = {};
4651
+ const model$1 = Model.getByName(modelName);
4652
+ if (model$1?.properties?.length) {
4653
+ propertySchemas = modelPropertiesToObject(model$1.properties);
4654
+ }
4655
+ // Create instances for all metadata records in parallel with propertyRecordSchema
4400
4656
  const createPromises = metadataRows.map(async (metaRow) => {
4401
4657
  try {
4402
- const property = await ItemProperty.find({
4403
- propertyName: metaRow.propertyName,
4658
+ const propertyName = metaRow.propertyName;
4659
+ if (!propertyName) {
4660
+ logger$p(`Metadata row missing propertyName, skipping`);
4661
+ return;
4662
+ }
4663
+ const createProps = {
4664
+ propertyName,
4404
4665
  seedLocalId,
4405
4666
  seedUid,
4406
- });
4667
+ modelName,
4668
+ propertyValue: metaRow.propertyValue ?? undefined,
4669
+ versionLocalId: metaRow.versionLocalId ?? undefined,
4670
+ versionUid: metaRow.versionUid ?? undefined,
4671
+ schemaUid: metaRow.schemaUid ?? undefined,
4672
+ propertyRecordSchema: propertySchemas[propertyName] ?? undefined,
4673
+ };
4674
+ const property = ItemProperty.create(createProps, { waitForReady: false });
4407
4675
  if (property) {
4408
- propertyInstances.set(metaRow.propertyName, property);
4409
- logger$p(`Created/cached ItemProperty instance for propertyName "${metaRow.propertyName}"`);
4676
+ propertyInstances.set(propertyName, property);
4677
+ logger$p(`Created/cached ItemProperty instance for propertyName "${propertyName}" with propertyRecordSchema: ${!!createProps.propertyRecordSchema}`);
4410
4678
  }
4411
4679
  else {
4412
- logger$p(`ItemProperty.find returned undefined for propertyName "${metaRow.propertyName}"`);
4680
+ logger$p(`ItemProperty.create returned undefined for propertyName "${propertyName}"`);
4413
4681
  }
4414
4682
  }
4415
4683
  catch (error) {
@@ -4429,7 +4697,6 @@ const createItemPropertyInstances = async (metadataRows, seedLocalId, seedUid) =
4429
4697
  const loadOrCreateItem = xstate.fromCallback(({ sendBack, input: { context } }) => {
4430
4698
  const _loadOrCreateItem = async () => {
4431
4699
  const { seedLocalId, seedUid, modelName } = context;
4432
- console.log(`[loadOrCreateItem] Called for modelName: ${modelName}, seedLocalId: ${seedLocalId}, seedUid: ${seedUid}`);
4433
4700
  logger$p(`loadOrCreateItem called for modelName: ${modelName}, seedLocalId: ${seedLocalId}, seedUid: ${seedUid}`);
4434
4701
  if (!seedLocalId && !seedUid) {
4435
4702
  throw new Error('seedLocalId or seedUid is required');
@@ -4541,16 +4808,11 @@ const loadOrCreateItem = xstate.fromCallback(({ sendBack, input: { context } })
4541
4808
  .from(metadata$1)
4542
4809
  .where(drizzleOrm.and(drizzleOrm.eq(metadata$1.seedLocalId, resolvedSeedLocalId), drizzleOrm.eq(metadata$1.versionLocalId, latestVersionLocalId)));
4543
4810
  logger$p(`Found ${metadataRecords.length} metadata records for version ${latestVersionLocalId}`);
4544
- console.log(`[loadOrCreateItem] Found ${metadataRecords.length} metadata records for version ${latestVersionLocalId}`);
4545
- if (metadataRecords.length > 0) {
4546
- console.log(`[loadOrCreateItem] Metadata property names:`, metadataRecords.map((r) => r.propertyName));
4547
- }
4548
4811
  // Step 4: Create ItemProperty instances from metadata records
4549
4812
  // This ensures they're in the cache when Item.properties getter is called
4550
4813
  const propertyInstances = metadataRecords.length > 0
4551
- ? await createItemPropertyInstances(metadataRecords, resolvedSeedLocalId, resolvedSeedUid)
4814
+ ? await createItemPropertyInstances(metadataRecords, resolvedSeedLocalId, resolvedSeedUid, modelName)
4552
4815
  : new Map();
4553
- console.log(`[loadOrCreateItem] Created ${propertyInstances.size} property instances:`, Array.from(propertyInstances.keys()));
4554
4816
  // Step 5: Return loaded item data with property instances
4555
4817
  sendBack({
4556
4818
  type: 'loadOrCreateItemSuccess',
@@ -4588,14 +4850,17 @@ const runPublish = xstate.fromCallback(({ sendBack, input: { context } }) => {
4588
4850
  return;
4589
4851
  }
4590
4852
  try {
4591
- const { Item } = await Promise.resolve().then(function () { return Item$1; });
4853
+ const itemMod = await Promise.resolve().then(function () { return Item$1; });
4854
+ const { Item } = itemMod;
4592
4855
  const item = await Item.find({ seedLocalId });
4593
4856
  if (!item) {
4594
4857
  sendBack({ type: 'publishError', error: new Error(`Item not found for seedLocalId: ${seedLocalId}`) });
4595
4858
  return;
4596
4859
  }
4597
- const { getPublishUploads } = await Promise.resolve().then(function () { return require('./getPublishUploads-CnC9aYxs.js'); });
4598
- const { getPublishPayload } = await Promise.resolve().then(function () { return require('./getPublishPayload-BD1qRob1.js'); });
4860
+ const getPublishUploadsMod = await Promise.resolve().then(function () { return require('./getPublishUploads-DDsT9zZ6.js'); });
4861
+ const { getPublishUploads } = getPublishUploadsMod;
4862
+ const getPublishPayloadMod = await Promise.resolve().then(function () { return require('./getPublishPayload-CoLriAMV.js'); });
4863
+ const { getPublishPayload } = getPublishPayloadMod;
4599
4864
  await getPublishUploads(item);
4600
4865
  // For first iteration: no Arweave sign/upload - pass empty uploadedTransactions.
4601
4866
  // Real upload/submit can be wired in later.
@@ -4767,14 +5032,18 @@ const itemMachineSingle = xstate.setup({
4767
5032
  actions: xstate.assign(({ context, event }) => {
4768
5033
  const item = event.item;
4769
5034
  const existingPropertyInstances = context.propertyInstances || new Map();
4770
- console.log(`[itemMachine] loadOrCreateItemSuccess for modelName: ${context.modelName}, propertyInstances from event:`, item.propertyInstances ? Array.from(item.propertyInstances.keys()) : 'none');
4771
- // Merge property instances from loadOrCreateItem
5035
+ // Merge property instances from loadOrCreateItem (Fix 2: preserve existing when it has propertyRecordSchema and incoming doesn't)
4772
5036
  if (item.propertyInstances) {
4773
5037
  for (const [propertyName, propertyInstance] of item.propertyInstances) {
5038
+ const existing = existingPropertyInstances.get(propertyName);
5039
+ const existingHasSchema = existing?.propertyDef;
5040
+ const incomingHasSchema = propertyInstance?.propertyDef;
5041
+ if (existingHasSchema && !incomingHasSchema) {
5042
+ continue; // Preserve existing instance with schema
5043
+ }
4774
5044
  existingPropertyInstances.set(propertyName, propertyInstance);
4775
5045
  }
4776
5046
  }
4777
- console.log(`[itemMachine] After merge, total propertyInstances:`, Array.from(existingPropertyInstances.keys()));
4778
5047
  return {
4779
5048
  ...context,
4780
5049
  seedLocalId: item.seedLocalId || context.seedLocalId,
@@ -5130,6 +5399,26 @@ const getItemData = async ({ modelName, seedLocalId, seedUid, }) => {
5130
5399
  }
5131
5400
  const seedRow = seedRows[0];
5132
5401
  const resolvedSeedLocalId = seedRow.seedLocalId;
5402
+ // Fix 5: Derive schemaName for multi-schema Model resolution (models -> model_schemas -> schemas)
5403
+ let schemaName;
5404
+ const normalizedModelName = modelName ? lodashEs.startCase(modelName) : (seedRow.type ? lodashEs.startCase(seedRow.type) : undefined);
5405
+ if (appDb && normalizedModelName) {
5406
+ try {
5407
+ const schemaRows = await appDb
5408
+ .select({ schemaName: schemas.name })
5409
+ .from(models$1)
5410
+ .innerJoin(modelSchemas, drizzleOrm.eq(models$1.id, modelSchemas.modelId))
5411
+ .innerJoin(schemas, drizzleOrm.eq(modelSchemas.schemaId, schemas.id))
5412
+ .where(drizzleOrm.eq(models$1.name, normalizedModelName))
5413
+ .limit(1);
5414
+ if (schemaRows.length > 0 && schemaRows[0].schemaName) {
5415
+ schemaName = schemaRows[0].schemaName;
5416
+ }
5417
+ }
5418
+ catch (error) {
5419
+ logger$n('[getItemData] Error deriving schemaName:', error);
5420
+ }
5421
+ }
5133
5422
  // Now get version data if it exists - query versions table directly
5134
5423
  let versionRow = {
5135
5424
  versionsCount: 0,
@@ -5160,6 +5449,7 @@ const getItemData = async ({ modelName, seedLocalId, seedUid, }) => {
5160
5449
  let itemData = {
5161
5450
  ...seedRow,
5162
5451
  ...versionRow,
5452
+ schemaName,
5163
5453
  };
5164
5454
  const propertiesData = await getItemProperties({
5165
5455
  seedLocalId,
@@ -5183,12 +5473,28 @@ const getItemData = async ({ modelName, seedLocalId, seedUid, }) => {
5183
5473
  return itemData;
5184
5474
  };
5185
5475
 
5186
- const getItemsData = async ({ modelName, deleted, }) => {
5476
+ const getItemsData = async ({ modelName, deleted, includeEas = false, addressFilter, }) => {
5187
5477
  const appDb = BaseDb.getAppDb();
5188
5478
  const conditions = [];
5479
+ if (!includeEas) {
5480
+ conditions.push(drizzleOrm.or(drizzleOrm.isNull(seeds.uid), drizzleOrm.eq(seeds.uid, '')));
5481
+ }
5189
5482
  if (modelName) {
5190
5483
  conditions.push(drizzleOrm.eq(seeds.type, casing.toSnakeCase(modelName)));
5191
5484
  }
5485
+ if (addressFilter === 'owned') {
5486
+ const ownedAddresses = await getOwnedAddressesFromDb();
5487
+ if (ownedAddresses.length > 0) {
5488
+ conditions.push(drizzleOrm.or(drizzleOrm.inArray(seeds.publisher, ownedAddresses), drizzleOrm.isNull(seeds.publisher)));
5489
+ }
5490
+ }
5491
+ else if (addressFilter === 'watched') {
5492
+ const watchedAddresses = await getWatchedAddressesFromDb();
5493
+ if (watchedAddresses.length === 0) {
5494
+ return [];
5495
+ }
5496
+ conditions.push(drizzleOrm.inArray(seeds.publisher, watchedAddresses));
5497
+ }
5192
5498
  if (deleted) {
5193
5499
  conditions.push(drizzleOrm.or(drizzleOrm.isNotNull(seeds._markedForDeletion), drizzleOrm.eq(seeds._markedForDeletion, 1)));
5194
5500
  }
@@ -5325,7 +5631,8 @@ const getModelSchemasFromEas = async () => {
5325
5631
  const queryClient = BaseQueryClient.getQueryClient();
5326
5632
  const easClient = BaseEasClient.getEasClient();
5327
5633
  // Dynamic import to break circular dependency
5328
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
5634
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
5635
+ const { Model } = modelMod;
5329
5636
  const allModels = await Model.all();
5330
5637
  const modelNames = allModels.map(m => m.modelName).filter((name) => !!name);
5331
5638
  // If there are no models, return empty array instead of querying
@@ -5654,7 +5961,8 @@ const resolveRelatedValue = xstate.fromCallback(({ sendBack, input: { context }
5654
5961
  const { isRelation, propertyValue, propertyName, seedUid, propertyRecordSchema, populatedFromDb, schemaUid, } = context;
5655
5962
  const _resolveRelatedValue = async () => {
5656
5963
  // Use dynamic import to break circular dependency
5657
- const { ModelPropertyDataTypes } = await Promise.resolve().then(function () { return require('./index-Dnywap_P.js'); });
5964
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-CvcOtzbi.js'); });
5965
+ const { ModelPropertyDataTypes } = schemaMod;
5658
5966
  if (!propertyValue || !isRelation || populatedFromDb) {
5659
5967
  return;
5660
5968
  }
@@ -5992,7 +6300,8 @@ const hydrateFromDb = xstate.fromCallback(({ sendBack, input: { context } }) =>
5992
6300
  // to use dynamically imported ModelPropertyDataTypes
5993
6301
  const _hydrateFromDb = async () => {
5994
6302
  // Use dynamic import to break circular dependency
5995
- const { ModelPropertyDataTypes } = await Promise.resolve().then(function () { return require('./index-Dnywap_P.js'); });
6303
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-CvcOtzbi.js'); });
6304
+ const { ModelPropertyDataTypes } = schemaMod;
5996
6305
  const appDb = BaseDb.getAppDb();
5997
6306
  const whereClauses = [];
5998
6307
  // Re-check types with dynamically imported ModelPropertyDataTypes
@@ -6144,7 +6453,8 @@ const hydrateFromDb = xstate.fromCallback(({ sendBack, input: { context } }) =>
6144
6453
  if (propertyRecordSchema &&
6145
6454
  propertyRecordSchema.storageType &&
6146
6455
  propertyRecordSchema.storageType === 'ItemStorage') {
6147
- const { Item } = await Promise.resolve().then(function () { return Item$1; });
6456
+ const itemMod = await Promise.resolve().then(function () { return Item$1; });
6457
+ const { Item } = itemMod;
6148
6458
  const item = await Item.find({
6149
6459
  seedLocalId: seedLocalId ?? undefined,
6150
6460
  modelName,
@@ -6221,8 +6531,8 @@ const loadOrCreateProperty = xstate.fromCallback(({ sendBack, input: { context }
6221
6531
  const modelName = metadataRecord.modelType || context.modelName;
6222
6532
  if (modelName) {
6223
6533
  try {
6224
- // Normalize to PascalCase so "post" (from seeds.type/metadata) matches "Post" in models table
6225
- const normalizedModelName = lodashEs.startCase(modelName);
6534
+ // Normalize snake_case to PascalCase: "test_post" -> "TestPost" (startCase gives "Test Post" which fails)
6535
+ const normalizedModelName = lodashEs.upperFirst(lodashEs.camelCase(modelName));
6226
6536
  // Query properties table to get property schema
6227
6537
  const modelRecords = await db
6228
6538
  .select({ id: models$1.id })
@@ -6253,6 +6563,28 @@ const loadOrCreateProperty = xstate.fromCallback(({ sendBack, input: { context }
6253
6563
  // Continue without propertyRecordSchema
6254
6564
  }
6255
6565
  }
6566
+ if (!propertyRecordSchema && modelName) {
6567
+ try {
6568
+ const { Model } = await Promise.resolve().then(function () { return Model$1; });
6569
+ const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
6570
+ const normalizedModelName = lodashEs.upperFirst(lodashEs.camelCase(modelName));
6571
+ // Try PascalCase first ("post" -> "Post"); then findByModelType for names with spaces ("new_model" -> "New model")
6572
+ let model$1 = Model.getByName(normalizedModelName);
6573
+ if (!model$1?.properties?.length) {
6574
+ model$1 = Model.findByModelType(casing.toSnakeCase(modelName));
6575
+ }
6576
+ if (model$1?.properties?.length) {
6577
+ const schemas = modelPropertiesToObject(model$1.properties);
6578
+ propertyRecordSchema = schemas[propertyName];
6579
+ if (propertyRecordSchema) {
6580
+ logger$k(`Fallback: loaded propertyRecordSchema from Model for propertyName "${propertyName}"`);
6581
+ }
6582
+ }
6583
+ }
6584
+ catch (error) {
6585
+ logger$k(`Fallback Model lookup failed for propertyName "${propertyName}": ${error}`);
6586
+ }
6587
+ }
6256
6588
  // Return loaded property data
6257
6589
  sendBack({
6258
6590
  type: 'loadOrCreatePropertySuccess',
@@ -6464,7 +6796,8 @@ const analyzeInput = xstate.fromCallback(({ sendBack, input: { context, event }
6464
6796
  }
6465
6797
  const _analyzeInput = async () => {
6466
6798
  // Use dynamic import to break circular dependency
6467
- const { ModelPropertyDataTypes } = await Promise.resolve().then(function () { return require('./index-Dnywap_P.js'); });
6799
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-CvcOtzbi.js'); });
6800
+ const { ModelPropertyDataTypes } = schemaMod;
6468
6801
  let propertyName = propertyNameRaw;
6469
6802
  if (!propertyName) {
6470
6803
  throw new Error('propertyName is required');
@@ -6821,7 +7154,8 @@ const saveRelation = xstate.fromCallback(({ sendBack, input: { context, event }
6821
7154
  }
6822
7155
  const _saveRelation = async () => {
6823
7156
  // Use dynamic import to break circular dependency
6824
- const { ModelPropertyDataTypes } = await Promise.resolve().then(function () { return require('./index-Dnywap_P.js'); });
7157
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-CvcOtzbi.js'); });
7158
+ const { ModelPropertyDataTypes } = schemaMod;
6825
7159
  if (!propertyNameRaw) {
6826
7160
  throw new Error('propertyName is required');
6827
7161
  }
@@ -7523,6 +7857,32 @@ Promise.resolve().then(function () { return Model$1; }).then(module => {
7523
7857
  // Return a default module structure to maintain type consistency
7524
7858
  return {};
7525
7859
  });
7860
+ /**
7861
+ * Resolve propertyRecordSchema from in-memory Model (Fix 6: enables value persistence when useItemProperty path doesn't go through loadOrCreateItem).
7862
+ * Tries getByName(pascalCase) first; if that fails (e.g. "New model" vs "NewModel"), falls back to findByModelType(modelType).
7863
+ */
7864
+ const resolvePropertyRecordSchemaFromModel = async (modelName, propertyName, modelType) => {
7865
+ if (!modelName && !modelType)
7866
+ return undefined;
7867
+ try {
7868
+ const { Model } = await Promise.resolve().then(function () { return Model$1; });
7869
+ const { modelPropertiesToObject } = await Promise.resolve().then(function () { return model; });
7870
+ let model$1 = modelName ? Model.getByName(modelName) : undefined;
7871
+ if (!model$1?.properties?.length && modelType) {
7872
+ model$1 = Model.findByModelType(modelType);
7873
+ }
7874
+ if (!model$1?.properties?.length)
7875
+ return undefined;
7876
+ const schemas = modelPropertiesToObject(model$1.properties);
7877
+ const schema = schemas[propertyName];
7878
+ return schema;
7879
+ }
7880
+ catch {
7881
+ return undefined;
7882
+ }
7883
+ };
7884
+ /** Convert modelType (snake_case from DB) to Model name (PascalCase). startCase adds spaces ("Test Post"); Model names are "TestPost". */
7885
+ const modelTypeToModelName = (modelType) => modelType ? lodashEs.upperFirst(lodashEs.camelCase(modelType)) : '';
7526
7886
  const logger$i = debug('seedSdk:property:class');
7527
7887
  // Define tracked properties for the Proxy
7528
7888
  // These properties will be read from/written to the actor context
@@ -7619,7 +7979,8 @@ class ItemProperty {
7619
7979
  return;
7620
7980
  }
7621
7981
  // Use dynamic import to break circular dependency
7622
- const { ModelPropertyDataTypes } = await Promise.resolve().then(function () { return require('./index-Dnywap_P.js'); });
7982
+ const schemaMod = await Promise.resolve().then(function () { return require('./index-CvcOtzbi.js'); });
7983
+ const { ModelPropertyDataTypes } = schemaMod;
7623
7984
  const { context } = snapshot;
7624
7985
  const { propertyRecordSchema } = context;
7625
7986
  if (context.seedLocalId && context.propertyName) {
@@ -7732,9 +8093,12 @@ class ItemProperty {
7732
8093
  setupState.subscriptionSetUp = true;
7733
8094
  logger(`[ItemProperty._setupLiveQuerySubscription] Setting up liveQuery for propertyName: ${propertyName}, seedLocalId: ${seedLocalId}`);
7734
8095
  try {
7735
- const { metadata } = await Promise.resolve().then(function () { return schema$1; });
7736
- const { eq, and, isNotNull } = await import('drizzle-orm');
7737
- const { getMetadataLatest } = await Promise.resolve().then(function () { return metadataLatest; });
8096
+ const seedSchemaMod = await Promise.resolve().then(function () { return schema$1; });
8097
+ const { metadata } = seedSchemaMod;
8098
+ const drizzleMod = await import('drizzle-orm');
8099
+ const { eq, and, isNotNull } = drizzleMod;
8100
+ const metadataLatestMod = await Promise.resolve().then(function () { return metadataLatest; });
8101
+ const { getMetadataLatest } = metadataLatestMod;
7738
8102
  const db = BaseDb.getAppDb();
7739
8103
  if (!db) {
7740
8104
  logger('[ItemProperty._setupLiveQuerySubscription] Database not available');
@@ -8004,10 +8368,14 @@ class ItemProperty {
8004
8368
  return undefined;
8005
8369
  }
8006
8370
  // Ensure modelName for constructor: metadata may have modelType only, or neither (e.g. when Item passes it)
8371
+ // Use modelTypeToModelName: modelType is snake_case ("test_post"); Model names are PascalCase ("TestPost")
8007
8372
  const data = propertyData;
8008
8373
  const modelName = data.modelName ??
8009
- ((data.modelType ? lodashEs.startCase(data.modelType) : '') || modelNameOption || '');
8010
- foundProperty = ItemProperty.create({ ...propertyData, modelName }, { waitForReady: false });
8374
+ ((data.modelType ? modelTypeToModelName(data.modelType) : '') || modelNameOption || '');
8375
+ // Fix 6: resolve propertyRecordSchema from Model so value setter can persist (useItemProperty path)
8376
+ // Pass modelType for fallback: "New model" -> "new_model" can't be reversed to exact name; findByModelType handles it
8377
+ const propertyRecordSchema = await resolvePropertyRecordSchemaFromModel(modelName, propertyName, data.modelType);
8378
+ foundProperty = ItemProperty.create({ ...propertyData, modelName, propertyRecordSchema }, { waitForReady: false });
8011
8379
  }
8012
8380
  if (!foundProperty) {
8013
8381
  return undefined;
@@ -8030,9 +8398,16 @@ class ItemProperty {
8030
8398
  const propertiesData = await getItemProperties({ seedLocalId, seedUid });
8031
8399
  const instances = [];
8032
8400
  for (const data of propertiesData) {
8401
+ const d = data;
8402
+ const modelName = d.modelName ?? (d.modelType ? modelTypeToModelName(d.modelType) : '') ?? '';
8403
+ // Fix 6: resolve propertyRecordSchema from Model so value setter can persist
8404
+ const propertyRecordSchema = d.propertyName
8405
+ ? await resolvePropertyRecordSchemaFromModel(modelName, d.propertyName, d.modelType)
8406
+ : undefined;
8033
8407
  const createProps = {
8034
8408
  ...data,
8035
- modelName: data.modelName ?? data.modelType ?? '',
8409
+ modelName,
8410
+ propertyRecordSchema,
8036
8411
  };
8037
8412
  const instance = this.create(createProps, { waitForReady: false });
8038
8413
  if (instance) {
@@ -8167,10 +8542,15 @@ class ItemProperty {
8167
8542
  });
8168
8543
  }
8169
8544
  async save() {
8545
+ const ctx = this._getSnapshotContext();
8546
+ const { assertItemOwned } = await Promise.resolve().then(function () { return require('./ownership-Dm5ER1nI.js'); });
8547
+ await assertItemOwned({
8548
+ seedLocalId: ctx?.seedLocalId ?? undefined,
8549
+ seedUid: ctx?.seedUid ?? undefined,
8550
+ });
8170
8551
  await xstate.waitFor(this._service, (snapshot) => !snapshot.context.isSaving && snapshot.value === 'idle', {
8171
8552
  timeout: 10000,
8172
8553
  });
8173
- const ctx = this._getSnapshotContext();
8174
8554
  const canonicalId = ctx?.seedLocalId ?? ctx?.seedUid;
8175
8555
  if (canonicalId) {
8176
8556
  eventEmitter.emit('itemProperty.saved', { seedLocalId: ctx.seedLocalId, seedUid: ctx.seedUid });
@@ -8247,8 +8627,10 @@ class ItemProperty {
8247
8627
  if (!propertyName || (!seedLocalId && !seedUid))
8248
8628
  return;
8249
8629
  if (db) {
8250
- const { metadata } = await Promise.resolve().then(function () { return schema$1; });
8251
- const { and, eq, or } = await import('drizzle-orm');
8630
+ const seedSchemaMod = await Promise.resolve().then(function () { return schema$1; });
8631
+ const { metadata } = seedSchemaMod;
8632
+ const drizzleMod = await import('drizzle-orm');
8633
+ const { and, eq, or } = drizzleMod;
8252
8634
  const conditions = [eq(metadata.propertyName, propertyName)];
8253
8635
  if (seedLocalId && seedUid) {
8254
8636
  conditions.push(or(eq(metadata.seedLocalId, seedLocalId), eq(metadata.seedUid, seedUid)));
@@ -8263,7 +8645,8 @@ class ItemProperty {
8263
8645
  await db.delete(metadata).where(and(...conditions));
8264
8646
  }
8265
8647
  }
8266
- const { Item } = await Promise.resolve().then(function () { return Item$1; });
8648
+ const itemMod = await Promise.resolve().then(function () { return Item$1; });
8649
+ const { Item } = itemMod;
8267
8650
  const item = Item.getById((seedLocalId || seedUid));
8268
8651
  if (item) {
8269
8652
  item.getService().send({ type: 'removePropertyInstance', propertyName });
@@ -8289,14 +8672,22 @@ const createNewItem = async ({ modelName, ...propertyData }) => {
8289
8672
  const newSeedId = await createSeed({ type: seedType });
8290
8673
  const newVersionId = await createVersion({ seedLocalId: newSeedId, seedType: casing.toSnakeCase(modelName) });
8291
8674
  // Dynamic import to break circular dependency
8292
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
8675
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
8676
+ const { Model } = modelMod;
8293
8677
  const model = await Model.getByNameAsync(modelName);
8294
8678
  const propertySchemas = model?.properties ? modelPropertiesToObject(model.properties) : undefined;
8295
- for (const [propertyName, propertyValue] of Object.entries(propertyData)) {
8296
- let propertyRecordSchema;
8297
- if (propertySchemas && propertySchemas[propertyName]) {
8298
- propertyRecordSchema = propertySchemas[propertyName];
8299
- }
8679
+ // Build set of all properties to create metadata for: union of model schema + propertyData
8680
+ // This ensures we create metadata for ALL model properties even when creating with no initial values
8681
+ // (fixes first-item persistence: loadOrCreateItem needs metadata rows to run createItemPropertyInstances)
8682
+ const allPropertyNames = new Set(Object.keys(propertyData));
8683
+ if (propertySchemas) {
8684
+ for (const name of Object.keys(propertySchemas)) {
8685
+ allPropertyNames.add(name);
8686
+ }
8687
+ }
8688
+ for (const propertyName of allPropertyNames) {
8689
+ const propertyValue = propertyData[propertyName];
8690
+ const propertyRecordSchema = propertySchemas?.[propertyName];
8300
8691
  await createMetadata({
8301
8692
  seedLocalId: newSeedId,
8302
8693
  versionLocalId: newVersionId,
@@ -8463,6 +8854,8 @@ class Item {
8463
8854
  });
8464
8855
  };
8465
8856
  this.publish = async () => {
8857
+ const { assertItemOwned } = await Promise.resolve().then(function () { return require('./ownership-Dm5ER1nI.js'); });
8858
+ await assertItemOwned(this);
8466
8859
  this._service.send({ type: 'startPublish' });
8467
8860
  return new Promise((resolve, reject) => {
8468
8861
  let wasPublishing = false;
@@ -8497,12 +8890,14 @@ class Item {
8497
8890
  };
8498
8891
  this.getPublishUploads = async () => {
8499
8892
  // Use dynamic import to break circular dependency
8500
- const { getPublishUploads } = await Promise.resolve().then(function () { return require('./getPublishUploads-CnC9aYxs.js'); });
8893
+ const getPublishUploadsMod = await Promise.resolve().then(function () { return require('./getPublishUploads-DDsT9zZ6.js'); });
8894
+ const { getPublishUploads } = getPublishUploadsMod;
8501
8895
  return await getPublishUploads(this);
8502
8896
  };
8503
8897
  this.getPublishPayload = async (uploadedTransactions) => {
8504
8898
  // Use dynamic import to break circular dependency
8505
- const { getPublishPayload } = await Promise.resolve().then(function () { return require('./getPublishPayload-BD1qRob1.js'); });
8899
+ const getPublishPayloadMod = await Promise.resolve().then(function () { return require('./getPublishPayload-CoLriAMV.js'); });
8900
+ const { getPublishPayload } = getPublishPayloadMod;
8506
8901
  return await getPublishPayload(this, uploadedTransactions);
8507
8902
  };
8508
8903
  this.persistSeedUid = async () => {
@@ -8777,8 +9172,10 @@ class Item {
8777
9172
  let modelRecords;
8778
9173
  // If we have a schema name, join with modelSchemas to filter by schema
8779
9174
  if (schemaName) {
8780
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
8781
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
9175
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
9176
+ const { modelSchemas } = modelSchemaSchemaMod;
9177
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
9178
+ const { schemas: schemasTable } = schemaSchemaMod;
8782
9179
  modelRecords = await db
8783
9180
  .select({ id: models$1.id })
8784
9181
  .from(models$1)
@@ -9030,8 +9427,8 @@ class Item {
9030
9427
  }
9031
9428
  }
9032
9429
  static async all(modelName, deleted, options) {
9033
- const { waitForReady = false, readyTimeout = 5000 } = options ?? {};
9034
- const itemsData = await getItemsData({ modelName, deleted });
9430
+ const { waitForReady = false, readyTimeout = 5000, includeEas = false, addressFilter, } = options ?? {};
9431
+ const itemsData = await getItemsData({ modelName, deleted, includeEas, addressFilter });
9035
9432
  const itemInstances = [];
9036
9433
  for (const itemData of itemsData) {
9037
9434
  itemInstances.push(await Item.create({
@@ -9368,9 +9765,12 @@ class Item {
9368
9765
  setupState.subscriptionSetUp = true;
9369
9766
  logger(`[Item._setupLiveQuerySubscription] Setting up liveQuery for seedLocalId: ${seedLocalId}`);
9370
9767
  try {
9371
- const { seeds, versions, metadata } = await Promise.resolve().then(function () { return schema$1; });
9372
- const { eq, and } = await import('drizzle-orm');
9373
- const { getVersionData } = await Promise.resolve().then(function () { return versionData; });
9768
+ const seedSchemaMod = await Promise.resolve().then(function () { return schema$1; });
9769
+ const { seeds, versions, metadata } = seedSchemaMod;
9770
+ const drizzleMod = await import('drizzle-orm');
9771
+ const { eq, and } = drizzleMod;
9772
+ const versionDataMod = await Promise.resolve().then(function () { return versionData; });
9773
+ const { getVersionData } = versionDataMod;
9374
9774
  const db = BaseDb.getAppDb();
9375
9775
  if (!db) {
9376
9776
  logger('[Item._setupLiveQuerySubscription] Database not available');
@@ -9413,7 +9813,8 @@ class Item {
9413
9813
  // CRITICAL: Create ItemProperty instances BEFORE updating context
9414
9814
  if (initialMetadataIds.length > 0) {
9415
9815
  try {
9416
- const { ItemProperty } = await Promise.resolve().then(function () { return ItemProperty$1; });
9816
+ const itemPropertyMod = await Promise.resolve().then(function () { return ItemProperty$1; });
9817
+ const { ItemProperty } = itemPropertyMod;
9417
9818
  const itemModelName = this._service.getSnapshot().context.modelName;
9418
9819
  const createPromises = initialMetadata.map(async (metaRow) => {
9419
9820
  try {
@@ -9521,7 +9922,8 @@ class Item {
9521
9922
  // CRITICAL: Create ItemProperty instances BEFORE updating context
9522
9923
  if (metadataRows.length > 0) {
9523
9924
  try {
9524
- const { ItemProperty } = await Promise.resolve().then(function () { return ItemProperty$1; });
9925
+ const itemPropertyMod = await Promise.resolve().then(function () { return ItemProperty$1; });
9926
+ const { ItemProperty } = itemPropertyMod;
9525
9927
  const itemModelName = this._service.getSnapshot().context.modelName;
9526
9928
  const createPromises = metadataRows.map(async (metaRow) => {
9527
9929
  try {
@@ -9642,6 +10044,8 @@ class Item {
9642
10044
  * Destroy the item: soft delete in DB, remove from caches, clean up subscriptions, stop service.
9643
10045
  */
9644
10046
  async destroy() {
10047
+ const { assertItemOwned } = await Promise.resolve().then(function () { return require('./ownership-Dm5ER1nI.js'); });
10048
+ await assertItemOwned(this);
9645
10049
  const context = this._getSnapshotContext();
9646
10050
  const cacheKey = context.seedUid || context.seedLocalId;
9647
10051
  const cacheKeys = cacheKey ? [cacheKey] : [];
@@ -9683,6 +10087,24 @@ class ConflictError extends Error {
9683
10087
  }
9684
10088
  }
9685
10089
 
10090
+ /**
10091
+ * Normalizes AddressConfiguration to { owned, watched }.
10092
+ * - string[] -> { owned: addresses, watched: [] }
10093
+ * - { owned, watched? } -> { owned, watched: watched ?? [] }
10094
+ */
10095
+ function normalizeAddressConfig(addresses) {
10096
+ if (!addresses) {
10097
+ return { owned: [], watched: [] };
10098
+ }
10099
+ if (Array.isArray(addresses)) {
10100
+ return { owned: addresses, watched: [] };
10101
+ }
10102
+ return {
10103
+ owned: addresses.owned ?? [],
10104
+ watched: addresses.watched ?? [],
10105
+ };
10106
+ }
10107
+
9686
10108
  const isNode = () => {
9687
10109
  return (typeof process !== 'undefined' &&
9688
10110
  process.versions != null &&
@@ -9719,7 +10141,8 @@ const setupServicesEventHandlers = () => {
9719
10141
  const schemaStringToModelRecord = new Map();
9720
10142
  const getModelSchemas = async () => {
9721
10143
  // Dynamic import to break circular dependency
9722
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
10144
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
10145
+ const { Model } = modelMod;
9723
10146
  const allModels = await Model.all();
9724
10147
  const modelRecords = [];
9725
10148
  const appDb = BaseDb.getAppDb();
@@ -9821,6 +10244,7 @@ const saveEasSeedsToDb = async ({ itemSeeds }) => {
9821
10244
  uid: seed.id,
9822
10245
  schemaUid: seed.schemaId,
9823
10246
  type: seed.schema.schemaNames[0].name,
10247
+ publisher: seed.attester,
9824
10248
  createdAt: Date.now(),
9825
10249
  attestationCreatedAt: seed.timeCreated * 1000,
9826
10250
  attestationRaw,
@@ -9954,7 +10378,8 @@ const saveEasPropertiesToDb = async ({ itemProperties, itemSeeds, }) => {
9954
10378
  isSavingToDb = true;
9955
10379
  const propertyUids = itemProperties.map((property) => property.id);
9956
10380
  // Dynamic import to break circular dependency
9957
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
10381
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
10382
+ const { Model } = modelMod;
9958
10383
  const allModels = await Model.all();
9959
10384
  const models = Object.fromEntries(allModels.map(m => [m.modelName, m]));
9960
10385
  const appDb = BaseDb.getAppDb();
@@ -10139,6 +10564,10 @@ const getRelatedSeedsAndVersions = async () => {
10139
10564
  });
10140
10565
  };
10141
10566
  const syncDbWithEasHandler = lodashEs.throttle(async (_) => {
10567
+ const addresses = await getAllAddressesFromDb();
10568
+ if (!addresses || addresses.length === 0) {
10569
+ return;
10570
+ }
10142
10571
  const appDb = BaseDb.getAppDb();
10143
10572
  const { schemaStringToModelRecord } = await getModelSchemas();
10144
10573
  const modelSchemas = await getModelSchemasFromEas();
@@ -10176,7 +10605,6 @@ const syncDbWithEasHandler = lodashEs.throttle(async (_) => {
10176
10605
  if (schemaUids.length === 0) {
10177
10606
  return;
10178
10607
  }
10179
- const addresses = await getAddressesFromDb();
10180
10608
  const itemSeeds = await getSeedsFromSchemaUids({
10181
10609
  schemaUids,
10182
10610
  addresses,
@@ -10352,11 +10780,14 @@ const platformClassesInit = xstate.fromCallback(({ sendBack, input: { context, e
10352
10780
  }
10353
10781
  // If it's an absolute path that exists or is a valid filesystem path, use it as-is
10354
10782
  }
10783
+ const normalizedAddresses = normalizeAddressConfig(addresses);
10355
10784
  sendBack({ type: 'updateContext', context: {
10356
10785
  models: models || {},
10357
10786
  endpoints,
10358
10787
  arweaveDomain,
10359
- addresses: addresses || [],
10788
+ addresses: normalizedAddresses.owned,
10789
+ ownedAddresses: normalizedAddresses.owned,
10790
+ watchedAddresses: normalizedAddresses.watched,
10360
10791
  filesDir: normalizedFilesDir,
10361
10792
  dbConfig,
10362
10793
  } });
@@ -10540,11 +10971,12 @@ const downloadAllFilesRequestHandler = async ({ endpoints, eventId, }) => {
10540
10971
  const downloadAllFilesBinaryRequestHandler = async () => {
10541
10972
  let addresses;
10542
10973
  if (BaseDb.isAppDbReady()) {
10543
- addresses = await getAddressesFromDb();
10974
+ addresses = await getAllAddressesFromDb();
10544
10975
  }
10545
10976
  if (!BaseDb.isAppDbReady()) {
10546
10977
  // Wait for ClientManager to be ready (DB_INIT state or later)
10547
- const { getClient } = await Promise.resolve().then(function () { return ClientManager$1; });
10978
+ const clientManagerMod = await Promise.resolve().then(function () { return ClientManager$1; });
10979
+ const { getClient } = clientManagerMod;
10548
10980
  const clientManager = getClient();
10549
10981
  const clientService = clientManager.getService();
10550
10982
  await xstate.waitFor(clientService, (snapshot) => {
@@ -10556,7 +10988,7 @@ const downloadAllFilesBinaryRequestHandler = async () => {
10556
10988
  state === 'addModelsToDb' ||
10557
10989
  state === 'idle';
10558
10990
  }, { timeout: 30000 });
10559
- addresses = await getAddressesFromDb();
10991
+ addresses = await getAllAddressesFromDb();
10560
10992
  }
10561
10993
  if (!addresses || addresses.length === 0) {
10562
10994
  return;
@@ -10908,7 +11340,7 @@ const addModelsToDb = xstate.fromCallback(({ sendBack, input: { context } }) =>
10908
11340
  const logger$a = debug('seedSdk:client:actors:saveConfig');
10909
11341
  const saveConfig = xstate.fromCallback(({ sendBack, input: { context } }) => {
10910
11342
  logger$a('saveConfig starting');
10911
- const { endpoints, addresses, arweaveDomain } = context;
11343
+ const { endpoints, addresses, ownedAddresses, watchedAddresses, arweaveDomain } = context;
10912
11344
  // Validate endpoints - required for proper initialization
10913
11345
  // If endpoints are missing or invalid, initialization should fail
10914
11346
  if (!endpoints || !endpoints.filePaths || !endpoints.files) {
@@ -10928,7 +11360,9 @@ const saveConfig = xstate.fromCallback(({ sendBack, input: { context } }) => {
10928
11360
  throw new Error('App DB not found');
10929
11361
  }
10930
11362
  const endpointsValueString = JSON.stringify(endpoints);
10931
- const addressesValueString = JSON.stringify(addresses);
11363
+ const owned = ownedAddresses ?? addresses ?? [];
11364
+ const watched = watchedAddresses ?? [];
11365
+ const addressesValueString = JSON.stringify({ owned, watched });
10932
11366
  // TODO: Figure out how to define on conflict with multiple rows added
10933
11367
  await appDb
10934
11368
  .insert(appState)
@@ -10942,7 +11376,7 @@ const saveConfig = xstate.fromCallback(({ sendBack, input: { context } }) => {
10942
11376
  value: endpointsValueString,
10943
11377
  },
10944
11378
  });
10945
- if (addresses) {
11379
+ if (owned.length > 0 || watched.length > 0) {
10946
11380
  await appDb
10947
11381
  .insert(appState)
10948
11382
  .values({
@@ -11374,8 +11808,10 @@ const logger$8 = debug('seedSdk:imports:json');
11374
11808
  * @returns Promise that resolves when properties are found, or rejects if not found after max retries
11375
11809
  */
11376
11810
  const verifyPropertiesPersisted = async (db, modelId, modelName, maxRetries = 10, retryDelay = 100) => {
11377
- const { properties: propertiesTable } = await Promise.resolve().then(function () { return ModelSchema; });
11378
- const { eq } = await import('drizzle-orm');
11811
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
11812
+ const { properties: propertiesTable } = modelSchemaMod;
11813
+ const drizzleMod = await import('drizzle-orm');
11814
+ const { eq } = drizzleMod;
11379
11815
  console.log(`[verifyPropertiesPersisted] Starting verification for model "${modelName}" (modelId: ${modelId})`);
11380
11816
  for (let attempt = 0; attempt < maxRetries; attempt++) {
11381
11817
  const props = await db
@@ -11691,7 +12127,8 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
11691
12127
  schemaFile = transformImportToSchemaFile(importData, version);
11692
12128
  }
11693
12129
  // Check if this is an internal SDK schema (should not create files in app directory)
11694
- const { isInternalSchema } = await Promise.resolve().then(function () { return constants; });
12130
+ const constantsMod = await Promise.resolve().then(function () { return constants; });
12131
+ const { isInternalSchema } = constantsMod;
11695
12132
  const isInternal = isInternalSchema(schemaFile.metadata.name, schemaFile.id);
11696
12133
  if (isInternal) {
11697
12134
  logger$8(`Skipping file creation for internal schema: ${schemaFile.metadata.name}`);
@@ -11785,7 +12222,8 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
11785
12222
  updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
11786
12223
  };
11787
12224
  // Use dynamic import to break circular dependency
11788
- const { addSchemaToDb, addModelsToDb } = await Promise.resolve().then(function () { return db; });
12225
+ const dbMod = await Promise.resolve().then(function () { return db; });
12226
+ const { addSchemaToDb, addModelsToDb } = dbMod;
11789
12227
  // Try to add schema and models to database if database is available
11790
12228
  try {
11791
12229
  const db = BaseDb.getAppDb();
@@ -11806,9 +12244,12 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
11806
12244
  // CRITICAL: Verify all expected models are linked via join table
11807
12245
  // Retry querying until all models are visible (browser environments may have delays)
11808
12246
  const expectedModelNames = Object.keys(schemaFile.models || {});
11809
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
11810
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
11811
- const { eq, and } = await import('drizzle-orm');
12247
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
12248
+ const { modelSchemas } = modelSchemaSchemaMod;
12249
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
12250
+ const { models: modelsTable } = modelSchemaMod;
12251
+ const drizzleMod = await import('drizzle-orm');
12252
+ const { eq, and } = drizzleMod;
11812
12253
  let allModelsLinked = false;
11813
12254
  for (let attempt = 0; attempt < 10; attempt++) {
11814
12255
  const modelLinks = await db
@@ -11979,10 +12420,11 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
11979
12420
  }
11980
12421
  }
11981
12422
  }
11982
- // After properties are created, ensure schemaFile has the correct IDs from database
12423
+ // After properties are created (internal schema path), ensure schemaFile has the correct IDs from database
11983
12424
  // Query the database to get the actual schemaFileId values that were used
11984
12425
  // This ensures schemaData matches what's actually in the database
11985
- const { properties: propertiesTable } = await Promise.resolve().then(function () { return ModelSchema; });
12426
+ const modelSchemaMod1 = await Promise.resolve().then(function () { return ModelSchema; });
12427
+ const { properties: propertiesTable } = modelSchemaMod1;
11986
12428
  let schemaFileUpdated = false;
11987
12429
  for (const [modelName, modelFileId] of modelFileIds.entries()) {
11988
12430
  // Get model record to find modelId
@@ -12015,7 +12457,8 @@ async function importJsonSchema(importFilePathOrContents, version = 1) {
12015
12457
  // This is important even if nothing changed, to ensure consistency
12016
12458
  const updatedSchemaData = JSON.stringify(schemaFile, null, 2);
12017
12459
  // Update the schema record in the database with current schemaData
12018
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
12460
+ const schemaSchemaMod1 = await Promise.resolve().then(function () { return SchemaSchema; });
12461
+ const { schemas: schemasTable } = schemaSchemaMod1;
12019
12462
  await db
12020
12463
  .update(schemasTable)
12021
12464
  .set({ schemaData: updatedSchemaData })
@@ -12229,7 +12672,8 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12229
12672
  updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
12230
12673
  };
12231
12674
  // Use dynamic import to break circular dependency
12232
- const { addSchemaToDb, addModelsToDb } = await Promise.resolve().then(function () { return db; });
12675
+ const dbMod = await Promise.resolve().then(function () { return db; });
12676
+ const { addSchemaToDb, addModelsToDb } = dbMod;
12233
12677
  // Try to add schema and models to database if database is available
12234
12678
  try {
12235
12679
  const db = BaseDb.getAppDb();
@@ -12251,9 +12695,12 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12251
12695
  await new Promise(resolve => setTimeout(resolve, 200));
12252
12696
  console.log(`[importJsonSchema] Starting property verification for schema "${schemaName}" (schemaRecord.id: ${schemaRecord.id})`);
12253
12697
  // Query the database to get model IDs that were just created
12254
- const { modelSchemas } = await Promise.resolve().then(function () { return ModelSchemaSchema; });
12255
- const { models: modelsTable } = await Promise.resolve().then(function () { return ModelSchema; });
12256
- const { eq } = await import('drizzle-orm');
12698
+ const modelSchemaSchemaMod = await Promise.resolve().then(function () { return ModelSchemaSchema; });
12699
+ const { modelSchemas } = modelSchemaSchemaMod;
12700
+ const modelSchemaMod = await Promise.resolve().then(function () { return ModelSchema; });
12701
+ const { models: modelsTable } = modelSchemaMod;
12702
+ const drizzleMod = await import('drizzle-orm');
12703
+ const { eq } = drizzleMod;
12257
12704
  // Try to find models directly by schemaFileId first (more reliable than join table)
12258
12705
  const seedModelId = modelFileIds.get('Seed');
12259
12706
  let seedModel = [];
@@ -12315,10 +12762,11 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12315
12762
  }
12316
12763
  }
12317
12764
  }
12318
- // After properties are created, ensure schemaFile has the correct IDs from database
12765
+ // After properties are created (file path), ensure schemaFile has the correct IDs from database
12319
12766
  // Query the database to get the actual schemaFileId values that were used
12320
12767
  // This ensures schemaData matches what's actually in the database
12321
- const { properties: propertiesTable } = await Promise.resolve().then(function () { return ModelSchema; });
12768
+ const modelSchemaMod2 = await Promise.resolve().then(function () { return ModelSchema; });
12769
+ const { properties: propertiesTable } = modelSchemaMod2;
12322
12770
  let schemaFileUpdated = false;
12323
12771
  for (const [modelName, modelFileId] of modelFileIds.entries()) {
12324
12772
  // Get model record to find modelId
@@ -12351,7 +12799,8 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12351
12799
  // This is important even if nothing changed, to ensure consistency
12352
12800
  const updatedSchemaData = JSON.stringify(schemaFile, null, 2);
12353
12801
  // Update the schema record in the database with current schemaData
12354
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return SchemaSchema; });
12802
+ const schemaSchemaMod = await Promise.resolve().then(function () { return SchemaSchema; });
12803
+ const { schemas: schemasTable } = schemaSchemaMod;
12355
12804
  await db
12356
12805
  .update(schemasTable)
12357
12806
  .set({ schemaData: updatedSchemaData })
@@ -12392,7 +12841,8 @@ const loadSchemaFromFile = async (schemaFilePath) => {
12392
12841
  */
12393
12842
  const createModelFromJson = async (modelName, modelDef, schemaName, modelFileId, // Optional modelFileId from JSON file
12394
12843
  propertyFileIds) => {
12395
- const { Model } = await Promise.resolve().then(function () { return Model$1; });
12844
+ const modelMod = await Promise.resolve().then(function () { return Model$1; });
12845
+ const { Model } = modelMod;
12396
12846
  // Convert JSON properties to schema format
12397
12847
  const convertedProperties = {};
12398
12848
  if (modelDef.properties) {
@@ -12897,14 +13347,17 @@ const clientManagerMachine = xstate.setup({
12897
13347
  actions: [
12898
13348
  xstate.assign(({ event, spawn }) => {
12899
13349
  const { addresses } = event;
13350
+ const normalized = normalizeAddressConfig(addresses);
12900
13351
  spawn('saveAppState', {
12901
13352
  input: {
12902
13353
  key: 'addresses',
12903
- value: addresses,
13354
+ value: { owned: normalized.owned, watched: normalized.watched },
12904
13355
  },
12905
13356
  });
12906
13357
  return {
12907
- addresses,
13358
+ addresses: normalized.owned,
13359
+ ownedAddresses: normalized.owned,
13360
+ watchedAddresses: normalized.watched,
12908
13361
  isSaving: true,
12909
13362
  };
12910
13363
  })
@@ -12977,6 +13430,8 @@ const clientInstance = {
12977
13430
  isSaving: false,
12978
13431
  endpoints: undefined,
12979
13432
  addresses: undefined,
13433
+ ownedAddresses: undefined,
13434
+ watchedAddresses: undefined,
12980
13435
  models: undefined,
12981
13436
  arweaveDomain: undefined,
12982
13437
  filesDir: undefined,
@@ -13031,9 +13486,17 @@ const clientInstance = {
13031
13486
  },
13032
13487
  getAddresses: async () => {
13033
13488
  ensureInitialized();
13034
- const db = await BaseDb.getAppDb();
13035
- const results = await db.select().from(appState).where(drizzleOrm.eq(appState.key, 'addresses'));
13036
- return JSON.parse(results[0]?.value);
13489
+ const owned = await getOwnedAddressesFromDb();
13490
+ const watched = await getWatchedAddressesFromDb();
13491
+ return { owned, watched };
13492
+ },
13493
+ getOwnedAddresses: async () => {
13494
+ ensureInitialized();
13495
+ return getOwnedAddressesFromDb();
13496
+ },
13497
+ getWatchedAddresses: async () => {
13498
+ ensureInitialized();
13499
+ return getWatchedAddressesFromDb();
13037
13500
  },
13038
13501
  addModel: async (modelDef) => {
13039
13502
  const db = await BaseDb.getAppDb();
@@ -13243,7 +13706,7 @@ const saveDraftLogger = debug('seedSdk:model:saveDraftToDb');
13243
13706
  // Lazy import cache for ModelProperty to avoid circular dependency
13244
13707
  // Eagerly start loading to minimize delay on first access
13245
13708
  let ModelPropertyClass = null;
13246
- const modelPropertyImportPromise = Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); })
13709
+ const modelPropertyImportPromise = Promise.resolve().then(function () { return require('./ModelProperty-DpjD0o0E.js'); })
13247
13710
  .then(module => {
13248
13711
  ModelPropertyClass = module.ModelProperty;
13249
13712
  return ModelPropertyClass;
@@ -13260,7 +13723,7 @@ function getModelProperty() {
13260
13723
  }
13261
13724
  // Lazy import cache for Schema to avoid circular dependency
13262
13725
  let SchemaClass = null;
13263
- const schemaImportPromise = Promise.resolve().then(function () { return require('./Schema-CVs9J6eP.js'); }).then(function (n) { return n.Schema$1; })
13726
+ const schemaImportPromise = Promise.resolve().then(function () { return require('./Schema-DkSBMBwz.js'); }).then(function (n) { return n.Schema$1; })
13264
13727
  .then(module => {
13265
13728
  SchemaClass = module.Schema;
13266
13729
  return SchemaClass;
@@ -13776,7 +14239,11 @@ class Model {
13776
14239
  // Step 11: Register with schema if requested, OR trigger write if properties are provided
13777
14240
  // If properties are provided, we need to write the model to get modelId for property creation
13778
14241
  // If schema provided, trigger write process instead of registration
13779
- const shouldTriggerWrite = (registerWithSchema && schemaInstance) || (options?.properties && Object.keys(options.properties).length > 0);
14242
+ // When schemaName is passed as string (e.g. useCreateModel), we must trigger write so runtime-created
14243
+ // models get persisted to DB and show up in useModels (which queries the database).
14244
+ const shouldTriggerWrite = (registerWithSchema && schemaInstance) ||
14245
+ (options?.properties && Object.keys(options.properties).length > 0) ||
14246
+ typeof schemaNameOrSchema === 'string';
13780
14247
  if (shouldTriggerWrite) {
13781
14248
  queueMicrotask(async () => {
13782
14249
  try {
@@ -14059,6 +14526,22 @@ class Model {
14059
14526
  }
14060
14527
  return undefined;
14061
14528
  }
14529
+ /**
14530
+ * Find Model by modelType (snake_case from DB/metadata).
14531
+ * Handles model names with spaces: "new_model" -> finds "New model" (toSnakeCase("New model") === "new_model").
14532
+ */
14533
+ static findByModelType(modelType) {
14534
+ if (!modelType)
14535
+ return undefined;
14536
+ for (const [nameKey, id] of this.instanceCacheByName.entries()) {
14537
+ const parts = nameKey.split(':', 2);
14538
+ const cachedModelName = parts[1];
14539
+ if (cachedModelName && casing.toSnakeCase(cachedModelName) === modelType) {
14540
+ return this.getById(id);
14541
+ }
14542
+ }
14543
+ return undefined;
14544
+ }
14062
14545
  /**
14063
14546
  * Get all Model instances for a schema from cache only (synchronous).
14064
14547
  * Includes models created at runtime via Model.create() that may not yet be in schema context.
@@ -14761,7 +15244,8 @@ class Model {
14761
15244
  doDestroy: async () => {
14762
15245
  const db = BaseDb.getAppDb();
14763
15246
  if (db && modelFileId) {
14764
- const { eq } = await import('drizzle-orm');
15247
+ const drizzleMod = await import('drizzle-orm');
15248
+ const { eq } = drizzleMod;
14765
15249
  const modelRecords = await db
14766
15250
  .select()
14767
15251
  .from(models$1)
@@ -15244,7 +15728,8 @@ var FileManager$1 = /*#__PURE__*/Object.freeze({
15244
15728
  const logger$4 = debug('seedSdk:node:db:Db');
15245
15729
  const getConfig = async (dotSeedDir, config) => {
15246
15730
  // Create config inline - config values can be passed in or use defaults
15247
- const { defineConfig } = await import('drizzle-kit');
15731
+ const drizzleKitMod = await import('drizzle-kit');
15732
+ const { defineConfig } = drizzleKitMod;
15248
15733
  const appSchemaDir = config?.schemaDir || path.join(dotSeedDir, 'schema');
15249
15734
  const outDir = config?.outDir || `${dotSeedDir}/db`;
15250
15735
  const dbUrl = config?.dbUrl || `${dotSeedDir}/db/seed.db`;
@@ -15293,105 +15778,6 @@ class Db extends BaseDb {
15293
15778
  // You can inspect what will happen before applying
15294
15779
  await apply();
15295
15780
  this.db = db;
15296
- // OLD CODE: Resolve better-sqlite3 from project's node_modules first, then fall back to SDK's node_modules
15297
- // This is important for tests and when the SDK is used as a dependency
15298
- // const projectDir = path.dirname(filesDir) // filesDir is .seed, so projectDir is the project root
15299
- // const projectBetterSqlite3Path = path.join(projectDir, 'node_modules', 'better-sqlite3')
15300
- //
15301
- // let Database: any
15302
- // try {
15303
- // const fs = await import('fs')
15304
- // if (fs.existsSync(projectBetterSqlite3Path)) {
15305
- // // Try to resolve from project's node_modules using the full path
15306
- // // For Bun, we can try importing directly from the path
15307
- // try {
15308
- // // First try using createRequire (works in Node.js)
15309
- // const { createRequire } = await import('module')
15310
- // const projectRequire = createRequire(path.join(projectDir, 'package.json'))
15311
- // const betterSqlite3Module = projectRequire('better-sqlite3')
15312
- // Database = betterSqlite3Module.default || betterSqlite3Module
15313
- // logger('[node/db/Db] Using better-sqlite3 from project node_modules via createRequire')
15314
- // } catch (requireError: any) {
15315
- // // If createRequire fails (e.g., in Bun), try direct path import
15316
- // logger('[node/db/Db] createRequire failed, trying direct import:', requireError.message)
15317
- // const betterSqlite3MainPath = path.join(projectBetterSqlite3Path, 'lib', 'database.js')
15318
- // if (fs.existsSync(betterSqlite3MainPath)) {
15319
- // // Use dynamic import with the full path
15320
- // const betterSqlite3Module = await import(betterSqlite3MainPath)
15321
- // Database = betterSqlite3Module.default || betterSqlite3Module.Database || betterSqlite3Module
15322
- // logger('[node/db/Db] Using better-sqlite3 from project node_modules via direct import')
15323
- // } else {
15324
- // throw new Error(`better-sqlite3 main file not found at ${betterSqlite3MainPath}`)
15325
- // }
15326
- // }
15327
- // } else {
15328
- // // Fall back to regular import (from SDK's node_modules)
15329
- // const betterSqlite3Module = await import('better-sqlite3')
15330
- // Database = betterSqlite3Module.default || betterSqlite3Module
15331
- // logger('[node/db/Db] Using better-sqlite3 from SDK node_modules')
15332
- // }
15333
- // } catch (importError: any) {
15334
- // logger('[node/db/Db] Error importing better-sqlite3:', importError.message)
15335
- // logger('[node/db/Db] projectDir:', projectDir)
15336
- // logger('[node/db/Db] projectBetterSqlite3Path:', projectBetterSqlite3Path)
15337
- // throw new Error(`Failed to import better-sqlite3: ${importError.message}. Please install better-sqlite3 in your project.`)
15338
- // }
15339
- // OLD CODE: Create Database instance
15340
- // const sqlite = new Database(dbPath)
15341
- //
15342
- // OLD CODE: Create drizzle instance with the Database
15343
- // const {drizzle} = await import('drizzle-orm/better-sqlite3')
15344
- // this.db = drizzle(sqlite, {
15345
- // logger: true,
15346
- // })
15347
- // // NEW CODE: Use libsql instead of better-sqlite3
15348
- // // Resolve @libsql/client from project's node_modules first, then fall back to SDK's node_modules
15349
- // const projectDir = path.dirname(filesDir) // filesDir is .seed, so projectDir is the project root
15350
- // const projectLibsqlClientPath = path.join(projectDir, 'node_modules', '@libsql', 'client')
15351
- // let createClient: any
15352
- // try {
15353
- // const fs = await import('fs')
15354
- // if (fs.existsSync(projectLibsqlClientPath)) {
15355
- // // Try to resolve from project's node_modules using the full path
15356
- // try {
15357
- // // First try using createRequire (works in Node.js)
15358
- // const { createRequire } = await import('module')
15359
- // const projectRequire = createRequire(path.join(projectDir, 'package.json'))
15360
- // const libsqlClientModule = projectRequire('@libsql/client')
15361
- // createClient = libsqlClientModule.createClient || libsqlClientModule.default?.createClient || libsqlClientModule.default
15362
- // logger('[node/db/Db] Using @libsql/client from project node_modules via createRequire')
15363
- // } catch (requireError: any) {
15364
- // // If createRequire fails, try direct import
15365
- // logger('[node/db/Db] createRequire failed, trying direct import:', requireError.message)
15366
- // const libsqlClientModule = await import('@libsql/client')
15367
- // createClient = libsqlClientModule.createClient
15368
- // logger('[node/db/Db] Using @libsql/client from project node_modules via direct import')
15369
- // }
15370
- // } else {
15371
- // // Fall back to regular import (from SDK's node_modules)
15372
- // const libsqlClientModule = await import('@libsql/client')
15373
- // createClient = libsqlClientModule.createClient
15374
- // logger('[node/db/Db] Using @libsql/client from SDK node_modules')
15375
- // }
15376
- // } catch (importError: any) {
15377
- // logger('[node/db/Db] Error importing @libsql/client:', importError.message)
15378
- // logger('[node/db/Db] projectDir:', projectDir)
15379
- // logger('[node/db/Db] projectLibsqlClientPath:', projectLibsqlClientPath)
15380
- // throw new Error(`Failed to import @libsql/client: ${importError.message}. Please install @libsql/client in your project.`)
15381
- // }
15382
- // // Convert file path to file: URL for libsql
15383
- // // If dbPath is already a file: URL, use it as is, otherwise convert it
15384
- // const dbUrl = dbPath.startsWith('file:') ? dbPath : `file:${path.resolve(dbPath)}`
15385
- // // Create libsql client instance
15386
- // const client = createClient({ url: dbUrl })
15387
- // // Create drizzle instance with the libsql client
15388
- // const {drizzle} = await import('drizzle-orm/libsql')
15389
- // this.db = drizzle(client, {
15390
- // logger: true,
15391
- // })
15392
- // if (!this.db) {
15393
- // throw new Error('Db not found')
15394
- // }
15395
15781
  return this.db;
15396
15782
  }
15397
15783
  static async connectToDb(pathToDir) {
@@ -15460,7 +15846,8 @@ class Db extends BaseDb {
15460
15846
  // In drizzle-kit, migrations are generated in the 'out' directory (which is pathToDbDir)
15461
15847
  // migrate(this.db, { migrationsFolder: pathToDbDir })
15462
15848
  // NEW CODE: Use libsql migrator
15463
- const { migrate } = await import('drizzle-orm/libsql/migrator');
15849
+ const migratorMod = await import('drizzle-orm/libsql/migrator');
15850
+ const { migrate } = migratorMod;
15464
15851
  // migrationsFolder should point to the directory containing migration SQL files
15465
15852
  // In drizzle-kit, migrations are generated in the 'out' directory (which is pathToDbDir)
15466
15853
  await migrate(this.db, { migrationsFolder: pathToDbDir });
@@ -16008,7 +16395,7 @@ const getTsImport = async (filePath) => {
16008
16395
 
16009
16396
  // Get the directory of this file to resolve relative paths
16010
16397
  // @ts-ignore - rollup plugin-typescript doesn't recognize import.meta with module: "preserve"
16011
- const __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cjs/index-BeKPbbk0.js', document.baseURI).href)));
16398
+ const __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cjs/index-B95Ng80C.js', document.baseURI).href)));
16012
16399
  path.dirname(__filename$1);
16013
16400
  const commandExists = (command) => {
16014
16401
  try {
@@ -16525,6 +16912,7 @@ exports.getItemData = getItemData;
16525
16912
  exports.getLatestSchemaVersion = getLatestSchemaVersion;
16526
16913
  exports.getModelId = getModelId;
16527
16914
  exports.getModelIdByFileId = getModelIdByFileId;
16915
+ exports.getOwnedAddressesFromDb = getOwnedAddressesFromDb;
16528
16916
  exports.getSchemaForItemProperty = getSchemaForItemProperty;
16529
16917
  exports.getSchemaUidForModel = getSchemaUidForModel;
16530
16918
  exports.getSchemaUidForSchemaDefinition = getSchemaUidForSchemaDefinition;
@@ -16559,4 +16947,4 @@ exports.versions = versions;
16559
16947
  exports.waitForEntityIdle = waitForEntityIdle;
16560
16948
  exports.withSeed = withSeed;
16561
16949
  exports.writeProcessMachine = writeProcessMachine;
16562
- //# sourceMappingURL=index-BeKPbbk0.js.map
16950
+ //# sourceMappingURL=index-B95Ng80C.js.map