@seedprotocol/sdk 0.1.105 → 0.1.106

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 (36) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/{constants-rmQ8zg8_.js → constants-qIJt7998.js} +2 -1
  3. package/dist/{constants-rmQ8zg8_.js.map → constants-qIJt7998.js.map} +1 -1
  4. package/dist/{index--nvTinP_.js → index-CvfKxmFw.js} +1453 -1252
  5. package/dist/index-CvfKxmFw.js.map +1 -0
  6. package/dist/{index-D5tYjtxh.js → index-DyEsLJAK.js} +4 -4
  7. package/dist/{index-D5tYjtxh.js.map → index-DyEsLJAK.js.map} +1 -1
  8. package/dist/main.js +3 -3
  9. package/dist/{seed.schema.config-wQXee2fb.js → seed.schema.config-C37yDUmq.js} +4 -4
  10. package/dist/{seed.schema.config-wQXee2fb.js.map → seed.schema.config-C37yDUmq.js.map} +1 -1
  11. package/dist/src/eas.ts +40 -0
  12. package/dist/src/getPublishPayload.ts +290 -78
  13. package/dist/src/initialize.ts +6 -11
  14. package/dist/src/saveImageSrc.ts +21 -1
  15. package/dist/src/syncDbWithEas.ts +13 -5
  16. package/dist/types/src/browser/db/read/getPublishPayload.d.ts.map +1 -1
  17. package/dist/types/src/browser/events/item/syncDbWithEas.d.ts.map +1 -1
  18. package/dist/types/src/browser/item/Item.d.ts.map +1 -1
  19. package/dist/types/src/browser/property/actors/initialize.d.ts.map +1 -1
  20. package/dist/types/src/browser/property/actors/saveValueToDb/saveImageSrc.d.ts.map +1 -1
  21. package/dist/types/src/browser/property/index.d.ts +0 -1
  22. package/dist/types/src/browser/property/index.d.ts.map +1 -1
  23. package/dist/types/src/browser/react/services.d.ts +1 -1
  24. package/dist/types/src/browser/services/global/actors/initialize.d.ts +1 -1
  25. package/dist/types/src/browser/services/global/actors/initialize.d.ts.map +1 -1
  26. package/dist/types/src/browser/services/global/globalMachine.d.ts +613 -44
  27. package/dist/types/src/browser/services/global/globalMachine.d.ts.map +1 -1
  28. package/dist/types/src/browser/stores/eas.d.ts +7 -0
  29. package/dist/types/src/browser/stores/eas.d.ts.map +1 -0
  30. package/dist/types/src/shared/helpers/constants.d.ts.map +1 -1
  31. package/dist/types/src/shared/helpers/index.d.ts +1 -0
  32. package/dist/types/src/shared/helpers/index.d.ts.map +1 -1
  33. package/dist/types/src/types/item.d.ts +1 -0
  34. package/dist/types/src/types/item.d.ts.map +1 -1
  35. package/package.json +2 -2
  36. package/dist/index--nvTinP_.js.map +0 -1
@@ -1,15 +1,14 @@
1
- import { b as __awaiter, d as __rest, i as internalPropertyNames, I as INTERNAL_DATA_TYPES, e as defaultAttestationData, V as VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA } from './constants-rmQ8zg8_.js';
1
+ import { b as __awaiter, d as __rest, i as internalPropertyNames, I as INTERNAL_DATA_TYPES, V as VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA, e as defaultAttestationData } from './constants-qIJt7998.js';
2
2
  import path, { basename } from 'path';
3
3
  import 'reflect-metadata';
4
4
  import { Type } from '@sinclair/typebox';
5
5
  import { fromCallback, createActor, waitFor, setup, assign, raise } from 'xstate';
6
- import { sql, relations, or, eq, and, max, count, isNotNull, isNull, gt, inArray, like, getTableColumns } from 'drizzle-orm';
6
+ import { sql, relations, count, max, eq, or, isNotNull, isNull, and, gt, inArray, like, getTableColumns } from 'drizzle-orm';
7
7
  import { fs, configureSingle } from '@zenfs/core';
8
8
  import 'dayjs';
9
9
  import { customAlphabet } from 'nanoid';
10
10
  import * as nanoIdDictionary from 'nanoid-dictionary';
11
11
  import debug from 'debug';
12
- import { startCase, throttle, camelCase, orderBy } from 'lodash-es';
13
12
  import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
14
13
  import { useState, useEffect, useRef, useCallback } from 'react';
15
14
  import { QueryClient } from '@tanstack/react-query';
@@ -19,6 +18,7 @@ import { persistQueryClient } from '@tanstack/react-query-persist-client';
19
18
  import { useImmer } from 'use-immer';
20
19
  import { useSelector } from '@xstate/react';
21
20
  import EventEmitter from 'eventemitter3';
21
+ import { startCase, throttle, camelCase, orderBy } from 'lodash-es';
22
22
  import { immerable, produce, enableMapSet } from 'immer';
23
23
  import pluralize from 'pluralize';
24
24
  import { createBrowserInspector } from '@statelyai/inspect';
@@ -26,7 +26,7 @@ import { BehaviorSubject } from 'rxjs';
26
26
  import { drizzle } from 'drizzle-orm/sqlite-proxy';
27
27
  import { WebAccess } from '@zenfs/dom';
28
28
  import Arweave from 'arweave';
29
- import { SchemaEncoder, ZERO_ADDRESS } from '@ethereum-attestation-service/eas-sdk';
29
+ import { ZERO_ADDRESS, SchemaEncoder } from '@ethereum-attestation-service/eas-sdk';
30
30
 
31
31
  const isNode = () => {
32
32
  return (typeof process !== 'undefined' &&
@@ -87,6 +87,63 @@ const withSeed$1 = (config, webpack, isServer) => {
87
87
  return config;
88
88
  };
89
89
 
90
+ const resolveRemoteStorage = fromCallback(({ sendBack, input: { context } }) => {
91
+ const { propertyInstances } = context;
92
+ if (!propertyInstances) {
93
+ throw new Error(`propertyInstances not found for ${context.seedLocalId}`);
94
+ }
95
+ if (!propertyInstances.has('storageTransactionId')) {
96
+ return;
97
+ }
98
+ const storageTransactionId = propertyInstances.get('storageTransactionId');
99
+ const _resolveRemoteStorage = () => __awaiter(void 0, void 0, void 0, function* () {
100
+ const path = yield import('path-browserify');
101
+ const { fs } = yield import('@zenfs/core');
102
+ const filesDirExists = yield fs.promises.exists('/files');
103
+ if (!filesDirExists) {
104
+ yield fs.promises.mkdir('/files');
105
+ }
106
+ const htmlDir = path.join('/files', 'html');
107
+ const htmlExists = yield fs.promises.exists(htmlDir);
108
+ if (htmlExists) {
109
+ const htmlFiles = yield fs.promises.readdir(htmlDir);
110
+ const matchingHtmlFile = htmlFiles.find((file) => file === `${storageTransactionId}.html`);
111
+ if (matchingHtmlFile) {
112
+ const htmlString = yield fs.promises.readFile(path.join(htmlDir, matchingHtmlFile), 'utf8');
113
+ sendBack({
114
+ type: 'updateValue',
115
+ propertyName: 'html',
116
+ propertyValue: htmlString,
117
+ });
118
+ }
119
+ }
120
+ if (!htmlExists) {
121
+ yield fs.promises.mkdir(htmlDir);
122
+ }
123
+ const jsonDir = path.join('/files', 'json');
124
+ const jsonExists = yield fs.promises.exists(jsonDir);
125
+ if (jsonExists) {
126
+ const jsonFiles = yield fs.promises.readdir(jsonDir);
127
+ const matchingJsonFile = jsonFiles.find((file) => file === `${storageTransactionId}.json`);
128
+ if (matchingJsonFile) {
129
+ const jsonString = yield fs.promises.readFile(path.join(jsonDir, matchingJsonFile), 'utf8');
130
+ sendBack({
131
+ type: 'updateValue',
132
+ propertyName: 'json',
133
+ propertyValue: jsonString,
134
+ });
135
+ }
136
+ }
137
+ if (!jsonExists) {
138
+ yield fs.promises.mkdir(jsonDir);
139
+ }
140
+ });
141
+ _resolveRemoteStorage().then(() => {
142
+ sendBack({ type: 'resolveRemoteStorageSuccess' });
143
+ return;
144
+ });
145
+ });
146
+
90
147
  let sqlite3InitModule;
91
148
  let sqliteWasmClient;
92
149
  let isPreparing = false;
@@ -157,55 +214,6 @@ const waitForDb$1 = fromCallback(({ sendBack }) => {
157
214
  });
158
215
  });
159
216
 
160
- const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
161
- const { isRelation, propertyName, storageTransactionId } = context;
162
- if (isRelation) {
163
- sendBack({ type: 'isRelatedProperty' });
164
- sendBack({ type: 'initializeSuccess' });
165
- return;
166
- }
167
- if (!isRelation) {
168
- if ((propertyName !== 'html' && propertyName !== 'json') ||
169
- !storageTransactionId) {
170
- sendBack({ type: 'initializeSuccess' });
171
- return;
172
- }
173
- const _getContentsFromFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
174
- if (propertyName === 'html') {
175
- const htmlFilePath = `/files/html/${storageTransactionId}.html`;
176
- const exists = yield fs.promises.exists(htmlFilePath);
177
- if (!exists) {
178
- return;
179
- }
180
- const renderValue = yield fs.promises
181
- .readFile(`/files/html/${storageTransactionId}.html`, 'utf8')
182
- .catch((error) => {
183
- console.warn('Error reading html file', error);
184
- });
185
- sendBack({ type: 'updateContext', renderValue });
186
- return;
187
- }
188
- if (propertyName === 'json') {
189
- const jsonFilePath = `/files/json/${storageTransactionId}.json`;
190
- const exists = yield fs.promises.exists(jsonFilePath);
191
- if (!exists) {
192
- return;
193
- }
194
- const renderValue = yield fs.promises
195
- .readFile(`/files/json/${storageTransactionId}.json`, 'utf8')
196
- .catch((error) => {
197
- console.warn('Error reading json file', error);
198
- });
199
- sendBack({ type: 'updateContext', renderValue });
200
- return;
201
- }
202
- });
203
- _getContentsFromFileSystem().then(() => {
204
- sendBack({ type: 'initializeSuccess' });
205
- });
206
- }
207
- });
208
-
209
217
  const logger$o = debug('app:shared:helpers');
210
218
  const { alphanumeric } = nanoIdDictionary;
211
219
  const generateId = () => {
@@ -278,6 +286,7 @@ const convertTxIdToImageSrc = (txId) => __awaiter(void 0, void 0, void 0, functi
278
286
  const imageBlob = new Blob([uint]);
279
287
  return URL.createObjectURL(imageBlob);
280
288
  });
289
+ const capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);
281
290
  const parseEasRelationPropertyName = (easPropertyName) => {
282
291
  // Split the input string on the first underscore
283
292
  const [singularProperty, modelName, idSegment] = easPropertyName.split('_');
@@ -416,777 +425,71 @@ relations(propertyUids, ({ one }) => ({
416
425
  property: one(properties),
417
426
  }));
418
427
 
419
- const getPropertyData = (propertyName, seedLocalId, seedUid) => __awaiter(void 0, void 0, void 0, function* () {
428
+ const getVersionData$1 = () => {
420
429
  const appDb = getAppDb();
421
- const whereClauses = [
422
- or(eq(metadata.propertyName, propertyName), eq(metadata.propertyName, propertyName + 'Id'), eq(metadata.propertyName, propertyName + 'Ids')),
423
- ];
424
- if (seedLocalId) {
425
- whereClauses.push(eq(metadata.seedLocalId, seedLocalId));
426
- }
427
- if (seedUid) {
428
- whereClauses.push(eq(metadata.seedUid, seedUid));
430
+ return appDb.$with('versionData').as(appDb
431
+ .select({
432
+ seedLocalId: versions.seedLocalId,
433
+ seedUid: versions.seedUid,
434
+ latestVersionUid: versions.uid,
435
+ latestVersionLocalId: versions.localId,
436
+ versionsCount: count(versions.localId).as('versionsCount'),
437
+ lastVersionPublishedAt: max(versions.attestationCreatedAt).as('lastVersionPublishedAt'),
438
+ lastLocalUpdateAt: max(versions.createdAt).as('lastLocalUpdateAt'),
439
+ })
440
+ .from(versions)
441
+ .groupBy(versions.seedLocalId));
442
+ };
443
+
444
+ const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
445
+ const appDb = getAppDb();
446
+ const conditions = [];
447
+ if (modelName) {
448
+ conditions.push(eq(seeds.type, modelName.toLowerCase()));
429
449
  }
430
- const rows = (yield appDb
431
- .select()
432
- .from(metadata)
433
- .where(and(...whereClauses))
434
- .orderBy(sql.raw(`COALESCE(attestation_created_at, created_at) DESC`)));
435
- if (!rows || rows.length === 0) {
436
- return;
450
+ if (deleted) {
451
+ conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
437
452
  }
438
- const row = rows[0];
439
- return Object.assign(Object.assign({}, row), { itemModelName: startCase(row.modelType) });
440
- });
441
- const seedUidToStorageTransactionId = new Map();
442
- const getStorageTransactionIdForSeedUid = (seedUid) => __awaiter(void 0, void 0, void 0, function* () {
443
- if (seedUidToStorageTransactionId.has(seedUid)) {
444
- return seedUidToStorageTransactionId.get(seedUid);
453
+ if (!deleted) {
454
+ conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
445
455
  }
446
- const appDb = getAppDb();
447
- const results = (yield appDb
456
+ const versionData = getVersionData$1();
457
+ let query = appDb
458
+ .with(versionData)
448
459
  .select({
449
- storageTransactionId: metadata.propertyValue,
460
+ seedLocalId: seeds.localId,
461
+ seedUid: seeds.uid,
462
+ schemaUid: seeds.schemaUid,
463
+ modelName: sql `${modelName}`,
464
+ attestationCreatedAt: seeds.attestationCreatedAt,
465
+ versionsCount: versionData.versionsCount,
466
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
467
+ lastLocalUpdateAt: versionData.lastLocalUpdateAt,
468
+ latestVersionUid: versionData.latestVersionUid,
469
+ latestVersionLocalId: versionData.latestVersionLocalId,
470
+ createdAt: seeds.createdAt,
450
471
  })
451
- .from(metadata)
452
- .where(and(eq(metadata.seedUid, seedUid), eq(metadata.propertyName, 'storageTransactionId'))));
453
- if (!results || results.length === 0) {
454
- return;
455
- }
456
- seedUidToStorageTransactionId.set(seedUid, results[0].storageTransactionId);
457
- return results[0].storageTransactionId;
472
+ .from(seeds)
473
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
474
+ .where(and(gt(versionData.versionsCount, 0), ...conditions))
475
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
476
+ .groupBy(seeds.localId);
477
+ const itemsData = (yield query);
478
+ return itemsData;
458
479
  });
459
- const getRelationValueData = (propertyValue) => __awaiter(void 0, void 0, void 0, function* () {
480
+
481
+ const createVersion = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid, seedType, uid, }) {
460
482
  const appDb = getAppDb();
461
- const rows = (yield appDb
462
- .select({
463
- propertyValue: metadata.propertyValue,
464
- attestationCreatedAt: max(metadata.attestationCreatedAt),
465
- refResolvedDisplayValue: metadata.refResolvedDisplayValue,
466
- refResolvedValue: metadata.refResolvedValue,
467
- refSeedType: metadata.refSeedType,
468
- easDataType: metadata.easDataType,
469
- })
470
- .from(metadata)
471
- .where(eq(metadata.propertyValue, propertyValue)));
472
- if (!rows || rows.length === 0) {
473
- return;
474
- }
475
- return rows[0];
476
- });
477
- const getExistingItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid, }) {
478
- const existingItemStatement = `SELECT local_id, uid, created_at
479
- FROM seeds
480
- WHERE (uid IS NOT NULL
481
- AND uid != ''
482
- AND uid != 'undefined'
483
- AND uid != 'null'
484
- AND uid != 'false'
485
- AND uid != '0'
486
- AND uid != 0
487
- AND uid = '${seedUid}'
488
- )
489
- OR (
490
- local_id IS NOT NULL
491
- AND local_id != ''
492
- AND local_id != 'undefined'
493
- AND local_id != 'null'
494
- AND local_id != 'false'
495
- AND local_id != '0'
496
- AND local_id != 0
497
- AND local_id = '${seedLocalId}'
498
- );
499
- `;
500
- const { rows } = yield runQueryForStatement(existingItemStatement);
501
- let existingItem;
502
- if (rows && rows.length > 0) {
503
- // We know the zero index is versionLocalId because we specifically asked for it first
504
- // in the SELECT statement above. Same with the rest of the indexes.
505
- let matchingRow = rows.find((row) => row[1] === seedUid);
506
- if (!matchingRow) {
507
- matchingRow = rows.find((row) => row[0] === seedLocalId);
508
- }
509
- if (matchingRow) {
510
- existingItem = {
511
- seedLocalId: matchingRow[0],
512
- seedUid: matchingRow[1],
513
- createdAt: matchingRow[2],
514
- };
515
- }
516
- }
517
- return existingItem;
518
- });
519
-
520
- const logger$n = debug('app:property:actors:resolveRelatedValue');
521
- const storageTransactionIdToContentUrl = new Map();
522
- const refResolvedValueToContentUrl = new Map();
523
- const seedUidToContentUrl = new Map();
524
- const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
525
- const { isRelation, propertyValue, propertyName, seedUid, propertyRecordSchema, populatedFromDb, schemaUid, } = context;
526
- const _resolveRelatedValue = () => __awaiter(void 0, void 0, void 0, function* () {
527
- if (!propertyValue || !isRelation || populatedFromDb) {
528
- return;
529
- }
530
- let parsedValue;
531
- try {
532
- parsedValue = JSON.parse(propertyValue);
533
- }
534
- catch (error) {
535
- logger$n(`${propertyName} value is not a JSON string.`);
536
- }
537
- if (!parsedValue && seedUidToContentUrl.has(propertyValue)) {
538
- const contentUrl = seedUidToContentUrl.get(propertyValue);
539
- sendBack({
540
- type: 'updateContext',
541
- renderValue: contentUrl,
542
- });
543
- sendBack({
544
- type: 'resolvingRelatedValueSuccess',
545
- resolvedDisplayValue: contentUrl,
546
- });
547
- return true;
548
- }
549
- if (Array.isArray(propertyValue)) {
550
- // TODO: Handle array of seedUids
551
- logger$n(`${propertyName} value is an array of seedUids`);
552
- return;
553
- }
554
- if (Array.isArray(parsedValue)) {
555
- logger$n(`${propertyName} value is a stringified array of seedUids`);
556
- return;
557
- }
558
- const storageTransactionId = yield getStorageTransactionIdForSeedUid(propertyValue);
559
- if (storageTransactionId) {
560
- if (storageTransactionIdToContentUrl.has(storageTransactionId)) {
561
- const contentUrl = storageTransactionIdToContentUrl.get(storageTransactionId);
562
- sendBack({
563
- type: 'updateContext',
564
- renderValue: contentUrl,
565
- });
566
- sendBack({
567
- type: 'resolvingRelatedValueSuccess',
568
- resolvedDisplayValue: contentUrl,
569
- resolvedValue: storageTransactionId,
570
- });
571
- return true;
572
- }
573
- const contentUrl = yield convertTxIdToImageSrc(storageTransactionId);
574
- if (contentUrl) {
575
- seedUidToContentUrl.set(propertyValue, contentUrl);
576
- }
577
- sendBack({
578
- type: 'updateContext',
579
- renderValue: contentUrl,
580
- });
581
- sendBack({
582
- type: 'resolvingRelatedValueSuccess',
583
- resolvedDisplayValue: contentUrl,
584
- resolvedValue: storageTransactionId,
585
- });
586
- return true;
587
- }
588
- const relationValueData = yield getRelationValueData(propertyValue);
589
- if (relationValueData) {
590
- const { refResolvedValue } = relationValueData;
591
- const propertyValueFromDb = relationValueData.propertyValue;
592
- // This handles a local-only relation value and resolves from the filesystem
593
- if (refResolvedValue &&
594
- propertyRecordSchema.dataType === 'Relation' &&
595
- propertyValueFromDb.length === 10 &&
596
- propertyRecordSchema.ref) {
597
- if (refResolvedValueToContentUrl.has(refResolvedValue)) {
598
- const contentUrl = refResolvedValueToContentUrl.get(refResolvedValue);
599
- sendBack({
600
- type: 'updateContext',
601
- renderValue: contentUrl,
602
- });
603
- sendBack({
604
- type: 'resolvingRelatedValueSuccess',
605
- resolvedDisplayValue: contentUrl,
606
- });
607
- return true;
608
- }
609
- const fileExists = yield fs.promises.exists('/files/images/' + refResolvedValue);
610
- if (fileExists) {
611
- const fileContents = yield fs.promises.readFile('/files/images/' + refResolvedValue);
612
- const fileHandler = new File([fileContents], refResolvedValue);
613
- const contentUrl = URL.createObjectURL(fileHandler);
614
- refResolvedValueToContentUrl.set(refResolvedValue, contentUrl);
615
- sendBack({
616
- type: 'updateContext',
617
- renderValue: contentUrl,
618
- });
619
- sendBack({
620
- type: 'resolvingRelatedValueSuccess',
621
- resolvedDisplayValue: contentUrl,
622
- });
623
- return true;
624
- }
625
- }
626
- if (typeof propertyValueFromDb === 'string') {
627
- // Check files for a filename that matches the propertyValue
628
- if (propertyRecordSchema &&
629
- propertyRecordSchema.refValueType === 'ImageSrc') {
630
- let contentUrl;
631
- if (storageTransactionIdToContentUrl.has(propertyValueFromDb)) {
632
- contentUrl =
633
- storageTransactionIdToContentUrl.get(propertyValueFromDb);
634
- }
635
- if (!contentUrl) {
636
- const imageFileExists = yield fs.promises.exists(`/images/${propertyValue}`);
637
- if (imageFileExists) {
638
- const fileContents = yield fs.promises.readFile(`/images/${propertyValue}`);
639
- const fileHandler = new File([fileContents], propertyValue);
640
- contentUrl = URL.createObjectURL(fileHandler);
641
- storageTransactionIdToContentUrl.set(propertyValueFromDb, contentUrl);
642
- }
643
- }
644
- if (contentUrl) {
645
- sendBack({
646
- type: 'updateContext',
647
- renderValue: contentUrl,
648
- });
649
- sendBack({
650
- type: 'resolvingRelatedValueSuccess',
651
- resolvedDisplayValue: contentUrl,
652
- });
653
- return true;
654
- }
655
- }
656
- }
657
- }
658
- });
659
- _resolveRelatedValue().then((success) => {
660
- // if (success) {
661
- // sendBack({
662
- // type: 'resolvingRelatedValueDone',
663
- // })
664
- // }
665
- // return
666
- sendBack({
667
- type: 'resolvingRelatedValueDone',
668
- });
669
- });
670
- });
671
- // const eventKey = `storage.transaction.${initialValue}.contentUrl.response`
672
- //
673
- // const contentUrlListener = async (event) => {
674
- // console.log('[itemProperty] [constructor] contentUrlListener', event)
675
- // }
676
- //
677
- // eventEmitter.once(eventKey, contentUrlListener)
678
- //
679
- // const ready = getArePropertyEventHandlersReady()
680
- //
681
- // console.log('[itemProperty] [constructor] ready', ready)
682
- //
683
- // eventEmitter.emit('storage.transaction.contentUrl.request', {
684
- // storageTransactionId: initialValue,
685
- // })
686
- // Related property values can either be seedUid or seedUid[]
687
- // let relatedSeedUid: string
688
- // let relatedSeedUids: string[]
689
- //
690
- // if (Array.isArray(propertyValue)) {
691
- // relatedSeedUids = propertyValue
692
- // } else {
693
- // relatedSeedUid = propertyValue
694
- // }
695
- //
696
- // if (relatedSeedUid) {
697
- // console.log(
698
- // `[property/actors] [resolveRelatedValue] seedUid: ${relatedSeedUid}`,
699
- // )
700
- // const latestVersionOfRelatedSeedQuery = await appDb.run(
701
- // sql.raw(
702
- // `
703
- // SELECT local_id, uid, MAX(attestation_created_at)
704
- // FROM versions
705
- // WHERE seed_uid = '${relatedSeedUid}';
706
- // `,
707
- // ),
708
- // )
709
- // if (
710
- // latestVersionOfRelatedSeedQuery &&
711
- // latestVersionOfRelatedSeedQuery.rows &&
712
- // latestVersionOfRelatedSeedQuery.rows.length > 0
713
- // ) {
714
- // const latestVersionOfRelatedSeed =
715
- // latestVersionOfRelatedSeedQuery.rows[0]
716
- // console.log(
717
- // '[property/actors] [resolveRelatedValue] latestVersionOfRelatedSeed',
718
- // latestVersionOfRelatedSeed,
719
- // )
720
- // const storageIdQuery = await appDb.run(
721
- // sql.raw(
722
- // `
723
- // SELECT property_value, MAX(attestation_created_at), ref_resolved_display_value, ref_resolved_value
724
- // FROM metadata
725
- // WHERE seed_uid = '${relatedSeedUid}'
726
- // AND property_name = 'storageTransactionId';
727
- // `,
728
- // ),
729
- // )
730
- //
731
- // if (
732
- // storageIdQuery &&
733
- // storageIdQuery.rows &&
734
- // storageIdQuery.rows.length > 0
735
- // ) {
736
- // const storageId = storageIdQuery.rows[0][0]
737
- //
738
- // if (!storageId) {
739
- // console.error(
740
- // `storageId not found for ${propertyName} with relatedSeedUid ${relatedSeedUid}`,
741
- // )
742
- // }
743
- //
744
- // const resolvedDisplayValue = storageIdQuery.rows[0][2]
745
- // let resolvedValue = storageIdQuery.rows[0][3]
746
- //
747
- // if (resolvedDisplayValue && resolvedValue) {
748
- // sendBack({
749
- // type: 'resolvingRelatedValueSuccess',
750
- // resolvedDisplayValue,
751
- // resolvedValue,
752
- // })
753
- // return
754
- // }
755
- //
756
- // console.log(
757
- // '[property/actors] [resolveRelatedValue] storageId',
758
- // storageId,
759
- // )
760
- //
761
- // const contentUrl = await convertTxIdToImageSrc(storageId)
762
- //
763
- // if (!contentUrl) {
764
- // throw new Error(
765
- // `contentUrl not found for ${propertyName} with relatedSeedUid ${relatedSeedUid}`,
766
- // )
767
- // }
768
- //
769
- // await appDb.run(
770
- // sql.raw(
771
- // `UPDATE metadata
772
- // SET ref_resolved_display_value = '${contentUrl}',
773
- // ref_resolved_value = '${storageId}'
774
- // WHERE seed_uid = '${relatedSeedUid}'
775
- // AND property_name = 'storageTransactionId';
776
- // `,
777
- // ),
778
- // )
779
- //
780
- // sendBack({
781
- // type: 'resolvingRelatedValueSuccess',
782
- // resolvedDisplayValue: contentUrl,
783
- // resolvedValue: storageId,
784
- // })
785
- // }
786
- // }
787
- //
788
- // const versionUidQuery = await appDb.run(
789
- // sql.raw(
790
- // `
791
- // SELECT uid
792
- // FROM versions
793
- // WHERE seed_uid = '${relatedSeedUid}';
794
- // `,
795
- // ),
796
- // )
797
- //
798
- // if (
799
- // versionUidQuery &&
800
- // versionUidQuery.rows &&
801
- // versionUidQuery.rows.length > 0
802
- // ) {
803
- // const versionUids = versionUidQuery.rows.map((row) => row[0])
804
- // console.log(
805
- // '[property/actors] [resolveRelatedValue] versionUids',
806
- // versionUids,
807
- // )
808
- // const { itemProperties } = await easClient.request(GET_PROPERTIES, {
809
- // where: {
810
- // refUID: {
811
- // in: versionUids,
812
- // },
813
- // decodedDataJson: {
814
- // contains: 'storage_transaction_id',
815
- // },
816
- // },
817
- // })
818
- //
819
- // console.log(
820
- // '[property/actors] [resolveRelatedValue] itemProperties',
821
- // itemProperties,
822
- // )
823
- //
824
- // if (itemProperties && itemProperties.length > 0) {
825
- // await savePropertiesToDb(itemProperties)
826
- // }
827
- // }
828
- // }
829
-
830
- const resolveRemoteStorage = fromCallback(({ sendBack, input: { context } }) => {
831
- const { propertyInstances } = context;
832
- if (!propertyInstances) {
833
- throw new Error(`propertyInstances not found for ${context.seedLocalId}`);
834
- }
835
- if (!propertyInstances.has('storageTransactionId')) {
836
- return;
837
- }
838
- const storageTransactionId = propertyInstances.get('storageTransactionId');
839
- const _resolveRemoteStorage = () => __awaiter(void 0, void 0, void 0, function* () {
840
- const path = yield import('path-browserify');
841
- const { fs } = yield import('@zenfs/core');
842
- const filesDirExists = yield fs.promises.exists('/files');
843
- if (!filesDirExists) {
844
- yield fs.promises.mkdir('/files');
845
- }
846
- const htmlDir = path.join('/files', 'html');
847
- const htmlExists = yield fs.promises.exists(htmlDir);
848
- if (htmlExists) {
849
- const htmlFiles = yield fs.promises.readdir(htmlDir);
850
- const matchingHtmlFile = htmlFiles.find((file) => file === `${storageTransactionId}.html`);
851
- if (matchingHtmlFile) {
852
- const htmlString = yield fs.promises.readFile(path.join(htmlDir, matchingHtmlFile), 'utf8');
853
- sendBack({
854
- type: 'updateValue',
855
- propertyName: 'html',
856
- propertyValue: htmlString,
857
- });
858
- }
859
- }
860
- if (!htmlExists) {
861
- yield fs.promises.mkdir(htmlDir);
862
- }
863
- const jsonDir = path.join('/files', 'json');
864
- const jsonExists = yield fs.promises.exists(jsonDir);
865
- if (jsonExists) {
866
- const jsonFiles = yield fs.promises.readdir(jsonDir);
867
- const matchingJsonFile = jsonFiles.find((file) => file === `${storageTransactionId}.json`);
868
- if (matchingJsonFile) {
869
- const jsonString = yield fs.promises.readFile(path.join(jsonDir, matchingJsonFile), 'utf8');
870
- sendBack({
871
- type: 'updateValue',
872
- propertyName: 'json',
873
- propertyValue: jsonString,
874
- });
875
- }
876
- }
877
- if (!jsonExists) {
878
- yield fs.promises.mkdir(jsonDir);
879
- }
880
- });
881
- _resolveRemoteStorage().then(() => {
882
- sendBack({ type: 'resolveRemoteStorageSuccess' });
883
- return;
884
- });
885
- });
886
-
887
- const updateMetadata = (metadataValues) => __awaiter(void 0, void 0, void 0, function* () {
888
- const appDb = getAppDb();
889
- const { localId } = metadataValues, rest = __rest(metadataValues, ["localId"]);
890
- if (!localId) {
891
- throw new Error('No localId provided to updateMetadata');
892
- }
893
- yield appDb.update(metadata).set(rest).where(eq(metadata.localId, localId));
894
- });
895
-
896
- const logger$m = debug('app:property:actors:hydrateFromDb');
897
- const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
898
- const { seedUid, seedLocalId, propertyName: propertyNameRaw, propertyValue, propertyRecordSchema, itemModelName, } = context;
899
- let propertyName = propertyNameRaw;
900
- if (propertyRecordSchema &&
901
- propertyRecordSchema.ref &&
902
- propertyRecordSchema.dataType === 'Relation' &&
903
- !propertyNameRaw.endsWith('Id')) {
904
- propertyName = propertyNameRaw + 'Id';
905
- }
906
- if (propertyRecordSchema &&
907
- propertyRecordSchema.ref &&
908
- propertyRecordSchema.dataType === 'List' &&
909
- !propertyNameRaw.endsWith('Ids')) {
910
- propertyName = propertyNameRaw + 'Ids';
911
- }
912
- const _hydrateFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
913
- const appDb = getAppDb();
914
- const isRelation = propertyRecordSchema &&
915
- propertyRecordSchema.ref &&
916
- propertyRecordSchema.dataType === 'Relation';
917
- const whereClauses = [];
918
- if (isRelation) {
919
- let missingPropertyNameVariant;
920
- if (propertyName.endsWith('Id')) {
921
- missingPropertyNameVariant = propertyName.slice(0, -2);
922
- }
923
- if (!propertyName.endsWith('Id')) {
924
- missingPropertyNameVariant = propertyName + 'Id';
925
- }
926
- if (missingPropertyNameVariant) {
927
- whereClauses.push(or(eq(metadata.propertyName, propertyName), eq(metadata.propertyName, missingPropertyNameVariant)));
928
- }
929
- if (!missingPropertyNameVariant) {
930
- whereClauses.push(eq(metadata.propertyName, propertyName));
931
- }
932
- }
933
- else {
934
- whereClauses.push(eq(metadata.propertyName, propertyName));
935
- }
936
- if (seedUid) {
937
- whereClauses.push(eq(metadata.seedUid, seedUid));
938
- }
939
- if (seedLocalId) {
940
- whereClauses.push(eq(metadata.seedLocalId, seedLocalId));
941
- }
942
- const rows = yield appDb
943
- .select()
944
- .from(metadata)
945
- .where(and(...whereClauses))
946
- .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'));
947
- if (!rows || !rows.length) {
948
- return;
949
- }
950
- const firstRow = rows[0];
951
- const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, versionLocalId: versionLocalIdFromDb, versionUid: versionUidFromDb, refValueType, localStorageDir, } = firstRow;
952
- let { refResolvedDisplayValue, refResolvedValue } = firstRow;
953
- let propertyValueProcessed = propertyValueFromDb;
954
- if (propertyName && !propertyNameFromDb) {
955
- logger$m(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
956
- }
957
- if (propertyName &&
958
- propertyNameFromDb &&
959
- !propertyNameFromDb.includes(propertyName) &&
960
- !propertyName.includes(propertyNameFromDb) &&
961
- propertyNameFromDb !== propertyName) {
962
- logger$m(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
963
- }
964
- if (propertyValue && propertyValueFromDb !== propertyValue) {
965
- logger$m(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
966
- }
967
- if (seedLocalIdFromDb !== seedLocalId) {
968
- logger$m(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
969
- }
970
- if (seedUidFromDb !== seedUid) {
971
- logger$m(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
972
- }
973
- if (propertyRecordSchema &&
974
- propertyRecordSchema.refValueType === 'ImageSrc') {
975
- let shouldReadFromFile = true;
976
- if (refResolvedValue &&
977
- refResolvedDisplayValue &&
978
- refResolvedDisplayValue.includes('http')) {
979
- try {
980
- const response = yield fetch(refResolvedDisplayValue, {
981
- method: 'HEAD',
982
- });
983
- // Check if the status is in the 200-299 range
984
- if (response.ok) {
985
- shouldReadFromFile = false;
986
- }
987
- }
988
- catch (error) {
989
- shouldReadFromFile = true;
990
- }
991
- }
992
- if (shouldReadFromFile) {
993
- let dir = localStorageDir;
994
- if (!dir &&
995
- propertyRecordSchema &&
996
- propertyRecordSchema.refValueType === 'ImageSrc') {
997
- dir = 'images';
998
- }
999
- dir = dir.replace(/^\//, '');
1000
- if (!refResolvedValue &&
1001
- propertyValueFromDb &&
1002
- propertyValueFromDb.length === 66) {
1003
- const storageTransactionQuery = yield appDb
1004
- .select({
1005
- propertyValue: metadata.propertyValue,
1006
- })
1007
- .from(metadata)
1008
- .where(and(eq(metadata.seedUid, propertyValueFromDb), eq(metadata.propertyName, 'storageTransactionId')));
1009
- if (storageTransactionQuery && storageTransactionQuery.length > 0) {
1010
- const row = storageTransactionQuery[0];
1011
- refResolvedValue = row.propertyValue;
1012
- console.log('storageTransactionId', refResolvedValue);
1013
- yield updateMetadata({
1014
- localId,
1015
- refResolvedValue,
1016
- localStorageDir: '/images',
1017
- });
1018
- }
1019
- }
1020
- const dirPath = `/files/${dir}`;
1021
- const files = yield fs.promises.readdir(dirPath);
1022
- const matchingFiles = files.filter((file) => {
1023
- return path.basename(file).includes(refResolvedValue);
1024
- });
1025
- let fileExists = false;
1026
- let filename;
1027
- let filePath;
1028
- if (matchingFiles && matchingFiles.length > 0) {
1029
- fileExists = true;
1030
- filename = matchingFiles[0];
1031
- filePath = `/files/${dir}/${filename}`;
1032
- }
1033
- if (fileExists && filename && filePath) {
1034
- const fileContents = yield fs.promises.readFile(filePath);
1035
- const fileHandler = new File([fileContents], filename);
1036
- refResolvedDisplayValue = URL.createObjectURL(fileHandler);
1037
- yield updateMetadata({
1038
- localId,
1039
- refResolvedValue: filename,
1040
- });
1041
- }
1042
- }
1043
- }
1044
- if (propertyRecordSchema &&
1045
- propertyRecordSchema.dataType === 'List' &&
1046
- propertyRecordSchema.ref &&
1047
- typeof propertyValueFromDb === 'string') {
1048
- propertyValueProcessed = propertyValueFromDb.split(',');
1049
- }
1050
- sendBack({
1051
- type: 'updateContext',
1052
- localId,
1053
- uid,
1054
- propertyValue: propertyValueProcessed,
1055
- seedLocalId: seedLocalIdFromDb,
1056
- seedUid: seedUidFromDb,
1057
- versionLocalId: versionLocalIdFromDb,
1058
- versionUid: versionUidFromDb,
1059
- schemaUid: schemaUidFromDb,
1060
- refValueType,
1061
- localStorageDir,
1062
- resolvedValue: refResolvedValue,
1063
- resolvedDisplayValue: refResolvedDisplayValue,
1064
- renderValue: refResolvedDisplayValue,
1065
- populatedFromDb: true,
1066
- });
1067
- if (propertyRecordSchema &&
1068
- propertyRecordSchema.storageType &&
1069
- propertyRecordSchema.storageType === 'ItemStorage') {
1070
- const { Item } = yield import('./index-D5tYjtxh.js');
1071
- const item = yield Item.find({
1072
- seedLocalId,
1073
- modelName: itemModelName,
1074
- });
1075
- if (item) {
1076
- const filePath = `/files/${localStorageDir}/${refResolvedValue}`;
1077
- const exists = yield fs.promises.exists(filePath);
1078
- if (!exists) {
1079
- return;
1080
- }
1081
- const renderValue = yield fs.promises.readFile(filePath, 'utf8');
1082
- const property = item.properties[propertyName];
1083
- property.getService().send({ type: 'updateContext', renderValue });
1084
- return;
1085
- }
1086
- }
1087
- });
1088
- _hydrateFromDb().then(() => {
1089
- sendBack({ type: 'hydrateFromDbSuccess' });
1090
- });
1091
- });
1092
-
1093
- const escapeSqliteString = (value) => {
1094
- if (typeof value !== 'string') {
1095
- throw new Error(`Value must be a string, instead got: ${JSON.stringify(value)}`);
1096
- }
1097
- return value.replace(/'/g, "''");
1098
- };
1099
- const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
1100
- const appDb = getAppDb();
1101
- if (!appDb) {
1102
- return new Promise((resolve) => {
1103
- setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
1104
- const addresses = yield getAddressesFromDb();
1105
- resolve(addresses);
1106
- }), 500);
1107
- });
1108
- }
1109
- const appStatesRecords = yield appDb
1110
- .select()
1111
- .from(appState)
1112
- .where(eq(appState.key, 'addresses'))
1113
- .limit(1);
1114
- if (!appStatesRecords || appStatesRecords.length === 0) {
1115
- throw new Error('No appStatesRecords for addresses found');
1116
- }
1117
- const addressRecord = appStatesRecords[0];
1118
- const addressArrayString = addressRecord.value;
1119
- if (!addressArrayString) {
1120
- throw new Error('No addresses found');
1121
- }
1122
- return JSON.parse(addressArrayString);
1123
- });
1124
-
1125
- const getVersionData$1 = () => {
1126
- const appDb = getAppDb();
1127
- return appDb.$with('versionData').as(appDb
1128
- .select({
1129
- seedLocalId: versions.seedLocalId,
1130
- seedUid: versions.seedUid,
1131
- latestVersionUid: versions.uid,
1132
- latestVersionLocalId: versions.localId,
1133
- versionsCount: count(versions.localId).as('versionsCount'),
1134
- lastVersionPublishedAt: max(versions.attestationCreatedAt).as('lastVersionPublishedAt'),
1135
- lastLocalUpdateAt: max(versions.createdAt).as('lastLocalUpdateAt'),
1136
- })
1137
- .from(versions)
1138
- .groupBy(versions.seedLocalId));
1139
- };
1140
-
1141
- const getItemsData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, deleted, }) {
1142
- const appDb = getAppDb();
1143
- const conditions = [];
1144
- if (modelName) {
1145
- conditions.push(eq(seeds.type, modelName.toLowerCase()));
1146
- }
1147
- if (deleted) {
1148
- conditions.push(or(isNotNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 1)));
1149
- }
1150
- if (!deleted) {
1151
- conditions.push(or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0)));
1152
- }
1153
- const versionData = getVersionData$1();
1154
- let query = appDb
1155
- .with(versionData)
1156
- .select({
1157
- seedLocalId: seeds.localId,
1158
- seedUid: seeds.uid,
1159
- schemaUid: seeds.schemaUid,
1160
- modelName: sql `${modelName}`,
1161
- attestationCreatedAt: seeds.attestationCreatedAt,
1162
- versionsCount: versionData.versionsCount,
1163
- lastVersionPublishedAt: versionData.lastVersionPublishedAt,
1164
- lastLocalUpdateAt: versionData.lastLocalUpdateAt,
1165
- latestVersionUid: versionData.latestVersionUid,
1166
- latestVersionLocalId: versionData.latestVersionLocalId,
1167
- createdAt: seeds.createdAt,
1168
- })
1169
- .from(seeds)
1170
- .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
1171
- .where(and(gt(versionData.versionsCount, 0), ...conditions))
1172
- .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
1173
- .groupBy(seeds.localId);
1174
- const itemsData = (yield query);
1175
- return itemsData;
1176
- });
1177
-
1178
- const createVersion = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid, seedType, uid, }) {
1179
- const appDb = getAppDb();
1180
- const newVersionLocalId = generateId();
1181
- yield appDb.insert(versions).values({
1182
- localId: newVersionLocalId,
1183
- createdAt: Date.now(),
1184
- seedLocalId,
1185
- seedUid: seedUid !== null && seedUid !== void 0 ? seedUid : 'NULL',
1186
- seedType,
1187
- uid: uid || 'NULL',
1188
- });
1189
- return newVersionLocalId;
483
+ const newVersionLocalId = generateId();
484
+ yield appDb.insert(versions).values({
485
+ localId: newVersionLocalId,
486
+ createdAt: Date.now(),
487
+ seedLocalId,
488
+ seedUid: seedUid !== null && seedUid !== void 0 ? seedUid : 'NULL',
489
+ seedType,
490
+ uid: uid || 'NULL',
491
+ });
492
+ return newVersionLocalId;
1190
493
  });
1191
494
 
1192
495
  const createMetadata = (metadataValues, propertyRecordSchema) => __awaiter(void 0, void 0, void 0, function* () {
@@ -1411,18 +714,119 @@ const createNewItem = (_a) => __awaiter(void 0, void 0, void 0, function* () {
1411
714
  // ),
1412
715
  // )
1413
716
  }
1414
- // eventEmitter.emit(`item.requestAll`, { modelName })
1415
- return {
1416
- modelName,
1417
- seedLocalId: newSeedId,
1418
- versionLocalId: newVersionId,
1419
- };
717
+ // eventEmitter.emit(`item.requestAll`, { modelName })
718
+ return {
719
+ modelName,
720
+ seedLocalId: newSeedId,
721
+ versionLocalId: newVersionId,
722
+ };
723
+ });
724
+
725
+ const eventEmitter = new EventEmitter();
726
+
727
+ const getPropertyData$1 = (propertyName, seedLocalId, seedUid) => __awaiter(void 0, void 0, void 0, function* () {
728
+ const appDb = getAppDb();
729
+ const whereClauses = [
730
+ or(eq(metadata.propertyName, propertyName), eq(metadata.propertyName, propertyName + 'Id'), eq(metadata.propertyName, propertyName + 'Ids')),
731
+ ];
732
+ if (seedLocalId) {
733
+ whereClauses.push(eq(metadata.seedLocalId, seedLocalId));
734
+ }
735
+ if (seedUid) {
736
+ whereClauses.push(eq(metadata.seedUid, seedUid));
737
+ }
738
+ const rows = (yield appDb
739
+ .select()
740
+ .from(metadata)
741
+ .where(and(...whereClauses))
742
+ .orderBy(sql.raw(`COALESCE(attestation_created_at, created_at) DESC`)));
743
+ if (!rows || rows.length === 0) {
744
+ return;
745
+ }
746
+ const row = rows[0];
747
+ return Object.assign(Object.assign({}, row), { itemModelName: startCase(row.modelType) });
748
+ });
749
+ const seedUidToStorageTransactionId = new Map();
750
+ const getStorageTransactionIdForSeedUid = (seedUid) => __awaiter(void 0, void 0, void 0, function* () {
751
+ if (seedUidToStorageTransactionId.has(seedUid)) {
752
+ return seedUidToStorageTransactionId.get(seedUid);
753
+ }
754
+ const appDb = getAppDb();
755
+ const results = (yield appDb
756
+ .select({
757
+ storageTransactionId: metadata.propertyValue,
758
+ })
759
+ .from(metadata)
760
+ .where(and(eq(metadata.seedUid, seedUid), eq(metadata.propertyName, 'storageTransactionId'))));
761
+ if (!results || results.length === 0) {
762
+ return;
763
+ }
764
+ seedUidToStorageTransactionId.set(seedUid, results[0].storageTransactionId);
765
+ return results[0].storageTransactionId;
766
+ });
767
+ const getRelationValueData = (propertyValue) => __awaiter(void 0, void 0, void 0, function* () {
768
+ const appDb = getAppDb();
769
+ const rows = (yield appDb
770
+ .select({
771
+ propertyValue: metadata.propertyValue,
772
+ attestationCreatedAt: max(metadata.attestationCreatedAt),
773
+ refResolvedDisplayValue: metadata.refResolvedDisplayValue,
774
+ refResolvedValue: metadata.refResolvedValue,
775
+ refSeedType: metadata.refSeedType,
776
+ easDataType: metadata.easDataType,
777
+ })
778
+ .from(metadata)
779
+ .where(eq(metadata.propertyValue, propertyValue)));
780
+ if (!rows || rows.length === 0) {
781
+ return;
782
+ }
783
+ return rows[0];
784
+ });
785
+ const getExistingItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid, }) {
786
+ const existingItemStatement = `SELECT local_id, uid, created_at
787
+ FROM seeds
788
+ WHERE (uid IS NOT NULL
789
+ AND uid != ''
790
+ AND uid != 'undefined'
791
+ AND uid != 'null'
792
+ AND uid != 'false'
793
+ AND uid != '0'
794
+ AND uid != 0
795
+ AND uid = '${seedUid}'
796
+ )
797
+ OR (
798
+ local_id IS NOT NULL
799
+ AND local_id != ''
800
+ AND local_id != 'undefined'
801
+ AND local_id != 'null'
802
+ AND local_id != 'false'
803
+ AND local_id != '0'
804
+ AND local_id != 0
805
+ AND local_id = '${seedLocalId}'
806
+ );
807
+ `;
808
+ const { rows } = yield runQueryForStatement(existingItemStatement);
809
+ let existingItem;
810
+ if (rows && rows.length > 0) {
811
+ // We know the zero index is versionLocalId because we specifically asked for it first
812
+ // in the SELECT statement above. Same with the rest of the indexes.
813
+ let matchingRow = rows.find((row) => row[1] === seedUid);
814
+ if (!matchingRow) {
815
+ matchingRow = rows.find((row) => row[0] === seedLocalId);
816
+ }
817
+ if (matchingRow) {
818
+ existingItem = {
819
+ seedLocalId: matchingRow[0],
820
+ seedUid: matchingRow[1],
821
+ createdAt: matchingRow[2],
822
+ };
823
+ }
824
+ }
825
+ return existingItem;
1420
826
  });
1421
827
 
1422
- const eventEmitter = new EventEmitter();
1423
-
1424
828
  var _a$2;
1425
- const logger$l = debug('app:property:class');
829
+ const logger$n = debug('app:property:class');
1426
830
  const namesThatEndWithId = [];
1427
831
  class ItemProperty {
1428
832
  // private constructor(localIdOrUid) {
@@ -1472,7 +876,7 @@ class ItemProperty {
1472
876
  serviceInput.propertyValue = JSON.parse(propertyValue);
1473
877
  }
1474
878
  catch (e) {
1475
- logger$l('List property value is not JSON', e);
879
+ logger$n('List property value is not JSON', e);
1476
880
  }
1477
881
  }
1478
882
  const propertyNameSingular = pluralize(propertyName, 1);
@@ -1555,7 +959,7 @@ class ItemProperty {
1555
959
  this._service.start();
1556
960
  }
1557
961
  _updateResponseListener(event) {
1558
- logger$l(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
962
+ logger$n(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1559
963
  }
1560
964
  static create(props) {
1561
965
  const { propertyName, seedLocalId, seedUid, versionLocalId, versionUid } = props;
@@ -1610,7 +1014,7 @@ class ItemProperty {
1610
1014
  });
1611
1015
  return instance;
1612
1016
  }
1613
- const propertyData = yield getPropertyData(propertyName, seedLocalId, seedUid);
1017
+ const propertyData = yield getPropertyData$1(propertyName, seedLocalId, seedUid);
1614
1018
  if (!propertyData) {
1615
1019
  return;
1616
1020
  }
@@ -1702,7 +1106,7 @@ class ItemProperty {
1702
1106
  }
1703
1107
  unload() {
1704
1108
  this._service.stop();
1705
- logger$l(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1109
+ logger$n(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1706
1110
  eventEmitter.removeListener(this._updateResponseEvent, this._updateResponseListener);
1707
1111
  }
1708
1112
  }
@@ -1724,7 +1128,7 @@ const waitForDb = fromCallback(({ sendBack }) => {
1724
1128
  });
1725
1129
  });
1726
1130
 
1727
- const initialize$2 = fromCallback(({ sendBack, input: { context } }) => {
1131
+ const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
1728
1132
  const { seedLocalId, seedUid, ModelClass } = context;
1729
1133
  const modelName = ModelClass.originalConstructor.name;
1730
1134
  const modelNamePlural = pluralize(modelName);
@@ -1981,6 +1385,38 @@ const GET_ALL_PROPERTIES_FOR_ALL_VERSIONS = graphql(/* GraphQL */ `
1981
1385
  }
1982
1386
  `);
1983
1387
 
1388
+ const escapeSqliteString = (value) => {
1389
+ if (typeof value !== 'string') {
1390
+ throw new Error(`Value must be a string, instead got: ${JSON.stringify(value)}`);
1391
+ }
1392
+ return value.replace(/'/g, "''");
1393
+ };
1394
+ const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
1395
+ const appDb = getAppDb();
1396
+ if (!appDb) {
1397
+ return new Promise((resolve) => {
1398
+ setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
1399
+ const addresses = yield getAddressesFromDb();
1400
+ resolve(addresses);
1401
+ }), 500);
1402
+ });
1403
+ }
1404
+ const appStatesRecords = yield appDb
1405
+ .select()
1406
+ .from(appState)
1407
+ .where(eq(appState.key, 'addresses'))
1408
+ .limit(1);
1409
+ if (!appStatesRecords || appStatesRecords.length === 0) {
1410
+ throw new Error('No appStatesRecords for addresses found');
1411
+ }
1412
+ const addressRecord = appStatesRecords[0];
1413
+ const addressArrayString = addressRecord.value;
1414
+ if (!addressArrayString) {
1415
+ throw new Error('No addresses found');
1416
+ }
1417
+ return JSON.parse(addressArrayString);
1418
+ });
1419
+
1984
1420
  const getModelSchemas = () => __awaiter(void 0, void 0, void 0, function* () {
1985
1421
  const models$1 = getModels();
1986
1422
  const modelRecords = [];
@@ -2308,6 +1744,7 @@ const saveEasPropertiesToDb = (_a) => __awaiter(void 0, [_a], void 0, function*
2308
1744
  let insertPropertiesQuery = `INSERT INTO metadata (local_id, uid, schema_uid, property_name, property_value,
2309
1745
  eas_data_type, version_uid, version_local_id, seed_uid,
2310
1746
  seed_local_id, model_type, ref_value_type, ref_seed_type,
1747
+ ref_schema_uid,
2311
1748
  created_at, attestation_created_at, attestation_raw,
2312
1749
  local_storage_dir, ref_resolved_value)
2313
1750
  VALUES `;
@@ -2316,17 +1753,20 @@ const saveEasPropertiesToDb = (_a) => __awaiter(void 0, [_a], void 0, function*
2316
1753
  const propertyLocalId = generateId();
2317
1754
  const metadata = JSON.parse(property.decodedDataJson)[0].value;
2318
1755
  let propertyNameSnake = metadata.name;
2319
- if (!propertyNameSnake) {
2320
- propertyNameSnake = metadata.name;
2321
- }
2322
1756
  if (!propertyNameSnake) {
2323
1757
  console.warn('[item/events] [syncDbWithEas] no propertyName found for property: ', property);
2324
- return;
1758
+ continue;
2325
1759
  }
2326
1760
  let isRelation = false;
2327
1761
  let refValueType;
2328
1762
  let refSeedType;
1763
+ let refSchemaUid;
2329
1764
  let isList = false;
1765
+ const schemaUid = property.schemaId;
1766
+ setSchemaUidForSchemaDefinition({
1767
+ text: propertyNameSnake,
1768
+ schemaUid,
1769
+ });
2330
1770
  if ((propertyNameSnake.endsWith('_id') ||
2331
1771
  propertyNameSnake.endsWith('_ids')) &&
2332
1772
  propertyNameSnake !== 'storage_transaction_id' &&
@@ -2359,12 +1799,14 @@ const saveEasPropertiesToDb = (_a) => __awaiter(void 0, [_a], void 0, function*
2359
1799
  const relatedSeed = itemSeeds.find((seed) => seed.id === metadata.value);
2360
1800
  if (relatedSeed && relatedSeed.schema && relatedSeed.schema.schemaNames) {
2361
1801
  refSeedType = relatedSeed.schema.schemaNames[0].name;
1802
+ refSchemaUid = relatedSeed.schemaId;
2362
1803
  }
2363
1804
  }
2364
1805
  if (isRelation && isList) {
2365
1806
  const relatedSeeds = itemSeeds.filter((seed) => metadata.value.includes(seed.id));
2366
1807
  if (relatedSeeds && relatedSeeds.length > 0) {
2367
1808
  refSeedType = relatedSeeds[0].schema.schemaNames[0].name;
1809
+ refSchemaUid = relatedSeeds[0].schemaId;
2368
1810
  }
2369
1811
  }
2370
1812
  const propertyName = camelCase(propertyNameSnake);
@@ -2389,6 +1831,7 @@ const saveEasPropertiesToDb = (_a) => __awaiter(void 0, [_a], void 0, function*
2389
1831
  '${versionLocalId}', '${seedUid}', '${seedLocalId}',
2390
1832
  '${modelType}', ${refValueType ? `'${refValueType}'` : 'NULL'},
2391
1833
  ${refSeedType ? `'${refSeedType}'` : 'NULL'},
1834
+ ${refSchemaUid ? `'${refSchemaUid}'` : 'NULL'},
2392
1835
  ${Date.now()}, ${attestationCreatedAt}, '${attestationRaw}',
2393
1836
  ${'NULL'},
2394
1837
  ${'NULL'})`;
@@ -2515,8 +1958,8 @@ const syncDbWithEasHandler = throttle((_) => __awaiter(void 0, void 0, void 0, f
2515
1958
  trailing: false,
2516
1959
  });
2517
1960
 
2518
- const logger$k = debug('app:services:global:actors:initialize');
2519
- const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
1961
+ const logger$m = debug('app:services:global:actors:initialize');
1962
+ const initialize$2 = fromCallback(({ sendBack, input: { event, context } }) => {
2520
1963
  const { internalService, models, endpoints } = context;
2521
1964
  const { addresses } = event;
2522
1965
  let environment = 'browser';
@@ -2536,7 +1979,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2536
1979
  const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
2537
1980
  return new Promise((resolve) => {
2538
1981
  internalSubscription = internalService.subscribe((snapshot) => {
2539
- logger$k('[sdk] [internal] snapshot', snapshot);
1982
+ logger$m('[sdk] [internal] snapshot', snapshot);
2540
1983
  if (snapshot.value === 'ready') {
2541
1984
  resolve();
2542
1985
  }
@@ -2569,15 +2012,21 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2569
2012
  }
2570
2013
  sendBack(Object.assign({ type: GLOBAL_INITIALIZING_CREATE_ALL_ITEMS_SERVICES }, payloadObj));
2571
2014
  });
2015
+ const _initEas = () => __awaiter(void 0, void 0, void 0, function* () {
2016
+ yield fetchSchemaUids();
2017
+ });
2572
2018
  _initFileSystem().then(() => {
2573
- logger$k('[global/actors] File system initialized');
2019
+ logger$m('[global/actors] File system initialized');
2574
2020
  });
2575
2021
  _initInternal()
2576
2022
  .then(() => {
2577
2023
  return _initAllItemsServices();
2578
2024
  })
2579
2025
  .then(() => {
2580
- logger$k('[global/actors] Internal initialized');
2026
+ return _initEas();
2027
+ })
2028
+ .then(() => {
2029
+ logger$m('[global/actors] Internal initialized');
2581
2030
  sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
2582
2031
  internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
2583
2032
  });
@@ -2591,7 +2040,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { event, context } }) => {
2591
2040
  };
2592
2041
  });
2593
2042
 
2594
- const logger$j = debug('app:services:global:actors:getSchemaForModel');
2043
+ const logger$l = debug('app:services:global:actors:getSchemaForModel');
2595
2044
  const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
2596
2045
  const { modelName } = event;
2597
2046
  if (!modelName) {
@@ -2607,12 +2056,12 @@ const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } })
2607
2056
  if (!model) {
2608
2057
  throw new Error(`Model ${modelName} not found`);
2609
2058
  }
2610
- logger$j('[service/actor] [getSchemaForModel] model:', model);
2059
+ logger$l('[service/actor] [getSchemaForModel] model:', model);
2611
2060
  sendBack({ type: 'schemaForModel', schema: model.schema });
2612
2061
  return () => { };
2613
2062
  });
2614
2063
 
2615
- const logger$i = debug('app:services:global:actors:addModelsToDb');
2064
+ const logger$k = debug('app:services:global:actors:addModelsToDb');
2616
2065
  const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2617
2066
  const { models: models$1 } = context;
2618
2067
  const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
@@ -2621,12 +2070,12 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2621
2070
  if (!models$1) {
2622
2071
  return;
2623
2072
  }
2624
- const { models: SeedModels } = yield import('./seed.schema.config-wQXee2fb.js');
2073
+ const { models: SeedModels } = yield import('./seed.schema.config-C37yDUmq.js');
2625
2074
  const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
2626
2075
  let hasModelsInDb = false;
2627
2076
  const schemaDefsByModelName = new Map();
2628
2077
  for (const [modelName, _] of Object.entries(allModels)) {
2629
- logger$i('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2078
+ logger$k('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
2630
2079
  let foundModel;
2631
2080
  const foundModelsQuery = yield appDb
2632
2081
  .select()
@@ -2636,7 +2085,7 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2636
2085
  yield appDb.insert(models).values({
2637
2086
  name: modelName,
2638
2087
  });
2639
- logger$i('[global/actors] [addModelsToDb] inserted model:', modelName);
2088
+ logger$k('[global/actors] [addModelsToDb] inserted model:', modelName);
2640
2089
  const foundModels = yield appDb
2641
2090
  .select({
2642
2091
  id: models.id,
@@ -2706,10 +2155,10 @@ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
2706
2155
  return () => { };
2707
2156
  });
2708
2157
 
2709
- const logger$h = debug('app:services:db:actors:checkStatus');
2158
+ const logger$j = debug('app:services:db:actors:checkStatus');
2710
2159
  const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
2711
2160
  const { dbName } = context;
2712
- logger$h('[db/actors] checkStatus context', context);
2161
+ logger$j('[db/actors] checkStatus context', context);
2713
2162
  const pathToDir = `${BROWSER_FS_TOP_DIR}`;
2714
2163
  const pathToDbDir = `${pathToDir}/db`;
2715
2164
  const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
@@ -2740,9 +2189,9 @@ const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
2740
2189
  });
2741
2190
  });
2742
2191
 
2743
- const logger$g = debug('app:services:db:actors:connectToDb');
2192
+ const logger$i = debug('app:services:db:actors:connectToDb');
2744
2193
  const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
2745
- logger$g('[db/actors] connectToDb context', context);
2194
+ logger$i('[db/actors] connectToDb context', context);
2746
2195
  const { dbName, pathToDir } = context;
2747
2196
  let isConnecting = false;
2748
2197
  let dbId;
@@ -2755,16 +2204,16 @@ const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
2755
2204
  const sqliteWasmClient = yield getSqliteWasmClient();
2756
2205
  //@ts-ignore
2757
2206
  response = yield sqliteWasmClient('config-get', {});
2758
- logger$g(response);
2759
- logger$g('Running SQLite3 version', response.result.version.libVersion);
2207
+ logger$i(response);
2208
+ logger$i('Running SQLite3 version', response.result.version.libVersion);
2760
2209
  //@ts-ignore
2761
2210
  response = yield sqliteWasmClient('open', {
2762
2211
  filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
2763
2212
  });
2764
- logger$g(response);
2213
+ logger$i(response);
2765
2214
  dbId = response.dbId;
2766
2215
  // logger(`dbId: ${dbId}`)
2767
- logger$g('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
2216
+ logger$i('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
2768
2217
  });
2769
2218
  const interval = setInterval(() => {
2770
2219
  // TODO: Add a timeout
@@ -2821,7 +2270,7 @@ const validate = fromCallback(({ sendBack, input: { context } }) => {
2821
2270
  });
2822
2271
  });
2823
2272
 
2824
- const logger$f = debug('app:services:db:actors:migrate');
2273
+ const logger$h = debug('app:services:db:actors:migrate');
2825
2274
  const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void 0, [dbId_1, params_1, sql_1, dbName_1, ...args_1], void 0, function* (dbId, params, sql, dbName, retries = 2) {
2826
2275
  const rowsToReturnRaw = [];
2827
2276
  const sqliteWasmClient = yield getSqliteWasmClient();
@@ -2887,7 +2336,7 @@ const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void
2887
2336
  });
2888
2337
  const migrate = fromCallback(({ sendBack, input: { context } }) => {
2889
2338
  const { pathToDbDir, dbId, dbName } = context;
2890
- logger$f('[db/actors] migrate context', context);
2339
+ logger$h('[db/actors] migrate context', context);
2891
2340
  const schemaGlobString = `${BROWSER_FS_TOP_DIR}/schema/*`;
2892
2341
  let journalExists = false;
2893
2342
  // const _initFs = async (): Promise<void> => {
@@ -3051,7 +2500,7 @@ const migrate = fromCallback(({ sendBack, input: { context } }) => {
3051
2500
  return () => { };
3052
2501
  });
3053
2502
 
3054
- const logger$e = debug('app:services:db:machine');
2503
+ const logger$g = debug('app:services:db:machine');
3055
2504
  const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
3056
2505
  const dbMachine = setup({
3057
2506
  types: {
@@ -3072,7 +2521,7 @@ const dbMachine = setup({
3072
2521
  [DB_WAITING_FOR_FILES_RECEIVED]: {
3073
2522
  actions: assign({
3074
2523
  hasFiles: ({ event }) => {
3075
- logger$e('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
2524
+ logger$g('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
3076
2525
  return true;
3077
2526
  },
3078
2527
  }),
@@ -3081,8 +2530,8 @@ const dbMachine = setup({
3081
2530
  target: `.${CHECKING_STATUS}`,
3082
2531
  actions: assign({
3083
2532
  hasFiles: ({ context, event }) => {
3084
- logger$e('[db/machine] updateHasFiles event:', event);
3085
- logger$e('[db/machine] updateHasFiles context:', context);
2533
+ logger$g('[db/machine] updateHasFiles event:', event);
2534
+ logger$g('[db/machine] updateHasFiles context:', context);
3086
2535
  return event.hasFiles;
3087
2536
  },
3088
2537
  }),
@@ -3298,7 +2747,7 @@ const prepareDb = fromCallback(({ sendBack }) => {
3298
2747
  };
3299
2748
  });
3300
2749
 
3301
- const logger$d = debug('app:services:internal:helpers');
2750
+ const logger$f = debug('app:services:internal:helpers');
3302
2751
  /**
3303
2752
  * Recursively create directories if they don't exist.
3304
2753
  * @param {string} dirPath - The directory path to create.
@@ -3374,7 +2823,7 @@ const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, f
3374
2823
  if (JSON.stringify(error).includes('File exists')) {
3375
2824
  yield fs.promises.readFile(localFilePath, 'utf-8');
3376
2825
  }
3377
- logger$d(`[Error] Failed to download file from ${url}:`, error);
2826
+ logger$f(`[Error] Failed to download file from ${url}:`, error);
3378
2827
  }
3379
2828
  busy = false;
3380
2829
  });
@@ -3412,7 +2861,7 @@ const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePat
3412
2861
  const fileList = yield fetchDirectory(filePaths);
3413
2862
  yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
3414
2863
  yield confirmFilesExist(fileList);
3415
- logger$d('[syncDbFiles] Files synced!');
2864
+ logger$f('[syncDbFiles] Files synced!');
3416
2865
  });
3417
2866
 
3418
2867
  const uploadBinaryData = fromCallback(({ sendBack, receive, input }) => { });
@@ -3651,7 +3100,7 @@ const saveAppState = (key, value) => __awaiter(void 0, void 0, void 0, function*
3651
3100
  });
3652
3101
  });
3653
3102
 
3654
- const logger$c = debug('app:files:download');
3103
+ const logger$e = debug('app:files:download');
3655
3104
  const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
3656
3105
  yield syncDbFiles(endpoints);
3657
3106
  eventEmitter.emit('fs.downloadAll.success', { eventId });
@@ -3735,7 +3184,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
3735
3184
  try {
3736
3185
  const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
3737
3186
  if (res.status !== 200) {
3738
- logger$c(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
3187
+ logger$e(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
3739
3188
  excludedTransactions.add(transactionId);
3740
3189
  yield saveAppState('excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
3741
3190
  continue;
@@ -3775,7 +3224,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
3775
3224
  // string: true,
3776
3225
  // })
3777
3226
  if (!dataString) {
3778
- logger$c(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
3227
+ logger$e(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
3779
3228
  }
3780
3229
  let contentType = identifyString(dataString);
3781
3230
  if (contentType !== 'json' &&
@@ -3783,7 +3232,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
3783
3232
  contentType !== 'html') {
3784
3233
  const possibleImageType = getDataTypeFromString(dataString);
3785
3234
  if (!possibleImageType) {
3786
- logger$c(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
3235
+ logger$e(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
3787
3236
  continue;
3788
3237
  }
3789
3238
  contentType = possibleImageType;
@@ -3850,7 +3299,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
3850
3299
  }
3851
3300
  }
3852
3301
  catch (error) {
3853
- logger$c(error);
3302
+ logger$e(error);
3854
3303
  }
3855
3304
  }
3856
3305
  });
@@ -3896,14 +3345,14 @@ const isFsInitialized = () => {
3896
3345
  return isInitialized;
3897
3346
  };
3898
3347
 
3899
- const logger$b = debug('app:internal:actors:configureFs');
3348
+ const logger$d = debug('app:internal:actors:configureFs');
3900
3349
  const configureFs = fromCallback(({ sendBack, input: { context } }) => {
3901
3350
  const { endpoints, appDbService } = context;
3902
- logger$b('[internal/actors] [configureFs] Configuring FS');
3351
+ logger$d('[internal/actors] [configureFs] Configuring FS');
3903
3352
  const _configureFs = () => __awaiter(void 0, void 0, void 0, function* () {
3904
- logger$b('[internal/actors] [configureFs] calling _configureFs');
3905
- logger$b('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
3906
- logger$b('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
3353
+ logger$d('[internal/actors] [configureFs] calling _configureFs');
3354
+ logger$d('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
3355
+ logger$d('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
3907
3356
  yield waitForEvent({
3908
3357
  req: {
3909
3358
  eventLabel: 'fs.downloadAll.request',
@@ -3932,7 +3381,7 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
3932
3381
  // }
3933
3382
  // }, 200)
3934
3383
  // })
3935
- logger$b('[internal/actors] [configureFs] fs configured!');
3384
+ logger$d('[internal/actors] [configureFs] fs configured!');
3936
3385
  });
3937
3386
  // Some of our dependencies use fs sync functions, which don't work with
3938
3387
  // OPFS. ZenFS creates an async cache of all files so that the sync functions
@@ -3945,7 +3394,7 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
3945
3394
  return () => { };
3946
3395
  });
3947
3396
 
3948
- const logger$a = debug('app:services:internal:actors:saveConfig');
3397
+ const logger$c = debug('app:services:internal:actors:saveConfig');
3949
3398
  const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
3950
3399
  if (typeof window === 'undefined') {
3951
3400
  console.error('seedInitBrowser called from non-browser context');
@@ -3996,20 +3445,20 @@ const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
3996
3445
  },
3997
3446
  setWhere: sql `key = 'addresses'`,
3998
3447
  });
3999
- logger$a('[sdk] [internal/actors] Should be done saving');
3448
+ logger$c('[sdk] [internal/actors] Should be done saving');
4000
3449
  }
4001
3450
  catch (error) {
4002
3451
  console.error('Error saving config:', error);
4003
3452
  }
4004
3453
  });
4005
3454
  _saveConfig().then(() => {
4006
- logger$a('[sdk] [internal/actors] Successfully saved config');
3455
+ logger$c('[sdk] [internal/actors] Successfully saved config');
4007
3456
  return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
4008
3457
  });
4009
3458
  return () => { };
4010
3459
  });
4011
3460
 
4012
- const logger$9 = debug('app:services:internal:actors:loadAppDb');
3461
+ const logger$b = debug('app:services:internal:actors:loadAppDb');
4013
3462
  const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4014
3463
  const { appDbService } = context;
4015
3464
  let subscription;
@@ -4030,7 +3479,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4030
3479
  });
4031
3480
  _loadAppDb().then(() => {
4032
3481
  sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
4033
- logger$9('[sdk] [internal/actors] Successfully loaded app DB');
3482
+ logger$b('[sdk] [internal/actors] Successfully loaded app DB');
4034
3483
  });
4035
3484
  return () => {
4036
3485
  if (subscription) {
@@ -4039,7 +3488,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
4039
3488
  };
4040
3489
  });
4041
3490
 
4042
- const logger$8 = debug('app:services:internal:machine');
3491
+ const logger$a = debug('app:services:internal:machine');
4043
3492
  createBrowserInspector({
4044
3493
  autoStart: false,
4045
3494
  });
@@ -4138,7 +3587,7 @@ const internalMachine = setup({
4138
3587
  [INTERNAL_LOADING_APP_DB_SUCCESS]: {
4139
3588
  target: SAVING_CONFIG,
4140
3589
  actions: () => {
4141
- logger$8('[sdk] [internal/index] App DB loaded!');
3590
+ logger$a('[sdk] [internal/index] App DB loaded!');
4142
3591
  },
4143
3592
  },
4144
3593
  },
@@ -4164,7 +3613,7 @@ const internalMachine = setup({
4164
3613
  },
4165
3614
  ready: {
4166
3615
  entry: () => {
4167
- logger$8('[sdk] [internal/index] Ready!');
3616
+ logger$a('[sdk] [internal/index] Ready!');
4168
3617
  },
4169
3618
  meta: {
4170
3619
  displayText: "Crossing the t's ...",
@@ -4179,7 +3628,7 @@ const internalMachine = setup({
4179
3628
  },
4180
3629
  },
4181
3630
  entry: () => {
4182
- logger$8('[sdk] [internal/index] Error!');
3631
+ logger$a('[sdk] [internal/index] Error!');
4183
3632
  },
4184
3633
  meta: {
4185
3634
  displayText: 'Whoops! Something went wrong.',
@@ -4223,7 +3672,7 @@ const internalMachine = setup({
4223
3672
  // })
4224
3673
  // internalService.start()
4225
3674
 
4226
- const initialize = fromCallback(({ sendBack, input: { context } }) => {
3675
+ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4227
3676
  const { modelName, modelAddedToDb, ModelClass, times } = context;
4228
3677
  const newTimes = {
4229
3678
  initialize: {
@@ -4415,7 +3864,7 @@ const fetchDbData = fromCallback(({ sendBack, input: { context } }) => {
4415
3864
  return () => { };
4416
3865
  });
4417
3866
 
4418
- const logger$7 = debug('app:allItemsActors:fetchSeeds');
3867
+ const logger$9 = debug('app:allItemsActors:fetchSeeds');
4419
3868
  const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4420
3869
  const { queryVariables, modelName } = context;
4421
3870
  if (!queryVariables) {
@@ -4425,7 +3874,7 @@ const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4425
3874
  const _fetchSeeds = () => __awaiter(void 0, void 0, void 0, function* () {
4426
3875
  const queryKey = [`getSeeds${modelName}`];
4427
3876
  const cachedResults = queryClient.getQueryData(queryKey);
4428
- logger$7(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
3877
+ logger$9(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4429
3878
  const results = yield queryClient.fetchQuery({
4430
3879
  queryKey,
4431
3880
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SEEDS, queryVariables); }),
@@ -4644,7 +4093,7 @@ const itemMachineAll = setup({
4644
4093
  input: {},
4645
4094
  },
4646
4095
  actors: {
4647
- initialize,
4096
+ initialize: initialize$1,
4648
4097
  fetchDbData,
4649
4098
  fetchSeeds,
4650
4099
  fetchVersions,
@@ -4870,13 +4319,13 @@ const preparePublishRequestData = fromCallback(({ sendBack, input: { context } }
4870
4319
  });
4871
4320
  });
4872
4321
 
4873
- const logger$6 = debug('app:services:publish:actors:upload');
4322
+ const logger$8 = debug('app:services:publish:actors:upload');
4874
4323
  const upload = fromCallback(({ sendBack, input: { context } }) => {
4875
4324
  const { localId } = context;
4876
4325
  const _upload = () => __awaiter(void 0, void 0, void 0, function* () {
4877
4326
  const item = yield Item.find({ seedLocalId: localId });
4878
4327
  if (!item) {
4879
- logger$6('no item with localId', localId);
4328
+ logger$8('no item with localId', localId);
4880
4329
  return false;
4881
4330
  }
4882
4331
  const editedProperties = yield item.getEditedProperties();
@@ -5006,7 +4455,7 @@ const globalMachine = setup({
5006
4455
  input: {},
5007
4456
  },
5008
4457
  actors: {
5009
- initialize: initialize$1,
4458
+ initialize: initialize$2,
5010
4459
  addModelsToDb,
5011
4460
  getSchemaForModel,
5012
4461
  savePublishService,
@@ -5520,7 +4969,7 @@ const itemMachineSingle = setup({
5520
4969
  },
5521
4970
  actors: {
5522
4971
  waitForDb,
5523
- initialize: initialize$2,
4972
+ initialize: initialize$3,
5524
4973
  hydrateExistingItem,
5525
4974
  hydrateNewItem,
5526
4975
  fetchDataFromEas,
@@ -5710,7 +5159,7 @@ const getSeedData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoc
5710
5159
  return rows[0];
5711
5160
  });
5712
5161
 
5713
- const logger$5 = debug('app:db:queries:getItem');
5162
+ const logger$7 = debug('app:db:queries:getItem');
5714
5163
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
5715
5164
  if (!seedLocalId && !seedUid) {
5716
5165
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -5718,7 +5167,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
5718
5167
  if (seedUid && !seedLocalId) {
5719
5168
  const seedData = yield getSeedData({ seedUid });
5720
5169
  if (!seedData) {
5721
- logger$5('[db/queries] [getItem] no seedData seedUid', seedUid);
5170
+ logger$7('[db/queries] [getItem] no seedData seedUid', seedUid);
5722
5171
  return;
5723
5172
  }
5724
5173
  seedLocalId = seedData.localId;
@@ -5745,7 +5194,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
5745
5194
  .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
5746
5195
  .groupBy(seeds.localId);
5747
5196
  if (!itemDataRows || itemDataRows.length === 0) {
5748
- logger$5('[db/queries] [getItemDataFromDb] no itemDataRows');
5197
+ logger$7('[db/queries] [getItemDataFromDb] no itemDataRows');
5749
5198
  return;
5750
5199
  }
5751
5200
  let itemData = itemDataRows[0];
@@ -5786,130 +5235,215 @@ const getItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName,
5786
5235
  return Item.create(itemInitObj);
5787
5236
  });
5788
5237
 
5789
- const getSchemaForItemProperty = (_a) => __awaiter(void 0, [_a], void 0, function* ({ schemaUid, propertyName, easDataType, }) {
5790
- const propertyNameSnakeCase = toSnakeCase(propertyName);
5791
- const isMissingSchemaUid = !schemaUid || schemaUid === 'null' || schemaUid === 'undefined';
5792
- let queryParams = {
5793
- where: {
5794
- id: {
5795
- equals: schemaUid,
5796
- },
5797
- },
5798
- };
5799
- if (easDataType) {
5800
- queryParams = {
5801
- where: {
5802
- schema: {
5803
- equals: `${easDataType} ${propertyNameSnakeCase}`,
5804
- },
5805
- },
5806
- };
5807
- }
5808
- if (!easDataType && isMissingSchemaUid) {
5809
- queryParams = {
5810
- where: {
5811
- schemaNames: {
5812
- some: {
5813
- name: {
5814
- equals: propertyNameSnakeCase,
5815
- },
5816
- },
5817
- },
5818
- },
5819
- };
5820
- }
5821
- const foundPropertySchema = yield queryClient.fetchQuery({
5822
- queryKey: [`getPropertySchema${propertyName}`],
5823
- queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SCHEMAS, queryParams); }),
5824
- networkMode: 'offlineFirst',
5825
- });
5826
- if (foundPropertySchema && foundPropertySchema.schemas.length > 0) {
5827
- return foundPropertySchema.schemas[0];
5238
+ const getVersionUid = (item) => {
5239
+ let versionUid;
5240
+ if (item.latestVersionUid &&
5241
+ item.latestVersionUid !== 'NULL' &&
5242
+ item.latestVersionUid !== 'undefined') {
5243
+ versionUid = item.latestVersionUid;
5244
+ }
5245
+ return versionUid || ZERO_ADDRESS;
5246
+ };
5247
+ const getPropertyData = (itemProperty) => __awaiter(void 0, void 0, void 0, function* () {
5248
+ const easDataType = INTERNAL_DATA_TYPES[itemProperty.propertyDef.dataType].eas;
5249
+ let schemaUid = itemProperty.schemaUid;
5250
+ const propertyNameForSchema = toSnakeCase(itemProperty.propertyName);
5251
+ const schemaDef = `${easDataType} ${propertyNameForSchema}`;
5252
+ if (!schemaUid) {
5253
+ schemaUid = getSchemaUidForSchemaDefinition(schemaDef);
5254
+ if (!schemaUid) {
5255
+ const schema = yield getSchemaForItemProperty({
5256
+ propertyName: 'version',
5257
+ easDataType: 'bytes32',
5258
+ });
5259
+ if (schema) {
5260
+ schemaUid = schema.id;
5261
+ }
5262
+ }
5828
5263
  }
5264
+ return {
5265
+ schemaUid,
5266
+ easDataType,
5267
+ schemaDef,
5268
+ propertyNameForSchema,
5269
+ };
5829
5270
  });
5830
-
5831
- const getPublishPayload = (seedLocalId) => __awaiter(void 0, void 0, void 0, function* () {
5832
- const item = yield getItem({ seedLocalId });
5833
- if (!item) {
5834
- throw new Error('Item not found');
5835
- }
5836
- const localId = item.seedLocalId;
5837
- const seedIsRevocable = true;
5838
- const seedSchemaUid = item.schemaUid;
5839
- const seedUid = item.seedUid;
5840
- const versionSchemaUid = VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA;
5841
- const listOfAttestations = [];
5842
- const propertiesToUpdate = [];
5843
- for (const [propertyName, itemProperty] of Object.entries(item.properties)) {
5844
- if (!itemProperty.value || !itemProperty.propertyDef) {
5271
+ const getSegmentedItemProperties = (item) => {
5272
+ const itemBasicProperties = [];
5273
+ const itemRelationProperties = [];
5274
+ const itemListProperties = [];
5275
+ const itemStorageProperties = [];
5276
+ for (const itemProperty of Object.values(item.properties)) {
5277
+ if (!itemProperty.propertyDef) {
5845
5278
  continue;
5846
5279
  }
5847
- const easDataType = INTERNAL_DATA_TYPES[itemProperty.propertyDef.dataType].eas;
5848
- let schemaUid = itemProperty.schemaUid;
5849
- let propertyNameForSchema = propertyName;
5850
- let propertyValue = itemProperty.getService().getSnapshot()
5851
- .context.propertyValue;
5852
5280
  if (itemProperty.propertyDef.dataType === 'Relation') {
5853
- propertyNameForSchema = `${propertyName}Id`;
5854
- }
5855
- if (itemProperty.propertyDef.dataType === 'List' &&
5856
- itemProperty.propertyDef.ref) {
5857
- const singularPropertyName = pluralize.singular(propertyName);
5858
- propertyNameForSchema = `${singularPropertyName}${itemProperty.propertyDef.ref}Ids`;
5859
- if (typeof propertyValue === 'string' && propertyValue.length === 66) {
5860
- propertyValue = [propertyValue];
5861
- }
5862
- if (typeof propertyValue === 'string' && propertyValue.length > 66) {
5863
- try {
5864
- propertyValue = JSON.parse(propertyValue);
5865
- }
5866
- catch (error) {
5867
- console.log('No-op due to error: ', error);
5868
- }
5869
- }
5281
+ itemRelationProperties.push(itemProperty);
5282
+ continue;
5283
+ }
5284
+ if (itemProperty.propertyDef.dataType === 'List') {
5285
+ itemListProperties.push(itemProperty);
5286
+ continue;
5870
5287
  }
5871
5288
  if (itemProperty.propertyDef.storageType &&
5872
5289
  itemProperty.propertyDef.storageType === 'ItemStorage') {
5290
+ itemStorageProperties.push(itemProperty);
5873
5291
  continue;
5874
5292
  }
5875
- const foundPropertySchema = yield getSchemaForItemProperty({
5876
- schemaUid,
5877
- propertyName: propertyNameForSchema,
5878
- easDataType,
5879
- });
5880
- if (!foundPropertySchema) {
5881
- throw new Error(`No schema found for property ${itemProperty.propertyName} ${itemProperty.localId}`);
5293
+ itemBasicProperties.push(itemProperty);
5294
+ }
5295
+ return {
5296
+ itemBasicProperties,
5297
+ itemRelationProperties,
5298
+ itemListProperties,
5299
+ itemStorageProperties,
5300
+ };
5301
+ };
5302
+ const processBasicProperties = (itemBasicProperties, itemPublishData) => __awaiter(void 0, void 0, void 0, function* () {
5303
+ for (const basicProperty of itemBasicProperties) {
5304
+ const value = basicProperty.getService().getSnapshot().context.propertyValue;
5305
+ if (!value || basicProperty.uid) {
5306
+ continue;
5882
5307
  }
5883
- schemaUid = foundPropertySchema.id;
5308
+ const { schemaUid, easDataType, schemaDef } = yield getPropertyData(basicProperty);
5309
+ const propertyNameForSchema = toSnakeCase(basicProperty.propertyName);
5884
5310
  const data = [
5885
5311
  {
5886
- name: toSnakeCase(propertyNameForSchema),
5312
+ name: propertyNameForSchema,
5887
5313
  type: easDataType,
5888
- value: propertyValue,
5314
+ value,
5889
5315
  },
5890
5316
  ];
5891
- const easSchemaDefinition = foundPropertySchema.schema;
5892
- const dataEncoder = new SchemaEncoder(easSchemaDefinition);
5317
+ const dataEncoder = new SchemaEncoder(schemaDef);
5893
5318
  const encodedData = dataEncoder.encodeData(data);
5894
- listOfAttestations.push({
5319
+ itemPublishData.listOfAttestations.push({
5895
5320
  schema: schemaUid,
5896
5321
  data: [
5897
5322
  Object.assign(Object.assign({}, defaultAttestationData), { data: encodedData }),
5898
5323
  ],
5899
5324
  });
5900
5325
  }
5901
- return [
5902
- {
5903
- localId,
5904
- seedIsRevocable,
5905
- seedSchemaUid,
5326
+ return itemPublishData;
5327
+ });
5328
+ const processRelationProperty = (relationProperty, multiPublishPayload) => __awaiter(void 0, void 0, void 0, function* () {
5329
+ const value = relationProperty.getService().getSnapshot()
5330
+ .context.propertyValue;
5331
+ if (!value || relationProperty.uid) {
5332
+ return multiPublishPayload;
5333
+ }
5334
+ const { localId: seedLocalId, uid: seedUid } = getCorrectId(value);
5335
+ const relatedItem = yield getItem({
5336
+ seedLocalId,
5337
+ seedUid,
5338
+ });
5339
+ if (!relatedItem) {
5340
+ throw new Error(`No related item found for relation property: ${relationProperty.propertyName}`);
5341
+ }
5342
+ const versionUid = getVersionUid(relatedItem);
5343
+ const seedSchemaUid = yield getSchemaUidForModel(relationProperty.propertyDef.ref);
5344
+ let publishPayload = {
5345
+ localId: relationProperty.localId,
5346
+ seedIsRevocable: true,
5347
+ versionSchemaUid: VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA,
5348
+ seedUid: seedUid || ZERO_ADDRESS,
5349
+ seedSchemaUid,
5350
+ versionUid,
5351
+ listOfAttestations: [],
5352
+ propertiesToUpdate: [],
5353
+ };
5354
+ const { itemBasicProperties } = getSegmentedItemProperties(relatedItem);
5355
+ publishPayload = yield processBasicProperties(itemBasicProperties, publishPayload);
5356
+ multiPublishPayload.push(publishPayload);
5357
+ return multiPublishPayload;
5358
+ });
5359
+ const processListProperty = (listProperty, multiPublishPayload) => __awaiter(void 0, void 0, void 0, function* () {
5360
+ let value = listProperty.getService().getSnapshot().context.propertyValue;
5361
+ if (!value || listProperty.uid) {
5362
+ return multiPublishPayload;
5363
+ }
5364
+ const singularPropertyName = pluralize.singular(listProperty.propertyName);
5365
+ `${singularPropertyName}${listProperty.propertyDef.ref}Ids`;
5366
+ if (typeof value === 'string' && value.length === 66) {
5367
+ value = [value];
5368
+ }
5369
+ if (typeof value === 'string' && value.length > 66) {
5370
+ try {
5371
+ value = JSON.parse(value);
5372
+ }
5373
+ catch (error) {
5374
+ value = value.split(',');
5375
+ }
5376
+ }
5377
+ for (const seedId of value) {
5378
+ const { localId: seedLocalId, uid: seedUid } = getCorrectId(seedId);
5379
+ const relatedItem = yield getItem({
5380
+ seedLocalId,
5381
+ seedUid,
5382
+ });
5383
+ if (!relatedItem) {
5384
+ throw new Error(`No related item found for list property: ${listProperty.propertyName}`);
5385
+ }
5386
+ if (relatedItem.seedUid) {
5387
+ return multiPublishPayload;
5388
+ }
5389
+ const versionUid = getVersionUid(relatedItem);
5390
+ const seedSchemaUid = yield getSchemaUidForModel(listProperty.propertyDef.ref);
5391
+ let publishPayload = {
5392
+ localId: relatedItem.seedLocalId,
5393
+ seedIsRevocable: true,
5394
+ versionSchemaUid: VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA,
5906
5395
  seedUid: seedUid || ZERO_ADDRESS,
5907
- versionUid: item.latestVersionUid || ZERO_ADDRESS,
5908
- versionSchemaUid,
5909
- listOfAttestations,
5910
- propertiesToUpdate,
5911
- },
5912
- ];
5396
+ seedSchemaUid,
5397
+ versionUid,
5398
+ listOfAttestations: [],
5399
+ propertiesToUpdate: [
5400
+ {
5401
+ publishLocalId: listProperty.localId,
5402
+ propertySchemaUid: listProperty.schemaUid,
5403
+ },
5404
+ ],
5405
+ };
5406
+ const { itemBasicProperties } = getSegmentedItemProperties(relatedItem);
5407
+ publishPayload = yield processBasicProperties(itemBasicProperties, publishPayload);
5408
+ multiPublishPayload.push(publishPayload);
5409
+ }
5410
+ return multiPublishPayload;
5411
+ });
5412
+ const getPublishPayload = (seedLocalId) => __awaiter(void 0, void 0, void 0, function* () {
5413
+ const item = yield getItem({ seedLocalId });
5414
+ if (!item) {
5415
+ throw new Error('Item not found');
5416
+ }
5417
+ // if (item.modelName === 'Post') {
5418
+ // item.authors = [
5419
+ // 'Sr0bIx9Fwj',
5420
+ // '0xc2879650e9503a303ceb46f966e55baab480b267dc20cede23ef503622eee6d7',
5421
+ // ]
5422
+ // }
5423
+ let multiPublishPayload = [];
5424
+ // Each PublishPayload is generated from a Seed that needs publishing
5425
+ // First we need to determine all Seeds to publish
5426
+ // That means the Seed of the Item, plus any Seeds pointed to by Relations
5427
+ let itemPublishData = {
5428
+ localId: item.seedLocalId,
5429
+ seedUid: item.seedUid || ZERO_ADDRESS,
5430
+ seedIsRevocable: true,
5431
+ seedSchemaUid: item.schemaUid,
5432
+ versionSchemaUid: VERSION_SCHEMA_UID_OPTIMISM_SEPOLIA,
5433
+ versionUid: item.latestVersionUid || ZERO_ADDRESS,
5434
+ listOfAttestations: [],
5435
+ propertiesToUpdate: [],
5436
+ };
5437
+ const { itemBasicProperties, itemRelationProperties, itemListProperties, itemStorageProperties, } = getSegmentedItemProperties(item);
5438
+ itemPublishData = yield processBasicProperties(itemBasicProperties, itemPublishData);
5439
+ multiPublishPayload.push(itemPublishData);
5440
+ for (const relationProperty of itemRelationProperties) {
5441
+ multiPublishPayload = yield processRelationProperty(relationProperty, multiPublishPayload);
5442
+ }
5443
+ for (const listProperty of itemListProperties) {
5444
+ multiPublishPayload = yield processListProperty(listProperty, multiPublishPayload);
5445
+ }
5446
+ return multiPublishPayload;
5913
5447
  });
5914
5448
 
5915
5449
  var _a$1;
@@ -6023,6 +5557,9 @@ class Item {
6023
5557
  }
6024
5558
  static create(props) {
6025
5559
  return __awaiter(this, void 0, void 0, function* () {
5560
+ if (!props.modelName && props.type) {
5561
+ props.modelName = capitalizeFirstLetter(props.type);
5562
+ }
6026
5563
  if (props.seedUid || props.seedLocalId) {
6027
5564
  const seedId = (props.seedUid || props.seedLocalId);
6028
5565
  if (Item.instanceCache.has(seedId)) {
@@ -6162,7 +5699,7 @@ class Item {
6162
5699
  _a$1 = immerable;
6163
5700
  Item.instanceCache = new Map();
6164
5701
 
6165
- const logger$4 = debug('app:react:services');
5702
+ const logger$6 = debug('app:react:services');
6166
5703
  const finalStrings = ['idle', 'ready', 'done', 'success', 'initialized'];
6167
5704
  const getServiceName = (service) => {
6168
5705
  let name = 'actor';
@@ -6209,7 +5746,7 @@ const getServiceUniqueKey = (service) => {
6209
5746
  snapshot = service.getSnapshot();
6210
5747
  }
6211
5748
  catch (error) {
6212
- logger$4('Error:', error);
5749
+ logger$6('Error:', error);
6213
5750
  return uniqueKey;
6214
5751
  }
6215
5752
  if (snapshot) {
@@ -6313,7 +5850,7 @@ const useGlobalServiceStatus = () => {
6313
5850
  };
6314
5851
  };
6315
5852
 
6316
- const logger$3 = debug('app:react:item');
5853
+ const logger$5 = debug('app:react:item');
6317
5854
  const useItem = ({ modelName, seedLocalId, seedUid }) => {
6318
5855
  // const [itemSubscription, setItemSubscription] = useState<
6319
5856
  // Subscription | undefined
@@ -6390,7 +5927,7 @@ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6390
5927
  seedUid,
6391
5928
  });
6392
5929
  if (!foundItem) {
6393
- logger$3('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
5930
+ logger$5('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6394
5931
  isReadingDb.current = false;
6395
5932
  return;
6396
5933
  }
@@ -6412,7 +5949,7 @@ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6412
5949
  const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
6413
5950
  const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
6414
5951
  if (!newItem) {
6415
- logger$3('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
5952
+ logger$5('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6416
5953
  return;
6417
5954
  }
6418
5955
  updateItem(newItem);
@@ -6439,19 +5976,131 @@ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6439
5976
  itemStatus,
6440
5977
  };
6441
5978
  };
6442
- const useItems = ({ modelName, deleted }) => {
6443
- const [items, setItems] = useImmer([]);
6444
- const { status, internalStatus } = useGlobalServiceStatus();
6445
- const modelNameRef = useRef(modelName);
5979
+ const useItems = ({ modelName, deleted }) => {
5980
+ const [items, setItems] = useImmer([]);
5981
+ const { status, internalStatus } = useGlobalServiceStatus();
5982
+ const modelNameRef = useRef(modelName);
5983
+ const isReadingDb = useRef(false);
5984
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5985
+ if (isReadingDb.current || internalStatus !== 'ready') {
5986
+ return;
5987
+ }
5988
+ isReadingDb.current = true;
5989
+ const allItems = yield Item.all(modelNameRef.current, deleted);
5990
+ setItems(() => []);
5991
+ setItems(() => allItems);
5992
+ isReadingDb.current = false;
5993
+ }), [internalStatus]);
5994
+ const listenerRef = useRef(readFromDb);
5995
+ useEffect(() => {
5996
+ listenerRef.current = readFromDb;
5997
+ }, [readFromDb]);
5998
+ useEffect(() => {
5999
+ if (internalStatus === 'ready') {
6000
+ listenerRef.current();
6001
+ }
6002
+ }, [internalStatus, status]);
6003
+ useEffect(() => {
6004
+ eventEmitter.addListener('item.requestAll', (event) => {
6005
+ if (!event ||
6006
+ !event.modelName ||
6007
+ event.modelName !== modelNameRef.current) {
6008
+ return;
6009
+ }
6010
+ listenerRef.current();
6011
+ });
6012
+ return () => {
6013
+ eventEmitter.removeListener('item.requestAll', readFromDb);
6014
+ };
6015
+ }, []);
6016
+ return {
6017
+ items: orderBy(items, [
6018
+ (item) => item.lastVersionPublishedAt ||
6019
+ item.attestationCreatedAt ||
6020
+ item.createdAt,
6021
+ ], ['desc']),
6022
+ isReadingDb,
6023
+ };
6024
+ };
6025
+ const useItemIsReady = () => {
6026
+ const [itemListenersReady, setItemListenersReady] = useState(false);
6027
+ const itemEventListenersHandler = useCallback((_) => {
6028
+ setItemListenersReady(true);
6029
+ }, []);
6030
+ useEffect(() => {
6031
+ const areReady = getAreItemEventHandlersReady();
6032
+ if (areReady) {
6033
+ itemEventListenersHandler(true);
6034
+ }
6035
+ eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
6036
+ return () => {
6037
+ eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
6038
+ };
6039
+ }, []);
6040
+ return {
6041
+ isReady: itemListenersReady,
6042
+ };
6043
+ };
6044
+ const useCreateItem = (modelName) => {
6045
+ const [isCreatingItem, setIsCreatingItem] = useState(false);
6046
+ const { isReady } = useItemIsReady();
6047
+ const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
6048
+ if (!isReady) {
6049
+ console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
6050
+ return;
6051
+ }
6052
+ if (isCreatingItem) {
6053
+ // TODO: should we setup a queue for this?
6054
+ console.error(`[useCreateItem] [createItem] already creating item`, itemData);
6055
+ return;
6056
+ }
6057
+ setIsCreatingItem(true);
6058
+ const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
6059
+ yield Item.find({ modelName, seedLocalId });
6060
+ eventEmitter.emit('item.requestAll', { modelName });
6061
+ setIsCreatingItem(false);
6062
+ }), [isCreatingItem, isReady]);
6063
+ return {
6064
+ createItem,
6065
+ isCreatingItem,
6066
+ };
6067
+ };
6068
+
6069
+ const logger$4 = debug('app:react:property');
6070
+ const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
6071
+ const [property, setProperty] = useState();
6072
+ const [isInitialized, setIsInitialized] = useState(false);
6073
+ const { internalStatus } = useGlobalServiceStatus();
6446
6074
  const isReadingDb = useRef(false);
6075
+ const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
6076
+ if (!snapshot || !snapshot.context) {
6077
+ return;
6078
+ }
6079
+ return snapshot.context.renderValue || snapshot.context.propertyValue;
6080
+ });
6081
+ const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6447
6082
  const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6448
- if (isReadingDb.current || internalStatus !== 'ready') {
6083
+ if (internalStatus !== 'ready' ||
6084
+ isReadingDb.current ||
6085
+ (!seedLocalId && !seedUid)) {
6449
6086
  return;
6450
6087
  }
6451
6088
  isReadingDb.current = true;
6452
- const allItems = yield Item.all(modelNameRef.current, deleted);
6453
- setItems(() => []);
6454
- setItems(() => allItems);
6089
+ const foundProperty = yield ItemProperty.find({
6090
+ propertyName,
6091
+ seedLocalId,
6092
+ seedUid,
6093
+ });
6094
+ if (!foundProperty) {
6095
+ logger$4(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6096
+ isReadingDb.current = false;
6097
+ return;
6098
+ }
6099
+ if (foundProperty.status === 'waitingForDb') {
6100
+ foundProperty.getService().send({ type: 'waitForDbSuccess' });
6101
+ }
6102
+ setProperty(foundProperty);
6103
+ setIsInitialized(true);
6455
6104
  isReadingDb.current = false;
6456
6105
  }), [internalStatus]);
6457
6106
  const listenerRef = useRef(readFromDb);
@@ -6460,292 +6109,829 @@ const useItems = ({ modelName, deleted }) => {
6460
6109
  }, [readFromDb]);
6461
6110
  useEffect(() => {
6462
6111
  if (internalStatus === 'ready') {
6463
- listenerRef.current();
6112
+ readFromDb();
6464
6113
  }
6465
- }, [internalStatus, status]);
6114
+ }, [internalStatus]);
6466
6115
  useEffect(() => {
6467
- eventEmitter.addListener('item.requestAll', (event) => {
6468
- if (!event ||
6469
- !event.modelName ||
6470
- event.modelName !== modelNameRef.current) {
6471
- return;
6472
- }
6116
+ eventEmitter.addListener(`property.${seedUid || seedLocalId}.${propertyName}.update`, () => {
6473
6117
  listenerRef.current();
6474
6118
  });
6475
6119
  return () => {
6476
- eventEmitter.removeListener('item.requestAll', readFromDb);
6120
+ eventEmitter.removeListener(`property.${seedUid || seedLocalId}.${propertyName}.update`);
6477
6121
  };
6478
6122
  }, []);
6479
6123
  return {
6480
- items: orderBy(items, [
6481
- (item) => item.lastVersionPublishedAt ||
6482
- item.attestationCreatedAt ||
6483
- item.createdAt,
6484
- ], ['desc']),
6485
- isReadingDb,
6124
+ property,
6125
+ isInitialized,
6126
+ value,
6127
+ status,
6486
6128
  };
6487
6129
  };
6488
- const useItemIsReady = () => {
6489
- const [itemListenersReady, setItemListenersReady] = useState(false);
6490
- const itemEventListenersHandler = useCallback((_) => {
6491
- setItemListenersReady(true);
6492
- }, []);
6130
+ const useItemProperties = (item) => {
6131
+ const [propertyObj, setPropertyObj] = useImmer({});
6132
+ useState(false);
6133
+ const updatePropertyObj = useCallback((event) => {
6134
+ if (!item) {
6135
+ console.error('[XXXXXX] [updatePropertyObj] no item when expected');
6136
+ return;
6137
+ }
6138
+ const { propertyName, propertyValue } = event;
6139
+ if (!propertyName) {
6140
+ return;
6141
+ }
6142
+ setPropertyObj((draft) => {
6143
+ draft[propertyName] = propertyValue;
6144
+ });
6145
+ }, [item]);
6493
6146
  useEffect(() => {
6494
- const areReady = getAreItemEventHandlersReady();
6495
- if (areReady) {
6496
- itemEventListenersHandler(true);
6147
+ if (!item) {
6148
+ return;
6497
6149
  }
6498
- eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
6150
+ const eventKey = `item.${item.seedLocalId}.property.update`;
6151
+ eventEmitter.addListener(eventKey, updatePropertyObj);
6499
6152
  return () => {
6500
- eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
6153
+ eventEmitter.removeListener(eventKey, updatePropertyObj);
6501
6154
  };
6502
- }, []);
6155
+ }, [item]);
6503
6156
  return {
6504
- isReady: itemListenersReady,
6157
+ properties: propertyObj,
6158
+ };
6159
+ };
6160
+
6161
+ debug('app:react:db');
6162
+
6163
+ const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
6164
+ const appDb = getAppDb();
6165
+ yield appDb
6166
+ .update(seeds)
6167
+ .set({
6168
+ _markedForDeletion: 1,
6169
+ })
6170
+ .where(or(eq(seeds.localId, seedLocalId), eq(seeds.uid, seedUid)));
6171
+ });
6172
+
6173
+ const useDeleteItem = () => {
6174
+ const [isDeletingItem, setIsDeletingItem] = useState(false);
6175
+ const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
6176
+ if (!item) {
6177
+ return;
6178
+ }
6179
+ setIsDeletingItem(true);
6180
+ const { modelName } = item.getService().getSnapshot().context;
6181
+ yield deleteItem({ seedLocalId: item.seedLocalId });
6182
+ eventEmitter.emit('item.requestAll', { modelName });
6183
+ setIsDeletingItem(false);
6184
+ }), [isDeletingItem]);
6185
+ useEffect(() => { }, []);
6186
+ return {
6187
+ deleteItem: destroy,
6188
+ isDeletingItem,
6189
+ };
6190
+ };
6191
+
6192
+ const logger$3 = debug('app:services:events');
6193
+ const handleServiceSaveState = (event) => {
6194
+ const { state, serviceId } = event;
6195
+ logger$3(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
6196
+ localStorage.setItem(`seed_sdk_service_${serviceId}`, JSON.stringify(state));
6197
+ };
6198
+ const setupServicesEventHandlers = () => {
6199
+ eventEmitter.addListener('service.saveState.request', handleServiceSaveState);
6200
+ };
6201
+
6202
+ const saveServiceHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
6203
+ const globalService = getGlobalService();
6204
+ if (!globalService || !globalService.getSnapshot().context) {
6205
+ return;
6206
+ }
6207
+ const { modelName } = event;
6208
+ const nameOfService = `${modelName}Service`;
6209
+ const service = globalService.getSnapshot().context[nameOfService];
6210
+ if (!service) {
6211
+ console.log(`[saveServiceHandler] service not found: ${nameOfService}`);
6212
+ return;
6213
+ }
6214
+ yield saveAppState(`snapshot__${modelName}`, JSON.stringify(service.getPersistedSnapshot()));
6215
+ });
6216
+
6217
+ const setupServiceHandlers = () => {
6218
+ eventEmitter.addListener('service.save', saveServiceHandler);
6219
+ };
6220
+
6221
+ const client = {
6222
+ init: ({ config, addresses }) => {
6223
+ const { endpoints, models } = config;
6224
+ for (const [key, value] of Object.entries(models)) {
6225
+ setModel(key, value);
6226
+ }
6227
+ setupFsListeners();
6228
+ setupAllItemsEventHandlers();
6229
+ setupServicesEventHandlers();
6230
+ setupServiceHandlers();
6231
+ if (areFsListenersReady()) {
6232
+ eventEmitter.emit('fs.init');
6233
+ }
6234
+ if (!areFsListenersReady()) {
6235
+ console.error('fs listeners not ready during init');
6236
+ }
6237
+ globalService.send({ type: 'init', endpoints, models, addresses });
6238
+ import('./seed.schema.config-C37yDUmq.js').then(({ models }) => {
6239
+ for (const [key, value] of Object.entries(models)) {
6240
+ setModel(key, value);
6241
+ }
6242
+ });
6243
+ },
6244
+ subscribe: (callback) => {
6245
+ callback({
6246
+ type: '@xstate.snapshot',
6247
+ actorRef: globalService,
6248
+ snapshot: globalService.getSnapshot(),
6249
+ });
6250
+ eventEmitter.addListener('globalService', callback);
6251
+ return {
6252
+ unsubscribe: () => {
6253
+ eventEmitter.removeListener('globalService', callback);
6254
+ },
6255
+ };
6256
+ },
6257
+ on: (outerEvent, callback) => {
6258
+ eventEmitter.addListener(outerEvent, callback);
6259
+ return {
6260
+ unsubscribe: () => {
6261
+ eventEmitter.removeListener(outerEvent, callback);
6262
+ },
6263
+ };
6264
+ },
6265
+ getSeedClass: () => __awaiter(void 0, void 0, void 0, function* () {
6266
+ return new Promise((resolve) => {
6267
+ const subscription = globalService.subscribe((snapshot) => {
6268
+ if (snapshot.status === 'done') {
6269
+ resolve(snapshot.output);
6270
+ }
6271
+ });
6272
+ globalService.send({ type: 'getSeed' });
6273
+ subscription.unsubscribe();
6274
+ });
6275
+ }),
6276
+ getModel: (modelName) => {
6277
+ return getModel(modelName);
6278
+ },
6279
+ getModels: () => {
6280
+ return getModels();
6281
+ },
6282
+ getModelNames: () => {
6283
+ return getModelNames();
6284
+ },
6285
+ };
6286
+
6287
+ const getSchemaForItemProperty = (_a) => __awaiter(void 0, [_a], void 0, function* ({ schemaUid, propertyName, easDataType, }) {
6288
+ const propertyNameSnakeCase = toSnakeCase(propertyName);
6289
+ const isMissingSchemaUid = !schemaUid || schemaUid === 'null' || schemaUid === 'undefined';
6290
+ let queryParams = {
6291
+ where: {
6292
+ id: {
6293
+ equals: schemaUid,
6294
+ },
6295
+ },
6505
6296
  };
6297
+ if (easDataType) {
6298
+ queryParams = {
6299
+ where: {
6300
+ schema: {
6301
+ equals: `${easDataType} ${propertyNameSnakeCase}`,
6302
+ },
6303
+ },
6304
+ };
6305
+ }
6306
+ if (!easDataType && isMissingSchemaUid) {
6307
+ queryParams = {
6308
+ where: {
6309
+ schemaNames: {
6310
+ some: {
6311
+ name: {
6312
+ equals: propertyNameSnakeCase,
6313
+ },
6314
+ },
6315
+ },
6316
+ },
6317
+ };
6318
+ }
6319
+ const foundPropertySchema = yield queryClient.fetchQuery({
6320
+ queryKey: [`getPropertySchema${propertyName}`],
6321
+ queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SCHEMAS, queryParams); }),
6322
+ networkMode: 'offlineFirst',
6323
+ });
6324
+ if (foundPropertySchema && foundPropertySchema.schemas.length > 0) {
6325
+ return foundPropertySchema.schemas[0];
6326
+ }
6327
+ });
6328
+
6329
+ const schemaUidForSchemaDefinition = new Map();
6330
+ const setSchemaUidForSchemaDefinition = ({ text, schemaUid }) => {
6331
+ const propertySnakeCase = toSnakeCase(text);
6332
+ schemaUidForSchemaDefinition.set(propertySnakeCase, schemaUid);
6506
6333
  };
6507
- const useCreateItem = (modelName) => {
6508
- const [isCreatingItem, setIsCreatingItem] = useState(false);
6509
- const { isReady } = useItemIsReady();
6510
- const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
6511
- if (!isReady) {
6512
- console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
6513
- return;
6514
- }
6515
- if (isCreatingItem) {
6516
- // TODO: should we setup a queue for this?
6517
- console.error(`[useCreateItem] [createItem] already creating item`, itemData);
6518
- return;
6519
- }
6520
- setIsCreatingItem(true);
6521
- const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
6522
- yield Item.find({ modelName, seedLocalId });
6523
- eventEmitter.emit('item.requestAll', { modelName });
6524
- setIsCreatingItem(false);
6525
- }), [isCreatingItem, isReady]);
6526
- return {
6527
- createItem,
6528
- isCreatingItem,
6529
- };
6334
+ const getSchemaUidForSchemaDefinition = (schemaText) => {
6335
+ const textSnakeCase = toSnakeCase(schemaText);
6336
+ if (!schemaUidForSchemaDefinition.has(textSnakeCase)) {
6337
+ return;
6338
+ }
6339
+ return schemaUidForSchemaDefinition.get(textSnakeCase);
6530
6340
  };
6341
+ const fetchSchemaUids = () => __awaiter(void 0, void 0, void 0, function* () {
6342
+ const versionSchemaUid = yield getSchemaForItemProperty({
6343
+ propertyName: 'version',
6344
+ easDataType: 'bytes32',
6345
+ });
6346
+ if (versionSchemaUid) {
6347
+ setSchemaUidForSchemaDefinition({
6348
+ text: 'version',
6349
+ schemaUid: versionSchemaUid,
6350
+ });
6351
+ }
6352
+ const imageSchemaUid = yield getSchemaForItemProperty({
6353
+ propertyName: 'image',
6354
+ easDataType: 'bytes32',
6355
+ });
6356
+ if (imageSchemaUid) {
6357
+ setSchemaUidForSchemaDefinition({
6358
+ text: 'image',
6359
+ schemaUid: imageSchemaUid,
6360
+ });
6361
+ }
6362
+ });
6531
6363
 
6532
- const logger$2 = debug('app:react:property');
6533
- const useItemProperty = ({ propertyName, seedLocalId, seedUid, }) => {
6534
- const [property, setProperty] = useState();
6535
- const [isInitialized, setIsInitialized] = useState(false);
6536
- const { internalStatus } = useGlobalServiceStatus();
6537
- const isReadingDb = useRef(false);
6538
- const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
6539
- if (!snapshot || !snapshot.context) {
6540
- return;
6364
+ const initialize = fromCallback(({ sendBack, input: { context } }) => {
6365
+ const { isRelation, propertyName, storageTransactionId } = context;
6366
+ let { schemaUid } = context;
6367
+ if (!schemaUid) {
6368
+ schemaUid = getSchemaUidForSchemaDefinition(propertyName);
6369
+ if (schemaUid) {
6370
+ sendBack({ type: 'updateContext', schemaUid });
6541
6371
  }
6542
- return snapshot.context.renderValue || snapshot.context.propertyValue;
6543
- });
6544
- const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6545
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6546
- if (internalStatus !== 'ready' ||
6547
- isReadingDb.current ||
6548
- (!seedLocalId && !seedUid)) {
6372
+ }
6373
+ if (isRelation) {
6374
+ sendBack({ type: 'isRelatedProperty' });
6375
+ sendBack({ type: 'initializeSuccess' });
6376
+ return;
6377
+ }
6378
+ if (!isRelation) {
6379
+ if ((propertyName !== 'html' && propertyName !== 'json') ||
6380
+ !storageTransactionId) {
6381
+ sendBack({ type: 'initializeSuccess' });
6549
6382
  return;
6550
6383
  }
6551
- isReadingDb.current = true;
6552
- const foundProperty = yield ItemProperty.find({
6553
- propertyName,
6554
- seedLocalId,
6555
- seedUid,
6384
+ const _getContentsFromFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
6385
+ if (propertyName === 'html') {
6386
+ const htmlFilePath = `/files/html/${storageTransactionId}.html`;
6387
+ const exists = yield fs.promises.exists(htmlFilePath);
6388
+ if (!exists) {
6389
+ return;
6390
+ }
6391
+ const renderValue = yield fs.promises
6392
+ .readFile(`/files/html/${storageTransactionId}.html`, 'utf8')
6393
+ .catch((error) => {
6394
+ console.warn('Error reading html file', error);
6395
+ });
6396
+ sendBack({ type: 'updateContext', renderValue });
6397
+ return;
6398
+ }
6399
+ if (propertyName === 'json') {
6400
+ const jsonFilePath = `/files/json/${storageTransactionId}.json`;
6401
+ const exists = yield fs.promises.exists(jsonFilePath);
6402
+ if (!exists) {
6403
+ return;
6404
+ }
6405
+ const renderValue = yield fs.promises
6406
+ .readFile(`/files/json/${storageTransactionId}.json`, 'utf8')
6407
+ .catch((error) => {
6408
+ console.warn('Error reading json file', error);
6409
+ });
6410
+ sendBack({ type: 'updateContext', renderValue });
6411
+ return;
6412
+ }
6556
6413
  });
6557
- if (!foundProperty) {
6558
- logger$2(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6559
- isReadingDb.current = false;
6414
+ _getContentsFromFileSystem().then(() => {
6415
+ sendBack({ type: 'initializeSuccess' });
6416
+ });
6417
+ }
6418
+ });
6419
+
6420
+ const logger$2 = debug('app:property:actors:resolveRelatedValue');
6421
+ const storageTransactionIdToContentUrl = new Map();
6422
+ const refResolvedValueToContentUrl = new Map();
6423
+ const seedUidToContentUrl = new Map();
6424
+ const resolveRelatedValue = fromCallback(({ sendBack, input: { context } }) => {
6425
+ const { isRelation, propertyValue, propertyName, seedUid, propertyRecordSchema, populatedFromDb, schemaUid, } = context;
6426
+ const _resolveRelatedValue = () => __awaiter(void 0, void 0, void 0, function* () {
6427
+ if (!propertyValue || !isRelation || populatedFromDb) {
6560
6428
  return;
6561
6429
  }
6562
- if (foundProperty.status === 'waitingForDb') {
6563
- foundProperty.getService().send({ type: 'waitForDbSuccess' });
6430
+ let parsedValue;
6431
+ try {
6432
+ parsedValue = JSON.parse(propertyValue);
6564
6433
  }
6565
- setProperty(foundProperty);
6566
- setIsInitialized(true);
6567
- isReadingDb.current = false;
6568
- }), [internalStatus]);
6569
- const listenerRef = useRef(readFromDb);
6570
- useEffect(() => {
6571
- listenerRef.current = readFromDb;
6572
- }, [readFromDb]);
6573
- useEffect(() => {
6574
- if (internalStatus === 'ready') {
6575
- readFromDb();
6434
+ catch (error) {
6435
+ logger$2(`${propertyName} value is not a JSON string.`);
6576
6436
  }
6577
- }, [internalStatus]);
6578
- useEffect(() => {
6579
- eventEmitter.addListener(`property.${seedUid || seedLocalId}.${propertyName}.update`, () => {
6580
- listenerRef.current();
6581
- });
6582
- return () => {
6583
- eventEmitter.removeListener(`property.${seedUid || seedLocalId}.${propertyName}.update`);
6584
- };
6585
- }, []);
6586
- return {
6587
- property,
6588
- isInitialized,
6589
- value,
6590
- status,
6591
- };
6592
- };
6593
- const useItemProperties = (item) => {
6594
- const [propertyObj, setPropertyObj] = useImmer({});
6595
- useState(false);
6596
- const updatePropertyObj = useCallback((event) => {
6597
- if (!item) {
6598
- console.error('[XXXXXX] [updatePropertyObj] no item when expected');
6437
+ if (!parsedValue && seedUidToContentUrl.has(propertyValue)) {
6438
+ const contentUrl = seedUidToContentUrl.get(propertyValue);
6439
+ sendBack({
6440
+ type: 'updateContext',
6441
+ renderValue: contentUrl,
6442
+ });
6443
+ sendBack({
6444
+ type: 'resolvingRelatedValueSuccess',
6445
+ resolvedDisplayValue: contentUrl,
6446
+ });
6447
+ return true;
6448
+ }
6449
+ if (Array.isArray(propertyValue)) {
6450
+ // TODO: Handle array of seedUids
6451
+ logger$2(`${propertyName} value is an array of seedUids`);
6599
6452
  return;
6600
6453
  }
6601
- const { propertyName, propertyValue } = event;
6602
- if (!propertyName) {
6454
+ if (Array.isArray(parsedValue)) {
6455
+ logger$2(`${propertyName} value is a stringified array of seedUids`);
6603
6456
  return;
6604
6457
  }
6605
- setPropertyObj((draft) => {
6606
- draft[propertyName] = propertyValue;
6458
+ const storageTransactionId = yield getStorageTransactionIdForSeedUid(propertyValue);
6459
+ if (storageTransactionId) {
6460
+ if (storageTransactionIdToContentUrl.has(storageTransactionId)) {
6461
+ const contentUrl = storageTransactionIdToContentUrl.get(storageTransactionId);
6462
+ sendBack({
6463
+ type: 'updateContext',
6464
+ renderValue: contentUrl,
6465
+ });
6466
+ sendBack({
6467
+ type: 'resolvingRelatedValueSuccess',
6468
+ resolvedDisplayValue: contentUrl,
6469
+ resolvedValue: storageTransactionId,
6470
+ });
6471
+ return true;
6472
+ }
6473
+ const contentUrl = yield convertTxIdToImageSrc(storageTransactionId);
6474
+ if (contentUrl) {
6475
+ seedUidToContentUrl.set(propertyValue, contentUrl);
6476
+ }
6477
+ sendBack({
6478
+ type: 'updateContext',
6479
+ renderValue: contentUrl,
6480
+ });
6481
+ sendBack({
6482
+ type: 'resolvingRelatedValueSuccess',
6483
+ resolvedDisplayValue: contentUrl,
6484
+ resolvedValue: storageTransactionId,
6485
+ });
6486
+ return true;
6487
+ }
6488
+ const relationValueData = yield getRelationValueData(propertyValue);
6489
+ if (relationValueData) {
6490
+ const { refResolvedValue } = relationValueData;
6491
+ const propertyValueFromDb = relationValueData.propertyValue;
6492
+ // This handles a local-only relation value and resolves from the filesystem
6493
+ if (refResolvedValue &&
6494
+ propertyRecordSchema.dataType === 'Relation' &&
6495
+ propertyValueFromDb.length === 10 &&
6496
+ propertyRecordSchema.ref) {
6497
+ if (refResolvedValueToContentUrl.has(refResolvedValue)) {
6498
+ const contentUrl = refResolvedValueToContentUrl.get(refResolvedValue);
6499
+ sendBack({
6500
+ type: 'updateContext',
6501
+ renderValue: contentUrl,
6502
+ });
6503
+ sendBack({
6504
+ type: 'resolvingRelatedValueSuccess',
6505
+ resolvedDisplayValue: contentUrl,
6506
+ });
6507
+ return true;
6508
+ }
6509
+ const fileExists = yield fs.promises.exists('/files/images/' + refResolvedValue);
6510
+ if (fileExists) {
6511
+ const fileContents = yield fs.promises.readFile('/files/images/' + refResolvedValue);
6512
+ const fileHandler = new File([fileContents], refResolvedValue);
6513
+ const contentUrl = URL.createObjectURL(fileHandler);
6514
+ refResolvedValueToContentUrl.set(refResolvedValue, contentUrl);
6515
+ sendBack({
6516
+ type: 'updateContext',
6517
+ renderValue: contentUrl,
6518
+ });
6519
+ sendBack({
6520
+ type: 'resolvingRelatedValueSuccess',
6521
+ resolvedDisplayValue: contentUrl,
6522
+ });
6523
+ return true;
6524
+ }
6525
+ }
6526
+ if (typeof propertyValueFromDb === 'string') {
6527
+ // Check files for a filename that matches the propertyValue
6528
+ if (propertyRecordSchema &&
6529
+ propertyRecordSchema.refValueType === 'ImageSrc') {
6530
+ let contentUrl;
6531
+ if (storageTransactionIdToContentUrl.has(propertyValueFromDb)) {
6532
+ contentUrl =
6533
+ storageTransactionIdToContentUrl.get(propertyValueFromDb);
6534
+ }
6535
+ if (!contentUrl) {
6536
+ const imageFileExists = yield fs.promises.exists(`/images/${propertyValue}`);
6537
+ if (imageFileExists) {
6538
+ const fileContents = yield fs.promises.readFile(`/images/${propertyValue}`);
6539
+ const fileHandler = new File([fileContents], propertyValue);
6540
+ contentUrl = URL.createObjectURL(fileHandler);
6541
+ storageTransactionIdToContentUrl.set(propertyValueFromDb, contentUrl);
6542
+ }
6543
+ }
6544
+ if (contentUrl) {
6545
+ sendBack({
6546
+ type: 'updateContext',
6547
+ renderValue: contentUrl,
6548
+ });
6549
+ sendBack({
6550
+ type: 'resolvingRelatedValueSuccess',
6551
+ resolvedDisplayValue: contentUrl,
6552
+ });
6553
+ return true;
6554
+ }
6555
+ }
6556
+ }
6557
+ }
6558
+ });
6559
+ _resolveRelatedValue().then((success) => {
6560
+ // if (success) {
6561
+ // sendBack({
6562
+ // type: 'resolvingRelatedValueDone',
6563
+ // })
6564
+ // }
6565
+ // return
6566
+ sendBack({
6567
+ type: 'resolvingRelatedValueDone',
6607
6568
  });
6608
- }, [item]);
6609
- useEffect(() => {
6610
- if (!item) {
6611
- return;
6612
- }
6613
- const eventKey = `item.${item.seedLocalId}.property.update`;
6614
- eventEmitter.addListener(eventKey, updatePropertyObj);
6615
- return () => {
6616
- eventEmitter.removeListener(eventKey, updatePropertyObj);
6617
- };
6618
- }, [item]);
6619
- return {
6620
- properties: propertyObj,
6621
- };
6622
- };
6623
-
6624
- debug('app:react:db');
6625
-
6626
- const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLocalId, seedUid }) {
6627
- const appDb = getAppDb();
6628
- yield appDb
6629
- .update(seeds)
6630
- .set({
6631
- _markedForDeletion: 1,
6632
- })
6633
- .where(or(eq(seeds.localId, seedLocalId), eq(seeds.uid, seedUid)));
6569
+ });
6634
6570
  });
6571
+ // const eventKey = `storage.transaction.${initialValue}.contentUrl.response`
6572
+ //
6573
+ // const contentUrlListener = async (event) => {
6574
+ // console.log('[itemProperty] [constructor] contentUrlListener', event)
6575
+ // }
6576
+ //
6577
+ // eventEmitter.once(eventKey, contentUrlListener)
6578
+ //
6579
+ // const ready = getArePropertyEventHandlersReady()
6580
+ //
6581
+ // console.log('[itemProperty] [constructor] ready', ready)
6582
+ //
6583
+ // eventEmitter.emit('storage.transaction.contentUrl.request', {
6584
+ // storageTransactionId: initialValue,
6585
+ // })
6586
+ // Related property values can either be seedUid or seedUid[]
6587
+ // let relatedSeedUid: string
6588
+ // let relatedSeedUids: string[]
6589
+ //
6590
+ // if (Array.isArray(propertyValue)) {
6591
+ // relatedSeedUids = propertyValue
6592
+ // } else {
6593
+ // relatedSeedUid = propertyValue
6594
+ // }
6595
+ //
6596
+ // if (relatedSeedUid) {
6597
+ // console.log(
6598
+ // `[property/actors] [resolveRelatedValue] seedUid: ${relatedSeedUid}`,
6599
+ // )
6600
+ // const latestVersionOfRelatedSeedQuery = await appDb.run(
6601
+ // sql.raw(
6602
+ // `
6603
+ // SELECT local_id, uid, MAX(attestation_created_at)
6604
+ // FROM versions
6605
+ // WHERE seed_uid = '${relatedSeedUid}';
6606
+ // `,
6607
+ // ),
6608
+ // )
6609
+ // if (
6610
+ // latestVersionOfRelatedSeedQuery &&
6611
+ // latestVersionOfRelatedSeedQuery.rows &&
6612
+ // latestVersionOfRelatedSeedQuery.rows.length > 0
6613
+ // ) {
6614
+ // const latestVersionOfRelatedSeed =
6615
+ // latestVersionOfRelatedSeedQuery.rows[0]
6616
+ // console.log(
6617
+ // '[property/actors] [resolveRelatedValue] latestVersionOfRelatedSeed',
6618
+ // latestVersionOfRelatedSeed,
6619
+ // )
6620
+ // const storageIdQuery = await appDb.run(
6621
+ // sql.raw(
6622
+ // `
6623
+ // SELECT property_value, MAX(attestation_created_at), ref_resolved_display_value, ref_resolved_value
6624
+ // FROM metadata
6625
+ // WHERE seed_uid = '${relatedSeedUid}'
6626
+ // AND property_name = 'storageTransactionId';
6627
+ // `,
6628
+ // ),
6629
+ // )
6630
+ //
6631
+ // if (
6632
+ // storageIdQuery &&
6633
+ // storageIdQuery.rows &&
6634
+ // storageIdQuery.rows.length > 0
6635
+ // ) {
6636
+ // const storageId = storageIdQuery.rows[0][0]
6637
+ //
6638
+ // if (!storageId) {
6639
+ // console.error(
6640
+ // `storageId not found for ${propertyName} with relatedSeedUid ${relatedSeedUid}`,
6641
+ // )
6642
+ // }
6643
+ //
6644
+ // const resolvedDisplayValue = storageIdQuery.rows[0][2]
6645
+ // let resolvedValue = storageIdQuery.rows[0][3]
6646
+ //
6647
+ // if (resolvedDisplayValue && resolvedValue) {
6648
+ // sendBack({
6649
+ // type: 'resolvingRelatedValueSuccess',
6650
+ // resolvedDisplayValue,
6651
+ // resolvedValue,
6652
+ // })
6653
+ // return
6654
+ // }
6655
+ //
6656
+ // console.log(
6657
+ // '[property/actors] [resolveRelatedValue] storageId',
6658
+ // storageId,
6659
+ // )
6660
+ //
6661
+ // const contentUrl = await convertTxIdToImageSrc(storageId)
6662
+ //
6663
+ // if (!contentUrl) {
6664
+ // throw new Error(
6665
+ // `contentUrl not found for ${propertyName} with relatedSeedUid ${relatedSeedUid}`,
6666
+ // )
6667
+ // }
6668
+ //
6669
+ // await appDb.run(
6670
+ // sql.raw(
6671
+ // `UPDATE metadata
6672
+ // SET ref_resolved_display_value = '${contentUrl}',
6673
+ // ref_resolved_value = '${storageId}'
6674
+ // WHERE seed_uid = '${relatedSeedUid}'
6675
+ // AND property_name = 'storageTransactionId';
6676
+ // `,
6677
+ // ),
6678
+ // )
6679
+ //
6680
+ // sendBack({
6681
+ // type: 'resolvingRelatedValueSuccess',
6682
+ // resolvedDisplayValue: contentUrl,
6683
+ // resolvedValue: storageId,
6684
+ // })
6685
+ // }
6686
+ // }
6687
+ //
6688
+ // const versionUidQuery = await appDb.run(
6689
+ // sql.raw(
6690
+ // `
6691
+ // SELECT uid
6692
+ // FROM versions
6693
+ // WHERE seed_uid = '${relatedSeedUid}';
6694
+ // `,
6695
+ // ),
6696
+ // )
6697
+ //
6698
+ // if (
6699
+ // versionUidQuery &&
6700
+ // versionUidQuery.rows &&
6701
+ // versionUidQuery.rows.length > 0
6702
+ // ) {
6703
+ // const versionUids = versionUidQuery.rows.map((row) => row[0])
6704
+ // console.log(
6705
+ // '[property/actors] [resolveRelatedValue] versionUids',
6706
+ // versionUids,
6707
+ // )
6708
+ // const { itemProperties } = await easClient.request(GET_PROPERTIES, {
6709
+ // where: {
6710
+ // refUID: {
6711
+ // in: versionUids,
6712
+ // },
6713
+ // decodedDataJson: {
6714
+ // contains: 'storage_transaction_id',
6715
+ // },
6716
+ // },
6717
+ // })
6718
+ //
6719
+ // console.log(
6720
+ // '[property/actors] [resolveRelatedValue] itemProperties',
6721
+ // itemProperties,
6722
+ // )
6723
+ //
6724
+ // if (itemProperties && itemProperties.length > 0) {
6725
+ // await savePropertiesToDb(itemProperties)
6726
+ // }
6727
+ // }
6728
+ // }
6635
6729
 
6636
- const useDeleteItem = () => {
6637
- const [isDeletingItem, setIsDeletingItem] = useState(false);
6638
- const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
6639
- if (!item) {
6640
- return;
6641
- }
6642
- setIsDeletingItem(true);
6643
- const { modelName } = item.getService().getSnapshot().context;
6644
- yield deleteItem({ seedLocalId: item.seedLocalId });
6645
- eventEmitter.emit('item.requestAll', { modelName });
6646
- setIsDeletingItem(false);
6647
- }), [isDeletingItem]);
6648
- useEffect(() => { }, []);
6649
- return {
6650
- deleteItem: destroy,
6651
- isDeletingItem,
6652
- };
6653
- };
6654
-
6655
- const logger$1 = debug('app:services:events');
6656
- const handleServiceSaveState = (event) => {
6657
- const { state, serviceId } = event;
6658
- logger$1(`[browser] [service.saveState.request] serviceId: ${serviceId}`);
6659
- localStorage.setItem(`seed_sdk_service_${serviceId}`, JSON.stringify(state));
6660
- };
6661
- const setupServicesEventHandlers = () => {
6662
- eventEmitter.addListener('service.saveState.request', handleServiceSaveState);
6663
- };
6664
-
6665
- const saveServiceHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
6666
- const globalService = getGlobalService();
6667
- if (!globalService || !globalService.getSnapshot().context) {
6668
- return;
6669
- }
6670
- const { modelName } = event;
6671
- const nameOfService = `${modelName}Service`;
6672
- const service = globalService.getSnapshot().context[nameOfService];
6673
- if (!service) {
6674
- console.log(`[saveServiceHandler] service not found: ${nameOfService}`);
6675
- return;
6730
+ const updateMetadata = (metadataValues) => __awaiter(void 0, void 0, void 0, function* () {
6731
+ const appDb = getAppDb();
6732
+ const { localId } = metadataValues, rest = __rest(metadataValues, ["localId"]);
6733
+ if (!localId) {
6734
+ throw new Error('No localId provided to updateMetadata');
6676
6735
  }
6677
- yield saveAppState(`snapshot__${modelName}`, JSON.stringify(service.getPersistedSnapshot()));
6736
+ yield appDb.update(metadata).set(rest).where(eq(metadata.localId, localId));
6678
6737
  });
6679
6738
 
6680
- const setupServiceHandlers = () => {
6681
- eventEmitter.addListener('service.save', saveServiceHandler);
6682
- };
6683
-
6684
- const client = {
6685
- init: ({ config, addresses }) => {
6686
- const { endpoints, models } = config;
6687
- for (const [key, value] of Object.entries(models)) {
6688
- setModel(key, value);
6739
+ const logger$1 = debug('app:property:actors:hydrateFromDb');
6740
+ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
6741
+ const { seedUid, seedLocalId, propertyName: propertyNameRaw, propertyValue, propertyRecordSchema, itemModelName, } = context;
6742
+ let propertyName = propertyNameRaw;
6743
+ if (propertyRecordSchema &&
6744
+ propertyRecordSchema.ref &&
6745
+ propertyRecordSchema.dataType === 'Relation' &&
6746
+ !propertyNameRaw.endsWith('Id')) {
6747
+ propertyName = propertyNameRaw + 'Id';
6748
+ }
6749
+ if (propertyRecordSchema &&
6750
+ propertyRecordSchema.ref &&
6751
+ propertyRecordSchema.dataType === 'List' &&
6752
+ !propertyNameRaw.endsWith('Ids')) {
6753
+ propertyName = propertyNameRaw + 'Ids';
6754
+ }
6755
+ const _hydrateFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
6756
+ const appDb = getAppDb();
6757
+ const isRelation = propertyRecordSchema &&
6758
+ propertyRecordSchema.ref &&
6759
+ propertyRecordSchema.dataType === 'Relation';
6760
+ const whereClauses = [];
6761
+ if (isRelation) {
6762
+ let missingPropertyNameVariant;
6763
+ if (propertyName.endsWith('Id')) {
6764
+ missingPropertyNameVariant = propertyName.slice(0, -2);
6765
+ }
6766
+ if (!propertyName.endsWith('Id')) {
6767
+ missingPropertyNameVariant = propertyName + 'Id';
6768
+ }
6769
+ if (missingPropertyNameVariant) {
6770
+ whereClauses.push(or(eq(metadata.propertyName, propertyName), eq(metadata.propertyName, missingPropertyNameVariant)));
6771
+ }
6772
+ if (!missingPropertyNameVariant) {
6773
+ whereClauses.push(eq(metadata.propertyName, propertyName));
6774
+ }
6689
6775
  }
6690
- setupFsListeners();
6691
- setupAllItemsEventHandlers();
6692
- setupServicesEventHandlers();
6693
- setupServiceHandlers();
6694
- if (areFsListenersReady()) {
6695
- eventEmitter.emit('fs.init');
6776
+ else {
6777
+ whereClauses.push(eq(metadata.propertyName, propertyName));
6696
6778
  }
6697
- if (!areFsListenersReady()) {
6698
- console.error('fs listeners not ready during init');
6779
+ if (seedUid) {
6780
+ whereClauses.push(eq(metadata.seedUid, seedUid));
6699
6781
  }
6700
- globalService.send({ type: 'init', endpoints, models, addresses });
6701
- import('./seed.schema.config-wQXee2fb.js').then(({ models }) => {
6702
- for (const [key, value] of Object.entries(models)) {
6703
- setModel(key, value);
6782
+ if (seedLocalId) {
6783
+ whereClauses.push(eq(metadata.seedLocalId, seedLocalId));
6784
+ }
6785
+ const rows = yield appDb
6786
+ .select()
6787
+ .from(metadata)
6788
+ .where(and(...whereClauses))
6789
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'));
6790
+ if (!rows || !rows.length) {
6791
+ return;
6792
+ }
6793
+ const firstRow = rows[0];
6794
+ const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, versionLocalId: versionLocalIdFromDb, versionUid: versionUidFromDb, refValueType, localStorageDir, } = firstRow;
6795
+ let { refResolvedDisplayValue, refResolvedValue } = firstRow;
6796
+ let propertyValueProcessed = propertyValueFromDb;
6797
+ if (propertyName && !propertyNameFromDb) {
6798
+ logger$1(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
6799
+ }
6800
+ if (propertyName &&
6801
+ propertyNameFromDb &&
6802
+ !propertyNameFromDb.includes(propertyName) &&
6803
+ !propertyName.includes(propertyNameFromDb) &&
6804
+ propertyNameFromDb !== propertyName) {
6805
+ logger$1(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
6806
+ }
6807
+ if (propertyValue && propertyValueFromDb !== propertyValue) {
6808
+ logger$1(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
6809
+ }
6810
+ if (seedLocalIdFromDb !== seedLocalId) {
6811
+ logger$1(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
6812
+ }
6813
+ if (seedUidFromDb !== seedUid) {
6814
+ logger$1(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
6815
+ }
6816
+ if (propertyRecordSchema &&
6817
+ propertyRecordSchema.refValueType === 'ImageSrc') {
6818
+ let shouldReadFromFile = true;
6819
+ if (refResolvedValue &&
6820
+ refResolvedDisplayValue &&
6821
+ refResolvedDisplayValue.includes('http')) {
6822
+ try {
6823
+ const response = yield fetch(refResolvedDisplayValue, {
6824
+ method: 'HEAD',
6825
+ });
6826
+ // Check if the status is in the 200-299 range
6827
+ if (response.ok) {
6828
+ shouldReadFromFile = false;
6829
+ }
6830
+ }
6831
+ catch (error) {
6832
+ shouldReadFromFile = true;
6833
+ }
6704
6834
  }
6705
- });
6706
- },
6707
- subscribe: (callback) => {
6708
- callback({
6709
- type: '@xstate.snapshot',
6710
- actorRef: globalService,
6711
- snapshot: globalService.getSnapshot(),
6712
- });
6713
- eventEmitter.addListener('globalService', callback);
6714
- return {
6715
- unsubscribe: () => {
6716
- eventEmitter.removeListener('globalService', callback);
6717
- },
6718
- };
6719
- },
6720
- on: (outerEvent, callback) => {
6721
- eventEmitter.addListener(outerEvent, callback);
6722
- return {
6723
- unsubscribe: () => {
6724
- eventEmitter.removeListener(outerEvent, callback);
6725
- },
6726
- };
6727
- },
6728
- getSeedClass: () => __awaiter(void 0, void 0, void 0, function* () {
6729
- return new Promise((resolve) => {
6730
- const subscription = globalService.subscribe((snapshot) => {
6731
- if (snapshot.status === 'done') {
6732
- resolve(snapshot.output);
6835
+ if (shouldReadFromFile) {
6836
+ let dir = localStorageDir;
6837
+ if (!dir &&
6838
+ propertyRecordSchema &&
6839
+ propertyRecordSchema.refValueType === 'ImageSrc') {
6840
+ dir = 'images';
6733
6841
  }
6734
- });
6735
- globalService.send({ type: 'getSeed' });
6736
- subscription.unsubscribe();
6842
+ dir = dir.replace(/^\//, '');
6843
+ if (!refResolvedValue &&
6844
+ propertyValueFromDb &&
6845
+ propertyValueFromDb.length === 66) {
6846
+ const storageTransactionQuery = yield appDb
6847
+ .select({
6848
+ propertyValue: metadata.propertyValue,
6849
+ })
6850
+ .from(metadata)
6851
+ .where(and(eq(metadata.seedUid, propertyValueFromDb), eq(metadata.propertyName, 'storageTransactionId')));
6852
+ if (storageTransactionQuery && storageTransactionQuery.length > 0) {
6853
+ const row = storageTransactionQuery[0];
6854
+ refResolvedValue = row.propertyValue;
6855
+ console.log('storageTransactionId', refResolvedValue);
6856
+ yield updateMetadata({
6857
+ localId,
6858
+ refResolvedValue,
6859
+ localStorageDir: '/images',
6860
+ });
6861
+ }
6862
+ }
6863
+ const dirPath = `/files/${dir}`;
6864
+ const files = yield fs.promises.readdir(dirPath);
6865
+ const matchingFiles = files.filter((file) => {
6866
+ return path.basename(file).includes(refResolvedValue);
6867
+ });
6868
+ let fileExists = false;
6869
+ let filename;
6870
+ let filePath;
6871
+ if (matchingFiles && matchingFiles.length > 0) {
6872
+ fileExists = true;
6873
+ filename = matchingFiles[0];
6874
+ filePath = `/files/${dir}/${filename}`;
6875
+ }
6876
+ if (fileExists && filename && filePath) {
6877
+ const fileContents = yield fs.promises.readFile(filePath);
6878
+ const fileHandler = new File([fileContents], filename);
6879
+ refResolvedDisplayValue = URL.createObjectURL(fileHandler);
6880
+ yield updateMetadata({
6881
+ localId,
6882
+ refResolvedValue: filename,
6883
+ });
6884
+ }
6885
+ }
6886
+ }
6887
+ if (propertyRecordSchema &&
6888
+ propertyRecordSchema.dataType === 'List' &&
6889
+ propertyRecordSchema.ref &&
6890
+ typeof propertyValueFromDb === 'string') {
6891
+ propertyValueProcessed = propertyValueFromDb.split(',');
6892
+ }
6893
+ sendBack({
6894
+ type: 'updateContext',
6895
+ localId,
6896
+ uid,
6897
+ propertyValue: propertyValueProcessed,
6898
+ seedLocalId: seedLocalIdFromDb,
6899
+ seedUid: seedUidFromDb,
6900
+ versionLocalId: versionLocalIdFromDb,
6901
+ versionUid: versionUidFromDb,
6902
+ schemaUid: schemaUidFromDb,
6903
+ refValueType,
6904
+ localStorageDir,
6905
+ resolvedValue: refResolvedValue,
6906
+ resolvedDisplayValue: refResolvedDisplayValue,
6907
+ renderValue: refResolvedDisplayValue,
6908
+ populatedFromDb: true,
6737
6909
  });
6738
- }),
6739
- getModel: (modelName) => {
6740
- return getModel(modelName);
6741
- },
6742
- getModels: () => {
6743
- return getModels();
6744
- },
6745
- getModelNames: () => {
6746
- return getModelNames();
6747
- },
6748
- };
6910
+ if (propertyRecordSchema &&
6911
+ propertyRecordSchema.storageType &&
6912
+ propertyRecordSchema.storageType === 'ItemStorage') {
6913
+ const { Item } = yield import('./index-DyEsLJAK.js');
6914
+ const item = yield Item.find({
6915
+ seedLocalId,
6916
+ modelName: itemModelName,
6917
+ });
6918
+ if (item) {
6919
+ const filePath = `/files/${localStorageDir}/${refResolvedValue}`;
6920
+ const exists = yield fs.promises.exists(filePath);
6921
+ if (!exists) {
6922
+ return;
6923
+ }
6924
+ const renderValue = yield fs.promises.readFile(filePath, 'utf8');
6925
+ const property = item.properties[propertyName];
6926
+ property.getService().send({ type: 'updateContext', renderValue });
6927
+ return;
6928
+ }
6929
+ }
6930
+ });
6931
+ _hydrateFromDb().then(() => {
6932
+ sendBack({ type: 'hydrateFromDbSuccess' });
6933
+ });
6934
+ });
6749
6935
 
6750
6936
  const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ localId, seedLocalId, uid, }) {
6751
6937
  const appDb = getAppDb();
@@ -7016,8 +7202,10 @@ const fetchImage = (url) => __awaiter(void 0, void 0, void 0, function* () {
7016
7202
  }
7017
7203
  return base64;
7018
7204
  });
7205
+ let imageSchemaUid;
7019
7206
  const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
7020
- const { localId, propertyName: propertyNameRaw, propertyValue: existingValue, propertyRecordSchema, itemModelName, seedLocalId, seedUid, versionLocalId, versionUid, schemaUid, } = context;
7207
+ const { localId, propertyName: propertyNameRaw, propertyValue: existingValue, propertyRecordSchema, itemModelName, seedLocalId, seedUid, versionLocalId, versionUid, } = context;
7208
+ let { schemaUid } = context;
7021
7209
  let newValue;
7022
7210
  if (event) {
7023
7211
  newValue = event.newValue;
@@ -7035,6 +7223,9 @@ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
7035
7223
  let fileData;
7036
7224
  let mimeType;
7037
7225
  let fileName;
7226
+ if (!imageSchemaUid) {
7227
+ imageSchemaUid = yield getSchemaUidForModel('Image');
7228
+ }
7038
7229
  if (typeof newValue === 'string') {
7039
7230
  newValueType = getDataTypeFromString(newValue);
7040
7231
  }
@@ -7081,6 +7272,9 @@ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
7081
7272
  yield fs.promises.writeFile(filePath, fileData);
7082
7273
  }
7083
7274
  const refResolvedDisplayValue = yield getContentUrlFromPath(filePath);
7275
+ if (!schemaUid) {
7276
+ schemaUid = getSchemaUidForSchemaDefinition(propertyName);
7277
+ }
7084
7278
  if (!localId) {
7085
7279
  yield createMetadata({
7086
7280
  propertyName,
@@ -7092,6 +7286,8 @@ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
7092
7286
  modelName: itemModelName,
7093
7287
  schemaUid,
7094
7288
  refSeedType: 'image',
7289
+ refModelUid: imageSchemaUid,
7290
+ refSchemaUid: imageSchemaUid,
7095
7291
  refResolvedDisplayValue,
7096
7292
  refResolvedValue: fileName,
7097
7293
  localStorageDir: '/images',
@@ -7110,6 +7306,8 @@ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
7110
7306
  refSeedType: 'image',
7111
7307
  refResolvedDisplayValue,
7112
7308
  refResolvedValue: fileName,
7309
+ refModelUid: imageSchemaUid,
7310
+ refSchemaUid: imageSchemaUid,
7113
7311
  localStorageDir: '/images',
7114
7312
  easDataType: 'bytes32',
7115
7313
  });
@@ -7118,9 +7316,12 @@ const saveImageSrc = fromCallback(({ sendBack, input: { context, event } }) => {
7118
7316
  type: 'updateContext',
7119
7317
  propertyValue: newImageSeedLocalId,
7120
7318
  refSeedType: 'image',
7319
+ refSchemaUid: imageSchemaUid,
7121
7320
  renderValue: refResolvedDisplayValue,
7122
7321
  resolvedDisplayValue: refResolvedDisplayValue,
7123
7322
  resolvedValue: fileName,
7323
+ localStorageDir: '/images',
7324
+ easDataType: 'bytes32',
7124
7325
  });
7125
7326
  });
7126
7327
  _saveImageSrc().then(() => {
@@ -7326,7 +7527,7 @@ const propertyMachine = setup({
7326
7527
  actors: {
7327
7528
  waitForDb: waitForDb$1,
7328
7529
  hydrateFromDb,
7329
- initialize: initialize$3,
7530
+ initialize,
7330
7531
  resolveRelatedValue,
7331
7532
  resolveRemoteStorage,
7332
7533
  analyzeInput,
@@ -7651,4 +7852,4 @@ if (isNode()) {
7651
7852
  }
7652
7853
 
7653
7854
  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_SCHEMA_BY_NAME as a, GET_SEEDS as b, GET_SEED_IDS as c, GET_STORAGE_TRANSACTION_ID as d, GET_VERSIONS as e, GET_PROPERTIES as f, GET_ALL_PROPERTIES_FOR_ALL_VERSIONS as g, itemMachineAll as h, itemMachineSingle as i, ImageSrc as j, ItemProperty as k, useItem as l, useItemProperties as m, useCreateItem as n, useItemProperty as o, useDeleteItem as p, useGlobalServiceStatus as q, useServices as r, getGlobalService as s, client as t, useItems as u, getCorrectId as v, withSeed as w };
7654
- //# sourceMappingURL=index--nvTinP_.js.map
7855
+ //# sourceMappingURL=index-CvfKxmFw.js.map