@seedprotocol/sdk 0.1.53 → 0.1.54

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 (44) hide show
  1. package/dist/{index-DcXK4ERW.js → index-DQKd-s2Q.js} +597 -456
  2. package/dist/index-DQKd-s2Q.js.map +1 -0
  3. package/dist/{index-5a9z-kqT.js → index-NmD9sjcJ.js} +2 -2
  4. package/dist/index-NmD9sjcJ.js.map +1 -0
  5. package/dist/main.js +1 -1
  6. package/dist/{seed.schema.config-BtfzZOfM.js → seed.schema.config-OyHsE0Zl.js} +2 -2
  7. package/dist/{seed.schema.config-BtfzZOfM.js.map → seed.schema.config-OyHsE0Zl.js.map} +1 -1
  8. package/dist/src/ItemProperty.ts +114 -68
  9. package/dist/src/createMetadata.ts +36 -0
  10. package/dist/src/getItem.ts +12 -37
  11. package/dist/src/getItemProperty.ts +35 -0
  12. package/dist/src/getItems.ts +11 -18
  13. package/dist/src/getVersionData.ts +36 -48
  14. package/dist/src/hydrateFromDb.ts +11 -15
  15. package/dist/src/propertyMachine.ts +18 -2
  16. package/dist/src/saveValueToDb.ts +183 -69
  17. package/dist/src/syncDbWithEas.ts +1 -1
  18. package/dist/src/versionData.ts +24 -0
  19. package/dist/types/src/browser/db/read/getItem.d.ts.map +1 -1
  20. package/dist/types/src/browser/db/read/getItemProperty.d.ts +6 -0
  21. package/dist/types/src/browser/db/read/getItemProperty.d.ts.map +1 -0
  22. package/dist/types/src/browser/db/read/getItems.d.ts.map +1 -1
  23. package/dist/types/src/browser/db/read/getVersionData.d.ts +5 -14
  24. package/dist/types/src/browser/db/read/getVersionData.d.ts.map +1 -1
  25. package/dist/types/src/browser/db/read/subqueries/versionData.d.ts +70 -0
  26. package/dist/types/src/browser/db/read/subqueries/versionData.d.ts.map +1 -0
  27. package/dist/types/src/browser/db/write/createMetadata.d.ts +6 -0
  28. package/dist/types/src/browser/db/write/createMetadata.d.ts.map +1 -0
  29. package/dist/types/src/browser/item/Item.d.ts +1 -7
  30. package/dist/types/src/browser/item/Item.d.ts.map +1 -1
  31. package/dist/types/src/browser/property/ItemProperty.d.ts +12 -5
  32. package/dist/types/src/browser/property/ItemProperty.d.ts.map +1 -1
  33. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  34. package/dist/types/src/browser/property/actors/saveValueToDb.d.ts +9 -1
  35. package/dist/types/src/browser/property/actors/saveValueToDb.d.ts.map +1 -1
  36. package/dist/types/src/browser/property/index.d.ts +9 -9
  37. package/dist/types/src/browser/property/propertyMachine.d.ts.map +1 -1
  38. package/dist/types/src/types/item.d.ts +17 -0
  39. package/dist/types/src/types/item.d.ts.map +1 -1
  40. package/dist/types/src/types/property.d.ts +9 -0
  41. package/dist/types/src/types/property.d.ts.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/index-5a9z-kqT.js.map +0 -1
  44. package/dist/index-DcXK4ERW.js.map +0 -1
@@ -2,8 +2,8 @@ import { b as __awaiter, d as __rest, i as internalPropertyNames, I as INTERNAL_
2
2
  import path, { basename } from 'path';
3
3
  import 'reflect-metadata';
4
4
  import { Type } from '@sinclair/typebox';
5
- import { fromCallback, assign, setup, createActor, waitFor, emit, raise } from 'xstate';
6
- import { sql, relations, and, eq, max, or, inArray, like, isNotNull, isNull, count, desc, getTableColumns } from 'drizzle-orm';
5
+ import { fromCallback, assign, createActor, waitFor, setup, emit, raise } from 'xstate';
6
+ import { sql, relations, and, eq, max, or, inArray, like, count, isNotNull, isNull, getTableColumns, gt } from 'drizzle-orm';
7
7
  import { fs, configureSingle } from '@zenfs/core';
8
8
  import 'dayjs';
9
9
  import { customAlphabet } from 'nanoid';
@@ -930,19 +930,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
930
930
  }
931
931
  propertyNameQuery = or(eq(metadata.propertyName, propertyName), eq(metadata.propertyName, missingPropertyNameVariant));
932
932
  }
933
- const selectFromStatement = db
934
- .select({
935
- localId: metadata.localId,
936
- uid: metadata.uid,
937
- propertyName: metadata.propertyName,
938
- propertyValue: metadata.propertyValue,
939
- seedLocalId: metadata.seedLocalId,
940
- seedUid: metadata.seedUid,
941
- schemaUid: metadata.schemaUid,
942
- refResolvedValue: metadata.refResolvedValue,
943
- refResolvedDisplayValue: metadata.refResolvedDisplayValue,
944
- })
945
- .from(metadata);
933
+ const selectFromStatement = db.select().from(metadata);
946
934
  if (seedUid && !seedLocalId) {
947
935
  hydrateQuery = selectFromStatement.where(and(eq(metadata.seedUid, seedUid), propertyNameQuery));
948
936
  }
@@ -960,7 +948,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
960
948
  return;
961
949
  }
962
950
  const firstRow = rows[0];
963
- const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, refResolvedValue, refResolvedDisplayValue, } = firstRow;
951
+ const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, versionLocalId: versionLocalIdFromDb, versionUid: versionUidFromDb, refValueType, refResolvedValue, refResolvedDisplayValue, localStorageDir, } = firstRow;
964
952
  if (propertyName && !propertyNameFromDb) {
965
953
  logger$m(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
966
954
  }
@@ -987,13 +975,17 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
987
975
  propertyValue: propertyValueFromDb,
988
976
  seedLocalId: seedLocalIdFromDb,
989
977
  seedUid: seedUidFromDb,
978
+ versionLocalId: versionLocalIdFromDb,
979
+ versionUid: versionUidFromDb,
990
980
  schemaUid: schemaUidFromDb,
991
- resolveValue: refResolvedValue,
992
- resolveDisplayValue: refResolvedDisplayValue,
981
+ refValueType,
982
+ localStorageDir,
983
+ resolvedValue: refResolvedValue,
984
+ resolvedDisplayValue: refResolvedDisplayValue,
993
985
  renderValue: refResolvedDisplayValue,
994
986
  });
995
987
  if (propertyNameFromDb === 'storageTransactionId') {
996
- const { Item } = yield import('./index-5a9z-kqT.js');
988
+ const { Item } = yield import('./index-NmD9sjcJ.js');
997
989
  const item = yield Item.find({
998
990
  seedLocalId,
999
991
  modelName: itemModelName,
@@ -1062,36 +1054,26 @@ const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoc
1062
1054
  return rows[0];
1063
1055
  });
1064
1056
 
1065
- const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId }) {
1066
- const getVersionStatement = `SELECT local_id,
1067
- uid,
1068
- seed_local_id,
1069
- seed_uid,
1070
- seed_type,
1071
- note,
1072
- attestation_created_at,
1073
- attestation_raw,
1074
- created_at,
1075
- updated_at
1076
- FROM versions
1077
- WHERE local_id = '${seedLocalId}';`;
1078
- const { rows } = yield runQueryForStatement(getVersionStatement);
1079
- if (!rows || !rows.length) {
1057
+ const getVersionData$1 = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, seedLocalId, uid, }) {
1058
+ const appDb = getAppDb();
1059
+ const whereClauses = [];
1060
+ if (seedLocalId) {
1061
+ whereClauses.push(eq(versions.localId, seedLocalId));
1062
+ }
1063
+ if (localId) {
1064
+ whereClauses.push(eq(versions.localId, localId));
1065
+ }
1066
+ if (uid) {
1067
+ whereClauses.push(eq(versions.uid, uid));
1068
+ }
1069
+ const queryRows = yield appDb
1070
+ .select()
1071
+ .from(versions)
1072
+ .where(and(...whereClauses));
1073
+ if (!queryRows || !queryRows.length) {
1080
1074
  return;
1081
1075
  }
1082
- const seedValues = rows[0];
1083
- return {
1084
- localId: seedValues[0],
1085
- uid: seedValues[1],
1086
- seedLocalId: seedValues[2],
1087
- seedUid: seedValues[3],
1088
- seedType: seedValues[4],
1089
- note: seedValues[5],
1090
- attestationCreatedAt: seedValues[6],
1091
- attestationRaw: seedValues[7],
1092
- createdAt: seedValues[8],
1093
- updatedAt: seedValues[9],
1094
- };
1076
+ return queryRows[0];
1095
1077
  });
1096
1078
 
1097
1079
  const eventEmitter = new EventEmitter();
@@ -1208,7 +1190,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1208
1190
  return;
1209
1191
  }
1210
1192
  const seedDataFromDb = yield getSeedData({ seedLocalId });
1211
- const versionDataFromDb = yield getVersionData({ versionLocalId });
1193
+ const versionDataFromDb = yield getVersionData$1({ versionLocalId });
1212
1194
  // Here we don't have a local-only record so we need to create a new one
1213
1195
  const newLocalId = generateId();
1214
1196
  const newPropertyStatement = `INSERT INTO metadata (local_id,
@@ -1252,7 +1234,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1252
1234
  }
1253
1235
  }
1254
1236
  if (!versionUid) {
1255
- const versionData = yield getVersionData({ versionLocalId });
1237
+ const versionData = yield getVersionData$1({ versionLocalId });
1256
1238
  if (versionData) {
1257
1239
  versionUid = versionData.uid;
1258
1240
  }
@@ -1435,213 +1417,6 @@ const updateMachineContext = {
1435
1417
  }),
1436
1418
  };
1437
1419
 
1438
- const saveValueToDb = fromCallback(({ sendBack, input: { context, event } }) => {
1439
- const { localId, propertyName: propertyNameRaw, seedLocalId, propertyValue: existingValue, propertyRecordSchema, itemModelName, schemaUid, } = context;
1440
- let { newValue } = event;
1441
- if (existingValue === newValue) {
1442
- sendBack({ type: 'saveValueToDbSuccess' });
1443
- return;
1444
- }
1445
- const _saveValueToDb = () => __awaiter(void 0, void 0, void 0, function* () {
1446
- let refResolvedValue;
1447
- let refResolvedDisplayValue;
1448
- let refSeedType;
1449
- let propertyName = propertyNameRaw;
1450
- let versionLocalId;
1451
- if (propertyRecordSchema &&
1452
- propertyRecordSchema.dataType === 'Relation') {
1453
- refResolvedValue = newValue;
1454
- if (!propertyName.endsWith('Id')) {
1455
- propertyName = `${propertyName}Id`;
1456
- }
1457
- let fileType;
1458
- const dirs = yield fs.promises.readdir('/files');
1459
- for (const dir of dirs) {
1460
- const files = yield fs.promises.readdir(`/files/${dir}`);
1461
- if (files.includes(newValue)) {
1462
- fileType = dir;
1463
- break;
1464
- }
1465
- }
1466
- if (fileType === 'images') {
1467
- const filePath = `/files/images/${newValue}`;
1468
- refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
1469
- refSeedType = 'image';
1470
- newValue = yield createSeed({
1471
- type: refSeedType,
1472
- });
1473
- versionLocalId = yield createVersion({
1474
- seedLocalId: newValue,
1475
- seedType: refSeedType,
1476
- });
1477
- }
1478
- }
1479
- yield updateItemPropertyValue({
1480
- propertyLocalId: localId,
1481
- propertyName,
1482
- newValue,
1483
- seedLocalId,
1484
- refSeedType,
1485
- refResolvedValue,
1486
- refResolvedDisplayValue,
1487
- versionLocalId,
1488
- modelName: itemModelName,
1489
- schemaUid,
1490
- });
1491
- sendBack({
1492
- type: 'updateContext',
1493
- propertyValue: newValue,
1494
- renderValue: refResolvedDisplayValue,
1495
- });
1496
- });
1497
- _saveValueToDb().then(() => {
1498
- sendBack({ type: 'saveValueToDbSuccess' });
1499
- });
1500
- });
1501
-
1502
- const propertyMachine = setup({
1503
- types: {
1504
- context: {},
1505
- },
1506
- actors: {
1507
- waitForDb: waitForDb$1,
1508
- hydrateFromDb,
1509
- initialize: initialize$3,
1510
- resolveRelatedValue,
1511
- resolveRemoteStorage,
1512
- saveValueToDb,
1513
- },
1514
- }).createMachine({
1515
- id: 'itemProperty',
1516
- initial: 'waitingForDb',
1517
- context: ({ input }) => input,
1518
- on: {
1519
- updatePropertyValue: {
1520
- target: '.resolvingRelatedValue',
1521
- guard: ({ context }) => !context.isDbReady,
1522
- actions: assign(({ event }) => {
1523
- return {
1524
- propertyValue: event.propertyValue,
1525
- };
1526
- }),
1527
- },
1528
- updateRenderValue: {
1529
- actions: assign(({ event, context }) => {
1530
- return {
1531
- renderValue: event.renderValue,
1532
- };
1533
- }),
1534
- },
1535
- save: {
1536
- actions: assign({
1537
- isSaving: true,
1538
- }),
1539
- target: '.saving',
1540
- },
1541
- updateContext: updateMachineContext,
1542
- },
1543
- states: {
1544
- idle: {},
1545
- waitingForDb: {
1546
- on: {
1547
- waitForDbSuccess: {
1548
- target: 'hydratingFromDb',
1549
- actions: assign({
1550
- isDbReady: true,
1551
- }),
1552
- },
1553
- },
1554
- invoke: {
1555
- src: 'waitForDb',
1556
- input: ({ context }) => ({ context }),
1557
- },
1558
- },
1559
- hydratingFromDb: {
1560
- on: {
1561
- hydrateFromDbSuccess: 'initializing',
1562
- },
1563
- invoke: {
1564
- src: 'hydrateFromDb',
1565
- input: ({ context }) => ({ context }),
1566
- },
1567
- },
1568
- initializing: {
1569
- on: {
1570
- initializeSuccess: 'idle',
1571
- isRelatedProperty: {
1572
- target: 'resolvingRelatedValue',
1573
- },
1574
- hasRemoteBackup: {
1575
- target: 'resolvingRemoteStorage',
1576
- },
1577
- },
1578
- invoke: {
1579
- src: 'initialize',
1580
- input: ({ context, event }) => ({ context, event }),
1581
- },
1582
- },
1583
- resolvingRelatedValue: {
1584
- on: {
1585
- resolvingRelatedValueSuccess: {
1586
- target: 'idle',
1587
- actions: assign({
1588
- resolvedDisplayValue: ({ event }) => event.resolvedDisplayValue,
1589
- resolvedValue: ({ event }) => event.resolvedValue,
1590
- }),
1591
- },
1592
- resolvingRelatedValueDone: {
1593
- target: 'idle',
1594
- },
1595
- },
1596
- invoke: {
1597
- src: 'resolveRelatedValue',
1598
- input: ({ context }) => ({ context }),
1599
- },
1600
- },
1601
- resolvingRemoteStorage: {
1602
- on: {
1603
- resolveRemoteStorageSuccess: {
1604
- target: 'idle',
1605
- },
1606
- },
1607
- invoke: {
1608
- src: 'resolveRemoteStorage',
1609
- input: ({ context }) => ({ context }),
1610
- },
1611
- },
1612
- saving: {
1613
- on: {
1614
- saveValueToDbSuccess: {
1615
- target: 'idle',
1616
- actions: assign({
1617
- isSaving: false,
1618
- }),
1619
- },
1620
- saveValueToDbFailure: {
1621
- target: 'idle',
1622
- actions: assign({
1623
- isSaving: false,
1624
- }),
1625
- },
1626
- },
1627
- invoke: {
1628
- src: 'saveValueToDb',
1629
- input: ({ context, event }) => ({ context, event }),
1630
- },
1631
- },
1632
- },
1633
- // conflict: {
1634
- // on: {
1635
- // resolveConflict: {
1636
- // target: 'saving',
1637
- // actions: assign({
1638
- // data: ({ context, event }) => event.output,
1639
- // }),
1640
- // },
1641
- // },
1642
- // },
1643
- });
1644
-
1645
1420
  const modelStore = new Map();
1646
1421
  const getModels = () => {
1647
1422
  return Object.fromEntries(modelStore);
@@ -1662,7 +1437,7 @@ const namesThatEndWithId = [];
1662
1437
  class ItemProperty {
1663
1438
  // private constructor(localIdOrUid) {
1664
1439
  // }
1665
- constructor({ propertyValue, seedUid, seedLocalId, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
1440
+ constructor({ propertyValue, seedUid, seedLocalId, versionLocalId, versionUid, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
1666
1441
  this._isRelation = false;
1667
1442
  this._isList = false;
1668
1443
  this[_a$2] = true;
@@ -1673,12 +1448,13 @@ class ItemProperty {
1673
1448
  if (!propertyName) {
1674
1449
  throw new Error(`Property name not provided`);
1675
1450
  }
1676
- this._lastRenderedValue = propertyValue;
1677
1451
  const serviceInput = {
1678
1452
  propertyValue,
1679
- seedUid,
1680
1453
  propertyName,
1681
1454
  seedLocalId,
1455
+ seedUid,
1456
+ versionLocalId,
1457
+ versionUid,
1682
1458
  itemModelName,
1683
1459
  storageTransactionId,
1684
1460
  propertyRecordSchema: ModelClass.schema[propertyName],
@@ -1723,8 +1499,12 @@ class ItemProperty {
1723
1499
  this._service = createActor(propertyMachine, {
1724
1500
  input: serviceInput,
1725
1501
  });
1726
- this._subscription = this._service.subscribe((snapshot) => {
1502
+ this._subscription = this._service.subscribe((snapshot) => __awaiter(this, void 0, void 0, function* () {
1503
+ if (!snapshot || !snapshot.context) {
1504
+ return;
1505
+ }
1727
1506
  const { context } = snapshot;
1507
+ const { propertyRecordSchema } = context;
1728
1508
  // if (this.uid && !cacheHasProperty(this.uid)) {
1729
1509
  // addPropertyToCache(this)
1730
1510
  // }
@@ -1746,7 +1526,21 @@ class ItemProperty {
1746
1526
  // this._updateResponseListener,
1747
1527
  // )
1748
1528
  }
1749
- const renderValue = context.renderValue || context.propertyValue;
1529
+ let renderValue;
1530
+ if (propertyRecordSchema &&
1531
+ propertyRecordSchema.storageType &&
1532
+ propertyRecordSchema.storageType === 'ItemStorage' &&
1533
+ context.resolvedValue &&
1534
+ context.localStorageDir) {
1535
+ const filePath = `/files/${context.localStorageDir}/${context.resolvedValue}`;
1536
+ const exists = yield fs.promises.exists(filePath);
1537
+ if (exists) {
1538
+ renderValue = yield fs.promises.readFile(filePath, 'utf-8');
1539
+ }
1540
+ }
1541
+ if (!renderValue) {
1542
+ renderValue = context.renderValue || context.propertyValue;
1543
+ }
1750
1544
  let transformedPropertyName = propertyName;
1751
1545
  const skipTransform = internalPropertyNames.includes(propertyName) || !!this._alias;
1752
1546
  if (!skipTransform && transformedPropertyName.endsWith('Id')) {
@@ -1766,14 +1560,14 @@ class ItemProperty {
1766
1560
  if (context.seedUid) {
1767
1561
  eventEmitter.emit(`item.${itemModelName}.${context.seedUid}.update`);
1768
1562
  }
1769
- });
1563
+ }));
1770
1564
  this._service.start();
1771
1565
  }
1772
1566
  _updateResponseListener(event) {
1773
1567
  logger$k(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1774
1568
  }
1775
1569
  static create(props) {
1776
- const { propertyName, seedLocalId, seedUid } = props;
1570
+ const { propertyName, seedLocalId, seedUid, versionLocalId, versionUid } = props;
1777
1571
  if (!propertyName || (!seedLocalId && !seedUid)) {
1778
1572
  return;
1779
1573
  }
@@ -1842,32 +1636,35 @@ class ItemProperty {
1842
1636
  getService() {
1843
1637
  return this._service;
1844
1638
  }
1639
+ _getSnapshot() {
1640
+ return this._service.getSnapshot();
1641
+ }
1845
1642
  get localId() {
1846
- return this._service.getSnapshot().context.localId;
1643
+ return this._getSnapshot().context.localId;
1847
1644
  }
1848
1645
  get uid() {
1849
- return this._service.getSnapshot().context.uid;
1646
+ return this._getSnapshot().context.uid;
1850
1647
  }
1851
1648
  get seedLocalId() {
1852
- return this._service.getSnapshot().context.seedLocalId;
1649
+ return this._getSnapshot().context.seedLocalId;
1853
1650
  }
1854
1651
  get seedUid() {
1855
- return this._service.getSnapshot().context.seedUid;
1652
+ return this._getSnapshot().context.seedUid;
1856
1653
  }
1857
1654
  get propertyName() {
1858
1655
  if (this._alias) {
1859
1656
  return this._alias;
1860
1657
  }
1861
- return this._service.getSnapshot().context.propertyName;
1658
+ return this._getSnapshot().context.propertyName;
1862
1659
  }
1863
1660
  get itemModelName() {
1864
- return this._service.getSnapshot().context.itemModelName;
1661
+ return this._getSnapshot().context.itemModelName;
1865
1662
  }
1866
1663
  get propertyDef() {
1867
- return this._service.getSnapshot().context.propertyRecordSchema;
1664
+ return this._getSnapshot().context.propertyRecordSchema;
1868
1665
  }
1869
1666
  get status() {
1870
- return this._service.getSnapshot().value;
1667
+ return this._getSnapshot().value;
1871
1668
  }
1872
1669
  get alias() {
1873
1670
  return this._alias;
@@ -1892,7 +1689,7 @@ class ItemProperty {
1892
1689
  });
1893
1690
  }
1894
1691
  get published() {
1895
- return !!this._service.getSnapshot().context.uid;
1692
+ return !!this._getSnapshot().context.uid;
1896
1693
  }
1897
1694
  subscribe(callback) {
1898
1695
  return this._subject.subscribe(callback);
@@ -1921,84 +1718,6 @@ class ItemProperty {
1921
1718
  _a$2 = immerable;
1922
1719
  ItemProperty.instanceCache = new Map();
1923
1720
 
1924
- const TPropertyDataType = Type.Union([
1925
- Type.Literal('Text'),
1926
- Type.Literal('Number'),
1927
- Type.Literal('List'),
1928
- Type.Literal('Relation'),
1929
- Type.Literal('ImageSrc'),
1930
- Type.Literal('FileSrc'),
1931
- Type.Literal('Json'),
1932
- Type.Literal('Blob'),
1933
- ]);
1934
- const TStorageType = Type.Union([
1935
- Type.Literal('ItemStorage'), // Looks for a storageTransactionId property on the item
1936
- Type.Literal('PropertyStorage'), // Looks for a storageTransactionId value on the property
1937
- ]);
1938
- const TProperty = Type.Object({
1939
- id: Type.Optional(Type.Number()),
1940
- name: Type.Optional(Type.String()),
1941
- dataType: TPropertyDataType,
1942
- ref: Type.Optional(Type.String()),
1943
- modelId: Type.Optional(Type.Number()),
1944
- refModelId: Type.Optional(Type.Number()),
1945
- refValueType: Type.Optional(TPropertyDataType),
1946
- storageType: Type.Optional(TStorageType),
1947
- localStorageDir: Type.Optional(Type.String()),
1948
- filenameSuffix: Type.Optional(Type.String()),
1949
- });
1950
- const TPropertyConstructor = Type.Function([
1951
- Type.Optional(Type.Union([Type.String(), TStorageType])),
1952
- Type.Optional(Type.Union([Type.String(), TPropertyDataType])),
1953
- Type.Optional(Type.String()),
1954
- ], TProperty);
1955
- Type.Record(TPropertyDataType, TPropertyConstructor);
1956
- const Property = {
1957
- Text: (storageType, localStorageDir, filenameSuffix) => ({
1958
- dataType: 'Text',
1959
- storageType,
1960
- localStorageDir,
1961
- filenameSuffix,
1962
- TObject: Type.String(),
1963
- }),
1964
- Json: () => ({ dataType: 'Json' }),
1965
- Blob: () => ({ dataType: 'Blob' }),
1966
- Number: () => ({ dataType: 'Number' }),
1967
- List: (ref, refValueType) => ({
1968
- dataType: 'List',
1969
- ref,
1970
- refValueType,
1971
- }),
1972
- Relation: (ref, refValueType) => ({
1973
- dataType: 'Relation',
1974
- ref,
1975
- refValueType,
1976
- }),
1977
- ImageSrc: () => ({ dataType: 'ImageSrc' }),
1978
- };
1979
- const PropertyMetadataKey = Symbol('property');
1980
- const PropertyConstructor = (propertyType) => {
1981
- return function (parentClassPrototype, propertyKey) {
1982
- const existingProperties = Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype) || [];
1983
- existingProperties.push({ propertyKey, propertyType });
1984
- // console.log('existingProperties', existingProperties)
1985
- // console.log('propertyKey', propertyKey)
1986
- // console.log('propertyType', propertyType)
1987
- // console.log('PropertyMetadataKey', PropertyMetadataKey)
1988
- // console.log('typeof target', typeof target)
1989
- Reflect.defineMetadata(PropertyMetadataKey, existingProperties, parentClassPrototype);
1990
- // console.log(
1991
- // `After adding ${propertyKey}:`,
1992
- // Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype),
1993
- // )
1994
- };
1995
- };
1996
- const Text = (storageType, srcDir, filenameSuffix) => PropertyConstructor(Property.Text(storageType, srcDir, filenameSuffix));
1997
- const Json = () => PropertyConstructor(Property.Json());
1998
- const ImageSrc = () => PropertyConstructor(Property.ImageSrc());
1999
- const Relation = (ref, refValueType) => PropertyConstructor(Property.Relation(ref, refValueType)); // Adjust for actual relation type
2000
- const List = (ref, reValueType) => PropertyConstructor(Property.List(ref, reValueType)); // Adjust for actual list type
2001
-
2002
1721
  const waitForDb = fromCallback(({ sendBack }) => {
2003
1722
  const _waitForDb = new Promise((resolve) => {
2004
1723
  const interval = setInterval(() => {
@@ -2553,7 +2272,7 @@ const createMetadataRecordsForStorageTransactionId = (storageTransactionIdProper
2553
2272
  versionLocalId,
2554
2273
  versionUid,
2555
2274
  refValueType: 'file',
2556
- refResolvedValue: `${propertyValue}.${propertyDef.filenameSuffix}`,
2275
+ refResolvedValue: `${propertyValue}${propertyDef.filenameSuffix}`,
2557
2276
  modelType: seedUidToModelType.get(seedUid),
2558
2277
  createdAt: Date.now(),
2559
2278
  updatedAt: Date.now(),
@@ -2894,7 +2613,7 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2894
2613
  if (!models$1) {
2895
2614
  return;
2896
2615
  }
2897
- const { models: SeedModels } = yield import('./seed.schema.config-BtfzZOfM.js');
2616
+ const { models: SeedModels } = yield import('./seed.schema.config-OyHsE0Zl.js');
2898
2617
  const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
2899
2618
  let hasModelsInDb = false;
2900
2619
  const schemaDefsByModelName = new Map();
@@ -3866,6 +3585,22 @@ const getArweave = () => {
3866
3585
  });
3867
3586
  };
3868
3587
 
3588
+ const getVersionData = () => {
3589
+ const appDb = getAppDb();
3590
+ return appDb.$with('versionData').as(appDb
3591
+ .select({
3592
+ seedLocalId: versions.seedLocalId,
3593
+ seedUid: versions.seedUid,
3594
+ latestVersionUid: versions.uid,
3595
+ latestVersionLocalId: versions.localId,
3596
+ versionsCount: count(versions.localId).as('versionsCount'),
3597
+ lastVersionPublishedAt: max(versions.attestationCreatedAt).as('lastVersionPublishedAt'),
3598
+ lastLocalUpdateAt: max(versions.createdAt).as('lastLocalUpdateAt'),
3599
+ })
3600
+ .from(versions)
3601
+ .groupBy(versions.seedLocalId));
3602
+ };
3603
+
3869
3604
  const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
3870
3605
  const appDb = getAppDb();
3871
3606
  const conditions = [];
@@ -3878,22 +3613,24 @@ const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelN
3878
3613
  if (!deleted) {
3879
3614
  conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
3880
3615
  }
3616
+ const versionData = getVersionData();
3881
3617
  let query = appDb
3618
+ .with(versionData)
3882
3619
  .select({
3883
3620
  seedLocalId: seeds.localId,
3884
3621
  seedUid: seeds.uid,
3885
3622
  schemaUid: seeds.schemaUid,
3886
3623
  modelName: sql `${modelName}`,
3887
3624
  attestationCreatedAt: seeds.attestationCreatedAt,
3888
- versionsCount: count(versions.localId),
3889
- lastVersionPublishedAt: max(versions.attestationCreatedAt),
3890
- lastLocalUpdateAt: max(versions.createdAt),
3625
+ versionsCount: versionData.versionsCount,
3626
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
3627
+ lastLocalUpdateAt: versionData.lastLocalUpdateAt,
3891
3628
  createdAt: seeds.createdAt,
3892
3629
  })
3893
3630
  .from(seeds)
3894
- .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
3631
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
3895
3632
  .where(and(...conditions))
3896
- .orderBy(desc(seeds.createdAt))
3633
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
3897
3634
  .groupBy(seeds.localId);
3898
3635
  const itemsData = (yield query);
3899
3636
  return itemsData;
@@ -5589,7 +5326,7 @@ const client = {
5589
5326
  console.error('fs listeners not ready during init');
5590
5327
  }
5591
5328
  globalService.send({ type: 'init', endpoints, models, addresses });
5592
- import('./seed.schema.config-BtfzZOfM.js').then(({ models }) => {
5329
+ import('./seed.schema.config-OyHsE0Zl.js').then(({ models }) => {
5593
5330
  for (const [key, value] of Object.entries(models)) {
5594
5331
  setModel(key, value);
5595
5332
  }
@@ -6562,98 +6299,6 @@ const getItemProperties = (_a) => __awaiter(void 0, [_a], void 0, function* ({ s
6562
6299
  // })
6563
6300
  // }
6564
6301
 
6565
- const logger = debug('app:db:queries:getItem');
6566
- const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
6567
- if (!seedLocalId && !seedUid) {
6568
- throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
6569
- }
6570
- if (seedUid && !seedLocalId) {
6571
- const seedData = yield getSeedData({ seedUid });
6572
- if (!seedData) {
6573
- logger('[db/queries] [getItem] no seedData seedUid', seedUid);
6574
- return;
6575
- }
6576
- seedLocalId = seedData.localId;
6577
- }
6578
- const appDb = getAppDb();
6579
- const _b = getTableColumns(seeds), rest = __rest(_b, ["localId", "uid"]);
6580
- const whereClauses = [];
6581
- if (modelName) {
6582
- whereClauses.push(eq(seeds.type, modelName.toLowerCase()));
6583
- }
6584
- if (seedUid) {
6585
- whereClauses.push(eq(seeds.uid, seedUid));
6586
- }
6587
- if (seedLocalId && !seedUid) {
6588
- whereClauses.push(eq(seeds.localId, seedLocalId));
6589
- }
6590
- // const uidWhereClause: SQL = seedUid
6591
- // ? eq(seeds.uid, seedUid)
6592
- // : isNull(seeds.uid)
6593
- // const localWhereClause: SQL = seedLocalId
6594
- // ? eq(seeds.localId, seedLocalId)
6595
- // : isNull(seeds.localId)
6596
- // whereClauses.push(or(localWhereClause, uidWhereClause) as SQL)
6597
- const latestVersions = appDb.$with('latestVersions').as(appDb
6598
- .select({
6599
- localId: versions.localId,
6600
- uid: versions.uid,
6601
- seedLocalId: versions.seedLocalId,
6602
- seedUid: versions.seedUid,
6603
- })
6604
- .from(versions)
6605
- .groupBy(versions.seedLocalId));
6606
- const itemDataRows = yield appDb
6607
- .with(latestVersions)
6608
- .select(Object.assign(Object.assign({}, rest), { seedLocalId: seeds.localId, seedUid: seeds.uid, versionsCount: count(versions.localId), lastVersionPublishedAt: max(versions.attestationCreatedAt), latestVersionUid: latestVersions.uid }))
6609
- .from(seeds)
6610
- .leftJoin(versions, eq(versions.seedLocalId, seeds.localId))
6611
- .leftJoin(latestVersions, eq(versions.seedLocalId, latestVersions.seedLocalId))
6612
- .where(and(...whereClauses))
6613
- .groupBy(seeds.localId);
6614
- if (!itemDataRows || itemDataRows.length === 0) {
6615
- logger('[db/queries] [getItemDataFromDb] no itemDataRows');
6616
- return;
6617
- }
6618
- let itemData = itemDataRows[0];
6619
- const propertiesData = yield getItemProperties({ seedLocalId, seedUid });
6620
- // const initObj: ItemData = {
6621
- // seedLocalId,
6622
- // seedUid,
6623
- // modelName,
6624
- // }
6625
- if (!propertiesData || propertiesData.length === 0) {
6626
- return itemData;
6627
- }
6628
- propertiesData[0];
6629
- for (const propertyData of propertiesData) {
6630
- const propertyName = propertyData.propertyName;
6631
- const propertyValue = propertyData.propertyValue;
6632
- // TODO: Find a better place for the property data below
6633
- // Since initObj is used to initialize an Item, the following values
6634
- // just overwrite each other for each property since they are Property
6635
- // specific.
6636
- // const refSeedType = propertyDbValues[11]
6637
- // if (refSeedType) {
6638
- // initObj.refSeedType = refSeedType
6639
- // }
6640
- // const refValueType = propertyDbValues[12]
6641
- // if (refValueType) {
6642
- // initObj.refValueType = refValueType
6643
- // }
6644
- //
6645
- // if (
6646
- // refSeedType &&
6647
- // refValueType === 'list' &&
6648
- // propertyName.endsWith('Ids')
6649
- // ) {
6650
- // logger('[db/queries] [getItemDataFromDb] propertyName', propertyName)
6651
- // }
6652
- itemData[propertyName] = propertyValue;
6653
- }
6654
- return itemData;
6655
- });
6656
-
6657
6302
  var _a$1;
6658
6303
  class Item {
6659
6304
  constructor(initialValues) {
@@ -6686,7 +6331,7 @@ class Item {
6686
6331
  },
6687
6332
  });
6688
6333
  });
6689
- const { modelName, seedUid, schemaUid, seedLocalId } = initialValues;
6334
+ const { modelName, seedUid, schemaUid, seedLocalId, latestVersionLocalId, latestVersionUid, } = initialValues;
6690
6335
  const ModelClass = getModel(modelName);
6691
6336
  if (ModelClass &&
6692
6337
  Object.keys(ModelClass === null || ModelClass === void 0 ? void 0 : ModelClass.schema).includes('storageTransactionId') &&
@@ -6699,15 +6344,14 @@ class Item {
6699
6344
  seedUid,
6700
6345
  schemaUid,
6701
6346
  ModelClass,
6347
+ latestVersionLocalId,
6348
+ latestVersionUid,
6702
6349
  storageTransactionId: this._storageTransactionId,
6703
6350
  },
6704
6351
  });
6705
6352
  this._subscription = this._service.subscribe((snapshot) => {
6706
6353
  const { context } = snapshot;
6707
- if (
6708
- // snapshot.value === 'waitingForDb' ||
6709
- // snapshot.value === 'initializing' ||
6710
- !context ||
6354
+ if (!context ||
6711
6355
  !context.propertyInstances ||
6712
6356
  context.propertyInstances.size === 0) {
6713
6357
  return;
@@ -6739,6 +6383,8 @@ class Item {
6739
6383
  const itemPropertyBase = {
6740
6384
  seedLocalId,
6741
6385
  seedUid,
6386
+ versionLocalId: latestVersionLocalId,
6387
+ versionUid: latestVersionUid,
6742
6388
  itemModelName: modelName,
6743
6389
  schemaUid,
6744
6390
  };
@@ -6762,6 +6408,9 @@ class Item {
6762
6408
  }
6763
6409
  static create(props) {
6764
6410
  return __awaiter(this, void 0, void 0, function* () {
6411
+ if (!props.seedUid) {
6412
+ console.log('Creating new item without seedUid');
6413
+ }
6765
6414
  if (props.seedUid || props.seedLocalId) {
6766
6415
  const seedId = (props.seedUid || props.seedLocalId);
6767
6416
  if (Item.instanceCache.has(seedId)) {
@@ -6806,6 +6455,13 @@ class Item {
6806
6455
  seedLocalId,
6807
6456
  seedUid,
6808
6457
  });
6458
+ if (!itemData) {
6459
+ console.error('No item data found', { modelName, seedLocalId, seedUid });
6460
+ return;
6461
+ }
6462
+ if (!(itemData === null || itemData === void 0 ? void 0 : itemData.seedUid)) {
6463
+ console.log('Item not found', { modelName, seedLocalId, seedUid });
6464
+ }
6809
6465
  return Item.create(Object.assign(Object.assign({}, itemData), { modelName }));
6810
6466
  });
6811
6467
  }
@@ -6882,6 +6538,491 @@ class Item {
6882
6538
  _a$1 = immerable;
6883
6539
  Item.instanceCache = new Map();
6884
6540
 
6541
+ const logger = debug('app:db:queries:getItem');
6542
+ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
6543
+ if (!seedLocalId && !seedUid) {
6544
+ throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
6545
+ }
6546
+ if (seedUid && !seedLocalId) {
6547
+ const seedData = yield getSeedData({ seedUid });
6548
+ if (!seedData) {
6549
+ logger('[db/queries] [getItem] no seedData seedUid', seedUid);
6550
+ return;
6551
+ }
6552
+ seedLocalId = seedData.localId;
6553
+ }
6554
+ const appDb = getAppDb();
6555
+ const _b = getTableColumns(seeds), rest = __rest(_b, ["localId", "uid"]);
6556
+ const whereClauses = [];
6557
+ if (modelName) {
6558
+ whereClauses.push(eq(seeds.type, modelName.toLowerCase()));
6559
+ }
6560
+ if (seedUid) {
6561
+ whereClauses.push(eq(seeds.uid, seedUid));
6562
+ }
6563
+ if (seedLocalId && !seedUid) {
6564
+ whereClauses.push(eq(seeds.localId, seedLocalId));
6565
+ }
6566
+ const versionData = getVersionData();
6567
+ const itemDataRows = yield appDb
6568
+ .with(versionData)
6569
+ .select(Object.assign(Object.assign({}, rest), { seedLocalId: seeds.localId, seedUid: seeds.uid, versionsCount: versionData.versionsCount, lastVersionPublishedAt: versionData.lastVersionPublishedAt, latestVersionUid: versionData.latestVersionUid, latestVersionLocalId: versionData.latestVersionLocalId }))
6570
+ .from(seeds)
6571
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
6572
+ .where(and(...whereClauses, gt(versionData.versionsCount, 0)))
6573
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
6574
+ .groupBy(seeds.localId);
6575
+ if (!itemDataRows || itemDataRows.length === 0) {
6576
+ logger('[db/queries] [getItemDataFromDb] no itemDataRows');
6577
+ return;
6578
+ }
6579
+ let itemData = itemDataRows[0];
6580
+ const propertiesData = yield getItemProperties({ seedLocalId, seedUid });
6581
+ // const initObj: ItemData = {
6582
+ // seedLocalId,
6583
+ // seedUid,
6584
+ // modelName,
6585
+ // }
6586
+ if (!propertiesData || propertiesData.length === 0) {
6587
+ return itemData;
6588
+ }
6589
+ propertiesData[0];
6590
+ for (const propertyData of propertiesData) {
6591
+ const propertyName = propertyData.propertyName;
6592
+ const propertyValue = propertyData.propertyValue;
6593
+ // TODO: Find a better place for the property data below
6594
+ // Since initObj is used to initialize an Item, the following values
6595
+ // just overwrite each other for each property since they are Property
6596
+ // specific.
6597
+ // const refSeedType = propertyDbValues[11]
6598
+ // if (refSeedType) {
6599
+ // initObj.refSeedType = refSeedType
6600
+ // }
6601
+ // const refValueType = propertyDbValues[12]
6602
+ // if (refValueType) {
6603
+ // initObj.refValueType = refValueType
6604
+ // }
6605
+ //
6606
+ // if (
6607
+ // refSeedType &&
6608
+ // refValueType === 'list' &&
6609
+ // propertyName.endsWith('Ids')
6610
+ // ) {
6611
+ // logger('[db/queries] [getItemDataFromDb] propertyName', propertyName)
6612
+ // }
6613
+ itemData[propertyName] = propertyValue;
6614
+ }
6615
+ return itemData;
6616
+ });
6617
+
6618
+ const getItemPropertyData = (props) => __awaiter(void 0, void 0, void 0, function* () {
6619
+ const appDb = getAppDb();
6620
+ const whereClauses = [];
6621
+ const tableColumns = getTableColumns(metadata);
6622
+ for (const [propertyName, propertyValue] of Object.entries(props)) {
6623
+ if (Object.keys(tableColumns).includes(propertyName)) {
6624
+ tableColumns[propertyName];
6625
+ whereClauses.push(eq(tableColumns[propertyName], propertyValue));
6626
+ }
6627
+ }
6628
+ const queryRows = yield appDb
6629
+ .select()
6630
+ .from(metadata)
6631
+ .where(and(...whereClauses));
6632
+ if (!queryRows || queryRows.length === 0) {
6633
+ return;
6634
+ }
6635
+ return queryRows[0];
6636
+ });
6637
+
6638
+ const createMetadata = (metadataValues, propertyRecordSchema) => __awaiter(void 0, void 0, void 0, function* () {
6639
+ const appDb = getAppDb();
6640
+ metadataValues.localId = generateId();
6641
+ if (propertyRecordSchema &&
6642
+ propertyRecordSchema.localStorageDir &&
6643
+ propertyRecordSchema.storageType === 'ItemStorage') {
6644
+ metadataValues.refResolvedValue = `${metadataValues.localId}${propertyRecordSchema.filenameSuffix}`;
6645
+ metadataValues.refValueType = 'file';
6646
+ }
6647
+ return appDb
6648
+ .insert(metadata)
6649
+ .values(Object.assign(Object.assign({}, metadataValues), { createdAt: Date.now(), updatedAt: Date.now() }))
6650
+ .returning();
6651
+ });
6652
+
6653
+ const saveValueToDb = fromCallback(({ sendBack, input: { context, event } }) => {
6654
+ const { localId, propertyName: propertyNameRaw, seedLocalId, seedUid, versionLocalId, versionUid, propertyValue: existingValue, propertyRecordSchema, itemModelName, schemaUid, } = context;
6655
+ let { newValue } = event;
6656
+ if (existingValue === newValue) {
6657
+ sendBack({ type: 'saveValueToDbSuccess' });
6658
+ return;
6659
+ }
6660
+ const _saveValueToDb = () => __awaiter(void 0, void 0, void 0, function* () {
6661
+ let refResolvedValue;
6662
+ let refResolvedDisplayValue;
6663
+ let refSeedType;
6664
+ let propertyName = propertyNameRaw;
6665
+ if (propertyRecordSchema && propertyRecordSchema.dataType === 'Relation') {
6666
+ refResolvedValue = newValue;
6667
+ if (!propertyName.endsWith('Id')) {
6668
+ propertyName = `${propertyName}Id`;
6669
+ }
6670
+ let fileType;
6671
+ const dirs = yield fs.promises.readdir('/files');
6672
+ for (const dir of dirs) {
6673
+ const files = yield fs.promises.readdir(`/files/${dir}`);
6674
+ if (files.includes(newValue)) {
6675
+ fileType = dir;
6676
+ break;
6677
+ }
6678
+ }
6679
+ if (fileType === 'images') {
6680
+ const filePath = `/files/images/${newValue}`;
6681
+ refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
6682
+ refSeedType = 'image';
6683
+ newValue = yield createSeed({
6684
+ type: refSeedType,
6685
+ });
6686
+ yield createVersion({
6687
+ seedLocalId,
6688
+ seedUid,
6689
+ seedType: refSeedType,
6690
+ });
6691
+ }
6692
+ }
6693
+ if (propertyRecordSchema &&
6694
+ propertyRecordSchema.storageType &&
6695
+ propertyRecordSchema.storageType === 'ItemStorage') {
6696
+ // Save value to file
6697
+ const appDb = getAppDb();
6698
+ let propertyData;
6699
+ if (localId) {
6700
+ propertyData = yield getItemPropertyData({
6701
+ localId,
6702
+ });
6703
+ }
6704
+ if (!localId && seedLocalId) {
6705
+ const itemData = yield getItemDataFromDb({
6706
+ seedLocalId,
6707
+ });
6708
+ if (itemData) {
6709
+ const whereClauses = [
6710
+ eq(metadata.propertyName, propertyName),
6711
+ eq(metadata.seedLocalId, seedLocalId),
6712
+ ];
6713
+ if (itemData.latestVersionLocalId) {
6714
+ whereClauses.push(eq(metadata.versionLocalId, itemData.latestVersionLocalId));
6715
+ }
6716
+ const queryRows = yield appDb
6717
+ .select()
6718
+ .from(metadata)
6719
+ .where(and(...whereClauses));
6720
+ if (queryRows && queryRows.length) {
6721
+ propertyData = queryRows[0];
6722
+ }
6723
+ if (!propertyData) {
6724
+ const propertyDataRows = yield createMetadata({
6725
+ propertyName,
6726
+ modelType: itemModelName.toLowerCase(),
6727
+ seedLocalId,
6728
+ seedUid,
6729
+ versionLocalId: itemData.latestVersionLocalId,
6730
+ versionUid: itemData.latestVersionUid,
6731
+ localStorageDir: propertyRecordSchema.localStorageDir,
6732
+ refValueType: 'file',
6733
+ }, propertyRecordSchema);
6734
+ propertyData = propertyDataRows[0];
6735
+ }
6736
+ // propertyData = {
6737
+ // propertyName,
6738
+ // seedLocalId,
6739
+ // seedUid,
6740
+ // versionLocalId: itemData.latestVersionLocalId,
6741
+ // versionUid: itemData.latestVersionUid,
6742
+ // schemaUid: itemData.schemaUid,
6743
+ // }
6744
+ }
6745
+ }
6746
+ const localStorageDir = propertyRecordSchema.localStorageDir || propertyData.localStorageDir;
6747
+ const fileName = propertyData.refResolvedValue ||
6748
+ `${propertyData.localId}${propertyRecordSchema.filenameSuffix}`;
6749
+ if (!localStorageDir || !fileName) {
6750
+ throw new Error(`Missing localStorageDir: ${localStorageDir} or fileName: ${fileName}`);
6751
+ }
6752
+ const filePath = `/files/${localStorageDir}/${fileName}`;
6753
+ yield fs.promises.writeFile(filePath, newValue);
6754
+ yield appDb
6755
+ .update(metadata)
6756
+ .set({
6757
+ refResolvedValue: fileName,
6758
+ })
6759
+ .where(eq(metadata.localId, propertyData.localId));
6760
+ sendBack({
6761
+ type: 'updateContext',
6762
+ renderValue: newValue,
6763
+ });
6764
+ return;
6765
+ }
6766
+ yield updateItemPropertyValue({
6767
+ propertyLocalId: localId,
6768
+ propertyName,
6769
+ newValue,
6770
+ seedLocalId,
6771
+ refSeedType,
6772
+ refResolvedValue,
6773
+ refResolvedDisplayValue,
6774
+ versionLocalId,
6775
+ modelName: itemModelName,
6776
+ schemaUid,
6777
+ });
6778
+ sendBack({
6779
+ type: 'updateContext',
6780
+ propertyValue: newValue,
6781
+ renderValue: refResolvedDisplayValue,
6782
+ });
6783
+ });
6784
+ _saveValueToDb().then(() => {
6785
+ sendBack({ type: 'saveValueToDbSuccess' });
6786
+ });
6787
+ });
6788
+
6789
+ // import { updateMachineContext } from '@/browser/helpers'
6790
+ const propertyMachine = setup({
6791
+ types: {
6792
+ context: {},
6793
+ },
6794
+ // actions: {
6795
+ // updateContext: updateMachineContext,
6796
+ // },
6797
+ actors: {
6798
+ waitForDb: waitForDb$1,
6799
+ hydrateFromDb,
6800
+ initialize: initialize$3,
6801
+ resolveRelatedValue,
6802
+ resolveRemoteStorage,
6803
+ saveValueToDb,
6804
+ },
6805
+ }).createMachine({
6806
+ id: 'itemProperty',
6807
+ initial: 'waitingForDb',
6808
+ context: ({ input }) => input,
6809
+ on: {
6810
+ updatePropertyValue: {
6811
+ target: '.resolvingRelatedValue',
6812
+ guard: ({ context }) => !context.isDbReady,
6813
+ actions: assign(({ event }) => {
6814
+ return {
6815
+ propertyValue: event.propertyValue,
6816
+ };
6817
+ }),
6818
+ },
6819
+ updateRenderValue: {
6820
+ actions: assign(({ event, context }) => {
6821
+ return {
6822
+ renderValue: event.renderValue,
6823
+ };
6824
+ }),
6825
+ },
6826
+ save: {
6827
+ actions: assign({
6828
+ isSaving: true,
6829
+ }),
6830
+ target: '.saving',
6831
+ },
6832
+ updateContext: {
6833
+ actions: assign(({ context, event }) => {
6834
+ const newContext = Object.assign({}, context);
6835
+ for (let i = 0; i < Object.keys(event).length; i++) {
6836
+ const key = Object.keys(event)[i];
6837
+ if (key === 'type') {
6838
+ continue;
6839
+ }
6840
+ newContext[key] = event[key];
6841
+ }
6842
+ return newContext;
6843
+ }),
6844
+ },
6845
+ },
6846
+ states: {
6847
+ idle: {},
6848
+ waitingForDb: {
6849
+ on: {
6850
+ waitForDbSuccess: {
6851
+ target: 'hydratingFromDb',
6852
+ actions: assign({
6853
+ isDbReady: true,
6854
+ }),
6855
+ },
6856
+ },
6857
+ invoke: {
6858
+ src: 'waitForDb',
6859
+ input: ({ context }) => ({ context }),
6860
+ },
6861
+ },
6862
+ hydratingFromDb: {
6863
+ on: {
6864
+ hydrateFromDbSuccess: 'initializing',
6865
+ },
6866
+ invoke: {
6867
+ src: 'hydrateFromDb',
6868
+ input: ({ context }) => ({ context }),
6869
+ },
6870
+ },
6871
+ initializing: {
6872
+ on: {
6873
+ initializeSuccess: 'idle',
6874
+ isRelatedProperty: {
6875
+ target: 'resolvingRelatedValue',
6876
+ },
6877
+ hasRemoteBackup: {
6878
+ target: 'resolvingRemoteStorage',
6879
+ },
6880
+ },
6881
+ invoke: {
6882
+ src: 'initialize',
6883
+ input: ({ context, event }) => ({ context, event }),
6884
+ },
6885
+ },
6886
+ resolvingRelatedValue: {
6887
+ on: {
6888
+ resolvingRelatedValueSuccess: {
6889
+ target: 'idle',
6890
+ actions: assign({
6891
+ resolvedDisplayValue: ({ event }) => event.resolvedDisplayValue,
6892
+ resolvedValue: ({ event }) => event.resolvedValue,
6893
+ }),
6894
+ },
6895
+ resolvingRelatedValueDone: {
6896
+ target: 'idle',
6897
+ },
6898
+ },
6899
+ invoke: {
6900
+ src: 'resolveRelatedValue',
6901
+ input: ({ context }) => ({ context }),
6902
+ },
6903
+ },
6904
+ resolvingRemoteStorage: {
6905
+ on: {
6906
+ resolveRemoteStorageSuccess: {
6907
+ target: 'idle',
6908
+ },
6909
+ },
6910
+ invoke: {
6911
+ src: 'resolveRemoteStorage',
6912
+ input: ({ context }) => ({ context }),
6913
+ },
6914
+ },
6915
+ saving: {
6916
+ on: {
6917
+ saveValueToDbSuccess: {
6918
+ target: 'idle',
6919
+ actions: assign({
6920
+ isSaving: false,
6921
+ }),
6922
+ },
6923
+ saveValueToDbFailure: {
6924
+ target: 'idle',
6925
+ actions: assign({
6926
+ isSaving: false,
6927
+ }),
6928
+ },
6929
+ },
6930
+ invoke: {
6931
+ src: 'saveValueToDb',
6932
+ input: ({ context, event }) => ({ context, event }),
6933
+ },
6934
+ },
6935
+ },
6936
+ // conflict: {
6937
+ // on: {
6938
+ // resolveConflict: {
6939
+ // target: 'saving',
6940
+ // actions: assign({
6941
+ // data: ({ context, event }) => event.output,
6942
+ // }),
6943
+ // },
6944
+ // },
6945
+ // },
6946
+ });
6947
+
6948
+ const TPropertyDataType = Type.Union([
6949
+ Type.Literal('Text'),
6950
+ Type.Literal('Number'),
6951
+ Type.Literal('List'),
6952
+ Type.Literal('Relation'),
6953
+ Type.Literal('ImageSrc'),
6954
+ Type.Literal('FileSrc'),
6955
+ Type.Literal('Json'),
6956
+ Type.Literal('Blob'),
6957
+ ]);
6958
+ const TStorageType = Type.Union([
6959
+ Type.Literal('ItemStorage'), // Looks for a storageTransactionId property on the item
6960
+ Type.Literal('PropertyStorage'), // Looks for a storageTransactionId value on the property
6961
+ ]);
6962
+ const TProperty = Type.Object({
6963
+ id: Type.Optional(Type.Number()),
6964
+ name: Type.Optional(Type.String()),
6965
+ dataType: TPropertyDataType,
6966
+ ref: Type.Optional(Type.String()),
6967
+ modelId: Type.Optional(Type.Number()),
6968
+ refModelId: Type.Optional(Type.Number()),
6969
+ refValueType: Type.Optional(TPropertyDataType),
6970
+ storageType: Type.Optional(TStorageType),
6971
+ localStorageDir: Type.Optional(Type.String()),
6972
+ filenameSuffix: Type.Optional(Type.String()),
6973
+ });
6974
+ const TPropertyConstructor = Type.Function([
6975
+ Type.Optional(Type.Union([Type.String(), TStorageType, Type.Undefined()])),
6976
+ Type.Optional(Type.Union([Type.String(), TPropertyDataType])),
6977
+ Type.Optional(Type.String()),
6978
+ ], TProperty);
6979
+ Type.Record(TPropertyDataType, TPropertyConstructor);
6980
+ const Property = {
6981
+ Text: (storageType, localStorageDir, filenameSuffix) => ({
6982
+ dataType: 'Text',
6983
+ storageType,
6984
+ localStorageDir,
6985
+ filenameSuffix,
6986
+ TObject: Type.String(),
6987
+ }),
6988
+ Json: () => ({ dataType: 'Json' }),
6989
+ Blob: () => ({ dataType: 'Blob' }),
6990
+ Number: () => ({ dataType: 'Number' }),
6991
+ List: (ref, refValueType) => ({
6992
+ dataType: 'List',
6993
+ ref,
6994
+ refValueType,
6995
+ }),
6996
+ Relation: (ref, refValueType) => ({
6997
+ dataType: 'Relation',
6998
+ ref,
6999
+ refValueType,
7000
+ }),
7001
+ ImageSrc: () => ({ dataType: 'ImageSrc' }),
7002
+ };
7003
+ const PropertyMetadataKey = Symbol('property');
7004
+ const PropertyConstructor = (propertyType) => {
7005
+ return function (parentClassPrototype, propertyKey) {
7006
+ const existingProperties = Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype) || [];
7007
+ existingProperties.push({ propertyKey, propertyType });
7008
+ // console.log('existingProperties', existingProperties)
7009
+ // console.log('propertyKey', propertyKey)
7010
+ // console.log('propertyType', propertyType)
7011
+ // console.log('PropertyMetadataKey', PropertyMetadataKey)
7012
+ // console.log('typeof target', typeof target)
7013
+ Reflect.defineMetadata(PropertyMetadataKey, existingProperties, parentClassPrototype);
7014
+ // console.log(
7015
+ // `After adding ${propertyKey}:`,
7016
+ // Reflect.getMetadata(PropertyMetadataKey, parentClassPrototype),
7017
+ // )
7018
+ };
7019
+ };
7020
+ const Text = (storageType, srcDir, filenameSuffix) => PropertyConstructor(Property.Text(storageType, srcDir, filenameSuffix));
7021
+ const Json = () => PropertyConstructor(Property.Json());
7022
+ const ImageSrc = () => PropertyConstructor(Property.ImageSrc());
7023
+ const Relation = (ref, refValueType) => PropertyConstructor(Property.Relation(ref, refValueType)); // Adjust for actual relation type
7024
+ const List = (ref, reValueType) => PropertyConstructor(Property.List(ref, reValueType)); // Adjust for actual list type
7025
+
6885
7026
  const TModelValues = Type.Record(Type.String(), Type.Any());
6886
7027
  const TModelSchema = Type.Record(Type.String(), TProperty);
6887
7028
  const TModelClass = Type.Object({
@@ -6956,4 +7097,4 @@ if (isNode()) {
6956
7097
  }
6957
7098
 
6958
7099
  export { GET_SCHEMAS as G, Item as I, Json as J, List as L, Model as M, Property as P, Relation as R, Text as T, 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, ImageSrc as h, itemMachineSingle as i, ItemProperty as j, useItem as k, useItemProperties as l, useCreateItem as m, useItemProperty as n, useDeleteItem as o, useGlobalServiceStatus as p, useServices as q, getGlobalService as r, client as s, getCorrectId as t, useItems as u, withSeed as w };
6959
- //# sourceMappingURL=index-DcXK4ERW.js.map
7100
+ //# sourceMappingURL=index-DQKd-s2Q.js.map