@seedprotocol/sdk 0.1.8 → 0.1.11

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 (33) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{index-BeywvMUe.js → index-CXe0BS3G.js} +2 -2
  3. package/dist/index-CXe0BS3G.js.map +1 -0
  4. package/dist/{index-Dg73YrcZ.js → index-Dd2ggBQg.js} +717 -673
  5. package/dist/index-Dd2ggBQg.js.map +1 -0
  6. package/dist/main.js +1 -1
  7. package/dist/{seed-Cqa2atpR.js → seed-CM9XY9k9.js} +3 -3
  8. package/dist/{seed-Cqa2atpR.js.map → seed-CM9XY9k9.js.map} +1 -1
  9. package/dist/{seed-CACUpI2x.js → seed-SjSegIMH.js} +2 -2
  10. package/dist/{seed-CACUpI2x.js.map → seed-SjSegIMH.js.map} +1 -1
  11. package/dist/{seed-CsQB9h6Q.js → seed-T0Gph_yX.js} +3 -3
  12. package/dist/{seed-CsQB9h6Q.js.map → seed-T0Gph_yX.js.map} +1 -1
  13. package/dist/{seed.schema.config-CxqrGPwe.js → seed.schema.config-Dg9Q0kx4.js} +2 -2
  14. package/dist/{seed.schema.config-CxqrGPwe.js.map → seed.schema.config-Dg9Q0kx4.js.map} +1 -1
  15. package/dist/types/src/browser/db/read/getItem.d.ts.map +1 -1
  16. package/dist/types/src/browser/db/read/getItems.d.ts.map +1 -1
  17. package/dist/types/src/browser/db/read.d.ts +2 -1
  18. package/dist/types/src/browser/db/read.d.ts.map +1 -1
  19. package/dist/types/src/browser/events/item/requestAll.d.ts.map +1 -1
  20. package/dist/types/src/browser/item/class.d.ts.map +1 -1
  21. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  22. package/dist/types/src/browser/property/actors/initialize.d.ts.map +1 -1
  23. package/dist/types/src/browser/property/actors/resolveRelatedValue.d.ts.map +1 -1
  24. package/dist/types/src/browser/property/actors/saveValueToDb.d.ts.map +1 -1
  25. package/dist/types/src/browser/property/class.d.ts.map +1 -1
  26. package/dist/types/src/browser/property/propertyMachine.d.ts.map +1 -1
  27. package/dist/types/src/browser/react/index.d.ts +1 -4
  28. package/dist/types/src/browser/react/index.d.ts.map +1 -1
  29. package/dist/types/src/types/item.d.ts +3 -3
  30. package/dist/types/src/types/item.d.ts.map +1 -1
  31. package/package.json +1 -1
  32. package/dist/index-BeywvMUe.js.map +0 -1
  33. package/dist/index-Dg73YrcZ.js.map +0 -1
@@ -3,7 +3,7 @@ import 'reflect-metadata';
3
3
  import { Type } from '@sinclair/typebox';
4
4
  import { fromCallback, createActor, waitFor, setup, assign, emit } from 'xstate';
5
5
  import { fs, configureSingle } from '@zenfs/core';
6
- import { sql, relations, eq, isNull, and } from 'drizzle-orm';
6
+ import { sql, count, max, eq, and, or, isNull, relations } from 'drizzle-orm';
7
7
  import { drizzle } from 'drizzle-orm/sqlite-proxy';
8
8
  import debug from 'debug';
9
9
  import 'dayjs';
@@ -692,6 +692,7 @@ const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
692
692
  const { isRelation, propertyName, storageTransactionId, seedLocalId } = context;
693
693
  if (isRelation) {
694
694
  sendBack({ type: 'isRelatedProperty' });
695
+ sendBack({ type: 'initializeSuccess' });
695
696
  return;
696
697
  }
697
698
  if (!isRelation) {
@@ -814,7 +815,7 @@ const parseEasRelationPropertyName = (easPropertyName) => {
814
815
  };
815
816
  };
816
817
 
817
- sqliteTable('seeds', {
818
+ const seeds = sqliteTable('seeds', {
818
819
  localId: text('local_id').unique(),
819
820
  uid: text('uid'),
820
821
  schemaUid: text('schema_uid'),
@@ -826,7 +827,7 @@ sqliteTable('seeds', {
826
827
  _markedForDeletion: int('_marked_for_deletion'),
827
828
  });
828
829
 
829
- sqliteTable('versions', {
830
+ const versions = sqliteTable('versions', {
830
831
  localId: text('local_id').unique(),
831
832
  uid: text('uid'),
832
833
  seedLocalId: text('seed_local_id'),
@@ -839,7 +840,7 @@ sqliteTable('versions', {
839
840
  attestationRaw: text('attestation_raw'),
840
841
  });
841
842
 
842
- sqliteTable('metadata', {
843
+ const metadata = sqliteTable('metadata', {
843
844
  localId: text('local_id').unique(),
844
845
  uid: text('uid'),
845
846
  propertyName: text('property_name'),
@@ -871,38 +872,21 @@ const appState = sqliteTable('appState', {
871
872
 
872
873
  const getItemsData = (modelName) => __awaiter(void 0, void 0, void 0, function* () {
873
874
  const appDb = getAppDb();
874
- const itemsFromDbQuery = yield appDb.run(sql.raw(`SELECT s.local_id,
875
- s.uid,
876
- s.schema_uid,
877
- s.attestation_created_at,
878
- s.created_at,
879
- COUNT(v.local_id) as versions_count,
880
- MAX(v.attestation_created_at) as last_version_published_at,
881
- MAX(v.created_at) as last_local_update_at
882
- FROM seeds s
883
- JOIN versions v ON s.local_id = v.seed_local_id
884
- WHERE s.type = '${modelName.toLowerCase()}'
885
- AND (_marked_for_deletion IS NULL
886
- OR _marked_for_deletion = 0)
887
- GROUP BY s.local_id;`));
888
- if (!itemsFromDbQuery ||
889
- !itemsFromDbQuery.rows ||
890
- itemsFromDbQuery.rows.length === 0) {
891
- return [];
892
- }
893
- const itemsData = [];
894
- for (const itemDbValues of itemsFromDbQuery.rows) {
895
- itemsData.push({
896
- seedLocalId: itemDbValues[0],
897
- seedUid: itemDbValues[1],
898
- schemaUid: itemDbValues[2],
899
- attestationCreatedAt: itemDbValues[3],
900
- createdAt: itemDbValues[4],
901
- versionsCount: itemDbValues[5],
902
- lastVersionPublishedAt: itemDbValues[6],
903
- lastLocalUpdateAt: itemDbValues[7],
904
- });
905
- }
875
+ const itemsData = (yield appDb
876
+ .select({
877
+ seedLocalId: seeds.localId,
878
+ seedUid: seeds.uid,
879
+ schemaUid: seeds.schemaUid,
880
+ modelName: sql `${modelName}`,
881
+ attestationCreatedAt: seeds.attestationCreatedAt,
882
+ versionsCount: count(versions.localId),
883
+ lastVersionPublishedAt: max(versions.attestationCreatedAt),
884
+ lastLocalUpdateAt: max(versions.createdAt),
885
+ })
886
+ .from(seeds)
887
+ .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
888
+ .where(and(eq(seeds.type, modelName.toLowerCase()), or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0))))
889
+ .groupBy(seeds.localId));
906
890
  return itemsData;
907
891
  });
908
892
 
@@ -951,36 +935,37 @@ const getPropertyData = (propertyName, seedLocalId) => __awaiter(void 0, void 0,
951
935
  updatedAt: row[12],
952
936
  };
953
937
  });
938
+ const seedUidToStorageTransactionId = new Map();
954
939
  const getStorageTransactionIdForSeedUid = (seedUid) => __awaiter(void 0, void 0, void 0, function* () {
955
- const storageTransactionIdStatement = `SELECT property_value,
956
- MAX(attestation_created_at),
957
- ref_resolved_display_value,
958
- ref_resolved_value,
959
- ref_seed_type,
960
- eas_data_type
961
- FROM metadata
962
- WHERE (
963
- seed_uid = '${seedUid}'
964
- AND property_name = 'storageTransactionId'
965
- );
966
- `;
967
- const { rows } = yield runQueryForStatement(storageTransactionIdStatement);
968
- if (!rows || rows.length === 0 || !rows[0][0]) {
940
+ if (seedUidToStorageTransactionId.has(seedUid)) {
941
+ return seedUidToStorageTransactionId.get(seedUid);
942
+ }
943
+ const appDb = getAppDb();
944
+ const results = (yield appDb
945
+ .select({
946
+ storageTransactionId: metadata.propertyValue,
947
+ })
948
+ .from(metadata)
949
+ .where(and(eq(metadata.seedUid, seedUid), eq(metadata.propertyName, 'storageTransactionId'))));
950
+ if (!results || results.length === 0) {
969
951
  return;
970
952
  }
971
- return rows[0][0];
953
+ seedUidToStorageTransactionId.set(seedUid, results[0].storageTransactionId);
954
+ return results[0].storageTransactionId;
972
955
  });
973
956
  const getRelationValueData = (propertyValue) => __awaiter(void 0, void 0, void 0, function* () {
974
- const propertyValueStatement = `SELECT property_value,
975
- MAX(attestation_created_at),
976
- ref_resolved_display_value,
977
- ref_resolved_value,
978
- ref_seed_type,
979
- eas_data_type
980
- FROM metadata
981
- WHERE property_value = '${propertyValue}';
982
- `;
983
- const { rows } = yield runQueryForStatement(propertyValueStatement);
957
+ const appDb = getAppDb();
958
+ const rows = (yield appDb
959
+ .select({
960
+ propertyValue: metadata.propertyValue,
961
+ attestationCreatedAt: max(metadata.attestationCreatedAt),
962
+ refResolvedDisplayValue: metadata.refResolvedDisplayValue,
963
+ refResolvedValue: metadata.refResolvedValue,
964
+ refSeedType: metadata.refSeedType,
965
+ easDataType: metadata.easDataType,
966
+ })
967
+ .from(metadata)
968
+ .where(eq(metadata.propertyValue, propertyValue)));
984
969
  if (!rows || rows.length === 0) {
985
970
  return;
986
971
  }
@@ -1029,16 +1014,50 @@ const getExistingItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ see
1029
1014
  return existingItem;
1030
1015
  });
1031
1016
 
1017
+ const storageTransactionIdToContentUrl = new Map();
1018
+ const refResolvedValueToContentUrl = new Map();
1019
+ const seedUidToContentUrl = new Map();
1032
1020
  const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
1033
1021
  const { isRelation, propertyValue, propertyName, seedUid, propertyRecordSchema, seedLocalId, schemaUid, } = context;
1034
- getAppDb();
1035
1022
  const _resolveRelatedValue = () => __awaiter(void 0, void 0, void 0, function* () {
1036
1023
  if (!propertyValue || !isRelation) {
1037
1024
  return;
1038
1025
  }
1026
+ if (seedUidToContentUrl.has(propertyValue)) {
1027
+ const contentUrl = seedUidToContentUrl.get(propertyValue);
1028
+ sendBack({
1029
+ type: 'updateRenderValue',
1030
+ renderValue: contentUrl,
1031
+ });
1032
+ sendBack({
1033
+ type: 'resolvingRelatedValueSuccess',
1034
+ resolvedDisplayValue: contentUrl,
1035
+ });
1036
+ return true;
1037
+ }
1038
+ if (Array.isArray(propertyValue)) {
1039
+ // TODO: Handle array of seedUids
1040
+ return;
1041
+ }
1039
1042
  const storageTransactionId = yield getStorageTransactionIdForSeedUid(propertyValue);
1040
1043
  if (storageTransactionId) {
1044
+ if (storageTransactionIdToContentUrl.has(storageTransactionId)) {
1045
+ const contentUrl = storageTransactionIdToContentUrl.get(storageTransactionId);
1046
+ sendBack({
1047
+ type: 'updateRenderValue',
1048
+ renderValue: contentUrl,
1049
+ });
1050
+ sendBack({
1051
+ type: 'resolvingRelatedValueSuccess',
1052
+ resolvedDisplayValue: contentUrl,
1053
+ resolvedValue: storageTransactionId,
1054
+ });
1055
+ return true;
1056
+ }
1041
1057
  const contentUrl = yield convertTxIdToImageSrc(storageTransactionId);
1058
+ if (contentUrl) {
1059
+ seedUidToContentUrl.set(propertyValue, contentUrl);
1060
+ }
1042
1061
  sendBack({
1043
1062
  type: 'updateRenderValue',
1044
1063
  renderValue: contentUrl,
@@ -1052,20 +1071,31 @@ const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
1052
1071
  }
1053
1072
  const relationValueData = yield getRelationValueData(propertyValue);
1054
1073
  if (relationValueData) {
1055
- const propertyValueFromDb = relationValueData[0];
1056
- const refResolvedValue = relationValueData[3];
1057
- relationValueData[4];
1058
- relationValueData[5];
1074
+ const { refResolvedValue } = relationValueData;
1075
+ const propertyValueFromDb = relationValueData.propertyValue;
1059
1076
  // This handles a local-only relation value and resolves from the filesystem
1060
1077
  if (refResolvedValue &&
1061
1078
  propertyRecordSchema.dataType === 'Relation' &&
1062
1079
  propertyValueFromDb.length === 10 &&
1063
1080
  propertyRecordSchema.ref) {
1081
+ if (refResolvedValueToContentUrl.has(refResolvedValue)) {
1082
+ const contentUrl = refResolvedValueToContentUrl.get(refResolvedValue);
1083
+ sendBack({
1084
+ type: 'updateRenderValue',
1085
+ renderValue: contentUrl,
1086
+ });
1087
+ sendBack({
1088
+ type: 'resolvingRelatedValueSuccess',
1089
+ resolvedDisplayValue: contentUrl,
1090
+ });
1091
+ return true;
1092
+ }
1064
1093
  const fileExists = yield fs.promises.exists('/files/images/' + refResolvedValue);
1065
1094
  if (fileExists) {
1066
1095
  const fileContents = yield fs.promises.readFile('/files/images/' + refResolvedValue);
1067
1096
  const fileHandler = new File([fileContents], refResolvedValue);
1068
1097
  const contentUrl = URL.createObjectURL(fileHandler);
1098
+ refResolvedValueToContentUrl.set(refResolvedValue, contentUrl);
1069
1099
  sendBack({
1070
1100
  type: 'updateRenderValue',
1071
1101
  renderValue: contentUrl,
@@ -1080,11 +1110,21 @@ const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
1080
1110
  if (typeof propertyValueFromDb === 'string') {
1081
1111
  // Check files for a filename that matches the propertyValue
1082
1112
  if (propertyRecordSchema.dataType === 'ImageSrc') {
1083
- const imageFileExists = yield fs.promises.exists(`/images/${propertyValue}`);
1084
- const fileContents = yield fs.promises.readFile(`/images/${propertyValue}`);
1085
- const fileHandler = new File([fileContents], propertyValue);
1086
- const contentUrl = URL.createObjectURL(fileHandler);
1087
- if (imageFileExists) {
1113
+ let contentUrl;
1114
+ if (storageTransactionIdToContentUrl.has(propertyValueFromDb)) {
1115
+ contentUrl =
1116
+ storageTransactionIdToContentUrl.get(propertyValueFromDb);
1117
+ }
1118
+ if (!contentUrl) {
1119
+ const imageFileExists = yield fs.promises.exists(`/images/${propertyValue}`);
1120
+ if (imageFileExists) {
1121
+ const fileContents = yield fs.promises.readFile(`/images/${propertyValue}`);
1122
+ const fileHandler = new File([fileContents], propertyValue);
1123
+ contentUrl = URL.createObjectURL(fileHandler);
1124
+ storageTransactionIdToContentUrl.set(propertyValueFromDb, contentUrl);
1125
+ }
1126
+ }
1127
+ if (contentUrl) {
1088
1128
  sendBack({
1089
1129
  type: 'updateRenderValue',
1090
1130
  renderValue: contentUrl,
@@ -1100,12 +1140,15 @@ const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
1100
1140
  }
1101
1141
  });
1102
1142
  _resolveRelatedValue().then((success) => {
1103
- if (!success) {
1104
- sendBack({
1105
- type: 'resolvingRelatedValueDone',
1106
- });
1107
- }
1108
- return;
1143
+ // if (success) {
1144
+ // sendBack({
1145
+ // type: 'resolvingRelatedValueDone',
1146
+ // })
1147
+ // }
1148
+ // return
1149
+ sendBack({
1150
+ type: 'resolvingRelatedValueDone',
1151
+ });
1109
1152
  });
1110
1153
  });
1111
1154
  // const eventKey = `storage.transaction.${initialValue}.contentUrl.response`
@@ -1528,164 +1571,6 @@ const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* ()
1528
1571
  return JSON.parse(addressArrayString);
1529
1572
  });
1530
1573
 
1531
- const logger$c = debug('app:property:actors:hydrateFromDb');
1532
- const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1533
- const { seedUid, seedLocalId, propertyName: propertyNameRaw, propertyValue, propertyRecordSchema, itemModelName, } = context;
1534
- let propertyName = propertyNameRaw;
1535
- if (propertyRecordSchema &&
1536
- propertyRecordSchema.ref &&
1537
- propertyRecordSchema.dataType === 'Relation' &&
1538
- !propertyNameRaw.endsWith('Id')) {
1539
- propertyName = propertyNameRaw + 'Id';
1540
- }
1541
- if (propertyRecordSchema &&
1542
- propertyRecordSchema.ref &&
1543
- propertyRecordSchema.dataType === 'List' &&
1544
- !propertyNameRaw.endsWith('Ids')) {
1545
- propertyName = propertyNameRaw + 'Ids';
1546
- }
1547
- const _hydrateFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
1548
- const db = getAppDb();
1549
- let hydrateQuery;
1550
- let safeValue = propertyValue;
1551
- let propertyNameQueryString = `property_name = '${propertyName}'`;
1552
- if (safeValue && typeof propertyValue === 'string') {
1553
- safeValue = escapeSqliteString(propertyValue);
1554
- }
1555
- if (propertyRecordSchema &&
1556
- propertyRecordSchema.ref &&
1557
- propertyRecordSchema.dataType === 'Relation') {
1558
- let missingPropertyNameVariant;
1559
- if (propertyName.endsWith('Id')) {
1560
- missingPropertyNameVariant = propertyName.slice(0, -2);
1561
- }
1562
- if (!propertyName.endsWith('Id')) {
1563
- missingPropertyNameVariant = propertyName + 'Id';
1564
- }
1565
- propertyNameQueryString += ` OR property_name = '${missingPropertyNameVariant}'`;
1566
- }
1567
- if (seedUid && !seedLocalId) {
1568
- hydrateQuery = yield db.run(sql.raw(`SELECT local_id,
1569
- uid,
1570
- property_name,
1571
- property_value,
1572
- seed_local_id,
1573
- seed_uid,
1574
- schema_uid,
1575
- ref_resolved_value,
1576
- ref_resolved_display_value
1577
- FROM metadata
1578
- WHERE seed_uid = '${seedUid}'
1579
- AND (${propertyNameQueryString})
1580
- ORDER BY COALESCE(attestation_created_at, created_at) DESC;
1581
- `));
1582
- }
1583
- if (seedUid && seedLocalId) {
1584
- hydrateQuery = yield db.run(sql.raw(`SELECT local_id,
1585
- uid,
1586
- property_name,
1587
- property_value,
1588
- seed_local_id,
1589
- seed_uid,
1590
- schema_uid,
1591
- ref_resolved_value,
1592
- ref_resolved_display_value
1593
- FROM metadata
1594
- WHERE seed_local_id = '${seedLocalId}'
1595
- AND (${propertyNameQueryString})
1596
- AND seed_uid = '${seedUid}'
1597
- ORDER BY COALESCE(attestation_created_at, created_at) DESC;
1598
- `));
1599
- }
1600
- if (!seedUid && seedLocalId) {
1601
- hydrateQuery = yield db.run(sql.raw(`SELECT local_id,
1602
- uid,
1603
- property_name,
1604
- property_value,
1605
- seed_local_id,
1606
- seed_uid,
1607
- schema_uid,
1608
- ref_resolved_value,
1609
- ref_resolved_display_value
1610
- FROM metadata
1611
- WHERE seed_local_id = '${seedLocalId}'
1612
- AND (${propertyNameQueryString})
1613
- ORDER BY COALESCE(attestation_created_at, created_at) DESC;
1614
- `));
1615
- }
1616
- if (hydrateQuery && hydrateQuery.rows && hydrateQuery.rows.length > 0) {
1617
- const firstRow = hydrateQuery.rows[0];
1618
- const localId = firstRow[0];
1619
- const uid = firstRow[1];
1620
- const propertyNameFromDb = firstRow[2];
1621
- const propertyValueFromDb = firstRow[3];
1622
- const seedLocalIdFromDb = firstRow[4];
1623
- const seedUidFromDb = firstRow[5];
1624
- const schemaUidFromDb = firstRow[6];
1625
- const refResolvedValue = firstRow[7];
1626
- const refResolvedDisplayValue = firstRow[8];
1627
- if (propertyNameFromDb !== propertyName) {
1628
- logger$c(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
1629
- }
1630
- if (propertyValueFromDb !== propertyValue) {
1631
- logger$c(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
1632
- }
1633
- if (seedLocalIdFromDb !== seedLocalId) {
1634
- logger$c(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
1635
- }
1636
- if (seedUidFromDb !== seedUid) {
1637
- logger$c(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
1638
- }
1639
- sendBack({
1640
- type: 'updateContext',
1641
- localId,
1642
- uid,
1643
- propertyName: propertyNameFromDb,
1644
- propertyValue: propertyValueFromDb,
1645
- seedLocalId: seedLocalIdFromDb,
1646
- seedUid: seedUidFromDb,
1647
- schemaUid: schemaUidFromDb,
1648
- resolveValue: refResolvedValue,
1649
- resolveDisplayValue: refResolvedDisplayValue,
1650
- renderValue: refResolvedDisplayValue,
1651
- });
1652
- if (propertyNameFromDb === 'storageTransactionId') {
1653
- const { Item } = yield import('./index-BeywvMUe.js');
1654
- const item = yield Item.find({
1655
- seedLocalId,
1656
- modelName: itemModelName,
1657
- });
1658
- if (item) {
1659
- for (const [propertyName, property] of Object.entries(item.properties)) {
1660
- if (propertyName === 'html' &&
1661
- propertyValueFromDb &&
1662
- propertyValueFromDb.length === 43) {
1663
- const htmlFilePath = `/files/html/${propertyValueFromDb}.html`;
1664
- const exists = yield fs.promises.exists(htmlFilePath);
1665
- if (!exists) {
1666
- logger$c(`HTML file does not exist for Property.${localId} at ${htmlFilePath}`);
1667
- return;
1668
- }
1669
- const renderValue = yield fs.promises
1670
- .readFile(htmlFilePath, 'utf8')
1671
- .catch((error) => {
1672
- logger$c('Error reading html file', error);
1673
- });
1674
- property
1675
- .getService()
1676
- .send({ type: 'updateRenderValue', renderValue });
1677
- return;
1678
- }
1679
- }
1680
- }
1681
- }
1682
- }
1683
- });
1684
- _hydrateFromDb().then(() => {
1685
- sendBack({ type: 'hydrateFromDbSuccess' });
1686
- });
1687
- });
1688
-
1689
1574
  const eventEmitter = new EventEmitter();
1690
1575
 
1691
1576
  const APP_DB_CONFIG = 'browser.app.db.config.ts';
@@ -1732,7 +1617,7 @@ const internalPropertyNames = [
1732
1617
  ];
1733
1618
 
1734
1619
  var _a$2;
1735
- const logger$b = debug('app:property:class');
1620
+ const logger$c = debug('app:property:class');
1736
1621
  const namesThatEndWithId = [];
1737
1622
  class ItemProperty {
1738
1623
  // private constructor(localIdOrUid) {
@@ -1780,7 +1665,7 @@ class ItemProperty {
1780
1665
  serviceInput.propertyValue = JSON.parse(propertyValue);
1781
1666
  }
1782
1667
  catch (e) {
1783
- logger$b('List property value is not JSON', e);
1668
+ logger$c('List property value is not JSON', e);
1784
1669
  }
1785
1670
  }
1786
1671
  const propertyNameSingular = pluralize(propertyName, 1);
@@ -1834,47 +1719,50 @@ class ItemProperty {
1834
1719
  }
1835
1720
  if (skipTransform && !this._alias) ;
1836
1721
  this._subject.next(renderValue);
1722
+ // eventEmitter.emit(
1723
+ // `item.${itemModelName},${seedUid || seedLocalId}.update`,
1724
+ // )
1837
1725
  // this._lastRenderedValue = renderValue
1838
1726
  });
1839
1727
  this._service.start();
1840
1728
  }
1841
1729
  _updateResponseListener(event) {
1842
- logger$b(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1730
+ logger$c(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1843
1731
  }
1844
1732
  static create(props) {
1845
1733
  const { propertyName, seedLocalId, uid } = props;
1846
1734
  if (seedLocalId && propertyName) {
1847
1735
  const cacheKey = ItemProperty.cacheKey(seedLocalId, propertyName);
1848
- if (this.instanceCache.has(cacheKey)) {
1849
- const { instance, refCount } = this.instanceCache.get(cacheKey);
1850
- this.instanceCache.set(cacheKey, {
1736
+ if (ItemProperty.instanceCache.has(cacheKey)) {
1737
+ const { instance, refCount } = ItemProperty.instanceCache.get(cacheKey);
1738
+ ItemProperty.instanceCache.set(cacheKey, {
1851
1739
  instance,
1852
1740
  refCount: refCount + 1,
1853
1741
  });
1854
- if (instance.status === 'idle') {
1855
- instance.getService().send({ type: 'refresh' });
1856
- }
1857
- if (seedLocalId === 'R4RYj2pYIQ' && propertyName === 'html') {
1858
- logger$b('[property/class] [create] [R4RYj2pYIQ] returning cached instance', instance.getService().getSnapshot().context);
1859
- }
1860
1742
  return instance;
1861
1743
  }
1744
+ if (!ItemProperty.instanceCache.has(cacheKey)) {
1745
+ const newInstance = new ItemProperty(props);
1746
+ ItemProperty.instanceCache.set(cacheKey, {
1747
+ instance: newInstance,
1748
+ refCount: 1,
1749
+ });
1750
+ return newInstance;
1751
+ }
1862
1752
  }
1863
1753
  if (uid) {
1864
1754
  if (this.instanceCache.has(uid)) {
1865
1755
  const { instance, refCount } = this.instanceCache.get(uid);
1866
1756
  this.instanceCache.set(uid, { instance, refCount: refCount + 1 });
1867
- if (seedLocalId === 'R4RYj2pYIQ' && propertyName === 'html') {
1868
- logger$b('[property/class] [create] [uid] [R4RYj2pYIQ] returning cached instance', instance.getService().getSnapshot().context);
1869
- }
1870
1757
  return instance;
1871
1758
  }
1759
+ if (!this.instanceCache.has(uid)) {
1760
+ const newInstance = new ItemProperty(props);
1761
+ this.instanceCache.set(uid, { instance: newInstance, refCount: 1 });
1762
+ return newInstance;
1763
+ }
1872
1764
  }
1873
- const newInstance = new ItemProperty(props);
1874
- if (props.seedLocalId === 'R4RYj2pYIQ' && propertyName === 'html') {
1875
- logger$b('[property/class] [create] [R4RYj2pYIQ] returning new instance', props, newInstance.getService().getSnapshot().context);
1876
- }
1877
- return newInstance;
1765
+ return new ItemProperty(props);
1878
1766
  }
1879
1767
  static find(_b) {
1880
1768
  return __awaiter(this, arguments, void 0, function* ({ propertyName, seedLocalId, }) {
@@ -1975,7 +1863,7 @@ class ItemProperty {
1975
1863
  }
1976
1864
  unload() {
1977
1865
  this._service.stop();
1978
- logger$b(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1866
+ logger$c(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1979
1867
  eventEmitter.removeListener(this._updateResponseEvent, this._updateResponseListener);
1980
1868
  }
1981
1869
  }
@@ -2069,7 +1957,7 @@ const getContentUrlFromPath = (path) => __awaiter(void 0, void 0, void 0, functi
2069
1957
  return URL.createObjectURL(fileHandler);
2070
1958
  });
2071
1959
 
2072
- const logger$a = debug('app:global:actors');
1960
+ const logger$b = debug('app:global:actors');
2073
1961
  const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2074
1962
  const { internalService, models, endpoints } = context;
2075
1963
  const { addresses } = event;
@@ -2090,7 +1978,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2090
1978
  const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
2091
1979
  return new Promise((resolve) => {
2092
1980
  internalSubscription = internalService.subscribe((snapshot) => {
2093
- logger$a('[sdk] [internal] snapshot', snapshot);
1981
+ logger$b('[sdk] [internal] snapshot', snapshot);
2094
1982
  if (snapshot.value === 'ready') {
2095
1983
  resolve();
2096
1984
  }
@@ -2099,10 +1987,10 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2099
1987
  });
2100
1988
  });
2101
1989
  _initFileSystem().then(() => {
2102
- logger$a('[global/actors] File system initialized');
1990
+ logger$b('[global/actors] File system initialized');
2103
1991
  });
2104
1992
  _initInternal().then(() => {
2105
- logger$a('[global/actors] Internal initialized');
1993
+ logger$b('[global/actors] Internal initialized');
2106
1994
  sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
2107
1995
  internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
2108
1996
  });
@@ -2123,12 +2011,12 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2123
2011
  if (!models$1) {
2124
2012
  return;
2125
2013
  }
2126
- const { models: SeedModels } = yield import('./seed.schema.config-CxqrGPwe.js');
2014
+ const { models: SeedModels } = yield import('./seed.schema.config-Dg9Q0kx4.js');
2127
2015
  const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
2128
2016
  let hasModelsInDb = false;
2129
2017
  const schemaDefsByModelName = new Map();
2130
2018
  for (const [modelName, _] of Object.entries(allModels)) {
2131
- logger$a('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2019
+ logger$b('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2132
2020
  let foundModel;
2133
2021
  const foundModelsQuery = yield sdkConfigDb
2134
2022
  .select()
@@ -2138,7 +2026,7 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2138
2026
  yield sdkConfigDb.insert(models).values({
2139
2027
  name: modelName,
2140
2028
  });
2141
- logger$a('[global/actors] [addModelsToDb] inserted model:', modelName);
2029
+ logger$b('[global/actors] [addModelsToDb] inserted model:', modelName);
2142
2030
  const foundModels = yield sdkConfigDb
2143
2031
  .select({
2144
2032
  id: models.id,
@@ -2222,7 +2110,7 @@ const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } })
2222
2110
  if (!model) {
2223
2111
  throw new Error(`Model ${modelName} not found`);
2224
2112
  }
2225
- logger$a('[service/actor] [getSchemaForModel] model:', model);
2113
+ logger$b('[service/actor] [getSchemaForModel] model:', model);
2226
2114
  sendBack({ type: 'schemaForModel', schema: model.schema });
2227
2115
  return () => { };
2228
2116
  });
@@ -2276,7 +2164,7 @@ class SqliteConnectionManager {
2276
2164
  }
2277
2165
  }
2278
2166
 
2279
- const logger$9 = debug('app:services:internal:helpers');
2167
+ const logger$a = debug('app:services:internal:helpers');
2280
2168
  /**
2281
2169
  * Recursively create directories if they don't exist.
2282
2170
  * @param {string} dirPath - The directory path to create.
@@ -2352,7 +2240,7 @@ const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, f
2352
2240
  if (JSON.stringify(error).includes('File exists')) {
2353
2241
  yield fs.promises.readFile(localFilePath, 'utf-8');
2354
2242
  }
2355
- logger$9(`[Error] Failed to download file from ${url}:`, error);
2243
+ logger$a(`[Error] Failed to download file from ${url}:`, error);
2356
2244
  }
2357
2245
  busy = false;
2358
2246
  });
@@ -2390,7 +2278,7 @@ const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePat
2390
2278
  const fileList = yield fetchDirectory(filePaths);
2391
2279
  yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
2392
2280
  yield confirmFilesExist(fileList);
2393
- logger$9('[syncDbFiles] Files synced!');
2281
+ logger$a('[syncDbFiles] Files synced!');
2394
2282
  });
2395
2283
 
2396
2284
  const uploadBinaryData = fromCallback(({ sendBack, receive, input }) => { });
@@ -2700,7 +2588,7 @@ const getArweave = () => {
2700
2588
  });
2701
2589
  };
2702
2590
 
2703
- const logger$8 = debug('app:files:download');
2591
+ const logger$9 = debug('app:files:download');
2704
2592
  const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
2705
2593
  yield syncDbFiles(endpoints);
2706
2594
  eventEmitter.emit('fs.downloadAll.success', { eventId });
@@ -2770,7 +2658,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
2770
2658
  try {
2771
2659
  const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
2772
2660
  if (res.status !== 200) {
2773
- logger$8(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
2661
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
2774
2662
  excludedTransactions.add(transactionId);
2775
2663
  yield writeAppState(seedDb, 'excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
2776
2664
  continue;
@@ -2784,7 +2672,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
2784
2672
  console.error(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`, error);
2785
2673
  });
2786
2674
  if (!dataString) {
2787
- logger$8(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
2675
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
2788
2676
  }
2789
2677
  let contentType = identifyString(dataString);
2790
2678
  if (contentType !== 'json' &&
@@ -2792,7 +2680,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
2792
2680
  contentType !== 'html') {
2793
2681
  const possibleImageType = getImageDataType(dataString);
2794
2682
  if (!possibleImageType) {
2795
- logger$8(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
2683
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
2796
2684
  continue;
2797
2685
  }
2798
2686
  contentType = possibleImageType;
@@ -2855,7 +2743,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
2855
2743
  }
2856
2744
  }
2857
2745
  catch (error) {
2858
- logger$8(error);
2746
+ logger$9(error);
2859
2747
  }
2860
2748
  }
2861
2749
  });
@@ -2901,7 +2789,7 @@ const isFsInitialized = () => {
2901
2789
  return isInitialized;
2902
2790
  };
2903
2791
 
2904
- const logger$7 = debug('app:internal:actors');
2792
+ const logger$8 = debug('app:internal:actors');
2905
2793
  let sqliteWasmClient;
2906
2794
  let manager;
2907
2795
  const validateInput = fromCallback(({ sendBack, input: { event } }) => {
@@ -2954,12 +2842,12 @@ const prepareDb = fromCallback(({ sendBack, input: { event, context } }) => {
2954
2842
  });
2955
2843
  const configureFs = fromCallback(({ sendBack, input: { context } }) => {
2956
2844
  const { endpoints, seedDbService, appDbService, sdkDbService } = context;
2957
- logger$7('[internal/actors] [configureFs] Configuring FS');
2845
+ logger$8('[internal/actors] [configureFs] Configuring FS');
2958
2846
  const services = [seedDbService, appDbService, sdkDbService];
2959
2847
  const _configureFs = () => __awaiter(void 0, void 0, void 0, function* () {
2960
- logger$7('[internal/actors] [configureFs] calling _configureFs');
2961
- logger$7('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
2962
- logger$7('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
2848
+ logger$8('[internal/actors] [configureFs] calling _configureFs');
2849
+ logger$8('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
2850
+ logger$8('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
2963
2851
  yield waitForEvent({
2964
2852
  req: {
2965
2853
  eventLabel: 'fs.downloadAll.request',
@@ -2991,7 +2879,7 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
2991
2879
  // }, 200)
2992
2880
  // })
2993
2881
  })));
2994
- logger$7('[internal/actors] [configureFs] fs configured!');
2882
+ logger$8('[internal/actors] [configureFs] fs configured!');
2995
2883
  });
2996
2884
  // Some of our dependencies use fs sync functions, which don't work with
2997
2885
  // OPFS. ZenFS creates an async cache of all files so that the sync functions
@@ -3077,14 +2965,14 @@ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
3077
2965
  },
3078
2966
  setWhere: sql `key = 'addresses'`,
3079
2967
  });
3080
- logger$7('[sdk] [internal/actors] Should be done saving');
2968
+ logger$8('[sdk] [internal/actors] Should be done saving');
3081
2969
  }
3082
2970
  catch (error) {
3083
2971
  console.error('Error saving config:', error);
3084
2972
  }
3085
2973
  });
3086
2974
  _saveConfig().then(() => {
3087
- logger$7('[sdk] [internal/actors] Successfully saved config');
2975
+ logger$8('[sdk] [internal/actors] Successfully saved config');
3088
2976
  return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
3089
2977
  });
3090
2978
  return () => { };
@@ -3109,7 +2997,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
3109
2997
  });
3110
2998
  _loadAppDb().then(() => {
3111
2999
  sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
3112
- logger$7('[sdk] [internal/actors] Successfully loaded app DB');
3000
+ logger$8('[sdk] [internal/actors] Successfully loaded app DB');
3113
3001
  });
3114
3002
  return () => {
3115
3003
  if (subscription) {
@@ -3119,7 +3007,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
3119
3007
  });
3120
3008
  const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
3121
3009
  const { sdkDbService } = context;
3122
- logger$7('[sdk] [internal/actors] Loading SDK DB');
3010
+ logger$8('[sdk] [internal/actors] Loading SDK DB');
3123
3011
  let subscription;
3124
3012
  const _loadSdkDb = () => __awaiter(void 0, void 0, void 0, function* () {
3125
3013
  return new Promise((resolve) => {
@@ -3142,7 +3030,7 @@ const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
3142
3030
  });
3143
3031
  _loadSdkDb().then(() => {
3144
3032
  sendBack({ type: INTERNAL_LOADING_SDK_DB_SUCCESS });
3145
- logger$7('[sdk] [internal/actors] Successfully loaded SDK DB');
3033
+ logger$8('[sdk] [internal/actors] Successfully loaded SDK DB');
3146
3034
  });
3147
3035
  return () => {
3148
3036
  if (subscription) {
@@ -3151,7 +3039,7 @@ const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
3151
3039
  };
3152
3040
  });
3153
3041
 
3154
- const logger$6 = debug('app:services:db:machine');
3042
+ const logger$7 = debug('app:services:db:machine');
3155
3043
  const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
3156
3044
  const dbMachine = setup({
3157
3045
  types: {
@@ -3172,7 +3060,7 @@ const dbMachine = setup({
3172
3060
  [DB_WAITING_FOR_FILES_RECEIVED]: {
3173
3061
  actions: assign({
3174
3062
  hasFiles: ({ event }) => {
3175
- logger$6('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
3063
+ logger$7('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
3176
3064
  return true;
3177
3065
  },
3178
3066
  }),
@@ -3181,8 +3069,8 @@ const dbMachine = setup({
3181
3069
  target: `.${CHECKING_STATUS}`,
3182
3070
  actions: assign({
3183
3071
  hasFiles: ({ context, event }) => {
3184
- logger$6('[db/machine] updateHasFiles event:', event);
3185
- logger$6('[db/machine] updateHasFiles context:', context);
3072
+ logger$7('[db/machine] updateHasFiles event:', event);
3073
+ logger$7('[db/machine] updateHasFiles context:', context);
3186
3074
  return event.hasFiles;
3187
3075
  },
3188
3076
  }),
@@ -3303,7 +3191,7 @@ const dbMachine = setup({
3303
3191
  },
3304
3192
  });
3305
3193
 
3306
- const logger$5 = debug('app:services:internal:machine');
3194
+ const logger$6 = debug('app:services:internal:machine');
3307
3195
  createBrowserInspector({
3308
3196
  autoStart: false,
3309
3197
  });
@@ -3465,7 +3353,7 @@ const internalMachine = setup({
3465
3353
  [INTERNAL_LOADING_APP_DB_SUCCESS]: {
3466
3354
  target: 'appDbLoaded',
3467
3355
  actions: () => {
3468
- logger$5('[sdk] [internal/index] App DB loaded!');
3356
+ logger$6('[sdk] [internal/index] App DB loaded!');
3469
3357
  },
3470
3358
  },
3471
3359
  },
@@ -3477,7 +3365,7 @@ const internalMachine = setup({
3477
3365
  appDbLoaded: {
3478
3366
  type: 'final',
3479
3367
  entry: () => {
3480
- logger$5('[sdk] [internal/index] Entered appDbLoaded!');
3368
+ logger$6('[sdk] [internal/index] Entered appDbLoaded!');
3481
3369
  },
3482
3370
  },
3483
3371
  },
@@ -3490,7 +3378,7 @@ const internalMachine = setup({
3490
3378
  [INTERNAL_LOADING_SDK_DB_SUCCESS]: {
3491
3379
  target: 'sdkConfigDbLoaded',
3492
3380
  actions: () => {
3493
- logger$5('[sdk] [internal/index] SDK Config DB loaded!');
3381
+ logger$6('[sdk] [internal/index] SDK Config DB loaded!');
3494
3382
  },
3495
3383
  },
3496
3384
  },
@@ -3502,7 +3390,7 @@ const internalMachine = setup({
3502
3390
  sdkConfigDbLoaded: {
3503
3391
  type: 'final',
3504
3392
  entry: () => {
3505
- logger$5('[sdk] [internal/index] Entered sdkConfigDbLoaded!');
3393
+ logger$6('[sdk] [internal/index] Entered sdkConfigDbLoaded!');
3506
3394
  },
3507
3395
  },
3508
3396
  },
@@ -3511,7 +3399,7 @@ const internalMachine = setup({
3511
3399
  onDone: {
3512
3400
  target: 'ready',
3513
3401
  actions: () => {
3514
- logger$5('[sdk] [internal/index] All DBs loaded! Should be headed to ready');
3402
+ logger$6('[sdk] [internal/index] All DBs loaded! Should be headed to ready');
3515
3403
  eventEmitter.emit('allDbsLoaded');
3516
3404
  },
3517
3405
  },
@@ -3523,7 +3411,7 @@ const internalMachine = setup({
3523
3411
  },
3524
3412
  ready: {
3525
3413
  entry: () => {
3526
- logger$5('[sdk] [internal/index] Ready!');
3414
+ logger$6('[sdk] [internal/index] Ready!');
3527
3415
  },
3528
3416
  meta: {
3529
3417
  displayText: "Crossing the t's ...",
@@ -3538,7 +3426,7 @@ const internalMachine = setup({
3538
3426
  },
3539
3427
  },
3540
3428
  entry: () => {
3541
- logger$5('[sdk] [internal/index] Error!');
3429
+ logger$6('[sdk] [internal/index] Error!');
3542
3430
  },
3543
3431
  meta: {
3544
3432
  displayText: 'Whoops! Something went wrong.',
@@ -3745,7 +3633,7 @@ const fetchDbData = fromCallback(({ sendBack, input: { context } }) => {
3745
3633
  return () => { };
3746
3634
  });
3747
3635
 
3748
- const logger$4 = debug('app:allItemsActors:fetchSeeds');
3636
+ const logger$5 = debug('app:allItemsActors:fetchSeeds');
3749
3637
  const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
3750
3638
  const { queryVariables, modelName } = context;
3751
3639
  if (!queryVariables) {
@@ -3755,7 +3643,7 @@ const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
3755
3643
  const _fetchSeeds = () => __awaiter(void 0, void 0, void 0, function* () {
3756
3644
  const queryKey = [`getSeeds${modelName}`];
3757
3645
  const cachedResults = queryClient.getQueryData(queryKey);
3758
- logger$4(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
3646
+ logger$5(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
3759
3647
  const results = yield queryClient.fetchQuery({
3760
3648
  queryKey,
3761
3649
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SEEDS, queryVariables); }),
@@ -4243,11 +4131,11 @@ const globalMachine = setup({
4243
4131
  (_a) => __awaiter(void 0, [_a], void 0, function* ({ context }) {
4244
4132
  let SeedClass;
4245
4133
  if (context.environment === 'node') {
4246
- const { SeedNode } = yield import('./seed-CsQB9h6Q.js');
4134
+ const { SeedNode } = yield import('./seed-T0Gph_yX.js');
4247
4135
  SeedClass = SeedNode;
4248
4136
  }
4249
4137
  else {
4250
- const { SeedBrowser } = yield import('./seed-Cqa2atpR.js');
4138
+ const { SeedBrowser } = yield import('./seed-CM9XY9k9.js');
4251
4139
  SeedClass = SeedBrowser;
4252
4140
  }
4253
4141
  return SeedClass;
@@ -5338,7 +5226,7 @@ const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoc
5338
5226
  };
5339
5227
  });
5340
5228
 
5341
- const logger$3 = debug('app:db:queries:getItem');
5229
+ const logger$4 = debug('app:db:queries:getItem');
5342
5230
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
5343
5231
  if (!seedLocalId && !seedUid) {
5344
5232
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -5346,7 +5234,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
5346
5234
  if (seedUid && !seedLocalId) {
5347
5235
  const seedData = yield getSeedData({ seedUid });
5348
5236
  if (!seedData) {
5349
- logger$3('[db/queries] [getItem] no seedData seedUid', seedUid);
5237
+ logger$4('[db/queries] [getItem] no seedData seedUid', seedUid);
5350
5238
  return;
5351
5239
  }
5352
5240
  seedLocalId = seedData.localId;
@@ -5489,17 +5377,30 @@ class Item {
5489
5377
  });
5490
5378
  }
5491
5379
  static create(props) {
5492
- if (props.seedUid) {
5493
- if (this.instanceCache.has(props.seedUid)) {
5494
- const { instance, refCount } = this.instanceCache.get(props.seedUid);
5495
- this.instanceCache.set(props.seedUid, {
5380
+ if (props.seedUid || props.seedLocalId) {
5381
+ const seedId = props.seedUid || props.seedLocalId;
5382
+ if (Item.instanceCache.has(seedId)) {
5383
+ const { instance, refCount } = Item.instanceCache.get(seedId);
5384
+ Item.instanceCache.set(seedId, {
5496
5385
  instance,
5497
5386
  refCount: refCount + 1,
5498
5387
  });
5499
5388
  return instance;
5500
5389
  }
5390
+ if (!Item.instanceCache.has(props.seedLocalId)) {
5391
+ const newInstance = new Item(props);
5392
+ Item.instanceCache.set(seedId, {
5393
+ instance: newInstance,
5394
+ refCount: 1,
5395
+ });
5396
+ return newInstance;
5397
+ }
5501
5398
  }
5502
5399
  const newInstance = new Item(props);
5400
+ Item.instanceCache.set(newInstance.seedUid || newInstance.seedLocalId, {
5401
+ instance: newInstance,
5402
+ refCount: 1,
5403
+ });
5503
5404
  return newInstance;
5504
5405
  }
5505
5406
  static find(_b) {
@@ -5644,345 +5545,44 @@ const GET_ALL_PROPERTIES_FOR_ALL_VERSIONS = graphql(/* GraphQL */ `
5644
5545
  }
5645
5546
  `);
5646
5547
 
5647
- const logger$2 = debug('app:react:index');
5648
- const useItemProperty = (propertyName, seedLocalId) => {
5649
- const [property, setProperty] = useImmer(undefined);
5650
- const [isReadingFromDb, setIsReadingFromDb] = useState(false);
5651
- const [isInitialized, setIsInitialized] = useState(false);
5652
- const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
5653
- if (!snapshot || !snapshot.context) {
5654
- return;
5655
- }
5656
- return snapshot.context.renderValue || snapshot.context.propertyValue;
5657
- });
5658
- const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5659
- useEffect(() => {
5660
- if (property && property.value !== value) {
5661
- readFromDb();
5662
- }
5663
- }, [property, value]);
5664
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5665
- if (isReadingFromDb) {
5666
- return;
5667
- }
5668
- setIsReadingFromDb(true);
5669
- const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
5670
- setIsReadingFromDb(false);
5671
- if (!foundProperty) {
5672
- logger$2(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
5673
- return;
5674
- }
5675
- setProperty(() => foundProperty);
5676
- setIsInitialized(true);
5677
- }), [isReadingFromDb]);
5678
- useEffect(() => {
5679
- readFromDb();
5680
- }, []);
5681
- // TODO: How can we force a re-render when the property is updated?
5682
- // Right now, the value will trigger an update because it's using a selector
5683
- // and a change is pushed to the hook listener.
5684
- return {
5685
- property,
5686
- isInitialized,
5687
- isReadingFromDb,
5688
- value,
5689
- status,
5690
- };
5691
- };
5692
- const useItem = ({ modelName, seedLocalId, seedUid }) => {
5693
- const [item, setItem] = useImmer(undefined);
5694
- const [isReadingFromDb, setIsReadingFromDb] = useState(false);
5695
- const [isInitialized, setIsInitialized] = useState(false);
5696
- const { status, internalStatus } = useGlobalServiceStatus();
5697
- const context = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.context);
5698
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5699
- if (internalStatus !== 'ready' ||
5700
- (!seedUid && !seedLocalId) ||
5701
- isReadingFromDb) {
5702
- return;
5703
- }
5704
- const foundItem = yield Item.find({
5705
- modelName,
5706
- seedLocalId,
5707
- seedUid,
5708
- });
5709
- if (!foundItem) {
5710
- logger$2('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
5711
- return;
5712
- }
5713
- setItem(() => foundItem);
5714
- setIsInitialized(true);
5715
- }), [internalStatus, isReadingFromDb]);
5716
- useEffect(() => {
5717
- if (internalStatus === 'ready') {
5718
- readFromDb();
5719
- }
5720
- }, [internalStatus, status]);
5721
- useEffect(() => {
5722
- const seedId = seedUid || seedLocalId;
5723
- eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
5724
- return () => {
5725
- eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
5726
- };
5727
- }, []);
5548
+ const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId }) {
5549
+ const getVersionStatement = `SELECT local_id,
5550
+ uid,
5551
+ seed_local_id,
5552
+ seed_uid,
5553
+ seed_type,
5554
+ note,
5555
+ attestation_created_at,
5556
+ attestation_raw,
5557
+ created_at,
5558
+ updated_at
5559
+ FROM versions
5560
+ WHERE local_id = '${seedLocalId}';`;
5561
+ const { rows } = yield runQueryForStatement(getVersionStatement);
5562
+ if (!rows || !rows.length) {
5563
+ return;
5564
+ }
5565
+ const seedValues = rows[0];
5728
5566
  return {
5729
- item,
5730
- isInitialized,
5731
- isReadingFromDb,
5732
- context,
5567
+ localId: seedValues[0],
5568
+ uid: seedValues[1],
5569
+ seedLocalId: seedValues[2],
5570
+ seedUid: seedValues[3],
5571
+ seedType: seedValues[4],
5572
+ note: seedValues[5],
5573
+ attestationCreatedAt: seedValues[6],
5574
+ attestationRaw: seedValues[7],
5575
+ createdAt: seedValues[8],
5576
+ updatedAt: seedValues[9],
5733
5577
  };
5734
- };
5735
- const useItems = ({ modelName, options }) => {
5736
- const [items, setItems] = useImmer([]);
5737
- const [isReadingDb, setIsReadingDb] = useState(false);
5738
- const [isInitialized, setIsInitialized] = useState(false);
5739
- const { dbsAreReady } = useDbsAreReady();
5740
- const modelNameRef = useRef(modelName);
5741
- const refresh = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5742
- eventEmitter.emit('item.requestAll', { modelName });
5743
- }), []);
5744
- const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
5745
- if (!event ||
5746
- !event.modelName ||
5747
- event.modelName !== modelNameRef.current ||
5748
- isReadingDb) {
5749
- return;
5750
- }
5751
- setIsReadingDb(true);
5752
- const allItems = yield Item.all(modelNameRef.current);
5753
- setItems(() => allItems);
5754
- setIsReadingDb(false);
5755
- }), [modelName]);
5756
- useEffect(() => {
5757
- if (dbsAreReady && !isInitialized) {
5758
- const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
5759
- yield readFromDb({ modelName });
5760
- setIsInitialized(true);
5761
- });
5762
- _fetchItems();
5763
- }
5764
- }, [dbsAreReady, isInitialized]);
5765
- useEffect(() => {
5766
- eventEmitter.addListener('item.requestAll', readFromDb);
5767
- return () => {
5768
- eventEmitter.removeListener('item.requestAll');
5769
- };
5770
- }, []);
5771
- return {
5772
- items: orderBy(items, [
5773
- (item) => item.lastVersionPublishedAt ||
5774
- item.attestationCreatedAt ||
5775
- item.createdAt,
5776
- ], ['desc']),
5777
- isReadingDb,
5778
- isInitialized,
5779
- refresh,
5780
- };
5781
- };
5782
- const useDbsAreReady = () => {
5783
- const [dbsAreReady, setDbsAreReady] = useState(false);
5784
- const update = useCallback(() => {
5785
- if (dbsAreReady) {
5786
- return;
5787
- }
5788
- setDbsAreReady(true);
5789
- }, []);
5790
- useEffect(() => {
5791
- let globalSubscription;
5792
- let internalSubscription;
5793
- const _waitForDbs = () => __awaiter(void 0, void 0, void 0, function* () {
5794
- const globalService = getGlobalService();
5795
- const internalService = globalService.getSnapshot().context.internalService;
5796
- if (!internalService) {
5797
- logger$2('[useDbsAreReady] [useEffect] no internalService');
5798
- globalSubscription = globalService.subscribe(({ context }) => {
5799
- if (!internalSubscription && context && context.internalService) {
5800
- globalSubscription === null || globalSubscription === void 0 ? void 0 : globalSubscription.unsubscribe();
5801
- internalSubscription = context.internalService.subscribe((snapshot) => {
5802
- if (snapshot.value === 'ready') {
5803
- update();
5804
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5805
- }
5806
- });
5807
- }
5808
- });
5809
- return;
5810
- }
5811
- const currentState = internalService.getSnapshot().value;
5812
- if (currentState === 'ready') {
5813
- update();
5814
- return;
5815
- }
5816
- internalSubscription = internalService.subscribe((snapshot) => {
5817
- if (snapshot.value === 'ready') {
5818
- update();
5819
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5820
- }
5821
- });
5822
- });
5823
- _waitForDbs();
5824
- return () => {
5825
- if (globalSubscription) {
5826
- globalSubscription.unsubscribe();
5827
- }
5828
- if (internalSubscription) {
5829
- internalSubscription.unsubscribe();
5830
- }
5831
- };
5832
- }, []);
5833
- return {
5834
- dbsAreReady,
5835
- };
5836
- };
5837
- const useItemIsReady = () => {
5838
- const [itemListenersReady, setItemListenersReady] = useState(false);
5839
- const itemEventListenersHandler = useCallback((_) => {
5840
- setItemListenersReady(true);
5841
- }, []);
5842
- useEffect(() => {
5843
- const areReady = getAreItemEventHandlersReady();
5844
- if (areReady) {
5845
- itemEventListenersHandler(true);
5846
- }
5847
- eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
5848
- return () => {
5849
- eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
5850
- };
5851
- }, []);
5852
- return {
5853
- isReady: itemListenersReady,
5854
- };
5855
- };
5856
- const useItemProperties = (item) => {
5857
- const [propertyObj, setPropertyObj] = useImmer({});
5858
- useState(false);
5859
- const updatePropertyObj = useCallback((event) => {
5860
- if (!item) {
5861
- console.error('[XXXXXX] [updatePropertyObj] no item when expected');
5862
- return;
5863
- }
5864
- const { propertyName, propertyValue } = event;
5865
- if (!propertyName) {
5866
- return;
5867
- }
5868
- setPropertyObj((draft) => {
5869
- draft[propertyName] = propertyValue;
5870
- });
5871
- }, [item]);
5872
- useEffect(() => {
5873
- if (!item) {
5874
- return;
5875
- }
5876
- const eventKey = `item.${item.seedLocalId}.property.update`;
5877
- eventEmitter.addListener(eventKey, updatePropertyObj);
5878
- return () => {
5879
- eventEmitter.removeListener(eventKey, updatePropertyObj);
5880
- };
5881
- }, [item]);
5882
- return {
5883
- properties: propertyObj,
5884
- };
5885
- };
5886
- const useCreateItem = (modelName) => {
5887
- const [isCreatingItem, setIsCreatingItem] = useState(false);
5888
- const { isReady } = useItemIsReady();
5889
- const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
5890
- if (!isReady) {
5891
- console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
5892
- return;
5893
- }
5894
- if (isCreatingItem) {
5895
- // TODO: should we setup a queue for this?
5896
- console.error(`[useCreateItem] [createItem] already creating item`, itemData);
5897
- return;
5898
- }
5899
- setIsCreatingItem(true);
5900
- const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
5901
- yield Item.find({ modelName, seedLocalId });
5902
- eventEmitter.emit('item.requestAll', { modelName });
5903
- setIsCreatingItem(false);
5904
- }), [isCreatingItem, isReady]);
5905
- return {
5906
- createItem,
5907
- isCreatingItem,
5908
- };
5909
- };
5910
- const useDeleteItem = () => {
5911
- const [isDeletingItem, setIsDeletingItem] = useState(false);
5912
- const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
5913
- if (!item) {
5914
- return;
5915
- }
5916
- setIsDeletingItem(true);
5917
- const { modelName } = item.getService().getSnapshot().context;
5918
- yield deleteItem({ seedLocalId: item.seedLocalId });
5919
- eventEmitter.emit('item.requestAll', { modelName });
5920
- setIsDeletingItem(false);
5921
- }), [isDeletingItem]);
5922
- useEffect(() => { }, []);
5923
- return {
5924
- deleteItem: destroy,
5925
- isDeletingItem,
5926
- };
5927
- };
5928
- const useGlobalServiceStatus = () => {
5929
- const globalService = getGlobalService();
5930
- const status = useSelector(globalService, (snapshot) => {
5931
- return snapshot.value;
5932
- });
5933
- const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
5934
- if (!snapshot) {
5935
- return;
5936
- }
5937
- return snapshot.value;
5938
- });
5939
- useSelector(globalService, (snapshot) => {
5940
- return snapshot.context.internalService;
5941
- });
5942
- return {
5943
- status,
5944
- internalStatus,
5945
- };
5946
- };
5947
-
5948
- const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId }) {
5949
- const getVersionStatement = `SELECT local_id,
5950
- uid,
5951
- seed_local_id,
5952
- seed_uid,
5953
- seed_type,
5954
- note,
5955
- attestation_created_at,
5956
- attestation_raw,
5957
- created_at,
5958
- updated_at
5959
- FROM versions
5960
- WHERE local_id = '${seedLocalId}';`;
5961
- const { rows } = yield runQueryForStatement(getVersionStatement);
5962
- if (!rows || !rows.length) {
5963
- return;
5964
- }
5965
- const seedValues = rows[0];
5966
- return {
5967
- localId: seedValues[0],
5968
- uid: seedValues[1],
5969
- seedLocalId: seedValues[2],
5970
- seedUid: seedValues[3],
5971
- seedType: seedValues[4],
5972
- note: seedValues[5],
5973
- attestationCreatedAt: seedValues[6],
5974
- attestationRaw: seedValues[7],
5975
- createdAt: seedValues[8],
5976
- updatedAt: seedValues[9],
5977
- };
5978
- });
5979
-
5980
- const logger$1 = debug('app:write');
5981
- const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
5982
- if (!modelName || (!seedLocalId && !seedUid)) {
5983
- return;
5984
- }
5985
- eventEmitter.emit(`item.${modelName}.${seedUid || seedLocalId}.update`);
5578
+ });
5579
+
5580
+ const logger$3 = debug('app:write');
5581
+ const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
5582
+ if (!modelName || (!seedLocalId && !seedUid)) {
5583
+ return;
5584
+ }
5585
+ eventEmitter.emit(`item.${modelName}.${seedUid || seedLocalId}.update`);
5986
5586
  };
5987
5587
  const createSeed = (_a) => __awaiter(void 0, [_a], void 0, function* ({ type }) {
5988
5588
  const appDb = getAppDb();
@@ -6055,7 +5655,7 @@ const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoca
6055
5655
  });
6056
5656
  const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function* ({ propertyLocalId, propertyName, newValue, seedUid, seedLocalId, modelName, refSeedType, refResolvedValue, refResolvedDisplayValue, versionLocalId, versionUid, schemaUid, }) {
6057
5657
  if (!propertyLocalId && !seedLocalId) {
6058
- logger$1(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
5658
+ logger$3(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
6059
5659
  return;
6060
5660
  }
6061
5661
  let safeNewValue = newValue;
@@ -6094,7 +5694,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
6094
5694
  const schemaUid = mostRecentRecord[9];
6095
5695
  const easDataType = mostRecentRecord[10];
6096
5696
  if (propertyValueFromDb === newValue) {
6097
- logger$1(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
5697
+ logger$3(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
6098
5698
  return;
6099
5699
  }
6100
5700
  // This means we already have a local-only record so we should just update that one
@@ -6190,25 +5790,473 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
6190
5790
  sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
6191
5791
  });
6192
5792
 
6193
- const saveValueToDb = fromCallback(({ sendBack, input: { context, event } }) => {
6194
- const { localId, propertyName: propertyNameRaw, seedLocalId, propertyValue: existingValue, propertyRecordSchema, itemModelName, schemaUid, } = context;
6195
- let { newValue } = event;
6196
- if (existingValue === newValue) {
6197
- sendBack({ type: 'saveValueToDbSuccess' });
6198
- return;
6199
- }
6200
- const _saveValueToDb = () => __awaiter(void 0, void 0, void 0, function* () {
6201
- let refResolvedValue;
6202
- let refResolvedDisplayValue;
6203
- let refSeedType;
6204
- let propertyName = propertyNameRaw;
6205
- let versionLocalId;
6206
- if (propertyRecordSchema &&
6207
- propertyRecordSchema.dataType === 'Relation') {
6208
- refResolvedValue = newValue;
6209
- if (!propertyName.endsWith('Id')) {
6210
- propertyName = `${propertyName}Id`;
6211
- }
5793
+ const logger$2 = debug('app:react:index');
5794
+ const useItemProperty = (propertyName, seedLocalId) => {
5795
+ const [property, setProperty] = useImmer(undefined);
5796
+ const [isReadingFromDb, setIsReadingFromDb] = useState(false);
5797
+ const [isInitialized, setIsInitialized] = useState(false);
5798
+ const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
5799
+ if (!snapshot || !snapshot.context) {
5800
+ return;
5801
+ }
5802
+ return snapshot.context.renderValue || snapshot.context.propertyValue;
5803
+ });
5804
+ const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5805
+ useEffect(() => {
5806
+ if (property && property.value !== value) {
5807
+ readFromDb();
5808
+ }
5809
+ }, [property, value]);
5810
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5811
+ if (isReadingFromDb) {
5812
+ return;
5813
+ }
5814
+ setIsReadingFromDb(true);
5815
+ const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
5816
+ setIsReadingFromDb(false);
5817
+ if (!foundProperty) {
5818
+ logger$2(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
5819
+ return;
5820
+ }
5821
+ setProperty(() => foundProperty);
5822
+ setIsInitialized(true);
5823
+ }), [isReadingFromDb]);
5824
+ useEffect(() => {
5825
+ readFromDb();
5826
+ }, []);
5827
+ // TODO: How can we force a re-render when the property is updated?
5828
+ // Right now, the value will trigger an update because it's using a selector
5829
+ // and a change is pushed to the hook listener.
5830
+ return {
5831
+ property,
5832
+ isInitialized,
5833
+ isReadingFromDb,
5834
+ value,
5835
+ status,
5836
+ };
5837
+ };
5838
+ const useItem = ({ modelName, seedLocalId, seedUid }) => {
5839
+ const [item, setItem] = useImmer(undefined);
5840
+ const [itemSubscription, setItemSubscription] = useState();
5841
+ const { status, internalStatus } = useGlobalServiceStatus();
5842
+ const isReadingDb = useRef(false);
5843
+ const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5844
+ const updateItem = useCallback((newItem) => {
5845
+ setItem(() => newItem);
5846
+ }, []);
5847
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5848
+ if (isReadingDb.current ||
5849
+ internalStatus !== 'ready' ||
5850
+ (!seedUid && !seedLocalId)) {
5851
+ return;
5852
+ }
5853
+ isReadingDb.current = true;
5854
+ const foundItem = yield Item.find({
5855
+ modelName,
5856
+ seedLocalId,
5857
+ seedUid,
5858
+ });
5859
+ if (!foundItem) {
5860
+ logger$2('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
5861
+ return;
5862
+ }
5863
+ updateItem(foundItem);
5864
+ isReadingDb.current = false;
5865
+ }), [internalStatus]);
5866
+ useEffect(() => {
5867
+ if (internalStatus === 'ready') {
5868
+ readFromDb();
5869
+ }
5870
+ }, [internalStatus, status]);
5871
+ useEffect(() => {
5872
+ if (item && !itemSubscription) {
5873
+ const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
5874
+ const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
5875
+ if (!newItem) {
5876
+ logger$2('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
5877
+ return;
5878
+ }
5879
+ setItem(() => newItem);
5880
+ }));
5881
+ setItemSubscription(subscription);
5882
+ }
5883
+ return () => {
5884
+ itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
5885
+ };
5886
+ }, [item, itemSubscription]);
5887
+ useEffect(() => {
5888
+ const seedId = seedUid || seedLocalId;
5889
+ eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
5890
+ return () => {
5891
+ eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
5892
+ };
5893
+ }, []);
5894
+ return {
5895
+ item,
5896
+ itemStatus,
5897
+ };
5898
+ };
5899
+ const useItems = ({ modelName, options }) => {
5900
+ const [items, setItems] = useImmer([]);
5901
+ const [isReadingDb, setIsReadingDb] = useState(false);
5902
+ const [isInitialized, setIsInitialized] = useState(false);
5903
+ const { dbsAreReady } = useDbsAreReady();
5904
+ const modelNameRef = useRef(modelName);
5905
+ const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
5906
+ if (!event ||
5907
+ !event.modelName ||
5908
+ event.modelName !== modelNameRef.current ||
5909
+ isReadingDb) {
5910
+ return;
5911
+ }
5912
+ setIsReadingDb(true);
5913
+ const allItems = yield Item.all(modelNameRef.current);
5914
+ setItems(() => allItems);
5915
+ setIsReadingDb(false);
5916
+ }), [modelName]);
5917
+ useEffect(() => {
5918
+ if (dbsAreReady && !isInitialized) {
5919
+ const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
5920
+ yield readFromDb({ modelName });
5921
+ setIsInitialized(true);
5922
+ });
5923
+ _fetchItems();
5924
+ }
5925
+ }, [dbsAreReady, isInitialized]);
5926
+ useEffect(() => {
5927
+ eventEmitter.addListener('item.requestAll', readFromDb);
5928
+ return () => {
5929
+ eventEmitter.removeListener('item.requestAll');
5930
+ };
5931
+ }, []);
5932
+ return {
5933
+ items: orderBy(items, [
5934
+ (item) => item.lastVersionPublishedAt ||
5935
+ item.attestationCreatedAt ||
5936
+ item.createdAt,
5937
+ ], ['desc']).slice(0, 10),
5938
+ isReadingDb,
5939
+ isInitialized,
5940
+ };
5941
+ };
5942
+ const useDbsAreReady = () => {
5943
+ const [dbsAreReady, setDbsAreReady] = useState(false);
5944
+ const update = useCallback(() => {
5945
+ if (dbsAreReady) {
5946
+ return;
5947
+ }
5948
+ setDbsAreReady(true);
5949
+ }, []);
5950
+ useEffect(() => {
5951
+ let globalSubscription;
5952
+ let internalSubscription;
5953
+ const _waitForDbs = () => __awaiter(void 0, void 0, void 0, function* () {
5954
+ const globalService = getGlobalService();
5955
+ const internalService = globalService.getSnapshot().context.internalService;
5956
+ if (!internalService) {
5957
+ logger$2('[useDbsAreReady] [useEffect] no internalService');
5958
+ globalSubscription = globalService.subscribe(({ context }) => {
5959
+ if (!internalSubscription && context && context.internalService) {
5960
+ globalSubscription === null || globalSubscription === void 0 ? void 0 : globalSubscription.unsubscribe();
5961
+ internalSubscription = context.internalService.subscribe((snapshot) => {
5962
+ if (snapshot.value === 'ready') {
5963
+ update();
5964
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5965
+ }
5966
+ });
5967
+ }
5968
+ });
5969
+ return;
5970
+ }
5971
+ const currentState = internalService.getSnapshot().value;
5972
+ if (currentState === 'ready') {
5973
+ update();
5974
+ return;
5975
+ }
5976
+ internalSubscription = internalService.subscribe((snapshot) => {
5977
+ if (snapshot.value === 'ready') {
5978
+ update();
5979
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5980
+ }
5981
+ });
5982
+ });
5983
+ _waitForDbs();
5984
+ return () => {
5985
+ if (globalSubscription) {
5986
+ globalSubscription.unsubscribe();
5987
+ }
5988
+ if (internalSubscription) {
5989
+ internalSubscription.unsubscribe();
5990
+ }
5991
+ };
5992
+ }, []);
5993
+ return {
5994
+ dbsAreReady,
5995
+ };
5996
+ };
5997
+ const useItemIsReady = () => {
5998
+ const [itemListenersReady, setItemListenersReady] = useState(false);
5999
+ const itemEventListenersHandler = useCallback((_) => {
6000
+ setItemListenersReady(true);
6001
+ }, []);
6002
+ useEffect(() => {
6003
+ const areReady = getAreItemEventHandlersReady();
6004
+ if (areReady) {
6005
+ itemEventListenersHandler(true);
6006
+ }
6007
+ eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
6008
+ return () => {
6009
+ eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
6010
+ };
6011
+ }, []);
6012
+ return {
6013
+ isReady: itemListenersReady,
6014
+ };
6015
+ };
6016
+ const useItemProperties = (item) => {
6017
+ const [propertyObj, setPropertyObj] = useImmer({});
6018
+ useState(false);
6019
+ const updatePropertyObj = useCallback((event) => {
6020
+ if (!item) {
6021
+ console.error('[XXXXXX] [updatePropertyObj] no item when expected');
6022
+ return;
6023
+ }
6024
+ const { propertyName, propertyValue } = event;
6025
+ if (!propertyName) {
6026
+ return;
6027
+ }
6028
+ setPropertyObj((draft) => {
6029
+ draft[propertyName] = propertyValue;
6030
+ });
6031
+ }, [item]);
6032
+ useEffect(() => {
6033
+ if (!item) {
6034
+ return;
6035
+ }
6036
+ const eventKey = `item.${item.seedLocalId}.property.update`;
6037
+ eventEmitter.addListener(eventKey, updatePropertyObj);
6038
+ return () => {
6039
+ eventEmitter.removeListener(eventKey, updatePropertyObj);
6040
+ };
6041
+ }, [item]);
6042
+ return {
6043
+ properties: propertyObj,
6044
+ };
6045
+ };
6046
+ const useCreateItem = (modelName) => {
6047
+ const [isCreatingItem, setIsCreatingItem] = useState(false);
6048
+ const { isReady } = useItemIsReady();
6049
+ const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
6050
+ if (!isReady) {
6051
+ console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
6052
+ return;
6053
+ }
6054
+ if (isCreatingItem) {
6055
+ // TODO: should we setup a queue for this?
6056
+ console.error(`[useCreateItem] [createItem] already creating item`, itemData);
6057
+ return;
6058
+ }
6059
+ setIsCreatingItem(true);
6060
+ const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
6061
+ yield Item.find({ modelName, seedLocalId });
6062
+ eventEmitter.emit('item.requestAll', { modelName });
6063
+ setIsCreatingItem(false);
6064
+ }), [isCreatingItem, isReady]);
6065
+ return {
6066
+ createItem,
6067
+ isCreatingItem,
6068
+ };
6069
+ };
6070
+ const useDeleteItem = () => {
6071
+ const [isDeletingItem, setIsDeletingItem] = useState(false);
6072
+ const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
6073
+ if (!item) {
6074
+ return;
6075
+ }
6076
+ setIsDeletingItem(true);
6077
+ const { modelName } = item.getService().getSnapshot().context;
6078
+ yield deleteItem({ seedLocalId: item.seedLocalId });
6079
+ eventEmitter.emit('item.requestAll', { modelName });
6080
+ setIsDeletingItem(false);
6081
+ }), [isDeletingItem]);
6082
+ useEffect(() => { }, []);
6083
+ return {
6084
+ deleteItem: destroy,
6085
+ isDeletingItem,
6086
+ };
6087
+ };
6088
+ const useGlobalServiceStatus = () => {
6089
+ const globalService = getGlobalService();
6090
+ const status = useSelector(globalService, (snapshot) => {
6091
+ return snapshot.value;
6092
+ });
6093
+ const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
6094
+ if (!snapshot) {
6095
+ return;
6096
+ }
6097
+ return snapshot.value;
6098
+ });
6099
+ useSelector(globalService, (snapshot) => {
6100
+ return snapshot.context.internalService;
6101
+ });
6102
+ return {
6103
+ status,
6104
+ internalStatus,
6105
+ };
6106
+ };
6107
+
6108
+ const logger$1 = debug('app:property:actors:hydrateFromDb');
6109
+ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
6110
+ const { seedUid, seedLocalId, propertyName: propertyNameRaw, propertyValue, propertyRecordSchema, itemModelName, } = context;
6111
+ let propertyName = propertyNameRaw;
6112
+ if (propertyRecordSchema &&
6113
+ propertyRecordSchema.ref &&
6114
+ propertyRecordSchema.dataType === 'Relation' &&
6115
+ !propertyNameRaw.endsWith('Id')) {
6116
+ propertyName = propertyNameRaw + 'Id';
6117
+ }
6118
+ if (propertyRecordSchema &&
6119
+ propertyRecordSchema.ref &&
6120
+ propertyRecordSchema.dataType === 'List' &&
6121
+ !propertyNameRaw.endsWith('Ids')) {
6122
+ propertyName = propertyNameRaw + 'Ids';
6123
+ }
6124
+ const _hydrateFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
6125
+ const db = getAppDb();
6126
+ let hydrateQuery;
6127
+ let safeValue = propertyValue;
6128
+ let propertyNameQuery = eq(metadata.propertyName, propertyName);
6129
+ if (safeValue && typeof propertyValue === 'string') {
6130
+ safeValue = escapeSqliteString(propertyValue);
6131
+ }
6132
+ if (propertyRecordSchema &&
6133
+ propertyRecordSchema.ref &&
6134
+ propertyRecordSchema.dataType === 'Relation') {
6135
+ let missingPropertyNameVariant;
6136
+ if (propertyName.endsWith('Id')) {
6137
+ missingPropertyNameVariant = propertyName.slice(0, -2);
6138
+ }
6139
+ if (!propertyName.endsWith('Id')) {
6140
+ missingPropertyNameVariant = propertyName + 'Id';
6141
+ }
6142
+ propertyNameQuery = or(eq(metadata.propertyName, propertyName), eq(metadata.propertyName, missingPropertyNameVariant));
6143
+ }
6144
+ const selectFromStatement = db
6145
+ .select({
6146
+ localId: metadata.localId,
6147
+ uid: metadata.uid,
6148
+ propertyName: metadata.propertyName,
6149
+ propertyValue: metadata.propertyValue,
6150
+ seedLocalId: metadata.seedLocalId,
6151
+ seedUid: metadata.seedUid,
6152
+ schemaUid: metadata.schemaUid,
6153
+ refResolvedValue: metadata.refResolvedValue,
6154
+ refResolvedDisplayValue: metadata.refResolvedDisplayValue,
6155
+ })
6156
+ .from(metadata);
6157
+ if (seedUid && !seedLocalId) {
6158
+ hydrateQuery = selectFromStatement.where(and(eq(metadata.seedUid, seedUid), propertyNameQuery));
6159
+ }
6160
+ if (seedUid && seedLocalId) {
6161
+ hydrateQuery = selectFromStatement.where(and(eq(metadata.seedLocalId, seedLocalId), eq(metadata.seedUid, seedUid), propertyNameQuery));
6162
+ }
6163
+ if (!seedUid && seedLocalId) {
6164
+ hydrateQuery = selectFromStatement.where(and(eq(metadata.seedLocalId, seedLocalId), propertyNameQuery));
6165
+ }
6166
+ if (!hydrateQuery) {
6167
+ return;
6168
+ }
6169
+ const rows = yield hydrateQuery.orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'));
6170
+ if (!rows || !rows.length) {
6171
+ return;
6172
+ }
6173
+ const firstRow = rows[0];
6174
+ const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, refResolvedValue, refResolvedDisplayValue, } = firstRow;
6175
+ if (propertyName && !propertyNameFromDb) {
6176
+ logger$1(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
6177
+ }
6178
+ if (propertyName &&
6179
+ propertyNameFromDb &&
6180
+ !propertyNameFromDb.includes(propertyName) &&
6181
+ !propertyName.includes(propertyNameFromDb) &&
6182
+ propertyNameFromDb !== propertyName) {
6183
+ logger$1(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
6184
+ }
6185
+ if (propertyValue && propertyValueFromDb !== propertyValue) {
6186
+ logger$1(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
6187
+ }
6188
+ if (seedLocalIdFromDb !== seedLocalId) {
6189
+ logger$1(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
6190
+ }
6191
+ if (seedUidFromDb !== seedUid) {
6192
+ logger$1(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
6193
+ }
6194
+ sendBack({
6195
+ type: 'updateContext',
6196
+ localId,
6197
+ uid,
6198
+ propertyValue: propertyValueFromDb,
6199
+ seedLocalId: seedLocalIdFromDb,
6200
+ seedUid: seedUidFromDb,
6201
+ schemaUid: schemaUidFromDb,
6202
+ resolveValue: refResolvedValue,
6203
+ resolveDisplayValue: refResolvedDisplayValue,
6204
+ renderValue: refResolvedDisplayValue,
6205
+ });
6206
+ if (propertyNameFromDb === 'storageTransactionId') {
6207
+ const { Item } = yield import('./index-CXe0BS3G.js');
6208
+ const item = yield Item.find({
6209
+ seedLocalId,
6210
+ modelName: itemModelName,
6211
+ });
6212
+ if (item) {
6213
+ for (const [propertyName, property] of Object.entries(item.properties)) {
6214
+ if (propertyName === 'html' &&
6215
+ propertyValueFromDb &&
6216
+ propertyValueFromDb.length === 43) {
6217
+ const htmlFilePath = `/files/html/${propertyValueFromDb}.html`;
6218
+ const exists = yield fs.promises.exists(htmlFilePath);
6219
+ if (!exists) {
6220
+ return;
6221
+ }
6222
+ const renderValue = yield fs.promises
6223
+ .readFile(htmlFilePath, 'utf8')
6224
+ .catch((error) => {
6225
+ logger$1('Error reading html file', error);
6226
+ });
6227
+ property
6228
+ .getService()
6229
+ .send({ type: 'updateRenderValue', renderValue });
6230
+ return;
6231
+ }
6232
+ }
6233
+ }
6234
+ }
6235
+ });
6236
+ _hydrateFromDb().then(() => {
6237
+ sendBack({ type: 'hydrateFromDbSuccess' });
6238
+ });
6239
+ });
6240
+
6241
+ const saveValueToDb = fromCallback(({ sendBack, input: { context, event } }) => {
6242
+ const { localId, propertyName: propertyNameRaw, seedLocalId, propertyValue: existingValue, propertyRecordSchema, itemModelName, schemaUid, } = context;
6243
+ let { newValue } = event;
6244
+ if (existingValue === newValue) {
6245
+ sendBack({ type: 'saveValueToDbSuccess' });
6246
+ return;
6247
+ }
6248
+ const _saveValueToDb = () => __awaiter(void 0, void 0, void 0, function* () {
6249
+ let refResolvedValue;
6250
+ let refResolvedDisplayValue;
6251
+ let refSeedType;
6252
+ let propertyName = propertyNameRaw;
6253
+ let versionLocalId;
6254
+ if (propertyRecordSchema &&
6255
+ propertyRecordSchema.dataType === 'Relation') {
6256
+ refResolvedValue = newValue;
6257
+ if (!propertyName.endsWith('Id')) {
6258
+ propertyName = `${propertyName}Id`;
6259
+ }
6212
6260
  let fileType;
6213
6261
  const dirs = yield fs.promises.readdir('/files');
6214
6262
  for (const dir of dirs) {
@@ -6245,7 +6293,6 @@ const saveValueToDb = fromCallback(({ sendBack, input: { context, event } }) =>
6245
6293
  });
6246
6294
  sendBack({
6247
6295
  type: 'updateContext',
6248
- isSaving: false,
6249
6296
  propertyValue: newValue,
6250
6297
  renderValue: refResolvedDisplayValue,
6251
6298
  });
@@ -6309,11 +6356,7 @@ const propertyMachine = setup({
6309
6356
  },
6310
6357
  },
6311
6358
  states: {
6312
- idle: {
6313
- on: {
6314
- refresh: 'hydratingFromDb',
6315
- },
6316
- },
6359
+ idle: {},
6317
6360
  waitingForDb: {
6318
6361
  on: {
6319
6362
  waitForDbSuccess: {
@@ -6325,6 +6368,7 @@ const propertyMachine = setup({
6325
6368
  },
6326
6369
  invoke: {
6327
6370
  src: 'waitForDb',
6371
+ input: ({ context }) => ({ context }),
6328
6372
  },
6329
6373
  },
6330
6374
  hydratingFromDb: {
@@ -6382,13 +6426,13 @@ const propertyMachine = setup({
6382
6426
  },
6383
6427
  saving: {
6384
6428
  on: {
6385
- saveSuccess: {
6429
+ saveValueToDbSuccess: {
6386
6430
  target: 'idle',
6387
6431
  actions: assign({
6388
6432
  isSaving: false,
6389
6433
  }),
6390
6434
  },
6391
- saveFailure: {
6435
+ saveValueToDbFailure: {
6392
6436
  target: 'idle',
6393
6437
  actions: assign({
6394
6438
  isSaving: false,
@@ -6821,7 +6865,7 @@ const client = {
6821
6865
  console.error('fs listeners not ready during init');
6822
6866
  }
6823
6867
  globalService.send({ type: 'init', endpoints, models, addresses });
6824
- import('./seed.schema.config-CxqrGPwe.js').then(({ models }) => {
6868
+ import('./seed.schema.config-Dg9Q0kx4.js').then(({ models }) => {
6825
6869
  for (const [key, value] of Object.entries(models)) {
6826
6870
  modelStore.set(key, value);
6827
6871
  }
@@ -6879,4 +6923,4 @@ const client = {
6879
6923
  };
6880
6924
 
6881
6925
  export { APP_DB_CONFIG as A, useCreateItem as B, CHILD_SNAPSHOT as C, DB_NAME_SDK_CONFIG as D, useItemProperty as E, useDeleteItem as F, GET_SCHEMAS as G, getGlobalService as H, Item as I, Json as J, getCorrectId as K, List as L, Model as M, Property as P, Relation as R, SCHEMA_NJK as S, Text as T, __decorate as _, GET_SEEDS as a, GET_SEED_IDS as b, GET_STORAGE_TRANSACTION_ID as c, GET_VERSIONS as d, GET_PROPERTIES as e, GET_ALL_PROPERTIES_FOR_ALL_VERSIONS as f, itemMachineAll as g, __metadata as h, itemMachineSingle as i, internalMachine as j, isNode as k, isBrowser as l, isReactNative as m, __awaiter as n, models as o, SCHEMA_TS as p, SDK_DB_CONFIG as q, SEED_DB_CONFIG as r, addModelsToInternalDb as s, client as t, ImageSrc as u, ItemProperty as v, withSeed as w, useItems as x, useItem as y, useItemProperties as z };
6882
- //# sourceMappingURL=index-Dg73YrcZ.js.map
6926
+ //# sourceMappingURL=index-Dd2ggBQg.js.map